blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
6
116
path
stringlengths
5
872
src_encoding
stringclasses
7 values
length_bytes
int64
10
4.68M
score
float64
2.52
5.63
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
7
4.81M
download_success
bool
1 class
cf5b0fd4e606e56496c58e49018732023a30b695
Swift
alisandagdelen/iOSBaseProject
/BaseProject/ContainerVC.swift
UTF-8
2,289
2.625
3
[]
no_license
// // ContainerVC.swift // BaseProject // // Created by alişan dağdelen on 11.07.2017. // Copyright © 2017 alisandagdeleb. All rights reserved. // import UIKit enum ContainerAnimaton { case none case bottomToTop case growUp(from:CGRect) } class ContainerVC: BaseVC { var currentVC:UIViewController! var beginRect:CGRect! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.clear } func showChildVC(_ vc:UIViewController, animation:ContainerAnimaton = .none) { if currentVC == nil { view.addSubview(vc.view) } else if currentVC != vc { transition(from: currentVC, to: vc, duration: 0, options: UIViewAnimationOptions(), animations: nil, completion:nil) } else { vc.view.removeFromSuperview() view.addSubview(vc.view) } switch animation { case .none: vc.view.frame = self.view.bounds case .bottomToTop: var frame = view.bounds frame.origin.y = frame.size.height vc.view.frame = frame vc.view.alpha = 0.5 UIView.animate(withDuration: 0.3, animations: { () -> Void in vc.view.frame = self.view.bounds vc.view.alpha = 1 }) case .growUp(let from): beginRect = self.view.convert(from, from:nil) vc.view.frame = beginRect UIView.animate(withDuration: 0.2, animations: { () -> Void in vc.view.frame = self.view.bounds }) } currentVC = vc } func prepareChildVC(_ vcClass:BaseVC.Type, withNavigationController hasNavController:Bool=false) -> UIViewController! { let vc = prepareVC(type: vcClass) vc.view.frame = view.bounds if hasNavController { let navController = UINavigationController(rootViewController:vc) navController.view.frame = view.bounds addChildViewController(navController) return navController } else { addChildViewController(vc) return vc } } }
true
d089f6c7802c49f1c2f8064936903f987730344a
Swift
antoniosferreira/BeeBants
/BeeBants/History/HistoryTableViewController.swift
UTF-8
4,919
2.515625
3
[]
no_license
// // HistoryTableViewController.swift // BeeBants // // Created by António Ferreira on 25/01/2021. // Copyright © 2021 BeeBants. All rights reserved. // import UIKit import Firebase import FirebaseFunctions import AuthenticationServices import FirebaseFirestoreSwift class HistoryTableViewController: UITableViewController { var history : [HistoryField] = [] var offset = 0 override func viewDidLoad() { super.viewDidLoad() loadTripsFromHistory(offset: offset) } func loadTripsFromHistory(offset: Int) { Functions.functions().httpsCallable("loadHistory").call(["offset":offset]) { (result, error) in if let error = error { print(error.localizedDescription) return } let results = (result?.data as? [String: Any])?["historyElements"] as! [String] var x = 0 for trip in results { x = x + 1 // Retrieve History Trip Data Firestore Firestore.firestore().collection("History").document(trip).getDocument { (document, error) in if let error = error { print(error.localizedDescription) } if let document = document, document.exists { let imgPath = (document.get("cityName") as! String) + "/Locations/" + (document.get("locImg") as! String) let storageRef = Storage.storage().reference(withPath: imgPath) storageRef.getData(maxSize: (1 * 4194304 * 4194304)) { (data, error) in if let _data = data { let img = UIImage(data: _data)! let row = HistoryField(name: document.get("spotName") as! String, img: img, timestamp: document.get("timestamp") as! Timestamp, review: document.get("review") as! Int, fileName: trip) self.history.append(row) if (x == results.count) { self.history.sort(by: {$0.stamp > $1.stamp}) self.tableView.reloadData() } } else { let row = HistoryField(name: document.get("spotName") as! String, img: UIImage(named: "BG_place")!, timestamp: document.get("timestamp") as! Timestamp, review: document.get("review") as! Int, fileName: trip) self.history.append(row) if (x == results.count) { self.history.sort(by: {$0.stamp > $1.stamp}) self.tableView.reloadData() } } } } else { // this trip not found } } } } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return history.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? HistoryTableViewCell else { fatalError("") } let row = history[indexPath.row] cell.nameLabel.text = row.spotName cell.dateLabel.text = row.date cell.locationImg.image = row.location cell.ranking = row.ranking print(row.historyFile) print(row.ranking) cell.historyFile = row.historyFile return cell } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { tableView.addLoading(indexPath) { self.offset += 1 self.loadTripsFromHistory(offset: self.offset) } } } extension UITableView{ func addLoading(_ indexPath:IndexPath, closure: @escaping (() -> Void)){ if let lastVisibleIndexPath = self.indexPathsForVisibleRows?.last { if indexPath == lastVisibleIndexPath && indexPath.row == self.numberOfRows(inSection: 0) - 1 { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { closure() } } } } }
true
50a6fd5b3a24566c83a80309a62eba2de438b3ee
Swift
takuma10Mi/Go_lang_learn
/test/test/Data.swift
UTF-8
742
3.03125
3
[]
no_license
// // Data.swift // test // // Created by 南端拓磨 on 2020/10/01. // import SwiftUI struct Post: Codable, Identifiable { let id = UUID() var type:String var slug: String class Api{ func getPosts(completion: @escaping ([Post]) -> ()) { // guardは条件に一致なかった場合に、処理を中断させるための構文 guard let url = URL(string: "https://fiber.fibe-group.com/wp-json/wp/v2/posts/") else {return} URLSession.shared.dataTask(with: url){ (data, _,_) in let posts = try! JSONDecoder().decode([Post].self,from:data!) DispatchQueue.main.async{ completion(posts) } } .resume() } }
true
41581e58b6a30dc809a1a51c0d600a6fff167f5e
Swift
jayrav13/hackhers-apiworkshop
/ios/apidemo/apidemo/API.swift
UTF-8
1,097
2.921875
3
[]
no_license
// // API.swift // apidemo // // Created by Jay Ravaliya on 2/25/16. // Copyright © 2016 JRav. All rights reserved. // import Alamofire import SwiftyJSON class API { static let baseURL : String = "https://maps.googleapis.com/maps/api/place/nearbysearch/json" static func getLocations(latitude : Double, longitude : Double, completion : (success : Bool, data : JSON) -> Void) -> Void { let parameters : [String : AnyObject] = [ "location" : "\(latitude),\(longitude)", "rankby" : "distance", "type" : "restaurant", "key" : Secret.GOOGLE_API_KEY ] Alamofire.request(Method.GET, self.baseURL, parameters: parameters, encoding: ParameterEncoding.URL, headers: nil).responseJSON { (response) -> Void in if(response.response?.statusCode == 200) { completion(success: true, data: JSON(response.result.value!)) } else { completion(success: true, data: nil) } } } }
true
354b5106653118215645d2461858d29b0aab066d
Swift
HellVitalii/colourNumbers-study
/Numbers/ViewModel/ViewModel.swift
UTF-8
3,364
2.9375
3
[]
no_license
// // ViewModel.swift // Numbers // // Created by stager on 19/07/2019. // Copyright © 2019 sbs. All rights reserved. // import UIKit protocol BaseViewModelDelegate: class { func deleteRow(fromIndexPath indexPath: IndexPath) } protocol ListsViewModelCoordinator: class{ func useEditViewController() } class BaseViewModel { var dataWithColorNumbers: FormattedNumbersStore! var selectedIndexPath: IndexPath? = nil; let sections = ["AddCellInTheEnd", "Numbers"] weak var delegate: BaseViewModelDelegate? weak var coordinator: ListsViewModelCoordinator? func numberOfSection() -> Int { return sections.count } func titleForSection(fromSection section: Int) -> String { return sections[section] } func numberOfRow(fromSection section: Int) -> Int { if section == 0 { return 1 } if section == 1 { return dataWithColorNumbers.numbers.count } return 0 } func cellViewModel(fromIndexPath indexPath: IndexPath) -> CellWithNumberViewModel? { if indexPath.section == 1 { if dataWithColorNumbers.loveNumbers!.contains(dataWithColorNumbers.numbers[indexPath.row]) { return CellWithNumberViewModel.init(formattedNumber: dataWithColorNumbers.numbers[indexPath.row], favorite: true) } else { return CellWithNumberViewModel.init(formattedNumber: dataWithColorNumbers.numbers[indexPath.row], favorite: false) } } return nil } func editViewViewModel() -> EditViewModel { return EditViewModel.init(number: dataWithColorNumbers.numbers[selectedIndexPath!.row].number) } func changeNumber(with number: Double) { if let index = dataWithColorNumbers.loveNumbers!.firstIndex(of: dataWithColorNumbers.numbers[selectedIndexPath!.row]) { dataWithColorNumbers.loveNumbers![index].number = number dataWithColorNumbers.saveFavoriteNumbers() } dataWithColorNumbers.numbers[selectedIndexPath!.row].number = number } func pressedCell(with indexPath: IndexPath) { self.selectedIndexPath = indexPath coordinator?.useEditViewController() } func add(number: Double) { dataWithColorNumbers.numbers.append(FormattedNumber.init(number: number)) } func delete(fromIndexPath indexPath: IndexPath) { if let index = dataWithColorNumbers.loveNumbers!.firstIndex(of: dataWithColorNumbers.numbers[indexPath.row]) { dataWithColorNumbers.loveNumbers!.remove(at: index) } dataWithColorNumbers.numbers.remove(at: indexPath.row) delegate?.deleteRow(fromIndexPath: indexPath) } /*func cell(fromIndexPath indexPath: IndexPath) -> AddingCellViewModel { }*/ func addToFavorite(fromIndexPath indexPath:IndexPath) { dataWithColorNumbers.loveNumbers!.append(dataWithColorNumbers.numbers[indexPath.row]) } func deleteFromFavorite(fromIndexPath indexPath:IndexPath) { guard let index = dataWithColorNumbers.loveNumbers!.firstIndex(of: dataWithColorNumbers.numbers[indexPath.row]) else {return} dataWithColorNumbers.loveNumbers!.remove(at: index) } }
true
48ea04b791112bf0f9c2378bf921fb57bb848304
Swift
sfwan2014/CodeTextFieldDemo
/CodeTextFieldDemo/ViewController.swift
UTF-8
1,027
2.640625
3
[]
no_license
// // ViewController.swift // CodeTextFieldDemo // // Created by tezwez on 2020/3/30. // Copyright © 2020 tezwez. All rights reserved. // import UIKit class ViewController: UIViewController, DCTextFieldDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let textField = DCTextField(frame: CGRect(x: 40, y: 200, width: UIScreen.main.bounds.size.width-80, height: 55)) view.addSubview(textField) // textField.isSecureTextEntry = true textField.delegate = self textField.font = UIFont(name: "PingFangSC-Semibold", size: 39)! textField.style = .border textField.keyboardType = UIKeyboardType.decimalPad textField.cursorColor = .red } func textFieldDidEndEdit(_ textField: DCTextField) { print(textField.text ?? "") } func textFieldReturn(_ textField: DCTextField) -> Bool { print(textField.text ?? "") return false } }
true
31c6335ed1f02993293950316251166cf6e95a2f
Swift
jonathanlu98/JLSptfy
/JLSptfy/Extension/JSONModel/SPTJSONError.swift
UTF-8
2,504
2.921875
3
[]
no_license
// // SPTJSONError.swift // JLSptfy // // Created by Jonathan Lu on 2020/2/18. // Copyright © 2020 Jonathan Lu. All rights reserved. // import UIKit // MARK: - SPTJSONError struct SPTJSONError: Codable { let error: ErrorItem? } // MARK: SPTJSONError convenience initializers and mutators extension SPTJSONError { init(data: Data) throws { self = try newJSONDecoder().decode(SPTJSONError.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( error: ErrorItem?? = nil ) -> SPTJSONError { return SPTJSONError( error: error ?? self.error ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } func getError() -> Error { let error = NSError.init(domain: JLSearchManagement.description(), code: (self.error?.status)!, userInfo: ["error":self.error?.message]) return error } } // MARK: - Error struct ErrorItem: Codable { let status: Int? let message: String? } // MARK: Error convenience initializers and mutators extension ErrorItem { init(data: Data) throws { self = try newJSONDecoder().decode(ErrorItem.self, from: data) } init(_ json: String, using encoding: String.Encoding = .utf8) throws { guard let data = json.data(using: encoding) else { throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil) } try self.init(data: data) } init(fromURL url: URL) throws { try self.init(data: try Data(contentsOf: url)) } func with( status: Int?? = nil, message: String?? = nil ) -> ErrorItem { return ErrorItem( status: status ?? self.status, message: message ?? self.message ) } func jsonData() throws -> Data { return try newJSONEncoder().encode(self) } func jsonString(encoding: String.Encoding = .utf8) throws -> String? { return String(data: try self.jsonData(), encoding: encoding) } }
true
778185ad7dc71acc5f5355777ce1469c92b48440
Swift
mutech/aka-ios-beacon
/AKABeacon/AKABeaconQuickTests/UITextViewBindingsSpec.swift
UTF-8
3,231
2.84375
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
import Quick import Nimble import AKABeacon class UITextViewBindingsSpec: QuickSpec { override func spec() { describe("UITextView") { // Arrange let initialText = "Initial text"; let view = UITextView(frame: CGRect()); view.text = initialText; context("when bound") { // Arrange let property = Selector("textBinding_aka") view.textBinding_aka = "textValue" let expression: AKABindingExpression! = AKABindingExpression(forTarget: view, property: property)! let bindingContext = TestModel(); let initialModelValue = bindingContext.textValue; let bindingType: AKAViewBinding.Type? = expression.specification?.bindingType as? AKAViewBinding.Type; // Act let binding = try! bindingType?.init(target: view, expression: expression, context: bindingContext, owner: nil, delegate: nil); let textAfterBindingCreation = view.text; // Assert it("did not yet change its initial text") { expect(textAfterBindingCreation).to(equal(initialText)); } context("when observing changes") { binding!.startObservingChanges() let textAfterStartObservingChanges = view.text; it("updates its text to bound value") { expect(textAfterStartObservingChanges).to(equal(initialModelValue)) } context("when model changes") { let changedModelValue = "new value" bindingContext.textValue = changedModelValue let textAfterModelChange = view.text it("updates text to new value") { expect(textAfterModelChange).to(equal(changedModelValue)) } } context("when view changes") { let changedViewValue = "new view Value" view.text = changedViewValue; view.delegate?.textViewDidChange!(view); let modelValueAfterViewChange = bindingContext.textValue; it("updates model value") { expect(modelValueAfterViewChange).to(equal(changedViewValue)) } } context("when no longer observing changes") { binding!.stopObservingChanges() let textAfterStopObservingChanges = view.text it("does not revert text to initial value") { expect(textAfterStopObservingChanges).toNot(equal(initialText)); } } } } } } }
true
7d894a801237c9a2f27a3c454df1adbec77d56c4
Swift
lynx56/Complete-iOS-App-Development
/FlowerClassification/FlowerClassification/Model/WikiApi.swift
UTF-8
2,113
2.859375
3
[]
no_license
// // WikiApi.swift // FlowerClassification // // Created by lynx on 24/05/2018. // Copyright © 2018 Gulnaz. All rights reserved. // import Foundation import UIKit import SwiftyJSON class WikiApi{ var url = "https://en.wikipedia.org/w/api.php" func getDescriptionForFlower(flowerName: String, completion: @escaping (WikiItem?, Error?)->Void ){ let session = URLSession(configuration: URLSessionConfiguration.default) let query = ["format" : "json", "action" : "query", "prop" : "extracts|pageimages|info", "exintro" : "", "explaintext" : "", "titles" : flowerName, "indexpageids" : "", "redirects" : "1", "pithumbsize" : "500", "inprop" : "url"] var urlComponents = URLComponents(string: url) urlComponents?.queryItems = query.map({URLQueryItem(name: $0.key, value: $0.value)}) let request = URLRequest(url: urlComponents!.url!) let task = session.dataTask(with: request){ (responseData, response, responseError) in guard responseError == nil else{ completion( nil, responseError) return } if let data = responseData{ let json = JSON(data) if let page = json["query"]["pageids"].array?.first?.string{ var result = WikiItem(name: "", image: nil, url: nil) result.name = json["query"]["pages"][page]["extract"].string ?? "" result.image = json["query"]["pages"][page]["thumbnail"].url result.url = json["query"]["pages"][page]["fullurl"].url completion(result, nil) return }else{ completion(nil, WikiErrors.invalidJSON) } }else{ completion(nil, WikiErrors.invalidData) } } task.resume() } } struct WikiItem{ var name: String var image: URL? var url: URL? } enum WikiErrors: Error{ case invalidData case invalidJSON }
true
3cdc7d16ff26243007d191499079356f6d1c42e7
Swift
Gunmer/Nurse
/Nurse/Classes/Engine/FactoryKey.swift
UTF-8
638
3.390625
3
[ "MIT" ]
permissive
import Foundation class FactoryKey { let type: String let name: String var key: String { return "\(type)\(name)" } init<T>(type: T.Type, name: String = "") { self.type = "\(type)" self.name = name } } extension FactoryKey: Hashable { var hashValue: Int { return key.hashValue } static func ==(lhs: FactoryKey, rhs: FactoryKey) -> Bool { return lhs.hashValue == rhs.hashValue } } extension FactoryKey: CustomStringConvertible { var description: String { return "Type: \(type) and name: \(name)" } }
true
47597d68667544edb428189546b039f050fc0998
Swift
mykoma/rxswiftfake
/RxSwiftFake/example/RxExample+Window.swift
UTF-8
1,821
2.796875
3
[]
no_license
// // RxExample+Window.swift // RxSwiftFake // // Created by Gang on 2019/5/29. // Copyright © 2019 goluk. All rights reserved. // import Foundation extension RxExample { /** window: 将 Observable 分解为多个子 Observable,周期性的将子 Observable 发出来 */ static func testWindow() { print("***************************************") let p1 = PublishSubject<Int>() _ = p1.window(timeSpan: 3, count: 3, scheduler: MainScheduler.instance).subscribe(onNext: { (s) in print("\(s)") _ = s.asObservable().subscribe(onNext: { (a) in print("\(a) 22222") }, onError: { (e) in print("error: \(e) 22222") }, onCompleted: { print("onCompleted 22222") }, onDisposed: { print("disposed 22222") }) }, onError: { (e) in print("onError: \(e)") }, onCompleted: { print("onCompleted") }) { print("disposed") } print("time: \(Date()), send 1, 2") p1.onNext(1) p1.onNext(2) p1.onNext(20) p1.onNext(21) p1.onNext(22) p1.onNext(23) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { print("time: \(Date()), send 3 4 5") p1.onNext(3) p1.onNext(4) p1.onNext(5) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { print("time: \(Date()), send 6 7") p1.onNext(6) p1.onNext(7) p1.onCompleted() } } } }
true
ccc90648246927472e0946c24be0c876a82c754c
Swift
shadiabuhilal/Add-Video-Calling
/AzureCommunicationVideoCallingSample/UIViewRepresentables/VideoStreamView.swift
UTF-8
615
2.546875
3
[ "MIT" ]
permissive
// // LocalRendererView.swift // AzureCommunicationVideoCallingSample // // Created by Hyounwoo Sung on 2021/02/03. // import SwiftUI import AzureCommunicationCalling struct VideoStreamView: UIViewRepresentable { // This should be passed when you instantiate this class. // You should use value of `self.localRendererView` variable in your case. let view: RendererView func makeUIView(context: Context) -> UIView { return view // Fix#2: do NOT create a new view but rather use value returned from `renderer.createView()` } func updateUIView(_ uiView: UIView, context: Context) {} }
true
24697e99915ad58c5e28df155f65f4b9ef773796
Swift
Gorgeous-Devs/cruFree_iOS
/cruFree/cruFree/Screens/Developers.swift
UTF-8
1,374
2.796875
3
[]
no_license
// // Developers.swift // cruFree // // Created by Doğancan Mavideniz on 16.10.2021. // import SwiftUI struct Developers: View { var body: some View { List{ Link("Doğancan Mavideniz", destination: URL(string: "https://www.twitter.com/dogancna")!) .foregroundColor(.black) Link("Doğancan Mavideniz", destination: URL(string: "https://www.twitter.com/dogancna")!) .foregroundColor(.black) Link("Doğancan Mavideniz", destination: URL(string: "https://www.twitter.com/dogancna")!) .foregroundColor(.black) Link("Doğancan Mavideniz", destination: URL(string: "https://www.twitter.com/dogancna")!) .foregroundColor(.black) Link("Doğancan Mavideniz", destination: URL(string: "https://www.twitter.com/dogancna")!) .foregroundColor(.black) Link("Doğancan Mavideniz", destination: URL(string: "https://www.twitter.com/dogancna")!) .foregroundColor(.black) Link("Doğancan Mavideniz", destination: URL(string: "https://www.twitter.com/dogancna")!) .foregroundColor(.black) .navigationBarTitle("Developers") .navigationBarTitleDisplayMode(.inline) } } } struct Developers_Previews: PreviewProvider { static var previews: some View { Developers() } }
true
1198efdf3914b4caf9af33448a7adcfac1006e5c
Swift
DingSoung/Extension
/Sources/UIKit/UIFont+SymbolicTraits.swift
UTF-8
838
2.640625
3
[ "MIT" ]
permissive
// Created by Songwen Ding on 2019/7/16. // Copyright © 2019 DingSoung. All rights reserved. #if canImport(UIKit) import UIKit extension UIFont { public func with(_ traits: UIFontDescriptor.SymbolicTraits...) -> UIFont { guard let descriptor = fontDescriptor.withSymbolicTraits(UIFontDescriptor.SymbolicTraits(traits) .union(fontDescriptor.symbolicTraits)) else { return self } return UIFont(descriptor: descriptor, size: 0) } public func without(_ traits: UIFontDescriptor.SymbolicTraits...) -> UIFont { guard let descriptor = fontDescriptor.withSymbolicTraits(fontDescriptor.symbolicTraits .subtracting(UIFontDescriptor.SymbolicTraits(traits))) else { return self } return UIFont(descriptor: descriptor, size: 0) } } #endif
true
c4b7d05bb04bd1b750c69590e5ef3b5879469c6b
Swift
bemsuero/Orks-and-Soldiers
/OrksAndSoldiers/ork.swift
UTF-8
462
2.78125
3
[]
no_license
// // ork.swift // OrksAndSoldiers // // Created by Bem on 6/12/16. // Copyright © 2016 Bem. All rights reserved. // import Foundation class Ork: Player { private var _name = "Player One" var name: String { get { return _name } } convenience init(name: String, hp: Int, attackPwr: Int) { self.init(hp: hp, attackPwr: attackPwr) _name = name } }
true
6518ba441c455d30974a629ceebc07498f33f19a
Swift
kensan914/otapick-ios-demo
/otapick-ios-demo/Fetchers/BlogsFetcher.swift
UTF-8
1,036
2.75
3
[]
no_license
// // BlogsFetcher.swift // otapick-ios-demo // // Created by 鳥海健人 on 2021/04/28. // Copyright © 2021 kentoToriumi. All rights reserved. // import Foundation class BlogsFetcher { private let group: Group private var url = otapickUrl + "/api/blogs/" private let qParams = "?sort=newer_post" init(group: Group) { self.group = group self.url = self.url + String(group.id) + "/" } func fetchBlogs(then: @escaping ([Blog]) -> Void) { URLSession.shared.dataTask(with: URL(string: url + qParams)!) { (data, response, error) in guard let data = data else { return } let decoder: JSONDecoder = JSONDecoder() do { let blogsData = try decoder.decode([Blog].self, from: data) DispatchQueue.main.async { then(blogsData) } } catch { print("json convert failed in JSONDecoder. " + error.localizedDescription) } }.resume() } }
true
2b08a49ccdff61396138c2ec1dc188029decf68e
Swift
ssy828/watashiIOS
/PROC/GrammerTrainning/GrammerTrainning/Closure.swift
UTF-8
1,434
4.0625
4
[]
no_license
// // Closure.swift // GrammerTrainning // // Created by SONGYEE SHIN on 2017. 9. 20.. // Copyright © 2017년 SONGYEE SHIN. All rights reserved. // import Foundation // 클로저 기본 문법 /* { (매개변수 목록) -> 반환타입 in 실행코드 } */ // 클로저 사용 // sum이라는 상수에 클로저를 할당 let sum: (Int,Int) -> Int = { (a: Int, b: Int) in return a+b } let sumResult: Int = sum(11,22) //print(sumResult) // 33 ///////////////////////////// class sample { // 프로퍼티 안에 클로저를 넣어둠 let sum = { (a: Int, b: Int) in return a+b } // 프로퍼티 접근: 인스턴스를 통해서만 가능!! // 프로퍼티 : 객체가 갖는 속성 // 예) 색상 // 인스턴스를 생성 ->> 호출 가능!!! // 하나의 프로퍼티는 하나의 기능만 가능!!! /* 프로퍼티 값을 바꿔주지 않는 이상 계속 그 기능만을 하고 있다 var x = 10 x = 20 으로 변경해 줄 때까지 10을 저장한 기능만 가지고 있으므로 */ // 클래스 -> 함수 -> 호출 func sampleFunc() { let sumResult: Int = sum(11,22) // 함수를 안 쓰면 쓸 수 없음 // 변수 sumResult에 함수호출을 쓴 것 // 클래스(도면): 함수랑 프로퍼티만 구현!! 호출은 메소드 안에서만 가능! } }
true
d458ecafa384841ed1d74d33ad2328a0d6b25bd3
Swift
hoangmtv075/PokemonFinder
/Pokemon/Controllers/PokeVC.swift
UTF-8
5,775
2.625
3
[]
no_license
// // PokeVC.swift // Pokemon // // Created by Jack Ily on 05/10/2017. // Copyright © 2017 Jack Ily. All rights reserved. // import UIKit import MapKit import FirebaseDatabase import GeoFire class PokeVC: UIViewController { @IBOutlet weak var mapView: MKMapView! var locationManager = CLLocationManager() var mapHasCenteredOnce = false var ref: DatabaseReference! var geoFire: GeoFire! override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self mapView.userTrackingMode = .follow mapView.delegate = self ref = Database.database().reference() geoFire = GeoFire(firebaseRef: ref) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) authStatus() } func authStatus() { if CLLocationManager.authorizationStatus() == .authorizedWhenInUse { mapView.showsUserLocation = true } else { locationManager.requestWhenInUseAuthorization() } } func region(location: CLLocation) { let distance: CLLocationDistance = 2000 let region = MKCoordinateRegionMakeWithDistance(location.coordinate, distance, distance) mapView.setRegion(region, animated: true) } func createSighting(forLocation location: CLLocation, ofKey keyId: Int) { geoFire.setLocation(location, forKey: "\(keyId)") } func showSightingOnMap(location: CLLocation) { let circleQuery = geoFire!.query(at: location, withRadius: 2.5) var _ = circleQuery?.observe(GFEventType.keyEntered, with: { (key, location) in if let key = key, let location = location { let annotation = PokeAnnotation(coordinate: location.coordinate, pokeNumber: Int(key)!) self.mapView.addAnnotation(annotation) } }) } @IBAction func RandomPoke() { let location = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude) let keyId = arc4random_uniform(151) + 1 createSighting(forLocation: location, ofKey: Int(keyId)) } } //MARK: - mapView delegate extension PokeVC: MKMapViewDelegate { func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) { if let location = userLocation.location { if !mapHasCenteredOnce { mapHasCenteredOnce = true region(location: location) } } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { var annotationView: MKAnnotationView? let identifier = "Pokemon Sighting" if annotation.isKind(of: MKUserLocation.self) { annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "User") annotationView?.image = UIImage(named: "ash") } else if let dequeue = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) { annotationView = dequeue annotationView?.annotation = annotation } else { let annotationViews = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier) let button = UIButton(type: .detailDisclosure) annotationViews.rightCalloutAccessoryView = button annotationView = annotationViews } if let annotationView = annotationView, let annotation = annotation as? PokeAnnotation { annotationView.canShowCallout = true annotationView.image = UIImage(named: "\(annotation.pokeNumber)") let button = UIButton() button.frame = CGRect(x: 0, y: 0, width: 30, height: 30) button.setImage(UIImage(named: "location-map-flat"), for: .normal) annotationView.rightCalloutAccessoryView = button } return annotationView } func mapView(_ mapView: MKMapView, regionWillChangeAnimated animated: Bool) { let location = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude) showSightingOnMap(location: location) } func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if let annotation = view.annotation as? PokeAnnotation { var placemark: MKPlacemark if #available(iOS 10.0, *) { placemark = MKPlacemark(coordinate: annotation.coordinate) } else { placemark = MKPlacemark(coordinate: annotation.coordinate, addressDictionary: nil) } let mapItem = MKMapItem(placemark: placemark) let distance: CLLocationDistance = 1000 let region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, distance, distance) let options: [String : Any] = [MKLaunchOptionsMapCenterKey: NSValue(mkCoordinate: region.center), MKLaunchOptionsMapSpanKey: NSValue(mkCoordinateSpan: region.span), MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving] MKMapItem.openMaps(with: [mapItem], launchOptions: options) } } } //MARK: locationManager delegate extension PokeVC: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedWhenInUse { mapView.showsUserLocation = true } } }
true
1a6f13a79722600adbecb1e68c58c8493eb35c2b
Swift
eunjin3786/TistorySample
/TistorySample/RIBs/Home/HomeBuilder.swift
UTF-8
940
2.53125
3
[]
no_license
import RIBs protocol HomeDependency: Dependency { } final class HomeComponent: Component<HomeDependency>, BlogDependency { } protocol HomeBuildable: Buildable { func build(withListener listener: HomeListener) -> HomeRouting } final class HomeBuilder: Builder<HomeDependency>, HomeBuildable { override init(dependency: HomeDependency) { super.init(dependency: dependency) } func build(withListener listener: HomeListener) -> HomeRouting { let component = HomeComponent(dependency: dependency) let viewController = HomeViewController() let interactor = HomeInteractor(presenter: viewController) interactor.listener = listener let blogBuilder = BlogBuilder(dependency: component, owner: .other) return HomeRouter(interactor: interactor, blogBuilder: blogBuilder, viewController: viewController) } }
true
42c88daf44aa2ae07aebaf4d33e63072ae8e83e8
Swift
jbrennan/Prototope
/Prototope/Double+Extensions.swift
UTF-8
762
3.875
4
[]
no_license
// // Double+Extensions.swift // Prototope // // Created by Jason Brennan on Apr-21-2015. // Copyright (c) 2015 Khan Academy. All rights reserved. // public extension Double { /** If self is not a number (i.e., NaN), returns 0. Otherwise returns self. */ var notNaNValue: Double { return self.isNaN ? 0 : self } public func toRadians() -> Double { return self * Double.pi / 180.0 } public func toDegrees() -> Double { return self * 180.0 / Double.pi } /** Clamps the receiver between the lower and the upper bounds. Basically the same as `clip()` but with a nicer API tbh. */ public func clamp(lower: Double, upper: Double) -> Double { if self < lower { return lower } if self > upper { return upper } return self } }
true
f5bdfe12db91442fdedc6fccb80e39ce7ed88b1d
Swift
airamrguez/electropoints
/ElectroPoints/ChargingPointsService.swift
UTF-8
879
2.765625
3
[]
no_license
// // ChargingPointsService.swift // ElectroPoints // // Created by Airam Rguez on 14/03/2020. // Copyright © 2020 Airam Rguez. All rights reserved. // import Foundation class PointsService { static let shared = PointsService() var allPoints: [ChargingPoint] = [] { didSet { let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted if let data = try? encoder.encode(allPoints) { UserDefaults.standard.set(data, forKey: "AllPoints") } } } func loadPoints() { if let points = UserDefaults.standard.data(forKey: "AllPoints") { let decoder = JSONDecoder() if let decoded = try? decoder.decode([ChargingPoint].self, from: points) { self.allPoints = decoded return } } } }
true
9bb929fcea8db6afc10f9ee9ff5a555d42023e39
Swift
fm6391/PetSafety
/PetSafety/PersistenceManager.swift
UTF-8
1,877
3.046875
3
[]
no_license
// // PersistenceManager.swift // PetSafety // // Created by Lambiase Salvatore on 12/07/18. // Copyright © 2018 De Cristofaro Paolo. All rights reserved. // import UIKit import CoreData class PersistenceManager { static let name = "PPet" static let nameUser = "PUser" static func getContext() -> NSManagedObjectContext { let appDelegate = UIApplication.shared.delegate as! AppDelegate return appDelegate.persistentContainer.viewContext } static func newEmptyPet () -> PPet { let context = getContext() let pPet = NSEntityDescription.insertNewObject(forEntityName: name, into: context) as! PPet pPet.name = "new name" pPet.birthdate = NSDate() pPet.race = "razza" pPet.order = 1 return pPet } static func fetchData () -> [PPet]{ var pets = [PPet] () let context = getContext() let fetchRequest = NSFetchRequest<PPet>(entityName: name) do { try pets = context.fetch(fetchRequest) } catch let error as NSError{ print("Errore in fetch \(error.code)") } return pets } static func fetchDataUser () -> [PUser]{ var user = [PUser] () let context = getContext() let fetchRequest = NSFetchRequest<PUser>(entityName: nameUser) do { try user = context.fetch(fetchRequest) } catch let error as NSError{ print("Errore in fetch \(error.code)") } return user } static func saveContext() { let context = getContext() do { try context.save() } catch let error as NSError { print("Errore in salvataggio \(error.code)") } } static func deletePet(pet: PPet) { let context = getContext() context.delete(pet) } }
true
ed1c60d1c22bf57cae3e988828b0a08cf6a9d013
Swift
itay2108/logbox
/Log Box/Controllers/mainVC/LogCell.swift
UTF-8
953
2.734375
3
[]
no_license
// // LogCellTableViewCell.swift // Log Box // // Created by itay gervash on 16/04/2020. // Copyright © 2020 itay gervash. All rights reserved. // import UIKit import AVFoundation class LogCell: UITableViewCell, AVAudioPlayerDelegate { @IBOutlet weak var logTitle: UILabel! @IBOutlet weak var logDuration: UILabel! @IBOutlet weak var logDate: UILabel! func setData(with log: Log) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "MMM d YYYY" logTitle.text = log.name logDate.text = dateFormatter.string(from: log.date) do { let player = try AVAudioPlayer(data: log.recording) let duration = getFormattedTimeFromSeconds(seconds: Int(player.duration)) logDuration.text = duration } catch { print("error parsing recording info from log: \(error)") } } }
true
9885bc679714bc2755fd02f45badfc318a69e80a
Swift
samwise2/Real-Physics-Table-Tennis-Game
/BeginningVC.swift
UTF-8
819
3.015625
3
[]
no_license
// // BeginningVC.swift // ping pong with gravity // // Created by Sam Orend on 2018-06-06. // Copyright © 2018 Sam Orend. All rights reserved. // //necessary imports import Foundation import UIKit //creates 2 possible cases for the basicMode that the user is in arcade or tournament enum basicMode { case arcade case tournament } //declares class for view controller class BeginningVC: UIViewController { //links button as action @IBAction func tournamentButton(_ sender: UIButton) { //assigns global variable for basic mode based on selection currentBasicMode = .tournament } //links button as action @IBAction func arcadeButton(_ sender: UIButton) { //assigns global variable for basic mode based on selection currentBasicMode = .arcade } }
true
21081edb1228ca2a7604806c5246fee6b7dbdfbf
Swift
giosvro/LokTarHackingRio
/LokTarHackingRio/LokTarHackingRio/Model/Pessoa.swift
UTF-8
536
2.875
3
[]
no_license
// // Pessoa.swift // LokTarHackingRio // // Created by Gabriel Almeida Hammes on 28/07/2018. // Copyright © 2018 Giovanni Severo Barros. All rights reserved. // import Foundation class Pessoa { var nome : String var cpf : String var nascimento : Date var email : String var telefone : String init(nome: String, cpf: String, nascimento: Date, email: String, telefone : String) { self.nome = nome self.cpf = cpf self.nascimento = nascimento self.email = email self.telefone = telefone } }
true
c168b6f45b35412ff11ccacf9023b7144a72026a
Swift
StepCheg/WatsonText
/WatsonTest/Models/NetworkManager.swift
UTF-8
3,497
2.78125
3
[]
no_license
// // NetworkManager.swift // WatsonTest // // Created by Stepan Chegrenev on 30/11/2018. // Copyright © 2018 Stepan Chegrenev. All rights reserved. // import Foundation class NetworkManager { static let sharedInstance = NetworkManager() public enum ApiMethod: String { case IdentifableLanguage = "api/v3/identifiable_languages?version=2018-12-01" case Identify = "api/v3/identify?version=2018-12-01" case Translate = "api/v3/translate?version=2018-12-01" } let userName = "6987a48d-342e-4a69-8adc-e65b1cc0b9da" let password = "MxYSIi6nQP2Y" let urlString = "https://gateway.watsonplatform.net/language-translator/" func getAuthString() -> String { let loginString = String(format: "%@:%@", userName, password) let loginData = loginString.data(using: String.Encoding.utf8)! return loginData.base64EncodedString() } func networkFunc(urlStr: String, params: [String:String],contenType: String, success: @escaping ((Any) -> Void), failure: @escaping ((String) -> Void)) { let authString = getAuthString() var request = URLRequest(url: URL(string: urlStr)!) request.httpMethod = "POST" request.setValue("Basic \(authString)", forHTTPHeaderField: "Authorization") request.addValue(contenType, forHTTPHeaderField: "Content-Type") let session = URLSession.shared guard let httpBody = try? JSONSerialization.data(withJSONObject: params, options: []) else { return } request.httpBody = httpBody session.dataTask(with: request) { (data, response, error) in guard let data = data else { return } do { let json = try JSONSerialization.jsonObject(with: data, options: []) success(json) } catch { print(error) failure(error as! String) } }.resume() } func getLanguage(fromText: String, success: @escaping ((String) -> Void), failure: @escaping ((String) -> Void)) { let urlStr = urlString + ApiMethod.Identify.rawValue let params = ["text": fromText] networkFunc(urlStr: urlStr, params: params, contenType: "text/plain", success: { (json) in let arr = (json as! Dictionary<String, Any>)["languages"] let dict = (arr as! Array<Any>)[0] let lang = (dict as! Dictionary<String, Any>)["language"] as! String success(lang) }) { (error) in failure(error) } } func translate(text: String, sourceLanguage: String, targetLanguage: String, success: @escaping ((String) -> Void), failure: @escaping ((String) -> Void)) { let urlStr = urlString + ApiMethod.Translate.rawValue let params = ["text": text, "source": sourceLanguage, "target": targetLanguage] networkFunc(urlStr: urlStr, params: params, contenType: "application/json", success: { (json) in let arr = (json as! Dictionary<String, Any>)["translations"] let dict = (arr as! Array<Any>)[0] let result = (dict as! Dictionary<String, Any>)["translation"] success(result as! String) }) { (error) in failure(error) } } }
true
fda40733cf1808cac7759eef60a0548f5e9748ea
Swift
izioto/100-Days-of-Swift
/014-From Sketch to XCode/From Sketch to XCode/From Sketch to XCode/DetailViewController.swift
UTF-8
2,414
2.578125
3
[]
no_license
// // DetailViewController.swift // From Sketch to XCode // // Created by MungYu-Lin on 16/5/29. // Copyright © 2016年 MY. All rights reserved. // import Foundation import UIKit class DetailViewController: UIViewController { var imageView: UIImageView! var nameLable: UILabel! var mobileLable: UILabel! var emailLable: UILabel! var notesLable: UILabel! let groups = ContactModel().dict let groupTitles = ContactModel().keys var data = NSObject() override func viewDidLoad() { super.viewDidLoad() self.title = "Info Card" let rightButton = UIBarButtonItem(title: "编辑", style: .Plain, target: self, action: #selector(editAction)) self.view.backgroundColor = UIColor.whiteColor() navigationItem.rightBarButtonItem = rightButton imageView = UIImageView(frame: CGRectMake(10, 100, 24, 24)) self.view.addSubview(imageView) nameLable = UILabel(frame: CGRectMake(10, 150, self.view.bounds.size.width, 50)) mobileLable = UILabel(frame: CGRectMake(10, 200, self.view.bounds.size.width, 50)) emailLable = UILabel(frame: CGRectMake(10, 250, self.view.bounds.size.width, 50)) notesLable = UILabel(frame: CGRectMake(10, 300, self.view.bounds.size.width, 100)) self.view.addSubview(nameLable) self.view.addSubview(mobileLable) self.view.addSubview(emailLable) self.view.addSubview(notesLable) let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let key = (appDelegate.selec! as NSString).substringToIndex(1).uppercaseString for value in groups[key]!.enumerate() { data = value.element if (data as! User).Name! == appDelegate.selec { break } } imageView.image = UIImage(named: (data as! User).Ico!) nameLable.text = "Name\n" + (data as! User).Name! nameLable.numberOfLines = 0 nameLable.textColor = UIColor.blueColor() mobileLable.text = "Mobile\n" + (data as! User).Mobile! mobileLable.numberOfLines = 0 emailLable.text = "Email\n" + (data as! User).Email! emailLable.numberOfLines = 0 notesLable.text = "Notes\n" + (data as! User).Notes! notesLable.numberOfLines = 0 } func editAction() { // } }
true
ed0b729d38fcfadb36ac06ab2563d1df00dc4198
Swift
mickyTwenty/Wyth_iOS
/SeatUs/SourceCode/ReusableComponents/Controllers/ViewControllers/DatePickerController/CustomDatePickerController.swift
UTF-8
3,611
2.703125
3
[]
no_license
// // CustomDatePickerController.swift // GlobalDents // // Created by Qazi Naveed on 9/8/17. // Copyright © 2017 Qazi Naveed. All rights reserved. // import UIKit protocol DatePickerDelegate: class { func datePickerViewController (_ datePicker :UIDatePicker, date:Date, sourceView:UIView) } class CustomDatePickerController: UIViewController { var selectedData:String! = "" var doneButtonTapped: ((String)->())? var sourceTxtFeild: UITextField! var format : String = ApplicationConstants.YearFormat weak var delegate: DatePickerDelegate? @IBOutlet weak var datePickerObj: UIDatePicker! var isShowingByPresenting : Bool! = false var mode:Int = 1 var interval:Int = 5 static func createDatePickerController(storyboardId:String)->CustomDatePickerController { let datePicker = UIStoryboard(name: FileNames.ReusableComponentsStoryBoard, bundle: nil).instantiateViewController(withIdentifier: storyboardId) as! CustomDatePickerController return datePicker } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. datePickerObj.datePickerMode = UIDatePicker.Mode(rawValue: mode)! datePickerObj.minuteInterval = interval } @IBAction func cancelButtonClicked(_ sender: Any) { if isShowingByPresenting { dismiss(animated: true, completion: nil) } else{ close() } } @IBAction func doneButtonClicked(_ sender: Any) { if isShowingByPresenting { sourceTxtFeild.text=Utility.getDateInString(datePickerObj.date, format: format) delegate?.datePickerViewController(datePickerObj, date: datePickerObj.date, sourceView: sourceTxtFeild) dismiss(animated: true, completion: nil) } else{ switch (mode){ case 0: selectedData = Utility.getTimeInString(datePickerObj.date, format: "HH:mm") break case 1: selectedData = Utility.getDateInString(datePickerObj.date, format: format) break default: break } doneButtonTapped?(selectedData) close() } } @IBAction func pickerValueChanged(_ sender: Any) { if isShowingByPresenting { sourceTxtFeild.text=Utility.getDateInString(datePickerObj.date, format: format) delegate?.datePickerViewController(datePickerObj, date: datePickerObj.date, sourceView: sourceTxtFeild) } else{ selectedData = Utility.getDateInString(datePickerObj.date, format: format) } } func show(controller:UIViewController) { controller.addChild(self) controller.view.addSubview(self.view) } func close() { self.view.removeFromSuperview() self.removeFromParent() } 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. } */ }
true
c9ac3f6808120106e2c81637ea114be0bcd507ca
Swift
Ma7m0ud3laa/PaymentWallTask
/PaymentWallTask/Core/Extensions/UIView/UIView+Constraint/UIView+Constraints.swift
UTF-8
2,056
2.8125
3
[]
no_license
// // UIView+Constraints.swift // InstagramCourse // // Created by SAMEH on 9/13/18. // Copyright © 2018 sameh. All rights reserved. // import UIKit extension UIView { func anchor(_ top: NSLayoutYAxisAnchor? = nil, _ bottom: NSLayoutYAxisAnchor? = nil, _ leading: NSLayoutXAxisAnchor? = nil, _ trailing: NSLayoutXAxisAnchor? = nil, padding: UIEdgeInsets? = nil) { translatesAutoresizingMaskIntoConstraints = false if let top = top { topAnchor.constraint(equalTo: top, constant: padding?.top ?? 0).isActive = true } if let bottom = bottom { bottomAnchor.constraint(equalTo: bottom, constant: padding?.bottom ?? 0).isActive = true } if let leading = leading { leadingAnchor.constraint(equalTo: leading, constant: padding?.left ?? 0).isActive = true } if let trailing = trailing { trailingAnchor.constraint(equalTo: trailing, constant: padding?.right ?? 0).isActive = true } } func addWidthConstraints(width: CGFloat?) { translatesAutoresizingMaskIntoConstraints = false if let width = width, width != 0 { widthAnchor.constraint(equalToConstant: width).isActive = true } } func addHeightConstraints(height: CGFloat?) { translatesAutoresizingMaskIntoConstraints = false if let height = height, height != 0 { heightAnchor.constraint(equalToConstant: height).isActive = true } } func addCenterConstraints(vertical: NSLayoutYAxisAnchor? = nil, horizontal: NSLayoutXAxisAnchor? = nil) { translatesAutoresizingMaskIntoConstraints = false if let vertical = vertical { centerYAnchor.constraint(equalTo: vertical).isActive = true } if let horizontal = horizontal { centerXAnchor.constraint(equalTo: horizontal).isActive = true } } }
true
7274773d35f073edb1e48c474011d82a347d001f
Swift
cplaverty/KeitaiWaniKani
/AlliCrab/ViewControllers/ReviewTimelineOptionsTableViewController.swift
UTF-8
5,888
2.71875
3
[ "MIT" ]
permissive
// // ReviewTimelineFilterTableViewController.swift // AlliCrab // // Copyright © 2017 Chris Laverty. All rights reserved. // import UIKit protocol ReviewTimelineOptionsDelegate: class { func reviewTimelineFilter(didChangeTo: ReviewTimelineFilter) func reviewTimelineCountMethod(didChangeTo: ReviewTimelineCountMethod) } class ReviewTimelineOptionsTableViewController: UITableViewController { private enum ReuseIdentifier: String { case basic = "Basic" } private enum TableViewSection: Int, CaseIterable { case filter = 0, countMethod } // MARK: - Properties weak var delegate: ReviewTimelineOptionsDelegate? var selectedFilterValue: ReviewTimelineFilter = ApplicationSettings.reviewTimelineFilterType var selectedCountMethodValue: ReviewTimelineCountMethod = ApplicationSettings.reviewTimelineValueType private var filterValues: [ReviewTimelineFilter] { return ReviewTimelineFilter.allCases } private var countMethodValues: [ReviewTimelineCountMethod] { return ReviewTimelineCountMethod.allCases } // MARK: - Actions @IBAction func done(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let tableViewSection = TableViewSection(rawValue: indexPath.section) else { fatalError("Invalid section index \(indexPath.section) requested") } let cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifier.basic.rawValue, for: indexPath) switch tableViewSection { case .filter: let valueForRow = filterValues[indexPath.row] switch valueForRow { case .none: cell.textLabel!.text = "All Reviews" case .currentLevel: cell.textLabel!.text = "Current Level Reviews" case .toBeBurned: cell.textLabel!.text = "Burn Reviews" } cell.accessoryType = valueForRow == selectedFilterValue ? .checkmark : .none case .countMethod: let valueForRow = countMethodValues[indexPath.row] switch valueForRow { case .histogram: cell.textLabel!.text = "Count" case .cumulative: cell.textLabel!.text = "Cumulative Total" } cell.accessoryType = valueForRow == selectedCountMethodValue ? .checkmark : .none } return cell } override func numberOfSections(in tableView: UITableView) -> Int { return TableViewSection.allCases.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let tableViewSection = TableViewSection(rawValue: section) else { fatalError("Invalid section index \(section) requested") } switch tableViewSection { case .filter: return filterValues.count case .countMethod: return countMethodValues.count } } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard let tableViewSection = TableViewSection(rawValue: section) else { fatalError("Invalid section index \(section) requested") } switch tableViewSection { case .filter: return "Filter" case .countMethod: return "Values" } } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let tableViewSection = TableViewSection(rawValue: indexPath.section) else { fatalError("Invalid section index \(indexPath.section) requested") } let previousSelection: IndexPath? switch tableViewSection { case .filter: previousSelection = IndexPath(row: filterValues.firstIndex(of: ApplicationSettings.reviewTimelineFilterType)!, section: indexPath.section) selectedFilterValue = filterValues[indexPath.row] if ApplicationSettings.reviewTimelineFilterType != selectedFilterValue { ApplicationSettings.reviewTimelineFilterType = selectedFilterValue delegate?.reviewTimelineFilter(didChangeTo: selectedFilterValue) } case .countMethod: previousSelection = IndexPath(row: countMethodValues.firstIndex(of: ApplicationSettings.reviewTimelineValueType)!, section: indexPath.section) selectedCountMethodValue = countMethodValues[indexPath.row] if ApplicationSettings.reviewTimelineValueType != selectedCountMethodValue { ApplicationSettings.reviewTimelineValueType = selectedCountMethodValue delegate?.reviewTimelineCountMethod(didChangeTo: selectedCountMethodValue) } } if let previousSelection = previousSelection { tableView.reloadRows(at: [previousSelection, indexPath], with: .automatic) } else { tableView.reloadRows(at: [indexPath], with: .automatic) } tableView.deselectRow(at: indexPath, animated: true) } } // MARK: - UIPopoverPresentationControllerDelegate extension ReviewTimelineOptionsTableViewController: UIPopoverPresentationControllerDelegate { func presentationController(_ controller: UIPresentationController, viewControllerForAdaptivePresentationStyle style: UIModalPresentationStyle) -> UIViewController? { if style == .popover || style == .none { return nil } return UINavigationController(rootViewController: controller.presentedViewController) } }
true
3caed0bf73237d8f81f73e7a7e63e8982095055c
Swift
MadeByDouglas/feather
/featherDemo/featherDemo/TextEditorController.swift
UTF-8
3,239
2.5625
3
[ "MIT" ]
permissive
// // TextEditorController.swift // SwiftStarWars // // Created by Douglas Hewitt on 11/1/19. // Copyright © 2019 Douglas Hewitt. All rights reserved. // import UIKit import Feather final class TextEditorController: UIViewController, UITextViewDelegate, TextViewerDelegate { var editView: TextEditor! var viewOnlyView: TextViewer! var button: UIButton! var button2: UIButton! var stack: UIStackView! override func loadView() { super.loadView() setup() } func setup() { #if targetEnvironment(macCatalyst) TextToolbarManager.shared.showToolbar() #endif editView = TextEditor(type: .froala) editView.translatesAutoresizingMaskIntoConstraints = false viewOnlyView = TextViewer(type: .froala, isScrollingEnabled: true) viewOnlyView.translatesAutoresizingMaskIntoConstraints = false viewOnlyView.textDelegate = self viewOnlyView.backgroundColor = .systemBlue button = UIButton(type: .contactAdd) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(didTapButton), for: .touchUpInside) button2 = UIButton(type: .roundedRect) button2.setTitle("Transfer", for: .normal) button2.translatesAutoresizingMaskIntoConstraints = false button2.addTarget(self, action: #selector(didTapButton2), for: .touchUpInside) let buttonStack = UIStackView(arrangedSubviews: [button, button2]) buttonStack.axis = .horizontal stack = UIStackView(arrangedSubviews: [editView, viewOnlyView, buttonStack]) stack.translatesAutoresizingMaskIntoConstraints = false stack.distribution = .fillEqually stack.alignment = .fill stack.axis = .vertical view.addSubview(stack) NSLayoutConstraint.activate([ stack.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), stack.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), stack.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ]) } @objc func didTapButton() { editView.insertHTML(text: "here's some text how about this 'text'") } @objc func didTapButton2() { editView.getHTML { (result) in switch result { case .success(let html): self.viewOnlyView.setHTML(text: html) case .failure(let error): print(error) } } } func textViewDidChange(_ textView: UITextView) { // let html = editView.getHTML() // sourceView.editorView.loadHTMLString(html, baseURL: nil) } func heightDidChange(newHeight: CGFloat) { viewOnlyView.heightAnchor.constraint(equalToConstant: newHeight).isActive = true } func didTapLink(_ url: URL) { //TODO: respond to links } func didFinishLoading() { //TODO: do something } }
true
cbf466727ab3ae87d43299f03324f4416aa9cdd3
Swift
weumj/TimerDemo
/TimerApp/TimerViewController.swift
UTF-8
3,731
2.734375
3
[]
no_license
// // TimerViewController.swift // TimerApp // // Created by mj on 2016. 11. 20.. // Copyright © 2016년 demo. All rights reserved. // import UIKit import Foundation class TimerViewController: UIViewController { @IBOutlet weak var btnStackView: UIStackView! @IBOutlet weak var startBtn: UIButton! @IBOutlet weak var resetBtn: UIButton! @IBOutlet weak var stopBtn: UIButton! @IBOutlet weak var timerLabel: UILabel! @IBOutlet weak var minuteSlider: UISlider!{ didSet{ minuteSlider.transform = CGAffineTransform.init(rotationAngle: CGFloat(-M_PI_2)) } } @IBOutlet weak var secondSlider: UISlider!{ didSet{ secondSlider.transform = CGAffineTransform.init(rotationAngle: CGFloat(-M_PI_2)) } } @IBOutlet weak var minuteLabel: UILabel! @IBOutlet weak var secondLabel: UILabel! var counter = 0 var timer = Timer() var timerIsRunning = false var stopWasPressed = false var lastValue = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func start(_ sender: Any) { if !timerIsRunning { timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) if stopWasPressed { counter = lastValue } else { counter += Int(secondSlider.value) + Int(minuteSlider.value) * 60 } timerLabel.text = "\(counter)" } stopWasPressed = false hideStartBtn(hide: true) timerIsRunning = true timerLabel.backgroundColor = UIColor.white } func updateTimer(){ counter -= 1; timerLabel.text = "\(counter)" if counter < 0 { counter = 0; timerLabel.text = "Time's UP!!!" timerLabel.backgroundColor = UIColor.red timer.invalidate() stopWasPressed = false hideStartBtn(hide: false) timerIsRunning = false } } @IBAction func stop(_ sender: Any) { timerIsRunning = false timer.invalidate() stopWasPressed = true lastValue = counter } @IBAction func reset(_ sender: Any) { hideStartBtn(hide: false) timerIsRunning = false counter = 0 timer.invalidate() timerLabel.text = String(counter) } @IBAction func minuteSliderChanged(_ sender: Any) { minuteLabel.text = "\(Int(minuteSlider.value)) min" } @IBAction func secondSliderChanged(_ sender: Any) { secondLabel.text = "\(Int(secondSlider.value)) sec" } func hideStartBtn(hide : Bool){ if hide { startBtn.isHidden = true btnStackView.isHidden = false resetBtn.isHidden = false stopBtn.isHidden = false } else { startBtn.isHidden = false btnStackView.isHidden = true resetBtn.isHidden = true stopBtn.isHidden = true } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
547582bbfa143684b0a4e83385ed2d69019bb643
Swift
DharaniKumarReddy/Machine
/Franziskaner Munchen/Controllers/NewsViewController.swift
UTF-8
3,742
2.5625
3
[]
no_license
// // NewsViewController.swift // Franziskaner Munchen // // Created by Dharani Reddy on 14/04/18. // Copyright © 2018 Integro Infotech. All rights reserved. // import UIKit class NewsViewController: UIViewController { // MARK:- Variables fileprivate var news: [NewsObject] = [] lazy var refreshControl = UIRefreshControl() // MARK:- IBOutlets @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var loadingIndicator: UIActivityIndicatorView! // MARK:- Life Cycle Methods override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 240 tableView.rowHeight = UITableView.automaticDimension loadingIndicator.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) loadingIndicator.startAnimating() getNews() addPulltoRefreshControl() // Do any additional setup after loading the view. } // MARK:- Private Methods @objc private func getNews() { APICaller.getInstance().getNews(onSuccess: { news in self.news = news?.news ?? [] self.sortNews() self.tableView.reloadData() self.tableView.isHidden = false self.refreshControl.endRefreshing() self.loadingIndicator.stopAnimating() }, onError: { error in }) } private func sortNews() { self.news.sort{ $0.date.compare($1.date) == .orderedDescending } } private func addPulltoRefreshControl() { refreshControl.attributedTitle = NSAttributedString(string: "") refreshControl.tintColor = .white refreshControl.addTarget(self, action:#selector(NewsViewController.getNews), for: UIControl.Event.valueChanged) tableView.insertSubview(refreshControl, at: 0) } } // MARK:- TableView Methods extension NewsViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return news.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: NewsTableCell.self)) as? NewsTableCell cell?.loadData(news: news[indexPath.row]) return cell ?? UITableViewCell() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let newsDetailedController = UIStoryboard(name: Constant.StoryBoard.Main, bundle: Bundle.main).instantiateViewController(withIdentifier: String(describing: NewsDetailedViewController.self)) as! NewsDetailedViewController let newsObject = news[indexPath.row] let share = "http://franciscansmunich.com/newsshare.php?id=\(newsObject.id)" newsDetailedController.configure(share: share,title: newsObject.title, description: newsObject.description, image: newsObject.image, date: newsObject.date) navigationController?.pushViewController(newsDetailedController, animated: true) } } class NewsTableCell: UITableViewCell { @IBOutlet private weak var newsImageView: UIImageView! @IBOutlet private weak var newsDateLabel: UILabel! @IBOutlet private weak var newsTitleLabel: UILabel! @IBOutlet private weak var newsDescLabel: UILabel! fileprivate func loadData(news: NewsObject) { newsImageView.downloadImageFrom(link: news.image, contentMode: .scaleToFill) newsDateLabel.text = DateFormatters.defaultDateFormatter().string(from: news.date) newsTitleLabel.text = news.title newsDescLabel.text = news.description } }
true
edcb19e6939714496672b22fcd956a644632e21f
Swift
yortuc/muziklen
/Muziklen/MListViewController.swift
UTF-8
2,409
2.703125
3
[]
no_license
// // MListViewController.swift // Muziklen // // Created by Evren Yortuçboylu on 05/05/16. // Copyright © 2016 Evren Yortuçboylu. All rights reserved. // import UIKit class MListViewController<Item, Cell: UITableViewCell>: UITableViewController { var items: [Item] var configCell: (cell: Cell, item: Item)-> Cell var onItemSelected: (selectedItem: Item) -> Void var cellNib: String let cellIdentifier = "Cell" init( title: String, defaultItems: [Item], cellNib:String, onItemSelected: (selectedItem: Item) -> Void, configCell: (cell: Cell, item: Item)-> Cell ) { self.items = defaultItems self.cellNib = cellNib self.configCell = configCell self.onItemSelected = onItemSelected super.init(style: .Plain) self.title = title self.tableView.reloadData() } func updateWith(items: [Item]) { self.items = items self.tableView.reloadData() } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return App.UI.artistImageSize + CGFloat(2*8) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } override func viewDidLoad() { tableView.registerNib(UINib(nibName: cellNib, bundle: nil), forCellReuseIdentifier: cellIdentifier) } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { cell.separatorInset = UIEdgeInsetsZero } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.onItemSelected(selectedItem: self.items[indexPath.row]) } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let item = self.items[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as! Cell return self.configCell(cell: cell, item: item) } } extension MListViewController { func request(request: ApiRequest<Item>) { } }
true
3ab733652c5afeb1b8edce4ff266531dc3ec98b8
Swift
sweetmandm/Validate
/Sources/Validate/ValidationAppearance.swift
UTF-8
433
2.640625
3
[ "MIT" ]
permissive
// // ValidationAppearance.swift // Validate // // Created by sweetman on 4/28/17. // Copyright © 2017 tinfish. All rights reserved. // import Foundation public protocol ValidationAppearanceValid: class { func applyValidStyle() } public protocol ValidationAppearanceNeutral: class { func applyNeutralStyle() } public protocol ValidationAppearanceInvalid: class { func applyInvalidStyle(error: ValidationError) }
true
ce179016620d0d608e5a0016b6d35f90223fb6e7
Swift
thanduchuy/SwiftUI-ForumApp
/Forum App/SwitfUI/CreatePost.swift
UTF-8
3,668
2.625
3
[]
no_license
// // CreatePost.swift // Forum App // // Created by MacBook Pro on 3/15/20. // Copyright © 2020 MacBook Pro. All rights reserved. // import SwiftUI import Firebase import FirebaseStorage import FirebaseAuth struct CreatePost : View { @Binding var show : Bool @State var txt = "" @State var picker = false @State var picData : Data = .init(count:0) @State var loading = false @EnvironmentObject var friend : AlertServices func getInfoUser() { let db = Firestore.firestore() let docRef = db.collection("User").document(Auth.auth().currentUser!.uid) docRef.getDocument { (document, error) in if error != nil { print((error?.localizedDescription)!) return } else { let name = document?.get("name") as! String let email = document?.get("email") as! String let avatar = document?.get("avatar") as! String self.postImagePicker(name: name, email: email, avatar: avatar) self.addAlert(name:name) } } } func addAlert(name:String) { friend.friend.forEach { (UserInfo) in Firestore.firestore().collection("User").document(UserInfo.uid).collection("Alert").document().setData(["name":name,"msg":"Your friends added a new post","date":Date(),"uid":Auth.auth().currentUser!.uid,"isLike":false,"isPost":true,"isMakeFriend":false]) } } var body : some View { VStack { HStack { Button(action: { self.show.toggle() }) { Text("Cancel") } Spacer() if loading { indicator() } else { Button(action: { self.picker.toggle() }) { Image(systemName: "photo.fill").resizable().frame(width: 35, height: 25) }.foregroundColor(Color("bg")) } Button(action: { self.getInfoUser() }) { Text("Post").padding() }.background(Color("bg")) .foregroundColor(.white) .clipShape(Capsule()) } multilineTextFiel(txt: $txt) }.padding() .sheet(isPresented: $picker) { imagePicker(picked: self.$picker, picData: self.$picData) } } func postImagePicker(name:String,email:String,avatar:String){ let storage = Storage.storage().reference() let id = Auth.auth().currentUser!.uid storage.child("pics").child(id).putData(self.picData, metadata: nil) { (data,error) in if error != nil { print((error?.localizedDescription)!) return } storage.child("pics").child(id).downloadURL { (url, error) in if error != nil { print((error?.localizedDescription)!) return } if !self.loading && self.picData.count != 0 { self.loading.toggle() addPost(msg: self.txt,pic:"\(url!)",name: name,email:email,avatar: avatar,uid: id,uidLikes: []) } else if !self.loading { addPost(msg: self.txt,pic:"",name:name,email:email,avatar:avatar,uid: id,uidLikes: []) } self.show.toggle() } } } }
true
43179cd643545e268e43aed340af8adfaada05b2
Swift
wendyliga/talking-emoji
/talkingEmoji.playground/Sources/EmojiFace.swift
UTF-8
10,444
2.6875
3
[]
no_license
import UIKit public class EmojiFace: UIView{ public var mode: Mode = .normal{ didSet{ print("berubah") } } private lazy var anthennaStick: UIView = { [unowned self] in let anthenaStick = UIView(frame: CGRect(x: self.frame.width/2 - (7), y: 0, width: 10, height: 30)) anthenaStick.backgroundColor = UIColor(red: 110/255, green: 91/255, blue: 135/255, alpha: 1) return anthenaStick }() private lazy var outter: UIView = { [unowned self] in let outter = UIView(frame: CGRect(x: (self.frame.width / 2) - ((self.frame.width * 0.9) / 2), y: (self.frame.height / 2) - ((self.frame.height * 0.9) / 2), width: self.frame.width * 0.9, height: self.frame.height * 0.9)) outter.clipsToBounds = true outter.layer.cornerRadius = outter.frame.width * 0.2 // create background gradient layer let outterGradientLayer = gradientLayer(firstColor: UIColor(red: 182/255, green: 199/255, blue: 193/255, alpha: 1), secondColor: UIColor(red: 19/255, green: 53/255, blue: 65/255, alpha: 1), frame: self.bounds) outter.layer.addSublayer(outterGradientLayer) return outter }() private lazy var inside: UIView = {[unowned self] in let inside = UIView(frame: CGRect(x: (self.frame.width / 2) - ((self.frame.width * 0.8) / 2), y: (self.frame.height / 2) - ((self.frame.height * 0.8) / 2), width: self.frame.width * 0.8, height: self.frame.height * 0.8)) inside.clipsToBounds = true inside.layer.cornerRadius = inside.frame.width * 0.2 // create background gradient layer let insideGradientLayer = gradientLayer(firstColor: UIColor(red: 223/255, green: 242/255, blue: 244/255, alpha: 1), secondColor: UIColor(red: 65/255, green: 126/255, blue: 140/255, alpha: 1), frame: self.bounds) inside.layer.addSublayer(insideGradientLayer) return inside }() private lazy var leftEyeOutter: UIView = {[unowned self] in let leftEyeOutline = UIView(frame: CGRect(x: self.frame.width * 0.15, y: self.frame.height * 0.2, width: self.frame.width * 0.25, height: self.frame.width * 0.25)) leftEyeOutline.backgroundColor = UIColor.clear leftEyeOutline.clipsToBounds = true leftEyeOutline.layer.cornerRadius = self.frame.width * 0.25 / 2 // add gradient color let leftEyeGradient = gradientLayer(firstColor: UIColor(red: 114/255, green: 246/255, blue: 252/255, alpha: 1), secondColor: UIColor(red: 72/255, green: 131/255, blue: 155/255, alpha: 1), frame: leftEyeOutline.bounds) leftEyeOutline.layer.addSublayer(leftEyeGradient) return leftEyeOutline }() private lazy var leftEye: UIView = {[unowned self] in let leftEye = UIView(frame: CGRect(x: self.frame.width * 0.2, y: self.frame.height * 0.2, width: self.frame.width * 0.2, height: self.frame.width * 0.2)) leftEye.center = self.leftEyeOutter.center leftEye.backgroundColor = UIColor.white leftEye.layer.cornerRadius = self.frame.width * 0.2 / 2 return leftEye }() private lazy var rightEyeOutter: UIView = {[unowned self] in let rightEyeOutline = UIView(frame: CGRect(x: self.frame.width * 0.6, y: self.frame.height * 0.2, width: self.frame.width * 0.25, height: self.frame.width * 0.25)) rightEyeOutline.backgroundColor = UIColor.blue rightEyeOutline.clipsToBounds = true rightEyeOutline.layer.cornerRadius = self.frame.width * 0.25 / 2 // add gradient color let rightEyeGradient = gradientLayer(firstColor: UIColor(red: 114/255, green: 246/255, blue: 252/255, alpha: 1), secondColor: UIColor(red: 72/255, green: 131/255, blue: 155/255, alpha: 1), frame: rightEyeOutline.bounds) rightEyeOutline.layer.addSublayer(rightEyeGradient) return rightEyeOutline }() private lazy var rightEye: UIView = {[unowned self] in let rightEye = UIView(frame: CGRect(x: self.frame.width * 0.6, y: self.frame.height * 0.2, width: self.frame.width * 0.2, height: self.frame.width * 0.2)) rightEye.center = self.rightEyeOutter.center rightEye.backgroundColor = UIColor.white rightEye.layer.cornerRadius = self.frame.width * 0.2 / 2 return rightEye }() private lazy var nose: UIView = {[unowned self] in let nose = TriangleView(frame: CGRect(x: self.frame.width / 2 - 12.5, y: rightEyeOutter.frame.height + 15, width: 25, height: 27)) self.addSubview(nose) return nose }() private lazy var leftEar: UIView = {[unowned self] in let leftEar = UIView(frame: CGRect(x: 0, y: self.frame.height/2 - ((self.frame.height * 0.3)/2), width: self.frame.width * 0.05, height: self.frame.height * 0.3)) leftEar.backgroundColor = UIColor.red leftEar.layer.cornerRadius = 5 return leftEar }() private lazy var rightEar: UIView = {[unowned self] in let rightEar = UIView(frame: CGRect(x: outter.frame.maxX, y: self.frame.height/2 - ((self.frame.height * 0.3)/2), width: self.frame.width * 0.05, height: self.frame.height * 0.3)) rightEar.backgroundColor = UIColor.red rightEar.layer.cornerRadius = 5 return rightEar }() private lazy var mouth: UIView = {[unowned self] in let mouth = UIView(frame: CGRect(x: self.frame.width/2 - ((self.frame.width * 0.45)/2), y: nose.frame.maxY + 20, width: self.frame.width * 0.45, height: self.frame.height * 0.1)) mouth.translatesAutoresizingMaskIntoConstraints = false mouth.clipsToBounds = true mouth.layer.borderColor = UIColor.black.cgColor mouth.layer.borderWidth = 2 mouth.layer.cornerRadius = mouth.frame.width * 0.07 mouth.backgroundColor = UIColor.white for i in 1..<4{ let tooth = UIView(frame: CGRect(x: (self.frame.width * 0.45 / 4 * CGFloat(i)) - (5/2), y: 0, width: 5, height: self.frame.height * 0.1)) tooth.backgroundColor = UIColor.black mouth.addSubview(tooth) } return mouth }() private lazy var mouthTopConstraint: NSLayoutConstraint = {[unowned self] in return mouth.topAnchor.constraint(equalTo: self.nose.bottomAnchor, constant: 20) }() private lazy var mouthCenterXConstraint: NSLayoutConstraint = {[unowned self] in return self.mouth.centerXAnchor.constraint(equalTo: self.centerXAnchor, constant: 0) }() private lazy var mouthWidthConstraint: NSLayoutConstraint = {[unowned self] in return self.mouth.widthAnchor.constraint(equalToConstant: self.frame.width * 0.45) }() private lazy var mouthHeightConstraint: NSLayoutConstraint = {[unowned self] in return self.mouth.heightAnchor.constraint(equalToConstant: self.frame.height * 0.1) }() override public init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear // set clip to bound true to prevent gradient layer to go out of bounds self.clipsToBounds = true } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func draw(_ rect: CGRect) { self.layer.cornerRadius = self.frame.width * 0.2 self.addSubview(anthennaStick) self.addSubview(outter) self.addSubview(inside) self.addSubview(leftEyeOutter) self.addSubview(leftEye) self.addSubview(rightEyeOutter) self.addSubview(rightEye) self.addSubview(mouth) self.addSubview(leftEar) self.addSubview(rightEar) NSLayoutConstraint.activate([ mouthTopConstraint, mouthCenterXConstraint, mouthWidthConstraint, mouthHeightConstraint ]) } func gradientLayer(firstColor: UIColor, secondColor: UIColor, frame: CGRect) -> CAGradientLayer{ let gradientLayer = CAGradientLayer() gradientLayer.colors = [firstColor.cgColor, secondColor.cgColor] let gradientPoint: (CGPoint,CGPoint) = (CGPoint(x: 0.5, y: 0), CGPoint(x: 0.5, y: 1)) gradientLayer.startPoint = gradientPoint.0 gradientLayer.endPoint = gradientPoint.1 gradientLayer.locations = [0, 1] gradientLayer.frame = frame return gradientLayer } public func speak(text: String){ let splittedString = text.components(separatedBy: " ") UIView.animateKeyframes(withDuration: 0.26 * Double(splittedString.count), delay: 0, options: .calculationModeCubic, animations: { let relativeDuration = Double((Double(1.0)/Double(splittedString.count))) for (index,text) in splittedString.enumerated(){ UIView.addKeyframe(withRelativeStartTime: relativeDuration * Double(index), relativeDuration: relativeDuration) { self.mouthWidthConstraint.constant = (self.frame.width * 0.45) / CGFloat(text.count) self.layoutIfNeeded() } } }) { (true) in self.mouthWidthConstraint.constant = (self.frame.width * 0.45) UIView.animate(withDuration: 0.3, animations: { self.layoutIfNeeded() }) } } } class TriangleView : UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear self.clipsToBounds = true } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func draw(_ rect: CGRect) { let path = UIBezierPath() path.lineWidth = 3 path.move(to: CGPoint(x: rect.width/2, y: 0)) path.addLine(to: CGPoint(x: rect.width, y: rect.height)) path.addLine(to: CGPoint(x: 0, y: rect.height)) path.close() UIColor(red: 189/255, green: 106/255, blue: 102/255, alpha: 1).setFill() path.fill() UIColor(red: 255/255, green: 62/255, blue: 50/255, alpha: 1).setStroke() path.stroke() } } public enum Mode{ case normal case wink case cry }
true
ccf646cbec15fd540f389bbf4d1c552bd4b77b58
Swift
Jonas94/WaterButler
/WaterButler/View/PlannerView.swift
UTF-8
2,981
2.90625
3
[]
no_license
// // PlannerView.swift // WaterButler // // Created by Jonas Fredriksson on 2021-05-09. // import SwiftUI struct PlannerView: View { @State var date = Date() @State var isLoading = false; @State var sliderValue: Double = 0 @State var response : String = "" @ObservedObject var apiCall = ApiCall() var body: some View { ZStack{ VStack{ VStack { DatePicker("", selection: $date, in: Date()...) .datePickerStyle(WheelDatePickerStyle()) .labelsHidden() .onChange(of: date, perform: { value in date = value print(date) }) .padding(100) if(isLoading){ ProgressView() .progressViewStyle(CircularProgressViewStyle(tint: .blue)) .scaleEffect(5) Spacer() } //.padding(.top, 10) HStack { Image(systemName: "minus") Text("🌵") Slider(value: $sliderValue, in: 0...30, step: 1) .padding() .accentColor(Color.blue) .overlay(RoundedRectangle(cornerRadius: 15.0) .stroke(lineWidth: 3.0) .foregroundColor(Color.green)) Text("💦") Image(systemName: "plus") }.foregroundColor(Color.green).padding(50) Text("Vattna i \(sliderValue, specifier: "%.0f") minuter") Button(action: {print("Button action") //isLoading = true let dateFormatterPrint = DateFormatter() dateFormatterPrint.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" apiCall.postEnableWatering(sliderValue: sliderValue, startDate: dateFormatterPrint.string(from: date)) }){ HStack { Text("Vattna 💦") .padding() } } } }.sheet(isPresented: $apiCall.showSuccessScreen, content: { ScheduledSuccessView(enabledWateringResponse: apiCall.enabledWateringResponse!) }) } } } struct PlannerView_Previews: PreviewProvider { static var previews: some View { PlannerView() } }
true
f957725aa8a4d344db54fbda92cbecc47c6a0cf1
Swift
wircho/Geometry
/Geometry/Drawing/LayerCanvas.swift
UTF-8
983
3.109375
3
[ "MIT" ]
permissive
// // LayerCanvas.swift // GeometrySample // // Created by AdolfoX Rodriguez on 2017-06-13. // Copyright © 2017 Trovy. All rights reserved. // import Foundation protocol LayerCanvas: class, Drawable, LayerDrawable { associatedtype RectType: RawRectProtocol associatedtype LayerType: Layer var layers: [LayerType] { get } var elements: [AnyLayerDrawable<RectType, LayerType>] { get set } } extension LayerCanvas { func draw(in rect: RectType, layer: LayerType) { for element in elements { element.draw(in: rect, layer: layer) } } func draw(in rect: RectType) { for layer in layers { draw(in: rect, layer: layer) } } private func add(_ element: AnyLayerDrawable<RectType, LayerType>) { elements.append(element) } func add<T: LayerDrawable>(drawable element: T) where T.RectType == RectType, T.LayerType == LayerType { add(AnyLayerDrawable(element)) } }
true
8299d57f20e6bc5a800dad1d6bcce3301986abf0
Swift
apparata/CLIKit
/Tests/CLIKitTests/Helpers/MainframeCommand.swift
UTF-8
358
2.640625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // Copyright © 2019 Apparata AB. All rights reserved. // import Foundation import CLIKit class MainframeCommand: Command { let description = "Starts the server." @CommandOption(short: "p", default: 4040, regex: #"^\d+$"#, description: "Listening port.") var port: Int func run() { print("Port: \(port)") } }
true
6d1c4cc2067224e1c012fe39f3741b665317cfba
Swift
meet2ns/codingchallenge
/CodingChallenge/CodingChallenge/Classes/Helpers/Extensions/UIBarButtonItems/ApplicationBarButtonItems.swift
UTF-8
586
2.515625
3
[]
no_license
// // ApplicationBarButtonItems.swift // Expo Mobile // // Created by Onebyte LLC on 6/9/17. // Copyright © 2017 Onebyte LLC. All rights reserved. // import Foundation import UIKit extension UIBarButtonItem { class func barButton(image: UIImage?, target: AnyObject, action: Selector) -> UIBarButtonItem { let button = UIButton(type: .custom) button.setImage(image, for: .normal) button.addTarget(target, action: action, for: .touchUpInside) let barButtonItem = UIBarButtonItem(customView: button) return barButtonItem } }
true
e7f84938e7f8547c9e5bdac29df7623c77b9e634
Swift
Cublax/Pocket_Luggage
/PocketLuggage/Source/Translator/TranslatorCoordinator.swift
UTF-8
2,388
2.8125
3
[]
no_license
// // TranslatorCoordinator.swift // PocketLuggage // // Created by Alexandre Quiblier on 13/06/2019. // Copyright © 2019 Alexandre Quiblier. All rights reserved. // import UIKit final class TranslatorCoordinator { // MARK: - Properties private let presenter: UINavigationController private let screens: Screens // MARK: - Initializer init(presenter: UINavigationController, screens: Screens) { self.presenter = presenter self.screens = screens } // MARK: - Coordinator private var defaultConfiguration = LanguageConfiguration(originLanguage: ("French", "fr", ""), destinationLanguage: ("English", "en", "")) func start() { showTranslate(with: defaultConfiguration) } private func showTranslate(with configuration: LanguageConfiguration) { let viewController = screens.createTranslatorViewController(with: configuration, delegate: self) presenter.viewControllers = [viewController] } private func showLanguages(with type: LanguageViewType) { let viewController = screens.createLanguagesViewController(languageType: type, delegate: self) presenter.show(viewController, sender: nil) } private func showAlert(for type: AlertType) { let alert = screens.createAlert(for: type) presenter.visibleViewController?.present(alert, animated: true, completion: nil) } } extension TranslatorCoordinator: TranslatorViewModelDelegate { func didPresentLanguages(for type: LanguageViewType) { showLanguages(with: type) } func shouldDisplayAlert(for type: AlertType) { showAlert(for: type) } } extension TranslatorCoordinator: LanguageViewModelDelegate { func languageScreenDidSelectDetail(with language: LanguageType) { presenter.popViewController(animated: true) switch language { case .origin(let value, let key): defaultConfiguration.originLanguage = (value, key, "") case .destination(let value, let key): defaultConfiguration.destinationLanguage = (value, key, "") } showTranslate(with: defaultConfiguration) } } enum LanguageType: Equatable { case origin(_ name: String, _ key: String) case destination(_ value: String, _ key: String) }
true
3a82d29c06ddf80407f8e8d1578855521347e28e
Swift
gcortes/jazzcat
/jazzcat/Labels.swift
UTF-8
4,473
2.8125
3
[ "Apache-2.0" ]
permissive
// // Labels.swift // jazzcat // // Created by Curt Rowe on 24/1/17. // Copyright © 2017 Curt Rowe. All rights reserved. // import Foundation let labelUpdateNotification = Notification.Name(rawValue:"com.zetcho.labelUpdated") class Labels: RailsData { // This class is a singleton static let shared = Labels() //################################################################################################ //Making it private prevents the use of the default '()' initializer for this class. private override init() { } //################################################################################################ func loadTable(wait: Bool = true) { if isLoaded == true { return } let rest = "labels" super.loadRailsTable(rest: rest) if wait == true { dispatchGroup.wait() } } //################################################################################################ func addRowAndNotify(rowData: Dictionary<String, Any>) { let rest = "labels" super.addRailsRow(rest: rest, rowData: rowData, completionHandler: labelWasAdded) dispatchGroup.wait() } //################################################################################################ func labelWasAdded(row: [String: Any]?) { var key = -1 if let name = row?["name"] as? String { for (index, label) in super.table.enumerated() { if name <= label["name"] as! String { key = index break } } // If key is unchanged, the name is greater than any in the table. // Append it to the end if key == -1 { super.table.append(row!) } else { super.table.insert(row!, at: key) } let nc = NotificationCenter.default nc.post(name:labelUpdateNotification, object: row, userInfo:["type":"add"]) } else { print("Labels: JSON missing name: ", row as Any) } } //################################################################################################ func updateRowAndNotify(row: String, rowData: Dictionary<String,Any>, roundTrip: Any? = nil) { let rest = "labels/" + row super.updateRailsRow(rest: rest, rowData: rowData, roundTrip: roundTrip, completionHandler: labelWasUpdated) } //################################################################################################ func labelWasUpdated(row: [String: Any]?, roundTrip: Any? = nil) { var key = -1 for (index, label) in super.table.enumerated() { if label["id"] as! Int == row?["id"] as! Int { key = index break } } if key >= 0 { super.table[key] = row! let nc = NotificationCenter.default nc.post(name:labelUpdateNotification, object: row, userInfo:["type":"update"]) } else { print("Labels: error Handling label update") } } //################################################################################################ func deleteRowAndNotify(row: String) { let rest = "labels/" + row super.deleteRailsRow(rest: rest, completionHandler: labelWasDeleted, roundTrip: row) } //################################################################################################ func labelWasDeleted(roundTrip: Any? = nil) { var key = -1 if let value = roundTrip as? String { let rowID = Int(value) for (index, label) in super.table.enumerated() { if label["id"] as? Int == rowID { key = index break } } if key >= 0 { super.table.remove(at: key) let nc = NotificationCenter.default nc.post(name: labelUpdateNotification, object: [ "id": roundTrip ], userInfo: ["type": "delete"]) } else { print("labelWasDeleted: deleted row not found in dictionary") } } else { print("labelWasDeleted: no roundTrip data") } } }
true
7ffeb9b94478324729c19e627ca0c975603a776e
Swift
sbear123/SearchImage
/SearchImage/Source/Models/Meta.swift
UTF-8
302
2.5625
3
[]
no_license
// // MetaModel.swift // SearchImage // // Created by 박지현 on 2021/06/25. // import Foundation struct Meta: Codable { var total_count: Int var pageable_count: Int var is_end: Bool init() { total_count = 0 pageable_count = 0 is_end = false } }
true
a464fb0d22256cdf65a65d322442d8617984a6a6
Swift
Steven0351/HackingWithSwift
/Milestone11Challenge/SecretPhotos/SecretPhotos/DetailVC.swift
UTF-8
1,575
2.828125
3
[]
no_license
// // DetailVC.swift // SecretPhotos // // Created by Steven Sherry on 7/17/17. // Copyright © 2017 Steven Sherry. All rights reserved. // import UIKit class DetailVC: UIViewController { @IBOutlet weak var imageView: UIImageView! var selectedImage = "" weak var vc: ViewController! override func viewDidLoad() { super.viewDidLoad() if selectedImage.contains("puppy") { imageView.image = UIImage(named: selectedImage) } else { navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePhoto)) let path = getDocumentsDirectory().appendingPathComponent(selectedImage) imageView.image = UIImage(contentsOfFile: path.path) } } func getDocumentsDirectory() -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return paths[0] } func deletePhoto() { let fileManager = FileManager.default do { try fileManager.removeItem(atPath: getDocumentsDirectory().appendingPathComponent(selectedImage).path) navigationController?.popToRootViewController(animated: true) } catch { let ac = UIAlertController(title: "Error", message: "Your image was not deleted", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } } }
true
9af5cb0b0fc3e6e5fd4385e57b946e6708a93acf
Swift
dfomin/hat-stat
/HatStat/Word.swift
UTF-8
560
2.671875
3
[]
no_license
// // Word.swift // HatStat // // Created by Dmitry Fomin on 26/05/2017. // Copyright © 2017 Pigowl. All rights reserved. // import Foundation class Word { let id: Int let word: String let level: Double let badItalic: Bool let packId: Int let usage: Int init(id: Int, json: JSON) { self.id = id word = json["word"].stringValue level = json["level"].doubleValue badItalic = json["baditalic"].boolValue packId = json["packid"].intValue usage = json["usage"].intValue } }
true
4b022354937db20bdaad8d77eb5af9054c5f3c5d
Swift
lucaspizzo/ios-movie-app
/some-shows/Service/ShowService.swift
UTF-8
1,522
3.03125
3
[]
no_license
// // ShowService.swift // some-shows // // Created by Lucas on 16/03/19. // Copyright © 2019 Lucas Pizzo. All rights reserved. // import Foundation class ShowService { typealias ListShowResponseCompletion = ([TvShow]?, Error? ) -> Void func listShow(completion: @escaping ListShowResponseCompletion) { let urlString = "http://api.tvmaze.com/search/shows?q=robot" guard let url = URL(string: urlString) else { return } 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 } let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let response = self.parseJSON(data: data) var shows: [TvShow] = [] for r in response { shows.append(TvShow(tvShowResponse: r)) } completion(shows, nil) } }.resume() } func parseJSON(data: Data) -> [TvShowResponse]{ do { let decoder = JSONDecoder() return try decoder.decode([TvShowResponse].self, from: data) } catch let error { print(error as Any) } return [] } }
true
efac0a134b2d49bafc64198ca033c15ac97b3eb7
Swift
mapsme/omim
/iphone/Maps/Core/Location/GeoTracker/Impl/GeoTracker.swift
UTF-8
2,264
2.515625
3
[ "Apache-2.0" ]
permissive
class GeoTracker: NSObject, IGeoTracker { private let trackerCore: IMWMGeoTrackerCore private let locationManager = CLLocationManager() private var trackingZones: [String : IMWMGeoTrackerZone]? private var zoneTrackers: [String : GeoZoneTracker] = [:] init(trackerCore: IMWMGeoTrackerCore) { self.trackerCore = trackerCore super.init() locationManager.delegate = self } deinit { locationManager.delegate = nil } @objc func startTracking() { if CLLocationManager.significantLocationChangeMonitoringAvailable() { locationManager.startMonitoringSignificantLocationChanges() } } @objc func endTracking() { locationManager.stopMonitoringSignificantLocationChanges() } } extension GeoTracker: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last { locationManager.monitoredRegions.forEach { locationManager.stopMonitoring(for: $0) } if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) { let zones = trackerCore.geoZones(forLat: location.coordinate.latitude, lon: location.coordinate.longitude, accuracy: location.horizontalAccuracy) zones.forEach { locationManager.startMonitoring( for: CLCircularRegion(center: CLLocationCoordinate2DMake($0.latitude, $0.longitude), radius: 100, identifier: $0.identifier)) } trackingZones = zones.reduce(into: [:]) { $0[$1.identifier] = $1 } } } } func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { if let zone = trackingZones?[region.identifier] { let zoneTracker = GeoZoneTracker(zone, trackerCore: trackerCore) zoneTracker.startTracking() zoneTrackers[region.identifier] = zoneTracker } } func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { if let zoneTracker = zoneTrackers[region.identifier] { zoneTracker.stopTracking() zoneTrackers[region.identifier] = nil } } }
true
e92dcee5c5fae6c3e84d6597889e02b823765ce3
Swift
aeddang/BtvPlusNew
/BtvPlusNew/scene/ui/BtvButton.swift
UTF-8
1,469
2.53125
3
[]
no_license
// // Banner.swift // Valla // // Created by JeongCheol Kim on 2020/08/28. // Copyright © 2020 JeongCheol Kim. All rights reserved. // import Foundation import SwiftUI struct BtvButton: PageView { @EnvironmentObject var pairing:Pairing @EnvironmentObject var appSceneObserver:AppSceneObserver var id:String var body: some View { Button(action: { if self.pairing.status != .pairing { self.appSceneObserver.alert = .needPairing() } else{ } }) { VStack(spacing:0){ Image( Asset.icon.watchBTv) .renderingMode(.original).resizable() .scaledToFit() .frame( width: Dimen.icon.regular, height: Dimen.icon.regular) Text(String.button.watchBtv) .modifier(MediumTextStyle( size: Font.size.tiny, color: Color.app.greyLight )) } }//btn }//body } #if DEBUG struct BtvButton_Previews: PreviewProvider { static var previews: some View { Form{ BtvButton( id:"" ) .environmentObject(Pairing()) .environmentObject(AppSceneObserver()) .environmentObject(Pairing()) } } } #endif
true
8d49a549483cd44c3e015742216a6eb73a604d4d
Swift
thegreenfrog/Shuttle-App
/Shuttle_Application/WelcomeViewController.swift
UTF-8
7,509
2.859375
3
[]
no_license
// // WelcomeViewController.swift // Shuttle_Application // // Created by Chris Lu on 4/6/16. // // import UIKit import Parse class WelcomeViewController: UIViewController { struct Constants { static let buttonFrame:CGRect = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 200, height: 45)) static let labelFrame:CGRect = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: 225, height: 100)) } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.clearColor() drawScreen() } func drawScreen() { let welcomeLabel = UILabel(frame: Constants.labelFrame) welcomeLabel.textColor = UIColor.whiteColor() welcomeLabel.numberOfLines = 0 welcomeLabel.text = "Welcome!" welcomeLabel.textAlignment = .Center welcomeLabel.translatesAutoresizingMaskIntoConstraints = false let driverlabel = UILabel(frame: Constants.buttonFrame) driverlabel.font = UIFont.systemFontOfSize(14) driverlabel.text = "Driver?\nSwipe Left!" driverlabel.textColor = UIColor.whiteColor() driverlabel.numberOfLines = 0 driverlabel.lineBreakMode = .ByWordWrapping driverlabel.textAlignment = .Left driverlabel.translatesAutoresizingMaskIntoConstraints = false let rightArrowPath = UIBezierPath() var start = CGPointZero rightArrowPath.moveToPoint(start) var next = CGPoint(x: start.x+25, y: start.y-20) rightArrowPath.addLineToPoint(next) next = CGPoint(x: next.x, y: next.y+10) rightArrowPath.addLineToPoint(next) next = CGPoint(x: next.x+50, y: next.y) rightArrowPath.addLineToPoint(next) next = CGPoint(x: next.x, y: next.y+20) rightArrowPath.addLineToPoint(next) next = CGPoint(x: next.x-50, y: next.y) rightArrowPath.addLineToPoint(next) next = CGPoint(x: next.x, y: next.y+10) rightArrowPath.addLineToPoint(next) rightArrowPath.addLineToPoint(start) rightArrowPath.closePath() let rightArrowShape = UIImage.shapeImageWithBezierPath(rightArrowPath, fillColor: UIColor.clearColor(), strokeColor: UIColor.whiteColor(), strokeWidth: 1.0) let rightImageView = UIImageView(image: rightArrowShape) let driverlabelStackView = UIStackView() driverlabelStackView.addArrangedSubview(driverlabel) driverlabelStackView.addArrangedSubview(rightImageView) driverlabelStackView.axis = .Vertical driverlabelStackView.spacing = 10 driverlabelStackView.distribution = .EqualSpacing driverlabelStackView.translatesAutoresizingMaskIntoConstraints = false let consumerLabel = UILabel(frame: Constants.buttonFrame) consumerLabel.font = UIFont.systemFontOfSize(14) consumerLabel.text = "User?\nSwipe Right!" consumerLabel.textColor = UIColor.whiteColor() consumerLabel.numberOfLines = 0 consumerLabel.lineBreakMode = .ByWordWrapping consumerLabel.textAlignment = .Right consumerLabel.translatesAutoresizingMaskIntoConstraints = false let leftArrowPath = UIBezierPath() start = CGPointZero leftArrowPath.moveToPoint(start) next = CGPoint(x: start.x-25, y: start.y-20) leftArrowPath.addLineToPoint(next) next = CGPoint(x: next.x, y: next.y+10) leftArrowPath.addLineToPoint(next) next = CGPoint(x: next.x-50, y: next.y) leftArrowPath.addLineToPoint(next) next = CGPoint(x: next.x, y: next.y+20) leftArrowPath.addLineToPoint(next) next = CGPoint(x: next.x+50, y: next.y) leftArrowPath.addLineToPoint(next) next = CGPoint(x: next.x, y: next.y+10) leftArrowPath.addLineToPoint(next) leftArrowPath.addLineToPoint(start) leftArrowPath.closePath() let leftArrowShape = UIImage.shapeImageWithBezierPath(leftArrowPath, fillColor: UIColor.clearColor(), strokeColor: UIColor.whiteColor(), strokeWidth: 1.0) let leftImageView = UIImageView(image: leftArrowShape) let consumerLabelStackView = UIStackView() consumerLabelStackView.addArrangedSubview(consumerLabel) consumerLabelStackView.addArrangedSubview(leftImageView) consumerLabelStackView.axis = .Vertical consumerLabelStackView.spacing = 10 consumerLabelStackView.distribution = .EqualSpacing consumerLabelStackView.translatesAutoresizingMaskIntoConstraints = false let labelStackView = UIStackView() labelStackView.addArrangedSubview(driverlabelStackView) labelStackView.addArrangedSubview(consumerLabelStackView) labelStackView.axis = .Horizontal labelStackView.distribution = .EqualSpacing labelStackView.translatesAutoresizingMaskIntoConstraints = false let screenStackView = UIStackView() screenStackView.addArrangedSubview(welcomeLabel) screenStackView.addArrangedSubview(labelStackView) screenStackView.axis = .Vertical screenStackView.distribution = .Fill screenStackView.spacing = 50 screenStackView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(screenStackView) screenStackView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor).active = true screenStackView.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor).active = true screenStackView.widthAnchor.constraintEqualToAnchor(self.view.widthAnchor, constant: -20).active = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } /* UIImage function that creates image from BezierPath. Used to create image of arrows copied from http://digitalleaves.com/blog/2015/07/bezier-paths-in-practice-i-from-basic-shapes-to-custom-designable-controls/ */ extension UIImage { class func shapeImageWithBezierPath(bezierPath: UIBezierPath, fillColor: UIColor?, strokeColor: UIColor?, strokeWidth: CGFloat = 0.0) -> UIImage! { //Normalize bezier path. We will apply a transform to our bezier path to ensure that it's placed at the coordinate axis. Then we can get its size. bezierPath.applyTransform(CGAffineTransformMakeTranslation(-bezierPath.bounds.origin.x, -bezierPath.bounds.origin.y)) let size = CGSizeMake(bezierPath.bounds.size.width, bezierPath.bounds.size.height) //Initialize an image context with our bezier path normalized shape and save current context UIGraphicsBeginImageContext(size) let context = UIGraphicsGetCurrentContext() CGContextSaveGState(context) //Set path CGContextAddPath(context, bezierPath.CGPath) //Set parameters and draw if strokeColor != nil { strokeColor!.setStroke() CGContextSetLineWidth(context, strokeWidth) } else { UIColor.clearColor().setStroke() } fillColor?.setFill() CGContextDrawPath(context, .FillStroke) //Get the image from the current image context let image = UIGraphicsGetImageFromCurrentImageContext() //Restore context and close everything CGContextRestoreGState(context) UIGraphicsEndImageContext() return image } }
true
16f03dc85b75951f6954bdb3245754ebf8ab3864
Swift
bio4554/Lines
/Lines/MainMenu.swift
UTF-8
1,363
2.515625
3
[]
no_license
// // MainMenu.swift // Lines // // Created by Austin Childress on 2/7/17. // Copyright © 2017 Austin Childress. All rights reserved. // import SpriteKit import GameplayKit class MainMenu: SKScene { override func didMove(to view: SKView) { self.backgroundColor = .black let text = SKLabelNode() text.text = "gra_vity" text.fontSize = 200 text.position = CGPoint(x: size.width/2, y: size.height/2) let goText = SKLabelNode() goText.text = "∨" goText.fontSize = 500 goText.fontColor = .white goText.position = CGPoint(x: size.width/2, y: size.height/4) let versionText = SKLabelNode() versionText.text = "v1.1 © Mars Dev 2017" versionText.fontSize = 100 //versionText.fontName = "AvenirNext-Bold" versionText.position = CGPoint(x: size.width/2, y: 100) addChild(text) addChild(goText) //addChild(versionText) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let trans = SKTransition.reveal(with: .down, duration: 0.5) let gameScene = GameScene(size: self.size) gameScene.scaleMode = .aspectFill self.view?.presentScene(gameScene, transition:trans) } }
true
f5da4a763f08d2f1dd1bbf24b72b7c63ea1184ed
Swift
SebastianPetric/houp
/Houp/ImageCache.swift
UTF-8
1,134
2.8125
3
[]
no_license
// // ImageCache.swift // Houp // // Created by Sebastian on 23.03.17. // Copyright © 2017 SP. All rights reserved. // import UIKit class HoupImageCache{ static var shared: HoupImageCache = HoupImageCache() let cache = NSCache<AnyObject, AnyObject>() func getImageFromCache(userID: String) -> UIImage?{ let url : NSString = "\(userID)_profileImage.jpeg" as NSString let urlStr : NSString = url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString let searchURL : NSURL = NSURL(string: urlStr as String)! if let image = cache.object(forKey: searchURL) as? UIImage{ return image }else{ return nil } } func saveImageToCache(userID: String, profile_image: UIImage){ let url : NSString = "\(userID)_profileImage.jpeg" as NSString let urlStr : NSString = url.addingPercentEscapes(using: String.Encoding.utf8.rawValue)! as NSString let searchURL : NSURL = NSURL(string: urlStr as String)! cache.setObject(profile_image, forKey: searchURL) } }
true
f5036be7d8dfd9868ca2d450fe90d7f46e5cfc06
Swift
ios-kitap/allBasicViews
/viewsExample/UIIMageViewViewController.swift
UTF-8
1,167
2.640625
3
[]
no_license
// // UIIMageViewViewController.swift // viewsExample // // Created by Emre Erol on 7.02.2019. // Copyright © 2019 Codework. All rights reserved. // import UIKit class UIIMageViewViewController: UIViewController { //ImageView IBOutlet Bağlantısı (Yuvarlar ImageView) @IBOutlet weak var radialImageView: UIImageView! @IBOutlet weak var golgeliImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() imageVieweGolgeEkle() imageViewiYuvarlakYap() } func imageVieweGolgeEkle(){ golgeliImageView.layer.shadowColor = UIColor.darkGray.cgColor golgeliImageView.layer.shadowOpacity = 0.7 golgeliImageView.layer.shadowOffset = CGSize.zero golgeliImageView.layer.shadowRadius = 6 } func imageViewiYuvarlakYap(){ self.radialImageView.layer.borderWidth = 1.0 self.radialImageView.layer.masksToBounds = false self.radialImageView.layer.borderColor = UIColor.white.cgColor self.radialImageView.layer.cornerRadius = self.radialImageView.frame.size.height / 2 self.radialImageView.clipsToBounds = true } }
true
9b98aa29b19e1c20020b24ecdd3129c106d2c269
Swift
itungdx/QuickPlayer.v2
/QuickPlayer.v2/ViewController.swift
UTF-8
3,232
2.671875
3
[]
no_license
// // ViewController.swift // QuickPlayer.v2 // // Created by Tung on 6/22/17. // Copyright © 2017 Tung. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, AVAudioPlayerDelegate { var audio = AVAudioPlayer() var status = 1 @IBOutlet weak var btn_play: UIButton! @IBOutlet weak var sld_Volume: UISlider! @IBOutlet weak var lbl_timeCurrent: UILabel! @IBOutlet weak var lbl_timeRight: UILabel! @IBOutlet weak var sld_duration: UISlider! @IBOutlet weak var sw_repeat: UISwitch! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. audio = try! AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: Bundle.main.path(forResource: "music", ofType:".mp3")!) as URL) addThumbImgForSlider() checkRepeat() audio.delegate = self let timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimeCurrent), userInfo: nil, repeats: true) } func updateTimeCurrent() { let currentTime = Int(audio.currentTime) let minTimeCurrent = currentTime/60 let secTimeCurrent = currentTime - minTimeCurrent*60 self.lbl_timeCurrent.text = String(format: "%02d:%02d", minTimeCurrent, secTimeCurrent) let durationTime = Int(audio.duration) let timeRight = durationTime - currentTime let minTimeRight = timeRight/60 let secTimeRight = timeRight - minTimeRight*60 self.lbl_timeRight.text = String(format: "%02d:%02d", minTimeRight, secTimeRight) self.sld_duration.value = Float(audio.currentTime/audio.duration) if audio.currentTime == 0 { changePlay() } } func addThumbImgForSlider(){ sld_Volume.setThumbImage(UIImage(named: "thumb.png"), for: .normal) sld_Volume.setThumbImage(UIImage(named: "thumbHightLight.png"), for: .highlighted) } func playPause(){ if status == 1{ btn_play.setImage(UIImage(named: "pause.png"), for: .normal) audio.play() status = 2 }else{ btn_play.setImage(UIImage(named: "play.png"), for: .normal) audio.pause() status = 1 } } func changePlay(){ print (String(audio.currentTime)) print(String(audio.duration)) if sw_repeat.isOn == false { btn_play.setImage(UIImage(named: "play.png"), for: .normal) } } func checkRepeat(){ if sw_repeat.isOn == true { audio.numberOfLoops = -1 }else{ audio.numberOfLoops = 0 } } @IBAction func sw_Repeat(_ sender: UISwitch) { checkRepeat() } @IBAction func sld_duration(_ sender: UISlider) { audio.currentTime = TimeInterval(Float(sender.value) * Float(audio.duration)) } @IBAction func action_play(_ sender: UIButton) { playPause() } @IBAction func sld_Volume(_ sender: UISlider) { audio.volume = sender.value } func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { } }
true
d5b8a224bac031bbc4129bff543040630fc5f4d3
Swift
thomasburguiere/XperLib
/Sources/XperLib/Model/Tree/Node.swift
UTF-8
2,881
2.765625
3
[]
no_license
// // Node.swift // Xper // // Created by Thomas Burguiere on 03/04/16. // Copyright © 2016 Thomas Burguiere. All rights reserved. // import Foundation open class Node<T: Treeable>: DatasetObjectWithResources, Equatable { open var object: T? open var name: String? open var detail: String? open var tree: Tree<T>? fileprivate var inapplicableStates: [State]? open func setInapplicableStates(_ inappStates: [State]) { if object is CategoricalDescriptor { inapplicableStates = inappStates } } open func getInapplicableStates() -> [State]? { if object is CategoricalDescriptor { return inapplicableStates } return nil } open func addInapplicableState(_ state: State) throws { if !(object is Descriptor) { throw XperError(message: "cannot add Inapplicable State to node that doesnt contain descriptor") } if (self.parentNode == nil) { throw XperError(message: "cannot add Inapplicable State to node that doesnt have a parent") } if (state.descriptor == nil) { throw XperError(message: "cannot add Inapplicable State that doesnt have descriptor") } if inapplicableStates == nil { inapplicableStates = [State]() } inapplicableStates?.append(state) } open func getApplicableStates() -> Array<State> { var appStates = Array<State>() if (self.parentNode != nil && self.parentNode?.object is CategoricalDescriptor) { let states = (self.parentNode?.object as! CategoricalDescriptor).getStates() for state in states { if (!self.inapplicableStates!.contains(state)) { appStates.append(state) } } } return appStates } fileprivate var parentNode: Node<T>? fileprivate var childNodes: [Node<T>] = [] public init (){} public init(object: T) { self.object = object } open func getParentNode() -> Node<T>? { return self.parentNode } open func setParentNode(_ parentNode: Node<T>) { self.parentNode = parentNode; parentNode.childNodes.append(self); } open func getChildNodes() -> [Node<T>] { return self.childNodes } open func setChildNodes(_ childNodes:[Node<T>]) { for childNode in childNodes { childNode.setParentNode(self); } self.childNodes = childNodes; } // MARK: DatasetObjectWithResources open var resources: [Resource] = [] deinit{ for r in resources { r.object = nil } } public static func ==(lhs: Node<T>, rhs: Node<T>) -> Bool { return lhs.name == rhs.name && lhs.object == rhs.object } }
true
eb88a87667663f1e7c528baad7645e83f234e408
Swift
Zedd0202/Swift_PS
/SwiftPratice/Sum of Odd Sequence.swift
UTF-8
406
2.78125
3
[]
no_license
// // main.swift // SwiftPratice // // Created by Zedd on 2020/03/18. // Copyright © 2020 Zedd. All rights reserved. // import Foundation let testCase = Int(readLine()!)! let oddArray = Array(1...100).filter { $0 % 2 != 0 }.map { $0 } for _ in 0..<testCase { let num = Int(readLine()!)! var sum = 0 for j in oddArray { if j > num { break } sum += j } print(sum) }
true
43ef34205f7fd7c7cc6c82b1bae6c405ce34c0e0
Swift
zvaavtre/messageprocessor
/HtmlPageParser.swift
UTF-8
1,380
3.234375
3
[]
no_license
// // HtmlPageParser.swift // MessageProcessor // // Created by M. David Minnigerode on 9/26/14. // Copyright (c) 2014 M. David Minnigerode. All rights reserved. // import Foundation /** Anything relating to parsing of html pages. */ class HtmlPageParser{ /** Simply get the title from the given page string. By default we truncate at 40 chars. NOTE: Length is not detailed in spec but the titles can get out of hand so want to set some limit. */ class func titleFromPage(page:NSString!, truncateAt:Int = 40) -> String!{ if page == nil { return "" } // input will typically be from NSData. let p = page as String // this regex is always case insensitive and we don't have class vars yet... so just drop in here. // Also this regex isn't perfect... If we want to be more robust probably be better to try an xml/html parser then fall back to regex. But overkill now. let titles:[String] = p.mpMatchStringsForRegex("<title\\b[^>]*>(.*?)</title>") if titles.count >= 1 { if countElements(titles[0]) > truncateAt { return titles[0].mpSubstringWithRange(NSMakeRange(0, truncateAt)) // TODO would be nice to trim this too }else{ return titles[0] } } return "" } }
true
b93294938370d3363285f112437387afe5b558d5
Swift
39199934/ChatByDesignModel
/ChatByDesignModel/Model/ClientInfos.swift
UTF-8
1,867
2.53125
3
[]
no_license
// // ClientInfos.swift // ChatByDesignModel // // Created by rolodestar on 2020/3/7. // Copyright © 2020 Rolodestar Studio. All rights reserved. // import Foundation import SwiftyJSON import CoreData class ClientInfos:Database<ClientInfo>{ init(){ super.init(entityName: "ClientInfoDatabase") delegate = self } } extension ClientInfos:DatabaseDelegate{ func databaseGetDatasFromObjects<T>(result: [NSManagedObject]) -> [T]? { var rtClasss : [ClientInfo] = [] for re in result{ let n = re.value(forKey: "name") as? String ?? "" let nick = re.value(forKey: "nickName") as? String ?? "" let password = re.value(forKey: "password") as? String ?? "" let uuid = re.value(forKey: "uuid") as? String ?? "" let rt = ClientInfo(newname: n, nick: nick, pass_word: password,new_uuid: uuid) rtClasss.append(rt) } return rtClasss as? [T] } func databaseViewDatas(result re: NSManagedObject) { let n = re.value(forKey: "name") as? String ?? "" let nick = re.value(forKey: "nickName") as? String ?? "" let password = re.value(forKey: "password") as? String ?? "" let uuid = re.value(forKey: "uuid") as? String ?? "" let rt = ClientInfo(newname: n, nick: nick, pass_word: password,new_uuid: uuid) print(rt.bag.dictionaryValue) } func databaseInsertValueToDatabase<T>(instans: T, obj: NSManagedObject) -> Bool { //let info = instans as! ClientInfo let info = instans as! ClientInfo obj.setValue(info.name, forKey: "name") obj.setValue(info.nickName, forKey: "nickName") obj.setValue(info.password, forKey: "password") obj.setValue(info.uuid, forKey: "uuid") return true } }
true
8b311fd4fc4e18991f09b0cb2ed3d79d6f3962d3
Swift
ayuram/ProCrastIOS
/ProCrastIOS/AppModel/Activity.swift
UTF-8
2,197
3.1875
3
[]
no_license
// // Activity.swift // ProCrast // // Created by Ayush Raman on 10/23/20. // Copyright © 2020 Answer Key. All rights reserved. // import Foundation import SwiftUI struct Textbook: Equatable, Codable, Identifiable { static func == (lhs: Textbook, rhs: Textbook) -> Bool{ lhs.id == rhs.id } var id: String var pages: ClosedRange<Int>? } struct Task : Codable { let activity: Activity var completed = false var reps = 1 } struct Entry : Codable { var time: Double var reps: ClosedRange<Int> func getUnitTime() -> Double { let range = reps.upperBound - reps.lowerBound return time / range.toDouble() } } struct Activity: Identifiable, Codable { var id: String var name: String var textbook: Textbook? = .none var entries: [Entry] init(_ n: String){ name = n entries = [] id = UUID().uuidString } func avgTime() -> Double? { guard entries.count != 0 else { return .none } return entries .map { $0.getUnitTime() } .mean() } func medianTime() -> Double? { guard entries.count != 0 else { return .none } return entries .map { $0.getUnitTime() } .median() } func formattedTime() -> String? { guard let avgTime = avgTime() else { return .none } return "\(Int(avgTime)) mins" } func formattedRecent() -> String { return "\(Int(entries[entries.count - 1].getUnitTime())) mins" } } // class for app model class Model: ObservableObject { @Published var activities: [Activity] // published stream of activity array @Published var tasks: [Task] // published stream of tasks init(){ self.activities = [] self.tasks = [] } func totalTime() -> Double { tasks .map { ($0.activity.avgTime() ?? 0) * $0.reps.double() } .reduce(0.0, +) } func highestTime() -> Double? { activities .map { ($0.entries.map { $0.getUnitTime() }.max() ?? 0) } .max() } }
true
a62df19a5952a916272eca0fde66be04d790a1a6
Swift
MadBrains/SLApiClientSwift
/SLApiClientSwift/Classes/Swaggers/Models/TupleQuery.swift
UTF-8
2,150
2.8125
3
[]
no_license
// // TupleQuery.swift // // Generated by swagger-codegen // https://github.com/swagger-api/swagger-codegen // import Foundation /** Объект запроса пользовательских кортежей */ open class TupleQuery: Codable { public enum Order: String, Codable { case desc = "DESC" case asc = "ASC" } public enum OrderBy: String, Codable { case createdAt = "created_at" case updatedAt = "updated_at" } /** Количество выбираемых элементов */ public var limit: Int64? /** Смещение от начала выборки */ public var offset: Int64? /** Порядок сортировки по полю указанному в orderBy. Доступны значения DESK и ASC */ public var order: Order? /** По какому полю должна происходить сортировка. Доступны поля created_at и updated_at */ public var orderBy: OrderBy? public init(limit: Int64?, offset: Int64?, order: Order?, orderBy: OrderBy?) { self.limit = limit self.offset = offset self.order = order self.orderBy = orderBy } // Encodable protocol methods public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: String.self) try container.encodeIfPresent(limit, forKey: "limit") try container.encodeIfPresent(offset, forKey: "offset") try container.encodeIfPresent(order, forKey: "order") try container.encodeIfPresent(orderBy, forKey: "orderBy") } // Decodable protocol methods public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: String.self) limit = try container.decodeIfPresent(Int64.self, forKey: "limit") offset = try container.decodeIfPresent(Int64.self, forKey: "offset") order = try container.decodeIfPresent(Order.self, forKey: "order") orderBy = try container.decodeIfPresent(OrderBy.self, forKey: "orderBy") } }
true
40528972396e83dd75655e21b1ac58fcebd64920
Swift
haitran2011/comicListRxSwift
/ComicContainer/VolumeResultsRealm.swift
UTF-8
982
2.515625
3
[]
no_license
// // VolumeResultsRealm.swift // ComicList // // Created by Charles Moncada on 23/11/16. // Copyright © 2016 Guillermo Gonzalez. All rights reserved. // import Foundation import RealmSwift internal final class VolumeResultsRealm: VolumeResultsType { // MARK: - VolumeResultsType var didUpdate: () -> Void = {} var numberOfVolumes: Int { return results.count } func volume(at index: Int) -> Volume { let entryRealm = results[index] return Volume(entryRealm: entryRealm) } // MARK: - Properties private var results: Results<VolumeEntryRealm> private var token = NotificationToken() //MARK: - Initialization init(container: Realm) { results = container.objects(VolumeEntryRealm.self) token = container.addNotificationBlock { [weak self] _, _ in self?.didUpdate() } } deinit { token.stop() } }
true
25423d9907c9f0a42323fedb0fa354968f15c60a
Swift
JasmeetDev/GithubRepoSearch
/Assignment/Assignment/Modules/RepoList/Model/Request/RepoRequest.swift
UTF-8
495
2.53125
3
[]
no_license
// // RepoRequest.swift // Assignment // // Created by Jasmeet Singh on 15/07/21. // import Foundation final class RepoListRequest: BaseRequest { required init(language: String, sortBy sort: String) { let parameters = ["q": "language:\(language)", "sort": sort, "order": "desc"] let basePath = ApiConstants.baseApiPath + "search/repositories" super.init(url: basePath, requestType: .get, parameters: parameters) } }
true
75ec677c41e6a550caee02f293d4d8b1f104dc03
Swift
Joannis/CodeEditor
/CodeEditor/EditorController.swift
UTF-8
9,210
2.671875
3
[]
no_license
// // EditorController..swift // CodeEditor // // Created by Mac Mini on 1/21/17. // Copyright © 2017 Armonia. All rights reserved. // import Cocoa import Foundation class EditorController: NSTextView, NSTextViewDelegate { let spacer = 4 // TODO: get from defaults /* TODO: - if } alone in line, unindent before inserting new line */ typealias IndentInfo = (count: Int, stop: Bool, last: Character) func process(_ range: NSRange) { guard self.string != nil else { return } let content = (self.string! as NSString) let cursor = range.location let index = NSRange(location: cursor, length: 0) let lineRange = content.lineRange(for: index) let lineText = content.substring(with: lineRange) //debugPrint("Line: \(lineText)") // Ending curly bracket? unindent if lineText.trimmingCharacters(in: .whitespacesAndNewlines) == "}" { //alignBracket(lineRange) } } // Stolen from SwiftEditor @ SourceKittenDaemon override func insertNewline(_ sender: Any?) { super.insertNewline(sender) let range = self.selectedRange() let cursor = range.location guard cursor != NSNotFound else { return } guard self.string != nil else { return } let content = self.string! as NSString guard let indent = getPrevLineIndent(range) else { return } let currentLineRange = content.lineRange(for: NSRange(location: cursor, length: 0)) /* let previousLineRange = content.lineRange(for: NSRange.init(location: currentLineRange.location - 1, length: 0)) let previousLine = content.substring(with: previousLineRange) // get the current indent let indentInfo = (count: 0, stop: false, last: Character(" ")) var indent = previousLine.characters.reduce(indentInfo) { (info: IndentInfo, char) -> IndentInfo in guard info.stop == false else { // remember the last non-whitespace char if char == " " || char == "\t" || char == "\n" { return info } else { return (count: info.count, stop: info.stop, last: char) } } switch char { case " " : return (stop: false, count: info.count + 1, last: info.last) case "\t": return (stop: false, count: info.count + spacer, last: info.last) default : return (stop: true , count: info.count, last: info.last) } } */ // find the last-non-whitespace char var spaceCount = indent.count switch indent.last { case "{": spaceCount += spacer case "}": spaceCount -= spacer; if spaceCount < 0 { spaceCount = 0 } default : break } //debugPrint("Last char: ", indent.last, indent.count) // insert the new indent let start = NSRange(location: currentLineRange.location, length: 0) let spaces = String(repeating: " ", count: spaceCount) self.insertText(spaces, replacementRange: start) } @IBAction func moveLineUp(_ sender: NSMenuItem) { self.selectLine(sender) self.cut(sender) self.moveUp(sender) self.moveToBeginningOfLine(sender) self.paste(sender) self.moveUp(sender) } @IBAction func moveLineDown(_ sender: NSMenuItem) { self.selectLine(sender) self.cut(sender) self.moveDown(sender) self.moveToBeginningOfLine(sender) self.paste(sender) self.moveUp(sender) } @IBAction func deleteLine(_ sender: NSMenuItem) { self.selectLine(sender) self.deleteBackward(sender) } @IBAction func eraseToEndOfLine(_ sender: NSMenuItem) { self.moveToEndOfLineAndModifySelection(sender) self.deleteToEndOfLine(sender) } @IBAction func duplicateLine(_ sender: NSMenuItem) { debugPrint("DUPLICATE LINE!") guard self.string != nil else { return } let content = self.string! as NSString self.selectLine(sender) let range = self.selectedRange() let text = content.substring(with: range) let newLineRange = NSRange(location: range.location + range.length, length: 0) //self.smartInsert(for: text, replacing: newLineRange, before: nil, after: nil) self.insertText(text, replacementRange: newLineRange) self.moveToBeginningOfLine(sender) self.moveDown(sender) } @IBAction func indentBlock(_ sender: NSMenuItem) { debugPrint("Indent") } @IBAction func unindentBlock(_ sender: NSMenuItem) { debugPrint("Unindent") } func alignBracket(_ range: NSRange) { debugPrint("Align bracket") /* guard self.string != nil else { return } guard let prevIndent = getPrevLineIndent(range) else { return } guard let thisIndent = getThisLineIndent(range) else { return } var idealIndent = prevIndent.count - spacer if idealIndent < 0 { idealIndent = 0 } debugPrint("Ideal indent: ", idealIndent) let currentLineRange = (self.string! as NSString).lineRange(for: NSRange(location: range.location, length: 0)) if thisIndent.count > idealIndent { debugPrint("Bracket unindented") //self.deleteToBeginOfLine() let start = NSRange(location: currentLineRange.location, length: thisIndent.count) let spaces = String(repeating: " ", count: idealIndent) self.replaceCharacters(in: start, with: spaces) //self.insertText(spaces, replacementRange: start) } else if thisIndent.count < idealIndent { debugPrint("Bracket indented") let start = NSRange(location: currentLineRange.location, length: 0) let spaces = String(repeating: " ", count: (idealIndent - thisIndent.count)) self.insertText(spaces, replacementRange: start) } else { debugPrint("Bracket in position") } */ } // Utils func getPrevLineIndent(_ range: NSRange) -> IndentInfo? { let cursor = range.location guard cursor != NSNotFound else { return nil } guard self.string != nil else { return nil } let content = self.string! as NSString let currentLineRange = content.lineRange(for: NSRange(location: cursor, length: 0)) let previousLineRange = content.lineRange(for: NSRange(location: currentLineRange.location - 1, length: 0)) let previousLineText = content.substring(with: previousLineRange) // get the current indent let indentInfo = (count: 0, stop: false, last: Character(" ")) let indent = previousLineText.characters.reduce(indentInfo) { (info: IndentInfo, char) -> IndentInfo in guard info.stop == false else { // remember the last non-whitespace char if char == " " || char == "\t" || char == "\n" { return info } else { return (count: info.count, stop: info.stop, last: char) } } switch char { case " " : return (stop: false, count: info.count + 1, last: info.last) case "\t": return (stop: false, count: info.count + spacer, last: info.last) default : return (stop: true , count: info.count, last: info.last) } } return indent } func getThisLineIndent(_ range: NSRange) -> IndentInfo? { let cursor = range.location guard cursor != NSNotFound else { return nil } guard self.string != nil else { return nil } let content = self.string! as NSString let currentLineRange = content.lineRange(for: NSRange(location: cursor, length: 0)) let currentLineText = content.substring(with: currentLineRange) // get the current indent let indentInfo = (count: 0, stop: false, last: Character(" ")) let indent = currentLineText.characters.reduce(indentInfo) { (info: IndentInfo, char) -> IndentInfo in guard info.stop == false else { // remember the last non-whitespace char if char == " " || char == "\t" || char == "\n" { return info } else { return (count: info.count, stop: info.stop, last: char) } } switch char { case " " : return (stop: false, count: info.count + 1, last: info.last) case "\t": return (stop: false, count: info.count + spacer, last: info.last) default : return (stop: true , count: info.count, last: info.last) } } return indent } }
true
515453c07af1b655e6d17d8ba37c532131f6cbdd
Swift
MarinRados/WeatherApp
/WeatherApp/LocationViewController.swift
UTF-8
4,158
2.734375
3
[]
no_license
// // LocationViewController.swift // WeatherApp // // Created by Marin Rados on 27/03/2017. // Copyright © 2017 Marin Rados. All rights reserved. // import UIKit class LocationViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, LocationDelegate { @IBOutlet weak var locationTableView: UITableView! var changeLocationDelegate: ChangeLocationDelegate? var locations = [Location]() var locationsDictionary = [[String: Any]]() var trackedLocation: Location? var currentLocation: Location? let locationsKey = "locations" override func viewDidLoad() { super.viewDidLoad() locationTableView.delegate = self locationTableView.dataSource = self } @IBAction func cancelModalView(_ sender: UIBarButtonItem) { if locations.isEmpty && !LocationService.isAuthorized { showAlertWith(message: "You have to enable current location tracking or add at least one location manually to use this app.") } else if trackedLocation == nil { showAlertWith(message: "Please select one of your added locations to see the weather.") } else { if let delegate = self.changeLocationDelegate { delegate.changeAllLocations(locations) } dismiss(animated: true, completion: nil) } } func showAlertWith(message: String) { let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert) let action = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(action) present(alertController, animated: true, completion: nil) } } extension LocationViewController { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return locations.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Location") as! LocationCell let index = indexPath.row if index == 0 && trackedLocation != nil { cell.backgroundColor = UIColor.gray } cell.cityLabel.text = locations[index].city cell.countryLabel.text = locations[index].country cell.selectionStyle = .none return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let index = indexPath.row if index == 0 && trackedLocation != nil { return 0.5 } else { return 60 } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let index = indexPath.row let newLocation = locations[index] if let delegate = self.changeLocationDelegate { delegate.changeAllLocations(locations) delegate.changeLocation(newLocation, atIndex: index) } dismiss(animated: true, completion: nil) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { locations.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .none) if let delegate = self.changeLocationDelegate { delegate.changeLocation(locations[0], atIndex: 0) } locationTableView.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Map" { let destinationViewController = segue.destination as! MapViewController destinationViewController.locationDelegate = self destinationViewController.currentLocation = trackedLocation } } func addLocation(_ location: Location) { locations.append(location) locationTableView.reloadData() } }
true
3e91f7af4057312c771f48210aa23d640f676e23
Swift
roox2/SwiftUI-BlueBottle
/BlueBottle/View/DrinkList/DrinkRow.swift
UTF-8
867
2.875
3
[]
no_license
// // DrinkRow.swift // BlueBottle // // Created by DV-LT-216 on 2020/07/07. // import SwiftUI struct DrinkRow: View { let drink: Drink var body: some View { Image(drink.imageURL) .resizable() .aspectRatio(contentMode: .fill) .overlay( VStack { Text(drink.name) .font(.headline) .padding(.vertical, 4) Text(drink.subtitle) .font(.footnote) .foregroundColor(.secondary) .multilineTextAlignment(.center) .lineSpacing(4) .padding(.vertical, 4) Spacer() } .padding(20) ) } }
true
908b4b6409be6f2027504835d2fbf09de2c0a920
Swift
mfd2144/EksiSozluk
/EksiSozlukKlon/Services/FireBase/FirebaseService-UserProcesses.swift
UTF-8
22,371
2.546875
3
[]
no_license
// // FirebaseService-UserProcesses.swift // EksiSozlukKlon // // Created by Mehmet fatih DOĞAN on 15.04.2021. // import Foundation import Firebase extension FirebaseService{ func createUser(userInfo:UserStruct,handler:@escaping ((String,Error?)->())) { guard let password = userInfo.password else { handler("password is needed",nil) return } userCollection.whereField(user_nick, isEqualTo: userInfo.nick).getDocuments { (querySnapshot, error) in if let error = error{ handler("fetching users document ID error",error) } if querySnapshot?.documents.first == nil{ Auth.auth().createUser(withEmail: userInfo.email, password: password) { authResult, error in if let error = error { handler("adding new user error",error) }else{ let changeRequest = authResult?.user.createProfileChangeRequest() changeRequest?.displayName = userInfo.nick changeRequest?.commitChanges(completion: { (error) in if let _ = error { handler("adding new users information error",error) } guard let currentUser = authResult?.user else {return} self.saveNewUsersInfo(userInfo,currentUser) handler("kullanıcı başarıyla kaydedildi",nil) }) } } }else{ handler("mail adresi kullanılıyor",nil) } } } func saveNewUsersInfo(_ userInfo: UserStruct,_ currentUser:User){ userCollection.whereField(user_ID, isEqualTo: currentUser.uid).getDocuments { (querySnapshot, error) in if let error = error{ print(error.localizedDescription) } if querySnapshot?.documents.first == nil{ let newUser = self.userCollection.document() newUser.setData([user_nick : userInfo.nick, user_email:userInfo.email, create_date: userInfo.createDate, user_birthday: userInfo.birtday as Any, user_gender:userInfo.gender, user_ID :currentUser.uid, user_docID:newUser.documentID, user_total_entity:userInfo.totalEntry, user_total_contact :userInfo.totalContact, ]) { error in self.getUserDocID(){ } guard let _ = error else {return} print("User information couldn't be added \(error!.localizedDescription)") } } } } func userSignIn(_ email:String,_ password:String){ Auth.auth().signIn(withEmail: email, password: password) { (auth, error) in if let error = error { print(error) }else{ self.authStatus?(.login) } } } func credentialLogin(_ credential:AuthCredential){ Auth.auth().signIn(with: credential) { (authDataResult, error) in if let error = error { print("while opening google user,an error ocurred \(error.localizedDescription)") } guard let userInfo = authDataResult?.user else {return} let changeRequest = userInfo.createProfileChangeRequest() changeRequest.displayName = userInfo.displayName?.lowercased() changeRequest.commitChanges(completion: { (error) in if let _ = error { print("while opening google user,an error ocurred \(error!.localizedDescription)") } }) let email = userInfo.email?.lowercased() let nick = userInfo.displayName?.lowercased() let gender = 3 //boşver/empty let user = UserStruct(email: email!, nick: nick!, password: nil, gender: gender, birthday:nil) guard let currentUser = Auth.auth().currentUser else {return} self.saveNewUsersInfo(user,currentUser ) } } func fetchUserInformation(handler:@escaping(UserStruct?,Error?)->() ){ guard let userDocID = userDocID else {handler(nil,nil);return} userCollection.document(userDocID).getDocument { docSnapshot, error in if let error = error { handler(nil,error) }else{ guard let userSnapshot = docSnapshot?.data() else { handler(nil,nil);return } let user = UserStruct.init(userSnapshot) handler(user,nil) } } } func logout(){ do { try Auth.auth().signOut() }catch{ print("logut error \(error.localizedDescription)") return } self.authStatus?(.logout) } func getUserDocID(handler:@escaping()->()){ user = Auth.auth().currentUser guard let uid = user?.uid else { return } userCollection.whereField(user_ID, isEqualTo: uid).getDocuments { (querySnapshot, error) in if let error = error{ print("fetching user document ID error \(error.localizedDescription)") return } guard let docID = querySnapshot?.documents.first?.data()[user_docID] as? String else {return} let singleton = AppSingleton.shared singleton.userDocID = docID handler() } } func addFollowedEntryToUser(entryID:String){ guard let docID = userDocID else { return } self.userCollection.document(docID).collection(followedPath).addDocument(data: [entry_ID:entryID]){ error in if let error = error { print("adding followed list error \(error.localizedDescription)") } } } func deleteFollowedEntryToUser(entryID:String){ guard let docID = userDocID else {return} self.userCollection.document(docID) .collection(followedPath) .whereField(entry_ID, isEqualTo: entryID) .getDocuments(completion: { (querySnapshot, error) in guard let followID = querySnapshot?.documents.first?.documentID else {return} self.userCollection.document(docID).collection(followedPath).document(followID).delete { (error) in if let error = error { print("followed list delete error \(error.localizedDescription)") } } }) } func deleteEntryLikeToUser(entryID:String){ guard let docID = userDocID else {return} self.userCollection.document(docID) .collection(likesPath) .whereField(entry_ID, isEqualTo: entryID) .getDocuments(completion: { (querySnapshot, error) in guard let likeID = querySnapshot?.documents.first?.documentID else {return} self.userCollection.document(docID).collection(likesPath).document(likeID).delete { (error) in if let error = error { print(" like erase error \(error.localizedDescription)") } } }) } func addLikedEntryToUser(entryID:String){ guard let docID = userDocID else { return } self.userCollection.document(docID).collection(likesPath).addDocument(data: [entry_ID:entryID]){ error in if let error = error { print("adding liked list error \(error.localizedDescription)") } } } // if user demand nothing this function return favorite entries list otherwise like entries list func fetchUserDemandedList(_ likeList:Bool? = nil,completion:@escaping ([String],Error?)->()){ var demandedEntryList = [String]() guard let docID = userDocID else { completion(demandedEntryList,nil); return } var query:Query? if likeList != nil{ query = userCollection.document(docID).collection(likesPath) }else{ query = userCollection.document(docID).collection(followedPath) } query!.getDocuments { (querySnapshot, error) in if let error = error { completion(demandedEntryList,error) }else{ guard let docs = querySnapshot?.documents else { completion(demandedEntryList,nil); return } for doc in docs{ demandedEntryList.append(doc[entry_ID] as? String ?? "") } completion(demandedEntryList,nil) } } } func addUserFavoriteList(_ commentID:String,entryID:String){ guard let docID = userDocID else { return } self.userCollection .document(docID) .collection(favoritesPath) .addDocument(data: [entry_ID:entryID, comment_ID:commentID]){ error in if let error = error { print("adding favorite from list error \(error.localizedDescription)") } } } func removeUserFavoriteList(_ commentID:String){ guard let docID = userDocID else {return} self.userCollection.document(docID) .collection(favoritesPath) .whereField(comment_ID, isEqualTo: commentID) .getDocuments(completion: { (querySnapshot, error) in guard let favoriteID = querySnapshot?.documents.first?.documentID else {return} self.userCollection.document(docID).collection(favoritesPath).document(favoriteID).delete { (error) in if let error = error { print("deleting favorite from list error \(error.localizedDescription)") } } }) } func fetchUserFavoriteList(completion:@escaping ([UserFavoriteStruct],Error?)->()){ var followedFavoriteList = [UserFavoriteStruct]() guard let docID = userDocID else { completion(followedFavoriteList,nil); return } userCollection.document(docID).collection(favoritesPath).getDocuments { (querySnapshot, error) in if let error = error { completion(followedFavoriteList,error) }else{ guard let docs = querySnapshot?.documents else { completion(followedFavoriteList,nil); return } for doc in docs{ followedFavoriteList.append(UserFavoriteStruct.init(doc)) } completion(followedFavoriteList,nil) } } } func editUserEntryValue(value:Int,handler:@escaping ((Error?)->())){ let userRef = userCollection.document(userDocID!) db.runTransaction { (transaction, errorPoint) -> Any? in var userDoc: DocumentSnapshot! do{ userDoc = try transaction.getDocument(userRef) }catch{ handler(error) } guard userDoc != nil, let oldValue = userDoc.data()?[user_total_entity] as? Int else {return nil} transaction.updateData([user_total_entity:oldValue + value], forDocument:userRef ) return nil } completion: { (_, error) in if let _ = error { handler(error!) } } } func deleteUser(completionHandler:@escaping (Error?)->()){ guard let _ = user, let _ = userDocID else { return } deleteUserSubFiles(subFileCollectionName: favoritesPath) {[self] (error) in if let error = error{ completionHandler(error) }else{ deleteUserSubFiles(subFileCollectionName: followedPath) { (error) in if let error = error{ completionHandler(error) }else{ deleteUserSubFiles(subFileCollectionName: contactsPath) { (error) in if let error = error{ completionHandler(error) }else{ userCollection.document(userDocID!).delete { (error) in if let error = error{ completionHandler(error) }else{ user?.delete(completion: { (error) in if let error = error{ completionHandler(error) } }) } } } } } } } } } private func deleteUserSubFiles(subFileCollectionName:String,completionHandler:@escaping (Error?)->()){ let subUserRef = userCollection.document(userDocID!).collection(subFileCollectionName) subUserRef.limit(to: 50).getDocuments { (querySnapshot, error) in guard let querySnapshot = querySnapshot else{ completionHandler(error) return } guard querySnapshot.count>0 else { completionHandler(nil); return } let batch = subUserRef.firestore.batch() querySnapshot.documents.forEach { batch.deleteDocument($0.reference) } batch.commit { (error) in if let error = error { completionHandler(error) }else{ self.deleteUserSubFiles(subFileCollectionName: subFileCollectionName, completionHandler: completionHandler) } } } } func searchForUser(keyWord:String,handler:@escaping (([BasicUserStruct],Error?)->())){ var users = [BasicUserStruct]() userCollection.whereField(user_nick, isGreaterThanOrEqualTo: keyWord).whereField(user_nick, isNotEqualTo: user?.displayName ?? "").getDocuments { (querys, error) in if let error = error{ handler(users,error) }else{ users = BasicUserStruct.getUsersForSeach(querys) handler(users,nil) } } } func checkUserInList(otherUserId:String,handler:@escaping(Bool,Error?)->()){ guard let userDocID = userDocID else {handler(false,nil);return} let userFollowedRef = userCollection.document(userDocID).collection(followedUserPath).whereField(followed_user_id, isEqualTo: otherUserId) userFollowedRef.getDocuments { querySnapshot,error in if let error = error { handler(false,error) }else{ if querySnapshot?.documents.first?.data() != nil{ handler(true,nil) }else{ handler(false,nil) } } } } func addUserToFollowList(otherUserId:String,handler:@escaping(Error?)->()){ guard let userDocID = userDocID else {handler(nil);return} let userRef = userCollection.document(userDocID) db.runTransaction { transaction, _ in var userDoc:DocumentSnapshot? do{ userDoc = try transaction.getDocument(userRef) }catch let error{ handler(error) } guard let contactNumber = userDoc?.data()?[user_total_contact] as? Int else{handler(nil);return nil} transaction.updateData([user_total_contact:contactNumber+1], forDocument: userRef) let userFollowedRef = userRef.collection(followedUserPath).document() transaction.setData([followed_user_id : otherUserId, "follow_date":FieldValue.serverTimestamp(), "pathID":userFollowedRef.documentID], forDocument: userFollowedRef) return nil } completion: { _, error in handler(error) } } func deleteUserFromFollowList(otherUserId:String,handler:@escaping(Error?)->()){ guard let userDocID = userDocID else {handler(nil);return} let userRef = userCollection.document(userDocID) userRef.collection(followedUserPath).whereField(followed_user_id,isEqualTo: otherUserId).getDocuments { querySnapshot, error in if let error = error { handler(error) }else{ guard let followedUserDocID = querySnapshot?.documents.first?.documentID else { return } self.db.runTransaction { transaction, _ in var userDoc:DocumentSnapshot? do{ userDoc = try transaction.getDocument(userRef) }catch let error{ handler(error) } guard let contactNumber = userDoc?.data()?[user_total_contact] as? Int else{handler(nil);return nil} transaction.updateData([user_total_contact:contactNumber-1], forDocument: userRef) let willDeletedRef = userRef.collection(followedUserPath).document(followedUserDocID) transaction.deleteDocument(willDeletedRef) return nil } completion: { _, error in handler(error) } } } } func resetUserLastUpdateDate(handler:@escaping (Error?)->()){ guard let userDocId = userDocID else {return} let ref = userCollection.document(userDocId).collection(followedUserPath) ref.getDocuments { querySnapshot, error in if let error = error { handler(error) }else{ guard let followedUserSnapshot = querySnapshot else { return } let batch = ref.firestore.batch() followedUserSnapshot.documents.forEach {batch.updateData([followed_date:FieldValue.serverTimestamp()], forDocument: $0.reference)} batch.commit { error in if let error = error{ handler(error) }else{ handler(nil) } } } } } func sendPasswordReset(email:String,handler:@escaping (Error?)->()){ Auth.auth().sendPasswordReset(withEmail: email) { error in if let error = error{ handler(error) }else{ handler(nil) } } } func changePassword(newPassword:String,handler:@escaping (Error?)->()) { print("qqq") user?.updatePassword(to: newPassword) { error in if let error = error{ handler(error) }else{ handler(nil) } } } func resetMailAdress(newMail:String,handler:@escaping (Error?)->()){ user?.updateEmail(to: newMail) {error in if let error = error{ handler(error) }else{ self.updateUserInformation(nick: nil, userBirtday: nil, gender: nil, email: newMail) { error in if let error = error { handler(error) }else{ handler(nil) } } } } } func updateUserInformation(nick:String?,userBirtday:Date?,gender:Int?,email:String?,handler:@escaping (Error?)->()){ guard let userDocID=userDocID else{return} let ref = userCollection.document(userDocID) db.runTransaction { transaction, _ in var userDoc:DocumentSnapshot! do{ userDoc = try transaction.getDocument(ref) }catch let error{ handler(error) return nil } guard let data = userDoc.data(),let userInfo = UserStruct(data) else {return nil} transaction.updateData([user_nick : nick ?? userInfo.nick, user_birthday: userBirtday ?? userInfo.birtday as Any, user_gender: gender ?? userInfo.gender, user_email:email ?? userInfo.email], forDocument: ref) handler(nil) return nil } completion: { _, error in if let error = error{ handler(error) }else{ handler(nil) } } } }
true
e5891e5320c26cb18248afe964f56ec6e80d42e5
Swift
JerryHaaser/RoundTimer
/RoundTimer/SetTimerViewController.swift
UTF-8
2,775
2.765625
3
[]
no_license
// // SetTimerViewController.swift // RoundTimer // // Created by Jerry haaser on 7/22/20. // Copyright © 2020 Jerry haaser. All rights reserved. // import UIKit protocol DatePickerDelegate { func destinationDateWasChosen(date: Date) } class SetTimerViewController: UIViewController { @IBOutlet weak var setRoundTimePicker: UIPickerView! @IBOutlet weak var setRestTimerPicker: UIPickerView! var delegate: DatePickerDelegate? var dateFormatter = DateFormatter() var minutes:Int = 0 var seconds:Int = 0 //var roundDateFormatter = dateFormatter.dateFormat = "HH:mm" override func viewDidLoad() { super.viewDidLoad() //setRoundPicker.delegate = self setViews() } func setViews() { setRoundTimePicker.delegate = self setRestTimerPicker.delegate = self dateFormatter.dateFormat = "mm:ss" //setRoundPicker.datePickerStyle(dateFormatter) } @IBAction func setButtonPressed(_ sender: UIButton) { // let date = setRoundTimePicker.date // delegate?.destinationDateWasChosen(date: date) dismiss(animated: true, completion: nil) _ = navigationController?.popToRootViewController(animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension SetTimerViewController:UIPickerViewDelegate,UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch component { case 0: return 60 case 1: return 60 default: return 0 } } func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return pickerView.frame.size.width/2 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch component { case 0: return "\(row) Minute" case 1: return "\(row) Second" default: return "" } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch component { case 0: minutes = row case 1: seconds = row default: break; } } }
true
c1ab47332283e0938c46005a2ec31971da05a7ac
Swift
jmkiley/swift-extensions-lab-ios-0616
/Extensions/Extensions.swift
UTF-8
1,989
3.671875
4
[]
no_license
// // Extensions.swift // Extensions // // Created by Jordan Kiley on 7/15/16. // Copyright © 2016 Flatiron School. All rights reserved. // import Foundation extension String { func whisper(sentence : String) -> String { return sentence.lowercaseString } func shout(sentence : String) -> String { return sentence.uppercaseString } var pigLatin : String { switch self.characters.count <= 1 { case true : return self default : var esultray = String() // doesn't take punctuation into account let arrayOfWords = self.componentsSeparatedByString(" ") for word in arrayOfWords { let firstCharacter = word[word.startIndex] var wordToChange = word wordToChange.removeAtIndex(wordToChange.startIndex) wordToChange.stringByAppendingString("\(firstCharacter)ay") esultray = esultray + " " + wordToChange } return esultray } } var points : Int { var totalPoints = 0 if self.characters.count == 0 { return 0 } for letter in self.characters { switch letter { case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", " ", ".", ",", "!", "?", "\"", "'" : totalPoints += 0 case "a", "e", "i", "o", "u" : totalPoints += 2 default : totalPoints += 1 } } return totalPoints } } extension Int { func half(input : Int) -> Int { return input / 2 } func isDivisibleBy(input : Int, divisor : Int) -> Bool { switch input % divisor { case 0 : return true default : return false } } var squared : Int { return self * self } var halved : Int { return self / 2 } }
true
602142d3c78dffbb122583d375c0703897d8db0a
Swift
PanRagon/V-rvarsler
/Værvarsler/Controller/MapWeatherView.swift
UTF-8
947
2.953125
3
[]
no_license
// // MapWeatherView.swift // Værvarsler // // Created by Kandidatnummer 10042 on 29/11/2020. // Copyright © 2020 Kandidatnummer 10042. All rights reserved. // /* import Foundation import UIKit class MapWeatherView: UIView, WeatherAPIDelegate { func didUpdateWeather(_ weatherAPI: WeatherAPI, weather: WeatherModel) { print(weather) } func didFailToUpdate(_ error: Error) { print(error) } //@IBOutlet weak var lonLabel: UILabel! @IBOutlet weak var latLabel: UILabel! @IBOutlet weak var symbolImage: UIImageView! let weatherAPI = WeatherAPI() func weatherAPI?.delegate = self var lat: Float? = nil var lon: Float? = nil func didU weatherManager.delegate = self func updateLocation(lat: Float, lon: Float) { print("new location..") self.lat = lat self.lon = lon weatherAPI.fetchWeather(lat: lat, lon: lon) } } */
true
40f82c74f8021b3c87b8aae661bfd6b4c649f740
Swift
eliperkins/Graphaello
/Sources/Graphaello/Processing/Pipeline/Component/4. Resolution/SubResolvers/ResolvedValueCollector.swift
UTF-8
382
2.578125
3
[ "MIT" ]
permissive
// // ValueExtractor.swift // Graphaello // // Created by Mathias Quintero on 09.12.19. // Copyright © 2019 Mathias Quintero. All rights reserved. // import Foundation protocol ResolvedValueCollector { associatedtype Resolved associatedtype Parent associatedtype Collected func collect(from value: Resolved, in parent: Parent) throws -> StructResolution.Result<Collected> }
true
e9f19fda82940420526fd3cf71e803b461c853c3
Swift
hathway/SwiftyMavenlink
/Sources/WorkspaceGroup.swift
UTF-8
2,105
2.609375
3
[]
no_license
// // WorkspaceGroup.swift // SwiftyMavenlink // // Created by Mike Maxwell on 6/28/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import ObjectMapper public struct WorkspaceGroup: Mappable, MavenlinkResource { public fileprivate(set) var id: Int? public fileprivate(set) var name: String? public fileprivate(set) var company: Bool? public fileprivate(set) var created_at: Date? public fileprivate(set) var updated_at: Date? public fileprivate(set) var workspace_ids: [Int]? public init?(map: Map) { } public static var resourceName: String { get { return "workspace_groups" } } public static var searchable: Bool { get { return false } } mutating public func mapping(map: Map) { id <- (map["id"], IntFormatter) name <- map["name"] company <- map["company"] created_at <- (map["created_at"], LongDateFormatter) updated_at <- (map["updated_at"], LongDateFormatter) workspace_ids <- (map["workspace_ids"], IntArrayFormatter) } } extension WorkspaceGroup { public enum Params: RESTApiParams { /// Include the workspace IDs contained in each group in the response. case includeWorkspaces public var paramName: String { get { switch(self) { case .includeWorkspaces: return "include" } } } public var queryParam: MavenlinkQueryParams { get { let value: AnyObject switch(self) { case .includeWorkspaces: value = "workspaces" as AnyObject } return [self.paramName: value] } } } } open class WorkspaceGroupService: MavenlinkResourceService<WorkspaceGroup> { // override public class func get(params: MavenlinkQueryParams? = WorkspaceGroup.Params.IncludeWorkspaces.queryParam) -> PagedResultSet<Resource> { // return PagedResultSet<Resource>(resource: Resource.resourceName, params: params) // } }
true
5f4ea66344dd95582653bf7e9f9ad10e54ca19be
Swift
CamMcLeod/Mastery
/Development Files/Mastery_iOS/Mastery_iOS/Create New Goal/GoalDescriptionTableViewCell.swift
UTF-8
1,575
2.703125
3
[]
no_license
// // GoalDescriptionTableViewCell.swift // Mastery_iOS // // Created by Ekam Singh Dhaliwal on 2019-07-28. // Copyright © 2019 Marina Mona June McPeak. All rights reserved. // import UIKit protocol GoalDescriptionCellDelegate { func getValueForDescription(theDescription: String) } class GoalDescriptionTableViewCell: UITableViewCell, UITextViewDelegate { var delegate: GoalDescriptionCellDelegate? @IBOutlet weak var descriptionTitle: UILabel! @IBOutlet weak var goalDescription: UITextView! override func awakeFromNib() { super.awakeFromNib() goalDescription.delegate = self } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { textView.resignFirstResponder() return false } guard let goalName = goalDescription.text, let rangeOfTextToReplace = Range(range, in: goalName) else { return false } let substringToReplace = goalName[rangeOfTextToReplace] let count = goalName.count - substringToReplace.count + text.count return count <= 200 } func textViewDidChange(_ textView: UITextView) { self.delegate?.getValueForDescription(theDescription: goalDescription.text) } func textViewDidEndEditing(_ textView: UITextView) { } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
true
438ab9b36c0eed30b6c962be7e8ac42339fa53b3
Swift
anday013/timeprod
/TimePad/Core/Screens/Views/TasksScreenView.swift
UTF-8
2,209
3
3
[]
no_license
// // Tasks.swift // TimePad // // Created by Anday on 07.07.21. // import SwiftUI struct TasksScreenView: View { @EnvironmentObject var tasksVM: TasksEnvironmentViewModel var body: some View { VStack { activeTaskBox HStack { Text("Today") .font(.title) .bold() Spacer() } .padding(.top, 32) .padding(.bottom, 16) taskList } .sheet(item: $tasksVM.selectedTask) { task in TaskSheetView(task: task) .environmentObject(tasksVM.self) } .padding() } func setSelectedTask(task: Task?) { tasksVM.selectedTask = task } } struct Tasks_Previews: PreviewProvider { static var previews: some View { Group { NavigationView { TasksScreenView() .navigationTitle("Task") } // NavigationView { // TasksScreenView() // .preferredColorScheme(.dark) // .navigationTitle("Task") // } } .environmentObject(TasksEnvironmentViewModel()) } } extension TasksScreenView { private var activeTaskBox: some View { Button(action: { setSelectedTask(task: tasksVM.activeTask) }) { CurrentTaskView(task: tasksVM.activeTask) .foregroundColor(.primary) } } private var taskList: some View { ScrollView(showsIndicators: false) { LazyVStack { ForEach(tasksVM.todaysTasks) { task in Button(action: { if !isTaskCompleted(task) { setSelectedTask(task: task) } }) { TaskView(task: task) .foregroundColor(.primary) } } } } } }
true
0d2c2689f45a60c5a0ad5185d2426f921251404f
Swift
Lukas-26/Shops
/Asia shops/AddDayTimeView.swift
UTF-8
3,399
2.640625
3
[]
no_license
// // File.swift // Asia shops // // Created by Lukáš Pechač on 15.02.16. // Copyright © 2016 Lukáš Pechač. All rights reserved. // import Foundation import UIKit import SnapKit class AddDayTimeView:UIView { weak var Day:UILabel? weak var FromTimeLabel:UILabel? weak var ToTimeLabel:UILabel? weak var AddFromTime:UIButton? weak var AddToTime:UIButton? weak var DeleteDay:ButtonWithNSObject? override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(patternImage: UIImage(named: "timeBackground")!) let timeFrom=UILabel() timeFrom.font = timeFrom.font.fontWithSize(14) timeFrom.text="--:--" self.addSubview(timeFrom) timeFrom.snp_makeConstraints { (make) in make.top.equalTo(42) make.right.equalTo(-35) } let odLabel=UILabel() odLabel.text="Od:" odLabel.font = odLabel.font.fontWithSize(14) self.addSubview(odLabel) odLabel.snp_makeConstraints { (make) in make.top.equalTo(42) make.left.equalTo(3) } let timeTo=UILabel() timeTo.text="--:--" timeTo.font = timeTo.font.fontWithSize(14) self.addSubview(timeTo) timeTo.snp_makeConstraints { (make) in make.top.equalTo(77) make.right.equalTo(-35) } let doLabel=UILabel() doLabel.font = doLabel.font.fontWithSize(14) doLabel.text="Do:" self.addSubview(doLabel) doLabel.snp_makeConstraints { (make) in make.top.equalTo(77) make.left.equalTo(3) } let dayName=UILabel() dayName.textAlignment = .Center; self.addSubview(dayName) dayName.snp_makeConstraints { (make) in make.left.equalTo(0) make.top.equalTo(10) make.width.equalTo(self.snp_width) } let addFrom=UIButton() addFrom.setImage(UIImage(named: "addIcon"), forState: .Normal) addFrom.imageView?.contentMode = UIViewContentMode.Center self.addSubview(addFrom) addFrom.snp_makeConstraints { (make) in make.top.equalTo(36) make.right.equalTo(0) make.height.width.equalTo(30) } let addTo=UIButton() addTo.setImage(UIImage(named: "addIcon"), forState: .Normal) addTo.imageView?.contentMode = UIViewContentMode.Center self.addSubview(addTo) addTo.snp_makeConstraints { (make) in make.top.equalTo(71) make.right.equalTo(0) make.height.width.equalTo(30) } let deleteDay=ButtonWithNSObject() deleteDay.setImage(UIImage(named: "trash"), forState: .Normal) deleteDay.imageView?.contentMode = UIViewContentMode.Center; self.addSubview(deleteDay) deleteDay.snp_makeConstraints { (make) in make.left.right.bottom.equalTo(0) make.height.equalTo(20) } self.Day=dayName self.FromTimeLabel=timeFrom self.ToTimeLabel=timeTo self.AddFromTime=addFrom self.AddToTime=addTo self.DeleteDay=deleteDay } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
9585af917ecf7ca0a19c2bb9338b56a2044cd250
Swift
kennycaiguo/iOS-Game-Development-Cookbook-2nd
/Chapter02/02009/RotatingImage/RotatingImage/ViewController.swift
UTF-8
1,101
3.046875
3
[ "MIT" ]
permissive
// // ViewController.swift // RotatingImage // // Created by CoderDream on 2019/7/15. // Copyright © 2019 CoderDream. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var transformedView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // BEGIN rotate self.transformedView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2)) // END rotate // BEGIN transform var transform = CGAffineTransform.identity // <1> 从默认的变换 identity transform 开始 transform = transform.translatedBy(x: 50, y: 0) // <2> 向右平移 50 像素 transform = transform.rotated(by: CGFloat(Double.pi / 2)) // <3> 顺时针旋转 90 度 transform = transform.scaledBy(x: 0.5, y: 2) // <4> x 轴缩放 50%, y 轴缩放 200% self.transformedView.transform = transform // <5> 应用变换 // END transform } }
true
f8b5bca2ef48387af05f2d6e49e4a35cb3add7b1
Swift
SebasChoo04/pointsfiesta
/SST House Points App/SignInViewController.swift
UTF-8
2,594
2.578125
3
[]
no_license
// // SignInViewController.swift // SST House Points App // // Created by Sebastian Choo on 6/8/18. // Copyright © 2018 SebastianChoo.Co. All rights reserved. // import UIKit import GoogleSignIn import FirebaseAuth class SignInViewController: UIViewController, GIDSignInUIDelegate, GIDSignInDelegate { @IBOutlet var googleSignInButton: GIDSignInButton! func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?) { if let error = error { print("\(error.localizedDescription)") } else { // Perform any operations on signed in user here. print("Successful!") UserDefaults.standard.set(user.userID, forKey: "userID") // For client-side use only! UserDefaults.standard.set(user.authentication.idToken, forKey: "authenticationToken") UserDefaults.standard.set(user.profile.name, forKey: "name") UserDefaults.standard.set(user.profile.email, forKey: "email") // ... guard let authentication = user.authentication else { return } let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken) Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in if let error = error { print("\(error.localizedDescription)") return } self.performSegue(withIdentifier: "signInDone", sender: self) // User is signed in // ... } } } @IBAction func googleButtonTapped(_ sender: Any) { GIDSignIn.sharedInstance().signIn() performSegue(withIdentifier: "signInDone", sender: sender) print("Test") } override func viewDidLoad() { super.viewDidLoad() GIDSignIn.sharedInstance().uiDelegate = self // Do any additional setup after loading the view. GIDSignIn.sharedInstance().clientID = "803179619735-g2pqb4rvenqpj9vrqsj98hqib19ioh0m.apps.googleusercontent.com" GIDSignIn.sharedInstance().delegate = self } // ... /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
true
bd421ea69c6e40fd50d6182deb6a25ddcff4432e
Swift
Lax/Learn-iOS-Swift-by-Examples
/DemoBots/DemoBots/Entities/TaskBot.swift
UTF-8
23,832
3
3
[ "Apache-2.0" ]
permissive
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A `GKEntity` subclass that provides a base class for `GroundBot` and `FlyingBot`. This subclass allows for convenient construction of the common AI-related components shared by the game's antagonists. */ import SpriteKit import GameplayKit class TaskBot: GKEntity, ContactNotifiableType, GKAgentDelegate, RulesComponentDelegate { // MARK: Nested types /// Encapsulates a `TaskBot`'s current mandate, i.e. the aim that the `TaskBot` is setting out to achieve. enum TaskBotMandate { // Hunt another agent (either a `PlayerBot` or a "good" `TaskBot`). case huntAgent(GKAgent2D) // Follow the `TaskBot`'s "good" patrol path. case followGoodPatrolPath // Follow the `TaskBot`'s "bad" patrol path. case followBadPatrolPath // Return to a given position on a patrol path. case returnToPositionOnPath(float2) } // MARK: Properties /// Indicates whether or not the `TaskBot` is currently in a "good" (benevolent) or "bad" (adversarial) state. var isGood: Bool { didSet { // Do nothing if the value hasn't changed. guard isGood != oldValue else { return } // Get the components we will need to access in response to the value changing. guard let intelligenceComponent = component(ofType: IntelligenceComponent.self) else { fatalError("TaskBots must have an intelligence component.") } guard let animationComponent = component(ofType: AnimationComponent.self) else { fatalError("TaskBots must have an animation component.") } guard let chargeComponent = component(ofType: ChargeComponent.self) else { fatalError("TaskBots must have a charge component.") } // Update the `TaskBot`'s speed and acceleration to suit the new value of `isGood`. agent.maxSpeed = GameplayConfiguration.TaskBot.maximumSpeedForIsGood(isGood: isGood) agent.maxAcceleration = GameplayConfiguration.TaskBot.maximumAcceleration if isGood { /* The `TaskBot` just turned from "bad" to "good". Set its mandate to `.ReturnToPositionOnPath` for the closest point on its "good" patrol path. */ let closestPointOnGoodPath = closestPointOnPath(path: goodPathPoints) mandate = .returnToPositionOnPath(float2(closestPointOnGoodPath)) if self is FlyingBot { // Enter the `FlyingBotBlastState` so it performs a curing blast. intelligenceComponent.stateMachine.enter(FlyingBotBlastState.self) } else { // Make sure the `TaskBot`s state is `TaskBotAgentControlledState` so that it follows its mandate. intelligenceComponent.stateMachine.enter(TaskBotAgentControlledState.self) } // Update the animation component to use the "good" animations. animationComponent.animations = goodAnimations // Set the appropriate amount of charge. chargeComponent.charge = 0.0 } else { /* The `TaskBot` just turned from "good" to "bad". Default to a `.ReturnToPositionOnPath` mandate for the closest point on its "bad" patrol path. This may be overridden by a `.HuntAgent` mandate when the `TaskBot`'s rules are next evaluated. */ let closestPointOnBadPath = closestPointOnPath(path: badPathPoints) mandate = .returnToPositionOnPath(float2(closestPointOnBadPath)) // Update the animation component to use the "bad" animations. animationComponent.animations = badAnimations // Set the appropriate amount of charge. chargeComponent.charge = chargeComponent.maximumCharge // Enter the "zapped" state. intelligenceComponent.stateMachine.enter(TaskBotZappedState.self) } } } /// The aim that the `TaskBot` is currently trying to achieve. var mandate: TaskBotMandate /// The points for the path that the `TaskBot` should patrol when "good" and not hunting. var goodPathPoints: [CGPoint] /// The points for the path that the `TaskBot` should patrol when "bad" and not hunting. var badPathPoints: [CGPoint] /// The appropriate `GKBehavior` for the `TaskBot`, based on its current `mandate`. var behaviorForCurrentMandate: GKBehavior { // Return an empty behavior if this `TaskBot` is not yet in a `LevelScene`. guard let levelScene = component(ofType: RenderComponent.self)?.node.scene as? LevelScene else { return GKBehavior() } let agentBehavior: GKBehavior let radius: Float // `debugPathPoints`, `debugPathShouldCycle`, and `debugColor` are only used when debug drawing is enabled. let debugPathPoints: [CGPoint] var debugPathShouldCycle = false let debugColor: SKColor switch mandate { case .followGoodPatrolPath, .followBadPatrolPath: let pathPoints = isGood ? goodPathPoints : badPathPoints radius = GameplayConfiguration.TaskBot.patrolPathRadius agentBehavior = TaskBotBehavior.behavior(forAgent: agent, patrollingPathWithPoints: pathPoints, pathRadius: radius, inScene: levelScene) debugPathPoints = pathPoints // Patrol paths are always closed loops, so the debug drawing of the path should cycle back round to the start. debugPathShouldCycle = true debugColor = isGood ? SKColor.green : SKColor.purple case let .huntAgent(targetAgent): radius = GameplayConfiguration.TaskBot.huntPathRadius (agentBehavior, debugPathPoints) = TaskBotBehavior.behaviorAndPathPoints(forAgent: agent, huntingAgent: targetAgent, pathRadius: radius, inScene: levelScene) debugColor = SKColor.red case let .returnToPositionOnPath(position): radius = GameplayConfiguration.TaskBot.returnToPatrolPathRadius (agentBehavior, debugPathPoints) = TaskBotBehavior.behaviorAndPathPoints(forAgent: agent, returningToPoint: position, pathRadius: radius, inScene: levelScene) debugColor = SKColor.yellow } if levelScene.debugDrawingEnabled { drawDebugPath(path: debugPathPoints, cycle: debugPathShouldCycle, color: debugColor, radius: radius) } else { debugNode.removeAllChildren() } return agentBehavior } /// The animations to use when a `TaskBot` is in its "good" state. var goodAnimations: [AnimationState: [CompassDirection: Animation]] { fatalError("goodAnimations must be overridden in subclasses") } /// The animations to use when a `TaskBot` is in its "bad" state. var badAnimations: [AnimationState: [CompassDirection: Animation]] { fatalError("badAnimations must be overridden in subclasses") } /// The `GKAgent` associated with this `TaskBot`. var agent: TaskBotAgent { guard let agent = component(ofType: TaskBotAgent.self) else { fatalError("A TaskBot entity must have a GKAgent2D component.") } return agent } /// The `RenderComponent` associated with this `TaskBot`. var renderComponent: RenderComponent { guard let renderComponent = component(ofType: RenderComponent.self) else { fatalError("A TaskBot must have an RenderComponent.") } return renderComponent } /// Used to determine the location on the `TaskBot` where contact with the debug beam occurs. var beamTargetOffset = CGPoint.zero /// Used to hang shapes representing the current path for the `TaskBot`. var debugNode = SKNode() // MARK: Initializers required init(isGood: Bool, goodPathPoints: [CGPoint], badPathPoints: [CGPoint]) { // Whether or not the `TaskBot` is "good" when first created. self.isGood = isGood // The locations of the points that define the `TaskBot`'s "good" and "bad" patrol paths. self.goodPathPoints = goodPathPoints self.badPathPoints = badPathPoints /* A `TaskBot`'s initial mandate is always to patrol. Because a `TaskBot` is positioned at the appropriate path's start point when the level is created, there is no need for it to pathfind to the start of its path, and it can patrol immediately. */ mandate = isGood ? .followGoodPatrolPath : .followBadPatrolPath super.init() // Create a `TaskBotAgent` to represent this `TaskBot` in a steering physics simulation. let agent = TaskBotAgent() agent.delegate = self // Configure the agent's characteristics for the steering physics simulation. agent.maxSpeed = GameplayConfiguration.TaskBot.maximumSpeedForIsGood(isGood: isGood) agent.maxAcceleration = GameplayConfiguration.TaskBot.maximumAcceleration agent.mass = GameplayConfiguration.TaskBot.agentMass agent.radius = GameplayConfiguration.TaskBot.agentRadius agent.behavior = GKBehavior() /* `GKAgent2D` is a `GKComponent` subclass. Add it to the `TaskBot` entity's list of components so that it will be updated on each component update cycle. */ addComponent(agent) // Create and add a rules component to encapsulate all of the rules that can affect a `TaskBot`'s behavior. let rulesComponent = RulesComponent(rules: [ PlayerBotNearRule(), PlayerBotMediumRule(), PlayerBotFarRule(), GoodTaskBotNearRule(), GoodTaskBotMediumRule(), GoodTaskBotFarRule(), BadTaskBotPercentageLowRule(), BadTaskBotPercentageMediumRule(), BadTaskBotPercentageHighRule() ]) addComponent(rulesComponent) rulesComponent.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: GKAgentDelegate func agentWillUpdate(_: GKAgent) { /* `GKAgent`s do not operate in the SpriteKit physics world, and are not affected by SpriteKit physics collisions. Because of this, the agent's position and rotation in the scene may have values that are not valid in the SpriteKit physics simulation. For example, the agent may have moved into a position that is not allowed by interactions between the `TaskBot`'s physics body and the level's scenery. To counter this, set the agent's position and rotation to match the `TaskBot` position and orientation before the agent calculates its steering physics update. */ updateAgentPositionToMatchNodePosition() updateAgentRotationToMatchTaskBotOrientation() } func agentDidUpdate(_: GKAgent) { guard let intelligenceComponent = component(ofType: IntelligenceComponent.self) else { return } guard let orientationComponent = component(ofType: OrientationComponent.self) else { return } if intelligenceComponent.stateMachine.currentState is TaskBotAgentControlledState { // `TaskBot`s always move in a forward direction when they are agent-controlled. component(ofType: AnimationComponent.self)?.requestedAnimationState = .walkForward // When the `TaskBot` is agent-controlled, the node position follows the agent position. updateNodePositionToMatchAgentPosition() // If the agent has a velocity, the `zRotation` should be the arctangent of the agent's velocity. Otherwise use the agent's `rotation` value. let newRotation: Float if agent.velocity.x > 0.0 || agent.velocity.y > 0.0 { newRotation = atan2(agent.velocity.y, agent.velocity.x) } else { newRotation = agent.rotation } // Ensure we have a valid rotation. if newRotation.isNaN { return } orientationComponent.zRotation = CGFloat(newRotation) } else { /* When the `TaskBot` is not agent-controlled, the agent position and rotation follow the node position and `TaskBot` orientation. */ updateAgentPositionToMatchNodePosition() updateAgentRotationToMatchTaskBotOrientation() } } // MARK: RulesComponentDelegate func rulesComponent(rulesComponent: RulesComponent, didFinishEvaluatingRuleSystem ruleSystem: GKRuleSystem) { let state = ruleSystem.state["snapshot"] as! EntitySnapshot // Adjust the `TaskBot`'s `mandate` based on the result of evaluating the rules. // A series of situations in which we prefer this `TaskBot` to hunt the player. let huntPlayerBotRaw = [ // "Number of bad TaskBots is high" AND "Player is nearby". ruleSystem.minimumGrade(forFacts: [ Fact.badTaskBotPercentageHigh.rawValue as AnyObject, Fact.playerBotNear.rawValue as AnyObject ]), /* There are already a lot of bad `TaskBot`s on the level, and the player is nearby, so hunt the player. */ // "Number of bad `TaskBot`s is medium" AND "Player is nearby". ruleSystem.minimumGrade(forFacts: [ Fact.badTaskBotPercentageMedium.rawValue as AnyObject, Fact.playerBotNear.rawValue as AnyObject ]), /* There are already a reasonable number of bad `TaskBots` on the level, and the player is nearby, so hunt the player. */ /* "Number of bad TaskBots is high" AND "Player is at medium proximity" AND "nearest good `TaskBot` is at medium proximity". */ ruleSystem.minimumGrade(forFacts: [ Fact.badTaskBotPercentageHigh.rawValue as AnyObject, Fact.playerBotMedium.rawValue as AnyObject, Fact.goodTaskBotMedium.rawValue as AnyObject ]), /* There are already a lot of bad `TaskBot`s on the level, so even though both the player and the nearest good TaskBot are at medium proximity, prefer the player for hunting. */ ] // Find the maximum of the minima from above. let huntPlayerBot = huntPlayerBotRaw.reduce(0.0, max) // A series of situations in which we prefer this `TaskBot` to hunt the nearest "good" TaskBot. let huntTaskBotRaw = [ // "Number of bad TaskBots is low" AND "Nearest good `TaskBot` is nearby". ruleSystem.minimumGrade(forFacts: [ Fact.badTaskBotPercentageLow.rawValue as AnyObject, Fact.goodTaskBotNear.rawValue as AnyObject ]), /* There are not many bad `TaskBot`s on the level, and a good `TaskBot` is nearby, so hunt the `TaskBot`. */ // "Number of bad TaskBots is medium" AND "Nearest good TaskBot is nearby". ruleSystem.minimumGrade(forFacts: [ Fact.badTaskBotPercentageMedium.rawValue as AnyObject, Fact.goodTaskBotNear.rawValue as AnyObject ]), /* There are a reasonable number of `TaskBot`s on the level, but a good `TaskBot` is nearby, so hunt the `TaskBot`. */ /* "Number of bad TaskBots is low" AND "Player is at medium proximity" AND "Nearest good TaskBot is at medium proximity". */ ruleSystem.minimumGrade(forFacts: [ Fact.badTaskBotPercentageLow.rawValue as AnyObject, Fact.playerBotMedium.rawValue as AnyObject, Fact.goodTaskBotMedium.rawValue as AnyObject ]), /* There are not many bad `TaskBot`s on the level, so even though both the player and the nearest good `TaskBot` are at medium proximity, prefer the nearest good `TaskBot` for hunting. */ /* "Number of bad `TaskBot`s is medium" AND "Player is far away" AND "Nearest good `TaskBot` is at medium proximity". */ ruleSystem.minimumGrade(forFacts: [ Fact.badTaskBotPercentageMedium.rawValue as AnyObject, Fact.playerBotFar.rawValue as AnyObject, Fact.goodTaskBotMedium.rawValue as AnyObject ]), /* There are a reasonable number of bad `TaskBot`s on the level, the player is far away, and the nearest good `TaskBot` is at medium proximity, so prefer the nearest good `TaskBot` for hunting. */ ] // Find the maximum of the minima from above. let huntTaskBot = huntTaskBotRaw.reduce(0.0, max) if huntPlayerBot >= huntTaskBot && huntPlayerBot > 0.0 { // The rules provided greater motivation to hunt the PlayerBot. Ignore any motivation to hunt the nearest good TaskBot. guard let playerBotAgent = state.playerBotTarget?.target.agent else { return } mandate = .huntAgent(playerBotAgent) } else if huntTaskBot > huntPlayerBot { // The rules provided greater motivation to hunt the nearest good TaskBot. Ignore any motivation to hunt the PlayerBot. mandate = .huntAgent(state.nearestGoodTaskBotTarget!.target.agent) } else { // The rules provided no motivation to hunt, so patrol in the "bad" state. switch mandate { case .followBadPatrolPath: // The `TaskBot` is already on its "bad" patrol path, so no update is needed. break default: // Send the `TaskBot` to the closest point on its "bad" patrol path. let closestPointOnBadPath = closestPointOnPath(path: badPathPoints) mandate = .returnToPositionOnPath(float2(closestPointOnBadPath)) } } } // MARK: ContactableType func contactWithEntityDidBegin(_ entity: GKEntity) {} func contactWithEntityDidEnd(_ entity: GKEntity) {} // MARK: Convenience /// The direct distance between this `TaskBot`'s agent and another agent in the scene. func distanceToAgent(otherAgent: GKAgent2D) -> Float { let deltaX = agent.position.x - otherAgent.position.x let deltaY = agent.position.y - otherAgent.position.y return hypot(deltaX, deltaY) } func distanceToPoint(otherPoint: float2) -> Float { let deltaX = agent.position.x - otherPoint.x let deltaY = agent.position.y - otherPoint.y return hypot(deltaX, deltaY) } func closestPointOnPath(path: [CGPoint]) -> CGPoint { // Find the closest point to the `TaskBot`. let taskBotPosition = agent.position let closestPoint = path.min { return distance_squared(taskBotPosition, float2($0)) < distance_squared(taskBotPosition, float2($1)) } return closestPoint! } /// Sets the `TaskBot` `GKAgent` position to match the node position (plus an offset). func updateAgentPositionToMatchNodePosition() { // `renderComponent` is a computed property. Declare a local version so we don't compute it multiple times. let renderComponent = self.renderComponent let agentOffset = GameplayConfiguration.TaskBot.agentOffset agent.position = float2(x: Float(renderComponent.node.position.x + agentOffset.x), y: Float(renderComponent.node.position.y + agentOffset.y)) } /// Sets the `TaskBot` `GKAgent` rotation to match the `TaskBot`'s orientation. func updateAgentRotationToMatchTaskBotOrientation() { guard let orientationComponent = component(ofType: OrientationComponent.self) else { return } agent.rotation = Float(orientationComponent.zRotation) } /// Sets the `TaskBot` node position to match the `GKAgent` position (minus an offset). func updateNodePositionToMatchAgentPosition() { // `agent` is a computed property. Declare a local version of its property so we don't compute it multiple times. let agentPosition = CGPoint(agent.position) let agentOffset = GameplayConfiguration.TaskBot.agentOffset renderComponent.node.position = CGPoint(x: agentPosition.x - agentOffset.x, y: agentPosition.y - agentOffset.y) } // MARK: Debug Path Drawing func drawDebugPath(path: [CGPoint], cycle: Bool, color: SKColor, radius: Float) { guard path.count > 1 else { return } debugNode.removeAllChildren() var drawPath = path if cycle { drawPath += [drawPath.first!] } var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 // Use RGB component accessor common between `UIColor` and `NSColor`. color.getRed(&red, green: &green, blue: &blue, alpha: &alpha) let strokeColor = SKColor(red: red, green: green, blue: blue, alpha: 0.4) let fillColor = SKColor(red: red, green: green, blue: blue, alpha: 0.2) for index in 0..<drawPath.count - 1 { let current = CGPoint(x: drawPath[index].x, y: drawPath[index].y) let next = CGPoint(x: drawPath[index + 1].x, y: drawPath[index + 1].y) let circleNode = SKShapeNode(circleOfRadius: CGFloat(radius)) circleNode.strokeColor = strokeColor circleNode.fillColor = fillColor circleNode.position = current debugNode.addChild(circleNode) let deltaX = next.x - current.x let deltaY = next.y - current.y let rectNode = SKShapeNode(rectOf: CGSize(width: hypot(deltaX, deltaY), height: CGFloat(radius) * 2)) rectNode.strokeColor = strokeColor rectNode.fillColor = fillColor rectNode.zRotation = atan(deltaY / deltaX) rectNode.position = CGPoint(x: current.x + (deltaX / 2.0), y: current.y + (deltaY / 2.0)) debugNode.addChild(rectNode) } } // MARK: Shared Assets class func loadSharedAssets() { ColliderType.definedCollisions[.TaskBot] = [ .Obstacle, .PlayerBot, .TaskBot ] ColliderType.requestedContactNotifications[.TaskBot] = [ .Obstacle, .PlayerBot, .TaskBot ] } }
true
107e8d3e03d5f39180193f191c70419845edddfd
Swift
Brightify/Reactant
/Source/Core/Wireframe/Wireframe.swift
UTF-8
4,101
2.734375
3
[ "MIT" ]
permissive
// // Wireframe.swift // Reactant // // Created by Filip Dolnik on 09.11.16. // Copyright © 2016 Brightify. All rights reserved. // import UIKit import RxSwift public protocol Wireframe { } extension Wireframe { /** * Method used for flexible and convenient **UIViewController** initializing without the need to pass UINavigationController around. * * As well as giving you an easy way to interact with navigation controller through **provider.navigation**, `create(factory:)` also lets you define a *reaction* using the controller without you having to initialize it beforehand. Both approaches are used in the simplified example below. * * To gain access to this function, your wireframe needs to conform to the `Wireframe` protocol. * * ## Example * From Wireframe: * ``` * private func login() -> LoginController { * return create { provider in * let dependencies = LoginController.Dependencies(accountService: module.accountService) * let reactions = LoginController.Reactions( * promptTouchID: { * provider.controller?.present(self.touchIDPrompt()) * }, * enterApplication: { * provider.navigation?.replaceAll(with: self.mainScreen()) * }, * openPasswordRecovery: { email in * provider.navigation?.push(controller: self.passwordRecovery(email: email)) * } * ) * return LoginController(dependencies: dependencies, reactions: reactions) * } * } * ``` * * - NOTE: For more info see: [Dependencies and everything about them](TODO), [Reactions, how do they work?](TODO), [Properties for flexible passing of variables to controllers](TODO) */ public func create<T>(factory: (FutureControllerProvider<T>) -> T) -> T { let futureControllerProvider = FutureControllerProvider<T>() let controller = factory(futureControllerProvider) futureControllerProvider.controller = controller return controller } /** * Method used for convenient creating **UIViewController** with Observable containing result value from the controller * Usage is very similar to the create<T> method, except now there are two closure parameters in create. * - returns: Tuple containg the requested **UIViewController** and Observable with the type of the result. */ public func create<T, U>(factory: (FutureControllerProvider<T>, AnyObserver<U>) -> T) -> (T, Observable<U>) { let futureControllerProvider = FutureControllerProvider<T>() let subject = PublishSubject<U>() let controller = factory(futureControllerProvider, subject.asObserver()) futureControllerProvider.controller = controller return (controller, subject.takeUntil(controller.rx.deallocated)) } /** * Used when you need a navigation controller embedded inside a controller that is already inside a navigation controller and is supposed to have a close button. */ public func branchNavigation(controller: UIViewController, closeButtonTitle: String?) -> UINavigationController { let navigationController = UINavigationController(rootViewController: controller) if let closeButtonTitle = closeButtonTitle { controller.navigationItem.leftBarButtonItem = UIBarButtonItem(title: closeButtonTitle, style: .done) { [weak navigationController] in navigationController?.dismiss(animated: true, completion: nil) } } return navigationController } /** * Used when you need a navigation controller embedded inside a controller that is already inside a navigation controller and is supposed to have a close button. */ public func branchNavigation<S, T>(controller: ControllerBase<S, T>) -> UINavigationController { let closeButtonTitle = controller.configuration.get(valueFor: Properties.closeButtonTitle) return branchNavigation(controller: controller, closeButtonTitle: closeButtonTitle) } }
true
108e69644d695586241c1e842d75cf22d73b51df
Swift
ioshitendra/ioscodesample
/sampleCode/QTickets/BaseClasses/Extensions/Date.swift
UTF-8
2,839
3.328125
3
[]
no_license
import Foundation extension Date { var weekdayName: String { let formatter = DateFormatter(); formatter.dateFormat = "E" return formatter.string(from: self as Date) } var weekdayNameFull: String { let formatter = DateFormatter(); formatter.dateFormat = "EEEE" return formatter.string(from: self as Date) } var monthName: String { let formatter = DateFormatter(); formatter.dateFormat = "MMMM" return formatter.string(from: self as Date) } var OnlyYear: String { let formatter = DateFormatter(); formatter.dateFormat = "YYYY" return formatter.string(from: self as Date) } var DatewithMonthDayWeek: String { let formatter = DateFormatter(); formatter.dateFormat = "MMM dd EEE" //formatter.dateStyle = .medium ; return formatter.string(from: self as Date) } var DatewithMonth: String { let formatter = DateFormatter(); formatter.dateFormat = "dd MMMM YYYY" //formatter.dateStyle = .medium ; return formatter.string(from: self as Date) } var DatewithYMD: String { let formatter = DateFormatter(); formatter.dateFormat = "YYYY-MM-dd" //formatter.dateStyle = .medium ; return formatter.string(from: self as Date) } var dayOfTheWeek: String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE" return dateFormatter.string(from: self) } func startOfMonth() -> Date? { let calendar = Calendar.current let currentDateComponents = calendar.dateComponents([.year, .month], from: self) let startOfMonth = calendar.date(from: currentDateComponents) return startOfMonth } func dateByAddingMonths(_ monthsToAdd: Int) -> Date? { let calendar = Calendar.current var months = DateComponents() months.month = monthsToAdd return calendar.date(byAdding: months, to: self) } func endOfMonth() -> Date? { guard let plusOneMonthDate = dateByAddingMonths(1) else { return nil } let calendar = Calendar.current let plusOneMonthDateComponents = calendar.dateComponents([.year, .month], from: plusOneMonthDate) let endOfMonth = calendar.date(from: plusOneMonthDateComponents)?.addingTimeInterval(-1) return endOfMonth } } extension String { func toDate(withFormat format: String = "MM/dd/yyyy") -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format guard let date = dateFormatter.date(from: self) else { preconditionFailure("Take a look to your format") } return date } }
true
a9bb8460b2e609eaad8492e4c46fd19d2679ac56
Swift
sylvan-d-ash/iOS-mvp-sample
/TestMVPTests/UserPresenterSpec.swift
UTF-8
4,078
2.6875
3
[]
no_license
// // UserPresenterSpec.swift // TestMVPTests // // Created by Sylvan Ash on 07/08/2018. // Copyright © 2018 is24. All rights reserved. // import Quick import Nimble @testable import TestMVP class UserPresenterSpec: QuickSpec { class UserServiceFake: UserService { private let users: [User] private let error: Error? init(_ users: [User], error: Error? = nil) { self.users = users self.error = error } override func getUsers(_ callBack: @escaping ([User], Error?) -> Void) { callBack(users, error) } } class UserViewMock: UserView { var setEmptyUsersCalled = false var wasErrorReturned = false var wasProgressShown = false var wasProgressHidden = false var users: [UserViewData] = [] func setUsers(_ users: [UserViewData]) { self.users = users } func setEmptyUsers() { setEmptyUsersCalled = true } func startLoading() { wasProgressShown = true } func finishLoading() { wasProgressHidden = true } func showError(error: Error) { wasErrorReturned = true } } override func spec() { var sut: UserPresenter! describe("UserPresenterSpec") { context("fetch users") { it("should show then hide activity loading indicator when fetching") { // given let userViewMock = UserViewMock() let userServiceFake = UserServiceFake([]) sut = UserPresenter(userService: userServiceFake) sut.attachView(userViewMock) // when sut.getUsers() // then expect(userViewMock.wasProgressShown).to(equal(true)) expect(userViewMock.wasProgressHidden).to(equal(true)) } it("should show empty view if no users available") { // given let userViewMock = UserViewMock() let userServiceFake = UserServiceFake([]) sut = UserPresenter(userService: userServiceFake) sut.attachView(userViewMock) // when sut.getUsers() // then expect(userViewMock.setEmptyUsersCalled).to(equal(true)) } it("should set users") { // given let users = [ User(firstName: "Jon", lastName: "Snow", email: "jon.snow@thewall.com", age: 29), User(firstName: "Arya", lastName: "Stark", email: "arya.stark@winterfell.com", age: 18) ] let userViewMock = UserViewMock() let userServiceFake = UserServiceFake(users) sut = UserPresenter(userService: userServiceFake) sut.attachView(userViewMock) // when sut.getUsers() // then expect(userViewMock.users.count).to(equal(users.count)) } it("should show an error if there was one") { // given let userViewMock = UserViewMock() let userServiceFake = UserServiceFake([], error: NetworkError.Unknown) sut = UserPresenter(userService: userServiceFake) sut.attachView(userViewMock) // when sut.getUsers() // then expect(userViewMock.wasErrorReturned).to(equal(true)) } } } } }
true
a4964a0b638f1a545a52e75d4338c1b0aa50f42e
Swift
patrickHD/iOSFinal
/iOSNoteTaker/NoteManager/NoteManager/Model/NoteType.swift
UTF-8
304
2.625
3
[]
no_license
// // NoteType.swift // NoteManager // // Created by Pat on 4/27/18. // Copyright © 2018 Mizzou. All rights reserved. // import UIKit enum NoteType: String{ case general case list case school var image: UIImage? { return UIImage(named: self.rawValue + "Icon") } }
true
7760395a861a22f391e515b5dfe839a7d0cd81f7
Swift
Ru5C55an/PartyMaker
/PartyMaker/CreateParty/View/CardView.swift
UTF-8
12,969
2.75
3
[]
no_license
// // CardView.swift // PartyMaker // // Created by Руслан Садыков on 04.01.2021. // import UIKit class CardView: UIView { let dateLabel = UILabel(text: "12 cентября", font: .sfProDisplay(ofSize: 16, weight: .regular)) let typeLabel = UILabel(text: "Музыкальная", font: .sfProDisplay(ofSize: 16, weight: .regular)) let partyName = UILabel(text: "Название вечеринки", font: .sfProDisplay(ofSize: 20, weight: .medium)) let startTime = UILabel(text: "12:59", font: .sfProDisplay(ofSize: 18, weight: .medium)) let endTime = UILabel(text: "14;00", font: .sfProDisplay(ofSize: 18, weight: .medium)) let arrowIcon = UILabel(text: "􀰑") let startTimeView = UIView() let endTimeView = UIView() let guestIcon = UILabel(text: "􀝊", font: .sfProDisplay(ofSize: 18, weight: .semibold)) let guestsCount = UILabel(text: "99/99", font: .sfProDisplay(ofSize: 18, weight: .medium)) let userImageView = UIImageView() let userName = UILabel(text: "Имя владельца", font: .sfProDisplay(ofSize: 18, weight: .medium)) let rating = UILabel(text: "􀋃 5.0", font: .sfProDisplay(ofSize: 18, weight: .medium)) let moneyView = UIView() let priceLabel = UILabel(text: "99999", font: .sfProDisplay(ofSize: 14, weight: .medium)) let priceIcon = UILabel(text: "􀖥", font: .sfProDisplay(ofSize: 14, weight: .semibold)) override init(frame: CGRect) { super.init(frame: frame) layer.shadowColor = UIColor(.black).cgColor layer.shadowRadius = 20 layer.shadowOpacity = 0.5 layer.shadowOffset = CGSize(width: -5, height: 10) userImageView.layer.cornerRadius = 20 userImageView.clipsToBounds = true startTime.textColor = .black endTime.textColor = .white priceLabel.textColor = .black startTimeView.layer.cornerRadius = 10 startTimeView.clipsToBounds = true startTimeView.layer.shadowColor = UIColor(.black).cgColor startTimeView.layer.shadowRadius = 20 startTimeView.layer.shadowOpacity = 0.5 startTimeView.layer.shadowOffset = CGSize(width: -5, height: 10) endTimeView.layer.cornerRadius = 10 endTimeView.clipsToBounds = true endTimeView.layer.shadowColor = UIColor(.white).cgColor endTimeView.layer.shadowRadius = 20 endTimeView.layer.shadowOpacity = 0.5 endTimeView.layer.shadowOffset = CGSize(width: -5, height: 10) priceIcon.textColor = .green setupConstraints() } override func layoutSubviews() { super.layoutSubviews() self.moneyView.layer.cornerRadius = 2 self.moneyView.clipsToBounds = true self.moneyView.layer.shadowColor = UIColor(.black).cgColor self.moneyView.layer.shadowRadius = 20 self.moneyView.layer.shadowOpacity = 0.5 self.moneyView.layer.shadowOffset = CGSize(width: -5, height: 10) } func configure<U>(with value: U) where U : Hashable { guard let party: Party = value as? Party else { return } //ToDo userimage // userImageView.image = UIImage(named: party.userImageString) userImageView.image = #imageLiteral(resourceName: "shit") //ToDo username // userName.text = party.username userName.text = "Временное имя" dateLabel.text = party.date typeLabel.text = party.type partyName.text = party.name startTime.text = party.startTime endTime.text = party.endTime priceLabel.text = party.price guestsCount.text = "\(party.currentPeople)/\(party.maximumPeople)" } var imageView = UIImageView(image: UIImage(named: "bc1")) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Setup constraints extension CardView { private func setupConstraints() { partyName.textAlignment = .center partyName.numberOfLines = 2 startTimeView.translatesAutoresizingMaskIntoConstraints = false startTime.translatesAutoresizingMaskIntoConstraints = false endTimeView.translatesAutoresizingMaskIntoConstraints = false endTime.translatesAutoresizingMaskIntoConstraints = false startTimeView.addSubview(startTime) endTimeView.addSubview(endTime) startTimeView.backgroundColor = .white endTimeView.backgroundColor = .black NSLayoutConstraint.activate([ startTimeView.heightAnchor.constraint(equalToConstant: 27), startTimeView.widthAnchor.constraint(equalToConstant: 53) ]) NSLayoutConstraint.activate([ endTimeView.heightAnchor.constraint(equalToConstant: 27), endTimeView.widthAnchor.constraint(equalToConstant: 53) ]) NSLayoutConstraint.activate([ startTime.centerXAnchor.constraint(equalTo: startTimeView.centerXAnchor), startTime.centerYAnchor.constraint(equalTo: startTimeView.centerYAnchor) ]) NSLayoutConstraint.activate([ endTime.centerXAnchor.constraint(equalTo: endTimeView.centerXAnchor), endTime.centerYAnchor.constraint(equalTo: endTimeView.centerYAnchor) ]) let timeStackView = UIStackView(arrangedSubviews: [startTimeView, arrowIcon, endTimeView], axis: .horizontal, spacing: 8) let guestsStackView = UIStackView(arrangedSubviews: [guestIcon, guestsCount], axis: .horizontal, spacing: 8) let userNameRatingStackView = UIStackView(arrangedSubviews: [userName, rating], axis: .vertical, spacing: 4) let userInfoStackView = UIStackView(arrangedSubviews: [userImageView, userNameRatingStackView], axis: .horizontal, spacing: 8) userInfoStackView.alignment = .center let priceStackView = UIStackView(arrangedSubviews: [priceLabel, priceIcon], axis: .horizontal, spacing: 4) let firstView = UIView() firstView.backgroundColor = .white let secondView = UIView() secondView.backgroundColor = .green let thirdView = UIView() thirdView.backgroundColor = .white firstView.addSubview(secondView) secondView.addSubview(thirdView) thirdView.addSubview(priceStackView) moneyView.addSubview(firstView) firstView.translatesAutoresizingMaskIntoConstraints = false secondView.translatesAutoresizingMaskIntoConstraints = false thirdView.translatesAutoresizingMaskIntoConstraints = false moneyView.translatesAutoresizingMaskIntoConstraints = false priceStackView.translatesAutoresizingMaskIntoConstraints = false addSubview(dateLabel) addSubview(typeLabel) addSubview(partyName) addSubview(userInfoStackView) addSubview(timeStackView) addSubview(guestsStackView) addSubview(moneyView) dateLabel.translatesAutoresizingMaskIntoConstraints = false typeLabel.translatesAutoresizingMaskIntoConstraints = false timeStackView.translatesAutoresizingMaskIntoConstraints = false guestsStackView.translatesAutoresizingMaskIntoConstraints = false userNameRatingStackView.translatesAutoresizingMaskIntoConstraints = false userInfoStackView.translatesAutoresizingMaskIntoConstraints = false userImageView.translatesAutoresizingMaskIntoConstraints = false partyName.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ userImageView.heightAnchor.constraint(equalToConstant: 64), userImageView.widthAnchor.constraint(equalToConstant: 64) ]) NSLayoutConstraint.activate([ dateLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 12), dateLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 12), dateLabel.trailingAnchor.constraint(equalTo: typeLabel.leadingAnchor, constant: 8) ]) NSLayoutConstraint.activate([ typeLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -12), typeLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 12), ]) NSLayoutConstraint.activate([ partyName.topAnchor.constraint(equalTo: dateLabel.bottomAnchor, constant: 8), partyName.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16), partyName.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16), partyName.heightAnchor.constraint(equalToConstant: 48) ]) NSLayoutConstraint.activate([ timeStackView.topAnchor.constraint(equalTo: partyName.bottomAnchor, constant: 16), timeStackView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16) ]) NSLayoutConstraint.activate([ guestsStackView.centerYAnchor.constraint(equalTo: timeStackView.centerYAnchor), guestsStackView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16) ]) NSLayoutConstraint.activate([ userInfoStackView.topAnchor.constraint(equalTo: timeStackView.bottomAnchor, constant: 16), userInfoStackView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 16), userInfoStackView.trailingAnchor.constraint(equalTo: moneyView.leadingAnchor, constant: -16), ]) NSLayoutConstraint.activate([ moneyView.heightAnchor.constraint(equalToConstant: 40), moneyView.widthAnchor.constraint(equalToConstant: 84), moneyView.centerYAnchor.constraint(equalTo: userInfoStackView.centerYAnchor), moneyView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -16) ]) NSLayoutConstraint.activate([ firstView.topAnchor.constraint(equalTo: moneyView.topAnchor), firstView.leadingAnchor.constraint(equalTo: moneyView.leadingAnchor), firstView.trailingAnchor.constraint(equalTo: moneyView.trailingAnchor), firstView.bottomAnchor.constraint(equalTo: moneyView.bottomAnchor) ]) NSLayoutConstraint.activate([ secondView.topAnchor.constraint(equalTo: firstView.topAnchor, constant: 4), secondView.leadingAnchor.constraint(equalTo: firstView.leadingAnchor, constant: 4), secondView.trailingAnchor.constraint(equalTo: firstView.trailingAnchor, constant: -4), secondView.bottomAnchor.constraint(equalTo: firstView.bottomAnchor, constant: -4) ]) NSLayoutConstraint.activate([ thirdView.topAnchor.constraint(equalTo: secondView.topAnchor, constant: 4), thirdView.leadingAnchor.constraint(equalTo: secondView.leadingAnchor, constant: 4), thirdView.trailingAnchor.constraint(equalTo: secondView.trailingAnchor, constant: -4), thirdView.bottomAnchor.constraint(equalTo: secondView.bottomAnchor, constant: -4) ]) NSLayoutConstraint.activate([ priceStackView.centerXAnchor.constraint(equalTo: thirdView.centerXAnchor), priceStackView.centerYAnchor.constraint(equalTo: thirdView.centerYAnchor) ]) imageView.translatesAutoresizingMaskIntoConstraints = false imageView.layer.cornerRadius = 20 imageView.clipsToBounds = true imageView.contentMode = .scaleToFill self.addSubview(imageView) self.sendSubviewToBack(imageView) NSLayoutConstraint.activate([ imageView.topAnchor.constraint(equalTo: self.topAnchor), imageView.leadingAnchor.constraint(equalTo: self.leadingAnchor), imageView.trailingAnchor.constraint(equalTo: self.trailingAnchor), imageView.bottomAnchor.constraint(equalTo: self.bottomAnchor) ]) let blurEffect = UIBlurEffect(style: .regular) let blurredEffectView = UIVisualEffectView(effect: blurEffect) blurredEffectView.layer.opacity = 0.8 blurredEffectView.frame = imageView.bounds blurredEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] imageView.addSubview(blurredEffectView) // let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect) // let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect) // vibrancyEffectView.frame = imageView.bounds // blurredEffectView.contentView.addSubview(vibrancyEffectView) // vibrancyEffectView.contentView.addSubview(guestsStackView) } }
true
e254b1e98c03fd8a2a90914fff18afa7a7cd9d23
Swift
qwer810520/Midterm-Exam
/swift程式練習(期中考).playground/Contents.swift
UTF-8
550
3.71875
4
[]
no_license
func sortArray(array1:[Int], array2:[Int]) -> [Int] { let array = array1 + array2 let set = Set(array) var newArray = Array(set) var x = true while x { x = false for i in 0..<newArray.count - 1 { if newArray[i] > newArray[i + 1] { let number = newArray[i + 1] newArray.remove(at: i + 1) newArray.insert(number, at: i) x = true } } } return newArray } sortArray(array1: [1,5,3], array2: [2,4,3])
true
8c34bf0743a178535e2f0b9ae79ef785747a4872
Swift
gudmunduro/addsite-cmd
/Sources/AddSite command/funcs.swift
UTF-8
1,207
3.09375
3
[]
no_license
import Foundation func YNQuestion(text: String) -> Bool { print(text) while true { if let input = readLine() { switch input { case "y": return true case "yes": return true case "n": return false case "no": return false default: break } } } } func shell(launchPath: String, arguments: [String]) -> String { let task = Process() task.launchPath = launchPath task.arguments = arguments let pipe = Pipe() task.standardOutput = pipe task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String(data: data, encoding: String.Encoding.utf8)! if output.characters.count > 0 { //remove newline character. let lastIndex = output.index(before: output.endIndex) return output[output.startIndex ..< lastIndex] } return output } func bash(command: String, arguments: [String]) -> String { let whichPathForCommand = shell(launchPath: "/bin/bash", arguments: [ "-l", "-c", "which \(command)" ]) return shell(launchPath: whichPathForCommand, arguments: arguments) }
true
2a663333ac1cec394ba30033e6c6f1106eb3643a
Swift
cresouls/source_code_swift
/Presenters/DefaultAlert.swift
UTF-8
1,938
3.03125
3
[]
no_license
// // DefaultAlert.swift // JoboyService // // Created by Sreejith Ajithkumar on 01/06/19. // Copyright © 2019 Sreejith Ajithkumar. All rights reserved. // import UIKit protocol DefaultAlert { func showAlert(_ title: String?, message: String, actionTitle: String) func showAlert(_ title: String?, message: String, actionTitle: String, cancelTitle: String, action: @escaping () -> ()) } extension DefaultAlert where Self: UIViewController { func showAlert(_ title: String?, message: String, actionTitle: String = "Ok") { var alertTitle: String! var alertMessage: String? if let title = title { alertTitle = title alertMessage = message } else { alertTitle = message } let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert) alertController.addAction(UIAlertAction(title: actionTitle, style: UIAlertAction.Style.default, handler: nil)) self.present(alertController, animated: true, completion: nil) } func showAlert(_ title: String?, message: String, actionTitle: String, cancelTitle: String, action: @escaping () -> () = { }) { var alertTitle: String! var alertMessage: String? if let title = title { alertTitle = title alertMessage = message } else { alertTitle = message } let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert) alertController.addAction(UIAlertAction(title: actionTitle, style: UIAlertAction.Style.default, handler: { (_) in action() })) alertController.addAction(UIAlertAction(title: cancelTitle, style: UIAlertAction.Style.cancel, handler: nil)) self.present(alertController, animated: true, completion: nil) } }
true
b30cd6e7b03bf1dbb8b1c8b0c18f9a8e9ae5b7ed
Swift
vmachiel/swift
/LearningSwift.playground/Pages/Static, Lazy, Self, Access, Sub.xcplaygroundpage/Contents.swift
UTF-8
9,830
4.5
4
[ "MIT" ]
permissive
// STATIC // Type properties and methods belong to a type like class or struct eg. // class PersonClass instead of an instance of a type like // var x = PersonClass(name: "Harry"), you do this to store shared data for example: // Or shared methods. class TaylorFan { static var favoriteSong = "Shake it off" static func singFavoriteSong() { print("I'm gonna \(favoriteSong), \(favoriteSong) Yeah Yeah Yeah") } init(name:String, age: Int) { self.name = name self.age = age } var name: String var age: Int func printNameAndAge() { print("My name is \(name), and I'm \(age) years old") } } let harry = TaylorFan(name: "Harry", age: 23) harry.printNameAndAge() // harry.favoriteSong won't work because it belongs to the struct, now the instance TaylorFan.favoriteSong TaylorFan.singFavoriteSong() // Built in lib has a lot of static, like Double: let d = Double.pi // static property // You can't call these on 3.45425 for instance because that is an instance of Double // Another example of type properties, this time with a struct. Let's say you have // the volume of an audio Channel. You want the a max volume, which would be the same // for all channels. And you want to keep track of the max volume set by users across // all channels. Also, if the set level turns out to be higher then the thresehold, // set it to threshold. And it it's higher than maxInputSet, update that. struct AudioChannel { static let thresholdLevel = 10 static var maxInputSet = 0 var currentLevel: Int = 0 { didSet { if currentLevel > AudioChannel.thresholdLevel { currentLevel = AudioChannel.thresholdLevel } if currentLevel > AudioChannel.maxInputSet { AudioChannel.maxInputSet = currentLevel } } } } var leftChannel = AudioChannel() var rightChannel = AudioChannel() // set leftChannel to 7. The maxInputSet of the class will now by 7 as well, // even though rightChannel never set it. leftChannel.currentLevel = 7 AudioChannel.maxInputSet // Set rightChannel to 11. The classes thresholdLevel will prevent that and set it // to 10. maxInput will be updated as well. rightChannel.currentLevel = 11 rightChannel.currentLevel AudioChannel.maxInputSet // Type Methods are also a thing! // With class, use the class keyword again: class Car { class func honkTheHorn() { print("Beep Beep ") } } Car.honkTheHorn() // With structs use the static keyword again: // Here is an example of a game with shared progress. When ever one person unlocks a level // all people (instances) can play it: // NOTE: The @discardableResults is there so the compiler won't warn when you don't do // anything with the false return. But you can use this somewhere else if you want to // check if advance has worked or not struct LevelTracker { static var highestUnlockedLevel = 1 var currentLevel = 1 static func unlock(_ level: Int) { if level > highestUnlockedLevel { highestUnlockedLevel = level } } static func isUnlocked(_ level: Int) -> Bool { return level <= highestUnlockedLevel } @discardableResult mutating func advance(to level: Int) -> Bool { if LevelTracker.isUnlocked(level) { currentLevel = level return true } else { return false } } } // Use type methods like this: class Player { var tracker = LevelTracker() let playerName: String init(name: String) { self.playerName = name } func complete(level: Int) { LevelTracker.unlock(level + 1) tracker.advance(to: level + 1) } } var machielPlayer = Player(name: "Machiel") machielPlayer.complete(level: 1) // Display what level is unlocked: LevelTracker.highestUnlockedLevel // Players share unlock var otherPlayer = Player(name: "snor") if otherPlayer.tracker.advance(to: 6) { print("Level 6 is good to go") } else { print("you haven't reach this level yet") } // LAZY: // Lazy properties aren't set until they are accessed by another property of method // So until someone creates and instance of SuperTaylorFan, and access property, // the var is not set. class SuperTaylorFan: TaylorFan { var fanStatus = "Super Mega Fan!" lazy var basedOnThisPerson = harry } let harry2 = SuperTaylorFan(name: "Harry", age: 23) // Still not set. Now, if I do this: harry2.basedOnThisPerson // The property is set. // YOU CANNOT USE PROPERTY OBSERVERS LIKE DIDSET{} WITH LAZY PROPERTIES. // You do this to delay expensive operations. Like calculator brain: let's set it's HUGE // and it's a value type as we know. Maybe don't set it in the viewController until it's // necessary. // Another reason to use them is: In swift, every var needs to be initialized. So // if you have a huge class or struct, you have to init everything before you can even // send a message. Even within your own class/struct. Initing everything when you don't // need to can be expensive, so you can use lazy if you want. // Or what if a property you want to init needs to call a method to do so. // You can't call methods until every thing else has been inited: use lazy. // That lazy property can't be accessed anyway until everything has been inited. And // lazy "count as inited" also, so you can use it on multiple vars!! // You can also lazy init with a closure, which is run when something access the var. // lazy var someProperty: Type = { closure code that returns value of type Type }() // NOTICE THE PARANTS!! Execute when access. // SELF // You don't have to write self in a struct/class: swift will use instance properties // automatically. Only when a parameter name in a method is the same as a instance // property, will swift give the parameter preference. You'll have to prefix the property // with self. // Use them in init: class Lamp { let typeOfBulp: String let maxWattage: Double var state = "on" init(_ typeOfBulp: String, strength maxWattage: Double) { self.typeOfBulp = typeOfBulp self.maxWattage = maxWattage } func description() { print("The is a \(typeOfBulp) lamp, its \(maxWattage) watts and it's \(state).") } } let lamp = Lamp("LED", strength: 12) lamp.state = "off" // REMEMBER: it's let so constant, but only a reference, so mutable! lamp.description() // You can also use self to assign new values in a mutating method: struct Point { var x = 0.0 var y = 0.0 // x is parameter, self.x is current property func isToTheRightOf(x: Double) -> Bool { return self.x > x } // Here the x is the self.x and deltaX is the parameter in the second line! mutating func moveBy(x deltaX: Double, y deltaY: Double) { self = Point(x: x + deltaX, y: y + deltaY) } } var somePoint = Point(x: 4.0, y: 5.0) if somePoint.isToTheRightOf(x: 1.0) { print("This point is to the right of the line where x == 1.0") } somePoint.moveBy(x: 9.0, y: 1.1) // And use them in enums like this: enum TriStateSwitch { case off, low, high mutating func next() { switch self { case .off: self = .low case .low: self = .high case .high: self = .off } } } /* Access. You can control the level of access. Access control lets you specify what data inside structs and classes should be exposed to the outside world, and you get to choose four modifiers: • Public: this means everyone can read and write the property. • Internal: this means only your Swift code can read and write the property. If you ship your code as a framework for others to use, they won’t be able to read the property. • File Private: this means that only Swift code in the same file as the type can read and write the property. • Private: this is the most restrictive option, and means the property is available only inside methods that belong to the type. Swift 4: AND EXTENSIONS! */ // Subscript can be used to define your own subscripts to access data, like the i in // Array[i] or the key in Dictionary[key] // Example: struct TimesTable { let multiplier: Int subscript(index: Int) -> Int { return multiplier * index } } let threeTable = TimesTable(multiplier: 3) threeTable[5] // You can also define types that take multiple subscripts, like a matrix: struct Matrix { let totalRows: Int let totalColumns: Int var grid: [Double] init(rows: Int, columns: Int) { self.totalRows = rows self.totalColumns = columns grid = Array(repeating: 0.0, count: rows * columns) } // A check to prevent out of bounds func indexIsValid(row: Int, column: Int) -> Bool { return row >= 0 && row < totalRows && column >= 0 && column < totalColumns } // This basically converts the double index i, j that you give a matrix to a // single index to use internally. Define what happens when you set or get the // double index subscript(row: Int, column: Int) -> Double { get { assert(indexIsValid(row: row, column: column), "Index out of range") // Notice!! row given * TOTAL columns + row given return grid[(row * totalColumns) + row] } set { assert(indexIsValid(row: row, column: column)) // Notice!! row given * TOTAL columns + row given grid[row * totalColumns + row] = newValue } } } var testMatrix = Matrix(rows: 2, columns: 3) testMatrix[0,0] = 3 testMatrix[1,2] = -2 print(testMatrix)
true
776fe124900599d09099448eda1f8fb048215dd1
Swift
MuthuMV/hackernews
/hackernews/ApiResponseHandler.swift
UTF-8
1,831
2.875
3
[]
no_license
// // ApiResponseHandler.swift // hackernews // // Created by Muthu on 9/11/17. // Copyright © 2017 UrbanPiper. All rights reserved. // import Foundation import ObjectMapper import Alamofire import ReachabilitySwift struct ApiResponseHandler<T: Mappable> { let reachability = Reachability() static func handleObjectResponse(response: Alamofire.DataResponse<Any>, completion: (_ data: T?, _ error: ErrorType?) -> Void) { switch response.result { case .success(let value): if let data = Mapper<T>().map(JSONObject: value) { completion(data, nil) } else { print("JSON PARSE FAILED for : \(value)") completion(nil, ErrorType.JSON_PARSING) } case .failure(let error): if !(Reachability()?.isReachable)! { completion(nil, ErrorType.INTERNET) } else { completion(nil, ErrorType.SERVER) } print("Error: \(error.localizedDescription)") } } static func handleArrayResponse(response: Alamofire.DataResponse<Any>, completion: (_ data: [T]?, _ error: ErrorType?) -> Void) { switch response.result { case .success(let value): if let data = Mapper<T>().mapArray(JSONObject: value) { completion(data, nil) } else { print("JSON PARSE FAILED for : \(value)") completion(nil, ErrorType.JSON_PARSING) } break case .failure(let error): if !(Reachability()?.isReachable)! { completion(nil, ErrorType.INTERNET) } else { completion(nil, ErrorType.SERVER) } print("Error: \(error.localizedDescription)") } } }
true
954b330ea41b7107a6a768838566280d8ae5ab8b
Swift
arrandacres/RunAid
/RunAid/Utils/ColoredPlaceholderTextField.swift
UTF-8
673
2.5625
3
[]
no_license
// // ColorBorderTextField.swift // RunAid // // Created by Arran Dacres on 27/02/2018. // Copyright © 2018 Arran Dacres. All rights reserved. // import Foundation import UIKit class ColorBorderTextField: UITextField { required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.setBorderColor() } required override init(frame: CGRect) { super.init(frame: frame) self.setBorderColor() } func setBorderColor(){ self.attributedPlaceholder = NSAttributedString(string: self.placeholder!, attributes: [NSAttributedStringKey.foregroundColor: UIColor(red: 182, green: 181, blue:182, alpha:0.3)]) } }
true
4bfa19bc40c8cffaa8f6d4c1dec24b1c035a5a20
Swift
YOCKOW/ySwiftExtensions
/utils/ySwiftExtensionsUpdater/Sources/yExtensionsUpdater/yExtensionsUpdater.swift
UTF-8
5,263
2.671875
3
[ "MIT", "Apache-2.0", "Swift-exception", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* ************************************************************************************************* yExtensionsUpdater.swift © 2020 YOCKOW. Licensed under MIT License. See "LICENSE.txt" for more information. ************************************************************************************************ */ import CoreFoundation import Foundation import StringComposition import yCodeUpdater import yExtensions private let _yExtensionsDirectory = ({ () -> URL in var url = URL(fileURLWithPath: #file, isDirectory: false) for _ in 0..<5 { url = url.deletingLastPathComponent() } url.appendPathComponent("Sources/yExtensions", isDirectory: true) return url })() private extension StringProtocol { func _trimCommentMarks() -> SubSequence { var string = self[self.startIndex..<self.endIndex] if string.hasPrefix("/*") { string = string.dropFirst(2) } if string.hasSuffix("*/") { string = string.dropLast(2) } guard let startIndex = string.firstIndex(where: { !$0.isWhitespace }) else { return "" } let endIndex = string.lastIndex(where: { !$0.isWhitespace })! return string[startIndex...endIndex] } func _trimmNonNumeric() -> SubSequence { func __isNumeric(_ character: Character) -> Bool { return character.isNumber || (character >= "a" && character <= "f") || (character >= "A" && character <= "F") } guard let startIndex = self.firstIndex(where: __isNumeric) else { return "" } let endIndex = self.lastIndex(where: __isNumeric)! return self[startIndex...endIndex] } } private extension CFStringEncoding { init<S>(_string: S) where S: StringProtocol { let string = _string._trimmNonNumeric() if string.hasPrefix("0x") { self.init(string.dropFirst(2), radix: 16)! } else { self.init(string, radix: 10)! } } } public final class yExtensionsUpdaterDelegate: CodeUpdaterDelegate { public init() {} public typealias IntermediateDataType = Intermediate public struct Intermediate { public let copyrightNotice: StringLines public let encodingTable: [String: CFStringEncoding] } public var sourceURLs: Array<URL> { return [ "https://raw.githubusercontent.com/apple/swift-corelibs-foundation/main/CoreFoundation/String.subproj/CFString.h", "https://raw.githubusercontent.com/apple/swift-corelibs-foundation/main/CoreFoundation/String.subproj/CFStringEncodingExt.h", ].map { URL(string: $0)! } } public var destinationURL: URL { return _yExtensionsDirectory.appendingPathComponent("CFStringEncodings.swift") } public func prepare(sourceURL: URL) throws -> IntermediateDataContainer<Intermediate> { enum _Error: Error { case stringConversionFailure case copyrightNoticeNotFound case unexpectedLine(String) } let data = yCodeUpdater.content(of: sourceURL) guard let string = String(data: data, encoding: .utf8) else { throw _Error.stringConversionFailure } let lines = StringLines(string) guard let firstCommentEndLineIndex = lines.firstIndex(where: { $0.payloadProperties.isEqual(to: "*/") }) else { throw _Error.copyrightNoticeNotFound } let copyrightNotice = StringLines(lines[0...firstCommentEndLineIndex].map({ String.Line($0.payload._trimCommentMarks())! })) var encodings: [String: CFStringEncoding] = [:] let prefix = "kCFStringEncoding" for line in lines[(firstCommentEndLineIndex + 1)...] { let payload = line.payload guard payload.hasPrefix(prefix) else { continue } let splitted = payload.split(whereSeparator: { $0.isWhitespace }) guard let indexOfEqual = splitted.firstIndex(of: "="), indexOfEqual < splitted.endIndex - 1 else { throw _Error.unexpectedLine(payload) } let name = splitted[0].dropFirst(prefix.count).lowerCamelCase let encoding = CFStringEncoding(_string: splitted[indexOfEqual + 1]) encodings[name] = encoding } return .init(content: Intermediate(copyrightNotice: copyrightNotice, encodingTable: encodings)) } public func convert<S>(_ intermediates: S) throws -> Data where S: Sequence, S.Element == IntermediateDataContainer<Intermediate> { var lines = StringLines() lines.append("import CoreFoundation") lines.appendEmptyLine() for interm in intermediates { var copyrightNotice = interm.content.copyrightNotice let encodings = interm.content.encodingTable lines.append("/*") copyrightNotice.shiftRight() lines.append(contentsOf: copyrightNotice) lines.append("*/") lines.append("extension CFString.Encoding {") let sortedPairs = encodings.sorted(by: { if $0.value < $1.value { return true } else if $0.value > $1.value { return false } else { return $0.key < $1.key } }) for (name, encoding) in sortedPairs { lines.append(String.Line("public static let \(name.swiftIdentifier) = CFString.Encoding(rawValue: 0x\(String(encoding, radix: 16, uppercase: true)))", indentLevel: 1)!) } lines.append("}") lines.appendEmptyLine() } return lines.data(using: .utf8)! } }
true
08a1d87c222df1663364ef4db2664350170608ef
Swift
beeth0ven/Experiment-Go
/Experiment Go/EditeTextTableViewController.swift
UTF-8
1,134
2.65625
3
[]
no_license
// // EditeTextTableViewController.swift // Experiment Go // // Created by luojie on 9/1/15. // Copyright © 2015 LuoJie. All rights reserved. // import UIKit class EditeTextTableViewController: EditeValueTableViewController { // MARK: - Properties var text: String? { get { return value as? String } set { value = newValue } } var done: ((String?) -> ())? override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) bodyTextView.becomeFirstResponder() } override func doneClicked() { bodyTextView.resignFirstResponder() done?(text) navigationController?.popViewControllerAnimated(true) } // MARK: - View Configure @IBOutlet weak var bodyTextView: UITextView! { didSet { bodyTextView.delegate = self } } override func updateUI() { bodyTextView?.text = text } } extension EditeTextTableViewController: UITextViewDelegate { func textViewDidChange(textView: UITextView) { text = textView.text navigationItem.rightBarButtonItem?.enabled = true } }
true
3419dfd43047dbb99089a122317a34746c60f564
Swift
Vilkelis/MyHabits
/MyHabits/HabitDetails/HabitDetailsViewController.swift
UTF-8
4,878
2.59375
3
[]
no_license
// // HabitDetailsViewController.swift // MyHabits // // Created by Stepas Vilkelis on 09.03.2021. // import UIKit class HabitDetailsViewController: UIViewController { var habit: Habit? { didSet { habitChanged() } } var onDelete: (() -> Void)? var onSave: (() -> Void)? private lazy var tableView: UITableView = { let tableView = UITableView(frame: .zero, style: .grouped) tableView.translatesAutoresizingMaskIntoConstraints = false tableView.dataSource = self tableView.delegate = self tableView.register(HabitDetailsTableViewCell.self, forCellReuseIdentifier: String(describing: HabitDetailsTableViewCell.self)) tableView.register(HabitDetailsTableViewHeader.self, forHeaderFooterViewReuseIdentifier: String(describing: HabitDetailsTableViewHeader.self)) tableView.backgroundColor = UIColor(named: "AppColor3") return tableView }() override func viewDidLoad() { super.viewDidLoad() habitChanged() self.view.backgroundColor = UIColor(named: "AppColorBackground") self.navigationItem.largeTitleDisplayMode = .never navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Править", style: .plain, target: self, action: #selector(editButtonPressed)) navigationController?.navigationBar.tintColor = UIColor(named: "AppColor4") view.addSubview(tableView) let constraints = [ tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) ] NSLayoutConstraint.activate(constraints) } //MARK: - Events @objc private func editButtonPressed() { let modalViewController = HabitViewController() modalViewController.onSave = { self.habitChanged() if let saveEvent = self.onSave { saveEvent() } } modalViewController.habit = self.habit modalViewController.onDelete = { modalViewController.dismiss(animated: true, completion: self.onDelete) } self.present(modalViewController, animated: true, completion: nil) } private func habitChanged(){ if let h = self.habit { self.navigationItem.title = h.name } else { self.navigationItem.title = "" } } } // MARK: - UITableViewDataSource extension HabitDetailsViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print(HabitsStore.shared.dates.count) return HabitsStore.shared.dates.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: HabitDetailsTableViewCell = tableView.dequeueReusableCell( withIdentifier: String(describing: HabitDetailsTableViewCell.self), for: indexPath) as! HabitDetailsTableViewCell let dateIndex = HabitsStore.shared.dates.count - indexPath.item - 1 cell.title = HabitsStore.shared.trackDateString(forIndex: dateIndex) ?? "" if let h = self.habit { let date = HabitsStore.shared.dates[dateIndex] cell.checked = HabitsStore.shared.habit(h, isTrackedIn: date) } else { cell.checked = false } return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: String(describing: HabitDetailsTableViewHeader.self)) as! HabitDetailsTableViewHeader return headerView } else { return nil } } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } } // MARK: - UITableViewDelegate extension HabitDetailsViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return UITableView.automaticDimension } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 12 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } }
true
8f88d538285cecc22743d125418ec06a86391021
Swift
tobitech/FacebookNewsFeed
/MyFacebookFeed/Post.swift
UTF-8
4,110
2.921875
3
[ "MIT" ]
permissive
// // Post.swift // MyFacebookFeed // // Created by Tobi Omotayo on 10/02/2017. // Copyright © 2017 Tobi Omotayo. All rights reserved. // import UIKit class Post { var name: String? var statusText: String? var profileImageName: String? var statusImageName: String? var numLikes: Int? var numComments: Int? var statusImageUrl: String? } class Posts { fileprivate let postsList: [Post] init() { let postMark = Post() postMark.name = "Mark Zuckerberg" postMark.profileImageName = "zuckprofile" postMark.statusText = "By giving people the power to share, we're making the world more transparent." postMark.statusImageName = "mark_zuckerberg_background" postMark.numLikes = 400 postMark.numComments = 123 postMark.statusImageUrl = "https://s3-us-west-2.amazonaws.com/letsbuildthatapp/mark_zuckerberg_background.jpg" let postSteve = Post() postSteve.name = "Steve Jobs" postSteve.profileImageName = "steve_profile" postSteve.statusText = "Design is not just what it looks like and feels like. Design is how it works.\n\n" + "Being the richest man in the cemetery doesn't matter to me. Going to bed at night saying we've done something wonderful, that's what matters to me.\n\n" + "Sometimes when you innovate, you make mistakes. It is best to admit them quickly, and get on with improving your other innovations." postSteve.statusImageName = "steve_status" postSteve.numLikes = 1000 postSteve.numComments = 55 postSteve.statusImageUrl = "https://s3-us-west-2.amazonaws.com/letsbuildthatapp/steve_jobs_background.jpg" let postGandhi = Post() postGandhi.name = "Mahatma Gandhi" postGandhi.profileImageName = "gandhi_profile" postGandhi.statusText = "Live as if you were to die tomorrow; learn as if you were to live forever.\n" + "The weak can never forgive. Forgiveness is the attribute of the strong.\n" + "Happiness is when what you think, what you say, and what you do are in harmony." postGandhi.statusImageName = "gandhi_status" postGandhi.numLikes = 333 postGandhi.numComments = 22 postGandhi.statusImageUrl = "https://s3-us-west-2.amazonaws.com/letsbuildthatapp/gandhi_status.jpg" let postBillGates = Post() postBillGates.name = "Bill Gates" postBillGates.profileImageName = "bill_gates_profile" postBillGates.statusText = "Success is a lousy teacher. It seduces smart people into thinking they can't lose.\n\n" + "Your most unhappy customers are your greatest source of learning.\n\n" + "As we look ahead into the next century, leaders will be those who empower others." postBillGates.statusImageUrl = "https://s3-us-west-2.amazonaws.com/letsbuildthatapp/gates_background.jpg" let postTimCook = Post() postTimCook.name = "Tim Cook" postTimCook.profileImageName = "tim_cook_profile" postTimCook.statusText = "The worst thing in the world that can happen to you if you're an engineer that has given his life to something is for someone to rip it off and put their name on it." postTimCook.statusImageUrl = "https://s3-us-west-2.amazonaws.com/letsbuildthatapp/Tim+Cook.png" let postDonaldTrump = Post() postDonaldTrump.name = "Donald Trump" postDonaldTrump.profileImageName = "donald_trump_profile" postDonaldTrump.statusText = "An ‘extremely credible source’ has called my office and told me that Barack Obama’s birth certificate is a fraud." postDonaldTrump.statusImageUrl = "https://s3-us-west-2.amazonaws.com/letsbuildthatapp/trump_background.jpg" postsList = [postMark, postSteve, postGandhi, postBillGates, postTimCook, postDonaldTrump] } func numberOfPosts() -> Int { return postsList.count } subscript(indexPath: IndexPath) -> Post { get { return postsList[indexPath.item] } } }
true
cc802d826216c0a410c267187b0f28b7d2bc994e
Swift
yFeii/partten-design
/对象创建/生成器(建造者)模式/生成器(建造者)模式/OC-PD/StandardCharacterBuilder.swift
UTF-8
1,901
3.265625
3
[]
no_license
// // StandardCharacterBuild.swift // 生成器(建造者)模式 // // Created by yFeii on 2019/10/5. // Copyright © 2019 yFeii. All rights reserved. // import Foundation //生成器 class StandardCharacterBuilder: CharacterBuilder { override func buildStrength(_ value: Float) -> CharacterBuilder { //根据value 更新 角色的防御值和攻击值 character?.protection = character.protection * value character.power = character.power * value return super.buildStrength(value) } //耐力 override func buildStamina(_ value: Float) -> CharacterBuilder { //根据value 更新 角色的防御值和攻击值 character?.protection = character.protection * value character.power = character.power * value return super.buildStamina(value) } //智力与力量成反比 override func buildIntelligence(_ value: Float) -> CharacterBuilder { //根据value 更新 角色的防御值和攻击值 character?.protection = character.protection * value character.power = character.power / value return super.buildIntelligence(value) } //耐力与力量成反比 override func buildAgility(_ value: Float) -> CharacterBuilder { //根据value 更新 角色的防御值和攻击值 character?.protection = character.protection * value character.power = character.power / value return super.buildAgility(value) } //攻击力 和防御成反比 override func buildAggressiveness(_ value: Float) -> CharacterBuilder { //根据value 更新 角色的防御值和攻击值 character?.protection = character.protection / value character.power = character.power * value return super.buildAggressiveness(value) } }
true
008d7f5255d0a3a407102ed377fcf924976d153f
Swift
FerryAWijayanto/SuitMedia
/SuitMedia/Login/LoginStore.swift
UTF-8
665
3.078125
3
[ "MIT" ]
permissive
// // HomeStore.swift // SuitMedia // // Created by Ferry Wijayanto on 25/04/20. // Copyright © 2020 Ferry Wijayanto. All rights reserved. // import Foundation class LoginStore { func isPalindrome(word: String, success: @escaping () -> Void, failure: @escaping () -> Void) -> Bool { let characters = Array(word) var currentIndex = 0 while currentIndex < characters.count / 2 { if characters[currentIndex] != characters[characters.count - currentIndex - 1] { failure() return false } currentIndex += 1 } success() return true } }
true
90b02ccf07f43705aaeff4a125fecf4c809e4084
Swift
mkelly3/Breakout2
/Break Out/ViewController.swift
UTF-8
6,512
2.53125
3
[]
no_license
// // ViewController.swift // Break Out // // Created by mkelly2 on 2/26/16. // Copyright © 2016 mkelly2. All rights reserved. // import UIKit class ViewController: UIViewController, UICollisionBehaviorDelegate { @IBOutlet weak var livesLabel: UILabel! var dynamicAnimator = UIDynamicAnimator() var paddle = UIView() var ball = UIView() var ballBehavior = UIDynamicItemBehavior() var blocks: [UIView] = [] var allObjects : [UIView] = [] var collisionBehavior = UICollisionBehavior() var lives = 0 override func viewDidLoad() { super.viewDidLoad() resetGame() } @IBAction func dragPaddle(sender: UIPanGestureRecognizer) { paddle.center = CGPointMake(sender.locationInView(view).x, paddle.center.y) dynamicAnimator.updateItemUsingCurrentState(paddle) } func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item: UIDynamicItem, withBoundaryIdentifier identifier: NSCopying?, atPoint p: CGPoint) { if item.isEqual(ball) && p.y > paddle.center.y { lives-- if lives > 0 { livesLabel.text = "Lives: \(lives)" ball.center = view.center dynamicAnimator.updateItemUsingCurrentState(ball) } else { gameOver("You Lost") } } } func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item1: UIDynamicItem, withItem item2: UIDynamicItem, atPoint p: CGPoint) { var hiddenBlockCount = 0 for block in blocks { if item1.isEqual(ball) && item2.isEqual(block) { if block.backgroundColor == UIColor.purpleColor() { block.backgroundColor = UIColor.greenColor() } else if block.backgroundColor == UIColor.blueColor() { block.backgroundColor = UIColor.purpleColor() } else { block.hidden = true collisionBehavior.removeItem(block) } ballBehavior.addLinearVelocity(CGPointMake(0, 10), forItem: ball) } if block.hidden == true { hiddenBlockCount++ } } if hiddenBlockCount == blocks.count { gameOver("You Won") } } func resetGame() { dynamicAnimator = UIDynamicAnimator(referenceView: view) allObjects = [] paddle = UIView(frame: CGRectMake(view.center.x, view.center.y * 1.7, 80 , 20)) paddle.backgroundColor = UIColor.redColor() view.addSubview(paddle) ball = UIView(frame: CGRectMake(view.center.x, view.center.y, 20, 20)) ball.layer.cornerRadius = 10 ball.backgroundColor = UIColor.blackColor() view.addSubview(ball) let pushBehavior = UIPushBehavior(items: [ball], mode: .Instantaneous) pushBehavior.pushDirection = CGVectorMake(0.5, 1.0) pushBehavior.magnitude = 0.15 dynamicAnimator.addBehavior(pushBehavior) let paddleBehavior = UIDynamicItemBehavior(items: [paddle]) paddleBehavior.density = 10000 paddleBehavior.resistance = 100 paddleBehavior.allowsRotation = false dynamicAnimator.addBehavior(paddleBehavior) allObjects.append(paddle) let ballDynamicBehavior = UIDynamicItemBehavior(items: [ball]) ballDynamicBehavior.friction = 0 ballDynamicBehavior.resistance = 0 ballDynamicBehavior.elasticity = 1.0 ballDynamicBehavior.allowsRotation = false dynamicAnimator.addBehavior(ballDynamicBehavior) allObjects.append(ball) let width = (Int)(view.bounds.size.width - 40) let margin = ((Int)(view.bounds.size.width) % 42)/2 for var x = margin; x < width; x += 42 {addBlock(x, y: 40, color: UIColor.blueColor())} for var x = margin; x < width; x += 42 {addBlock(x, y: 62, color: UIColor.purpleColor())} for var x = margin; x < width; x += 42 {addBlock(x, y: 84, color: UIColor.purpleColor())} for var x = margin; x < width; x += 42 {addBlock(x, y: 106, color: UIColor.purpleColor())} for var x = margin; x < width; x += 42 {addBlock(x, y: 128, color: UIColor.purpleColor())} for var x = margin; x < width; x += 42 {addBlock(x, y: 150 , color: UIColor.greenColor())} for var x = margin; x < width; x += 42 {addBlock(x, y: 172, color: UIColor.greenColor())} for var x = margin; x < width; x += 42 {addBlock(x, y: 194, color: UIColor.greenColor())} let blockBehavior = UIDynamicItemBehavior(items: blocks) blockBehavior.allowsRotation = false blockBehavior.density = 1000 blockBehavior.elasticity = 1.0 dynamicAnimator.addBehavior(blockBehavior) collisionBehavior = UICollisionBehavior(items: allObjects) collisionBehavior.translatesReferenceBoundsIntoBoundary = true collisionBehavior.collisionMode = UICollisionBehaviorMode.Everything collisionBehavior.collisionDelegate = self dynamicAnimator.addBehavior(collisionBehavior) lives = 5 livesLabel.text = "Lives: \(lives)" } func gameOver(message :String) { ball.removeFromSuperview() collisionBehavior.removeItem(ball) dynamicAnimator.updateItemUsingCurrentState(ball) paddle.removeFromSuperview() collisionBehavior.removeItem(paddle) dynamicAnimator.updateItemUsingCurrentState(paddle) let alert = UIAlertController(title: message, message: nil, preferredStyle: UIAlertControllerStyle.Alert) let resetAction = UIAlertAction(title: "New Game", style: UIAlertActionStyle.Default) { (action) -> Void in self.resetGame() } alert.addAction(resetAction) let quitAction = UIAlertAction(title: "Quit", style: UIAlertActionStyle.Default) { (action) -> Void in exit(0) } alert.addAction(quitAction) presentViewController(alert, animated: true, completion: nil) } func addBlock(x: Int, y: Int, color: UIColor) { let block = UIView(frame: CGRectMake((CGFloat)(x),(CGFloat)(y), 40,20)) block.backgroundColor = color view.addSubview(block) blocks.append(block) allObjects.append(block) } }
true
9dc1101513b182b6626805f4674ce813a77e833f
Swift
ye7ia33/El-Matar-Photo-Task
/Photo/ARC/V-VC/LoginVC.swift
UTF-8
2,158
2.703125
3
[]
no_license
// // AuthenticationVC.swift // Photo // // Created by Yahia El-Dow on 7/25/19. // Copyright © 2019 Yahia El-Dow. All rights reserved. // import UIKit class LoginVC: UIViewController { @IBOutlet weak var txtEmail: UITextField! @IBOutlet weak var txtPassword: UITextField! override func viewDidLoad() { super.viewDidLoad() view.accessibilityIdentifier = "loginView" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.isNavigationBarHidden = true } @IBAction func loginButtonAction(_ sender: Any) { if self.inputIsValid() { let authVM = AuthenticationViewModel() guard let email = self.txtEmail.text else {return} guard let password = self.txtPassword.text else {return} self.showLoader() authVM.login(WithEmailAddress: email , password: password) authVM.completionHandler = { err in if authVM.currentUser != nil { self.hideLoader() self.performSegue(withIdentifier: "goToTabViewController", sender: nil) return } self.hideLoader() self.showAlert(WithMessage: "<#T##String#>") } } } private func inputIsValid()-> Bool{ if self.txtEmail.text?.isEmpty ?? true { self.showAlert(WithMessage: "Enter Your Email Address.") return false } if self.txtEmail.text?.isValidEmail() == false { self.showAlert(WithMessage: "Insert Right Email Format.") return false } if self.txtPassword.text?.isEmpty ?? false { self.showAlert(WithMessage: "Enter Password.") return false } if self.txtPassword.text?.count ?? 0 < 6 { self.showAlert(WithMessage: "Password is minimum 6 digits") return false } return true } }
true
3d1e39495c4a23bf5acd4434e31e32f33f29cea4
Swift
shutdownr/augmented-breadcrumbs
/AugmentedBreadcrumbs/AugmentedBreadcrumbs/LocationExtension.swift
UTF-8
1,600
3.328125
3
[ "MIT" ]
permissive
// // LocationExtension.swift // AugmentedBreadcrumbs // // Created by Tim on 10.05.19. // Copyright © 2019 Tim. All rights reserved. // import Foundation import CoreLocation extension CLLocation{ func angleTo(location: CLLocation) -> Double { let lat1 = DegreeHelper.degreesToRadians(degrees: location.coordinate.latitude) let lon1 = DegreeHelper.degreesToRadians(degrees: location.coordinate.longitude) let lat2 = DegreeHelper.degreesToRadians(degrees: self.coordinate.latitude) let lon2 = DegreeHelper.degreesToRadians(degrees: self.coordinate.longitude) let dLon = lon2 - lon1 let y = sin(dLon) * cos(lat2) let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon) let radiansBearing = atan2(y, x) return radiansBearing } func getXZDistance(location: CLLocation, currentHeading: Double) -> (x: Double, z: Double) { let distanceToPosition = self.distance(from: location) let angleToPosition = self.angleTo(location: location) let userAngleToPosition = angleToPosition + currentHeading let x = -distanceToPosition * sin(DegreeHelper.degreesToRadians(degrees: userAngleToPosition)) let z = -distanceToPosition * cos(DegreeHelper.degreesToRadians(degrees: userAngleToPosition)) return (x: x, z: z) } } private class DegreeHelper { static func degreesToRadians(degrees: Double) -> Double { return degrees * .pi / 180 } static func radiansToDegrees(radians: Double) -> Double { return radians * 180 / .pi } }
true
c7008f6f49362d290ae0562693d906337df04353
Swift
alobanov/ALUtils
/Sources/dbutils/jsonEntityExporter/NSManagedObject+Serialization.swift
UTF-8
10,370
2.625
3
[ "MIT" ]
permissive
// // NSManagedObject+Serialization.swift // EntitySerialization // // Created by Lobanov Aleksey on 17/11/2017. // Copyright © 2017 Lobanov Aleksey. All rights reserved. // import Foundation import CoreData public enum MapperRelationshipType: Int { case none = 0 case array case nested }; public enum MapperInflectionType: Int { case snakeCase = 0 case camelCase } public struct Constant { static let CompatiblePrimaryKey = "remoteID" static let RemotePrimaryKey = "id" static let NestedAttributesKey = "attributes" static let CustomExportKey = "exportKey" static let NonExportableKey = "export" static let CustomValueTransformerKey = "exportTransformer" } public extension NSManagedObject { func remotePrefixUsing(inflectionType: MapperInflectionType) -> String { switch (inflectionType) { case .snakeCase: return "\(self.entity.name?.toSnakeCase() ?? "")_" case .camelCase: return self.entity.name ?? "" } } func attributesForToOne(relationship: NSManagedObject, relationshipName:String, relationshipType: MapperRelationshipType, parent: NSManagedObject, dateFormatter: DateFormatter, inflectionType: MapperInflectionType) -> [String: Any] { var attributesForToOneRelationship = [String: Any]() let attributes = relationship.toJSON(parent: parent, dateFormatter: dateFormatter, inflectionType: inflectionType, relationshipType: relationshipType) if (attributes.count > 0) { var key: String = "" switch (inflectionType) { case .snakeCase: key = relationshipName.toSnakeCase() case .camelCase: key = relationshipName } if (relationshipType == .nested) { switch (inflectionType) { case .snakeCase: key = "\(key)_\(Constant.NestedAttributesKey)" break; case .camelCase: key = "\(key)\(Constant.NestedAttributesKey.capitalized)" break; } } attributesForToOneRelationship[key] = attributes } return attributesForToOneRelationship; } func reservedKeys(using inflectionType: MapperInflectionType) -> [String] { var keys: [String] = [] for attribute in NSManagedObject.reservedAttributes() { keys.append(self.prefixedAttribute(attribute: attribute, inflectionType: inflectionType)) } return keys } func remoteKey(attributeDescription: NSAttributeDescription, relationshipType: MapperRelationshipType, inflectionType: MapperInflectionType) -> String { let localKey = attributeDescription.name var remoteKey: String? let customRemoteKey = attributeDescription.customKey() if let crk = customRemoteKey { remoteKey = crk } else if localKey == Constant.RemotePrimaryKey || localKey == Constant.CompatiblePrimaryKey { remoteKey = Constant.RemotePrimaryKey } else { switch inflectionType { case .snakeCase: remoteKey = localKey.toSnakeCase() case .camelCase: remoteKey = localKey } } let isReservedKey = self.reservedKeys(using: inflectionType).contains(remoteKey ?? "") if (isReservedKey) { var prefixedKey = remoteKey ?? "" let start = prefixedKey.index(prefixedKey.startIndex, offsetBy: 0) let end = prefixedKey.index(prefixedKey.endIndex, offsetBy: 0) let myRange = start..<end prefixedKey = prefixedKey.replacingOccurrences(of: self.remotePrefixUsing(inflectionType: inflectionType), with: "", options: String.CompareOptions.caseInsensitive, range: myRange) remoteKey = prefixedKey // if (inflectionType == .camelCase) { // remoteKey = remoteKey // } } return remoteKey ?? "" } func valueFor(attributeDescription :NSAttributeDescription, dateFormatter: DateFormatter, relationshipType: MapperRelationshipType) -> Any { var value: Any? if attributeDescription.attributeType != NSAttributeType.transformableAttributeType { value = self.value(forKey: attributeDescription.name) let nilOrNullValue = (value == nil || value is NSNull) let customTransformerName: String? = attributeDescription.customTransformerName() if (nilOrNullValue) { value = NSNull() } else if let date = value as? NSDate { value = dateFormatter.string(from: date as Date) } else if let custom = customTransformerName { let transformer = ValueTransformer(forName: NSValueTransformerName(rawValue: custom)) if transformer != nil, let v = value { value = transformer?.transformedValue(v) } } } return value ?? NSNull() } func attributesForToMany(relationships: NSSet, relationshipName: String, relationshipType: MapperRelationshipType, parent: NSManagedObject, dateFormatter: DateFormatter, inflectionType: MapperInflectionType) -> [String: Any] { var attributesForToManyRelationship = [String: Any]() var relationIndex = 0; var relationsDictionary = [String: Any]() var relationsArray = [[String: Any]]() for relationship in relationships { var attributes = [String: Any]() if let r = relationship as? NSManagedObject { attributes = r.toJSON(parent: parent, dateFormatter: dateFormatter, inflectionType: inflectionType, relationshipType: relationshipType) } if attributes.count > 0 { if (relationshipType == .array) { relationsArray.append(attributes) } else if (relationshipType == .nested) { let relationIndexString = String(relationIndex) relationsDictionary[relationIndexString] = attributes relationIndex+=1 } } } var key = "" switch (inflectionType) { case .snakeCase: key = relationshipName.toSnakeCase() case .camelCase: key = relationshipName } if (relationshipType == .array) { attributesForToManyRelationship[key] = relationsArray } else if (relationshipType == .nested) { let nestedAttributesPrefix = "\(key)_\(Constant.NestedAttributesKey)" attributesForToManyRelationship[nestedAttributesPrefix] = relationsDictionary } return attributesForToManyRelationship; } func toJSON() -> [String: Any] { return self.toJSON(parent: nil, dateFormatter: NSManagedObject.defaultDateFormatter, inflectionType: .camelCase, relationshipType: .array) } func toJSON(parent: NSManagedObject?, dateFormatter: DateFormatter, inflectionType: MapperInflectionType, relationshipType: MapperRelationshipType) -> [String: Any] { var managedObjectAttributes = Dictionary<String, Any>() for propertyDescription in self.entity.properties { if let pd = propertyDescription as? NSAttributeDescription { if pd.shouldExportAttribute() { let value = self.valueFor(attributeDescription: pd, dateFormatter: dateFormatter, relationshipType: relationshipType) let remoteKey = self.remoteKey(attributeDescription: pd, relationshipType: relationshipType, inflectionType: inflectionType) managedObjectAttributes[remoteKey] = value; } } else if (propertyDescription is NSRelationshipDescription && relationshipType != .none) { let relationshipDescription = propertyDescription as! NSRelationshipDescription if relationshipDescription.shouldExportAttribute() { let isValidRelationship = !(parent != nil && parent?.entity == relationshipDescription.destinationEntity && !relationshipDescription.isToMany) if (isValidRelationship) { let relationshipName = relationshipDescription.name let relationships = self.value(forKey: relationshipName) if let rlship = relationships { let isToOneRelationship = (!(relationships is NSSet) && !(relationships is NSOrderedSet)) let rn = relationshipDescription.relationCustomKey() ?? relationshipDescription.name if (isToOneRelationship) { let attributesForToOneRelationship = self.attributesForToOne(relationship: rlship as! NSManagedObject, relationshipName: rn, relationshipType: relationshipType, parent: self, dateFormatter: dateFormatter, inflectionType: inflectionType) managedObjectAttributes.merge(with: attributesForToOneRelationship) } else { let attributesForToManyRelationship = self.attributesForToMany(relationships: rlship as! NSSet, relationshipName: rn, relationshipType: relationshipType, parent: self, dateFormatter: dateFormatter, inflectionType: inflectionType) managedObjectAttributes.merge(with: attributesForToManyRelationship) } } } } } } return managedObjectAttributes } public static var defaultDateFormatter: (DateFormatter) = { // this gets executed once let _dateFormatter = DateFormatter() _dateFormatter.locale = Locale(identifier: "ru") _dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return _dateFormatter; //But no access to instance variables... }() func prefixedAttribute(attribute: String, inflectionType:MapperInflectionType) -> String { let remotePrefix = self.remotePrefixUsing(inflectionType: inflectionType) switch (inflectionType) { case .snakeCase: return "\(remotePrefix)\(attribute)" case .camelCase: return "\(remotePrefix)\(attribute.capitalized)" } } class func reservedAttributes() -> [String] { return ["type", "description", "signed"] } }
true
166c52ad5c851b85eca70f210d4651ea22c0913a
Swift
Marceeelll/codingbat-swift
/CodingBat - Recursion-1.playground/Pages/09powerN.xcplaygroundpage/Contents.swift
UTF-8
632
4.03125
4
[]
no_license
import Foundation /* Given base and n that are both 1 or more, compute recursively (no loops) the value of base to the n power, so powerN(3, 2) is 9 (3 squared). powerN(3, 1) → 3 powerN(3, 2) → 9 powerN(3, 3) → 27 */ func powerN(_ base: Int, _ n: Int) -> Int { if n == 0 { return 1 } else if n == 1 { return base } else { return base * powerN(base, n-1) } } powerN(3, 1) == 3 powerN(3, 2) == 9 powerN(3, 3) == 27 powerN(2, 1) == 2 powerN(2, 2) == 4 powerN(2, 3) == 8 powerN(2, 4) == 16 powerN(2, 5) == 32 powerN(10, 1) == 10 powerN(10, 2) == 100 powerN(10, 3) == 1000
true
2377f0723ba1532db2ef3f16756800a21a2a2ff1
Swift
YoDobchev/Ichan
/IOS 4chan/ThreadView.swift
UTF-8
2,739
3
3
[ "MIT" ]
permissive
// // ThreadView.swift // IOS 4chan // // Created by Yoan Dobchev on 15.09.21. // import SwiftUI extension String { func load() -> UIImage { do { guard let url = URL(string: self) else { return UIImage() } let data : Data = try Data(contentsOf: url) return UIImage(data: data) ?? UIImage() } catch { } return UIImage() } } struct ThreadView: View { var boardTitle : String @State var threadArr : Array<thread>? @State var showThreads = false @State var showPostView = false @State var threadId : Int64 var body: some View { GeometryReader { geometry in NavigationView { ScrollView(.vertical) { VStack { if showThreads { ForEach((threadArr!), id: \.self) { th in ForEach((th.threads!), id: \.self) { t in VStack { Button(action: { threadId = t.no showPostView = true }) { if ((t.tim) != nil) { Image(uiImage: "https://i.4cdn.org/\(boardTitle)/\(t.tim!)s.jpg".load()) } } if (t.sub != nil) { Text("\(t.sub!)") .fontWeight(.bold) } if (t.com != nil) { Text("\(t.com!)") .padding(.horizontal) } } .frame(width: geometry.size.width, alignment: .center) .border(Color.green) } } } }.onAppear() { threadArr = getThreads("\(boardTitle)") showThreads = true } } }.navigationBarTitleDisplayMode(.inline) } NavigationLink( destination: PostView(threadId: self.threadId, boardTitle: boardTitle, playerMap: nil), isActive: $showPostView) { } } } struct ThreadView_Previews: PreviewProvider { static var previews: some View { ThreadView(boardTitle: "a", threadArr: nil, threadId: 55) } }
true