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
8fb83e8ec988b452bdc3b39af022cd4ff4d4b5e8
Swift
csr/iOS-Weather-API
/Weather Clothing/Controller/WeatherController/WeatherController-MapKit.swift
UTF-8
2,106
3
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // WeatherController-Location.swift // Weather Clothing // // Created by Cesare de Cal on 11/1/18. // Copyright © 2018 Cesare Gianfilippo Astianatte de Cal. All rights reserved. // import UIKit import MapKit extension WeatherController: CLLocationManagerDelegate { func getCurrentUserLocation() { if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyKilometer locationManager.requestLocation() } } func getLocationName(location: CLLocation) { fetchCityAndCountry(from: location) { city, countryCode, error in guard let city = city, let countryCode = countryCode, error == nil else { print("Error occurred while fetching city and country") return } print("here is your location name") self.labelLocation.text = city + ", " + countryCode print(city + ", " + countryCode) // Rio de Janeiro, Brazil self.getWeatherData(cityName: city, countryCode: countryCode, scale: self.getCurrentTemperatureScaleSelection()) } } func fetchCityAndCountry(from location: CLLocation, completion: @escaping (_ city: String?, _ country: String?, _ error: Error?) -> ()) { CLGeocoder().reverseGeocodeLocation(location) { placemarks, error in completion(placemarks?.first?.locality, placemarks?.first?.isoCountryCode, error) } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = manager.location else { print("Warning: location is nil") return } print("locations count:", locations.count) // activityIndicatorView.isHidden = false getLocationName(location: location) } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print(error.localizedDescription) } }
true
242c420c819553d4d3e86ce755a9ee6914e52d2b
Swift
parkchanwoong/AlgorithmPractice
/Programmers/Level1/Lessons12910.playground/Contents.swift
UTF-8
382
2.984375
3
[]
no_license
import UIKit func solution(_ arr:[Int], _ divisor:Int) -> [Int] { let arrTemp = arr.sorted().filter {$0 % divisor == 0} return arrTemp.isEmpty ? [-1] : arrTemp } solution([3,2,6], 10) // 다른 사람의 풀이 //func solution(_ arr:[Int], _ divisor:Int) -> [Int] { // let array = arr.sorted().filter{ $0 % divisor == 0 } // return array == [] ? [-1] : array //}
true
f309cc96b028d0b20b8fba18913178b0c405dd10
Swift
ThePowerOfSwift/AFoundation
/AFoundationUnitTesting/Bytes/BytesUnitTesting.swift
UTF-8
936
2.625
3
[ "MIT" ]
permissive
// // BytesUnitTesting.swift // AFoundationUnitTesting // // Created by Ihor Myroniuk on 3/3/20. // Copyright © 2020 Ihor Myroniuk. All rights reserved. // import XCTest @testable import AFoundation class BytesUnitTesting: XCTestCase { private var testBytes: ABytes { let bytes: ABytes = [0x55, 0x01, 0x03, 0x73, 0x99] return bytes } func testAdditionAssignmentOperatorBytes() { var bytes = testBytes bytes += [0x53, 0x41] let expectedBytes: ABytes = [0x55, 0x01, 0x03, 0x73, 0x99, 0x53, 0x41] assert(bytes == expectedBytes, "Actual bytes [\(bytes)] is not equal to [\(expectedBytes)]") } func testAdditionAssignmentOperatorByte() { var bytes = testBytes bytes += 0x53 let expectedBytes: ABytes = [0x55, 0x01, 0x03, 0x73, 0x99, 0x53] assert(bytes == expectedBytes, "Actual bytes [\(bytes)] is not equal to [\(expectedBytes)]") } }
true
92885576c75d612a145adc5a20a07209d4a26ea9
Swift
torinpitchers/ThetaBooking
/ThetaBooking/User.swift
UTF-8
1,796
3.34375
3
[]
no_license
// // Staff.swift // ThetaBooking // // Created by Matthew Copson on 25/01/2016. // Copyright © 2016 Harry Moy. All rights reserved. // import Foundation import UIKit enum UserError:ErrorType { case IndexNotValid } struct User { var name: String //Searchable var email: String //Primary Key var staff: Bool var skills: [String] var bio: String var picture: NSData } class Users { private var UserList:[User] var searchResults:[User] // static class public property that returns a Budget object static let getInstance = Users() init() { UserList = [] searchResults = [] } func count() -> Int { return self.UserList.count } func getUser(Index:Int) throws -> User { if 0 > Index || Index > self.UserList.count - 1 { throw UserError.IndexNotValid } return UserList[Index] } func getList() -> [User] { return UserList } func search(text:String) { searchResults = [] //empty the search results container let searchRange = Range(start: text.startIndex, end: text.endIndex) //calulate range of search for person in Users.getInstance.getList() { if searchRange.count > person.name.characters.count { continue } let substring = person.name.substringWithRange(searchRange) //get substring from range if substring.lowercaseString == text.lowercaseString { searchResults.append(person) } } print(searchResults.count) } func clear() -> Void { self.searchResults = [] self.UserList = [] } }
true
5e62022420d4c94bb5d6a610d27ea779e0d8b5c5
Swift
MarcusSmith/swift-aqueduct-test
/Sources/Aqueduct/RequestChannel.swift
UTF-8
664
2.640625
3
[]
no_license
// // RequestChannel.swift // Aqueduct // // Created by Marcus Smith on 2/24/19. // import Foundation import Promises public protocol RequestChannel { func prepare() -> Promise<Void> func transform(_ error: Error) -> Response var entryPoint: Controller { get } } public extension RequestChannel { func prepare() -> Promise<Void> { return Promise(()) } func transform(_ error: Error) -> Response { if let statusError = error as? StatusCodeError { return Response(statusCode: statusError.statusCode, value: statusError.localizedDescription) } return Response(statusCode: 500) } }
true
a13a068417a5a0cfc08968ccef981e33773492a3
Swift
LiuLongyang0305/LeetCode
/swift/Math/970_PowerfulNumber.swift
UTF-8
1,233
3.796875
4
[]
no_license
//https://leetcode.com/problems/powerful-integers/ class Solution { func powerfulIntegers(_ x: Int, _ y: Int, _ bound: Int) -> [Int] { var ans = [Int]() let xTimesLimit = x == 1 ? 1 : Int(log2(Double(bound)) / log2(Double(x))) + 1 let yTimesLimit = y == 1 ? 1 : Int(log2(Double(bound)) / log2(Double(y))) + 1 var xExponential = Array<Int>(repeating: 1, count: xTimesLimit) if x != 1 { for i in 1..<xTimesLimit { xExponential[i] = x * xExponential[i - 1] } } var yExponential = Array<Int>(repeating: 1, count: yTimesLimit) if y != 1 { for i in 1..<yTimesLimit { yExponential[i] = y * yExponential[i - 1] } } var exist = Set<Int>() for i in 0..<xTimesLimit { for j in 0..<yTimesLimit { let temp = xExponential[i] + yExponential[j] if temp <= bound { if !exist.contains(temp) { ans.append(temp) exist.insert(temp) } } } } return ans } } Solution().powerfulIntegers(2, 1, 10)
true
185bc16293c572d53713e178d1cbcaee052292d5
Swift
rmorbach/networking-tests-swift
/NetworkTestingTests/URLProtocolMock.swift
UTF-8
823
2.703125
3
[ "Apache-2.0" ]
permissive
// // URLProtocolMock.swift // NetworkTesting // // Created by Rodrigo Morbach on 15/06/19. // Copyright © 2019 Morbach Inc. All rights reserved. // import Foundation class URLProtocolMock: URLProtocol { static var mockedURLs: [String: Data] = [:] override class func canInit(with request: URLRequest) -> Bool { return true } override class func canonicalRequest(for request: URLRequest) -> URLRequest { return request } override func startLoading() { if let url = request.url { if let data = URLProtocolMock.mockedURLs[url.absoluteString] { self.client?.urlProtocol(self, didLoad: data) } } self.client?.urlProtocolDidFinishLoading(self) } override func stopLoading() { } }
true
04b2ca35c2845df0b6c76b17efbb08e3dc3b0512
Swift
vincefried/M2
/M2/ViewModel/Messages/MessagesListViewModel.swift
UTF-8
8,871
2.6875
3
[]
no_license
// // MessagesListViewModel.swift // M2 // // Created by Vincent Friedrich on 23.02.19. // Copyright © 2019 neoxapps. All rights reserved. // import Foundation import UIKit /// A delegate for the MessagesListViewModel. protocol MessagesListViewModelDelegate: class { /// Indicates that the UI needs to be updated. func updateUINeeded() } /// A ListViewModel for the MessagesViewController. class MessagesListViewModel: ListViewModel<Message, MessageCellViewModel> { /// Private var for the ViewModel data for change observing implementation. private var _data: [MessageCellViewModel] = [] /// The ViewModel data. Always gets returned in reversed order because of the MessagesViewController UITableView reversed implementation. override var data: [MessageCellViewModel] { get { return _data.reversed() } set { _data = newValue } } /// An AudioPlayingWorker instance for playing a sound when the user received a message. let messageAudioPlayingWorker = AudioPlayingWorker(sound: .message) /// An AudioPlayingWorker instance for playing a sound when the user received a new typed letter in a message. let messageEditingAudioPlayingWorker = AudioPlayingWorker(sound: .messageEditing) /// An AudioPlayingWorker instance for playing a sound when the user goes online. let onlineAudioPlayingWorker = AudioPlayingWorker(sound: .online) /// An AudioPlayingWorker instance for playing a sound when the user goes offline. let offlineAudioPlayingWorker = AudioPlayingWorker(sound: .offline) /// An AudioRecordingWOrker instance for recording audio for the voice memos. var recordingWorker: AudioRecordingWorker? /// The number of maximum lines of the messages text view. let messagesTextFieldMaxLines: Int = 4 /// The title of the ViewController. let title: String /// A temp variable for saving the old number of lines before updating the View. var oldNumberOfLines: Int = 0 /// If the toolbar with the messages text view and all buttons is hidden. var isToolbarHidden: Bool { return !messagesProvider.chat.isComplete } /// If the messages list needs to be scrolled to the bottom. var needsBottomScroll: Bool { guard let message = messagesProvider.messages.last as? TextMessage else { return false } return message.isEditing && message.text.count == 1 } /// If the other user is online. var isOnline: Bool { return messagesProvider.chat.otherUserIsActive } /// If the ViewController's UITableView for displaying the messages should be reversed. var reverseTableView: Bool { return !messagesProvider.messages.isEmpty } /// If a placeholder should be shown if the other chat partner is missing. var showsOtherMissingPlaceholder: Bool { return !messagesProvider.chat.isComplete } /// The image for the missing placeholder. var emptyDataSetImage: UIImage? { return messagesProvider.chat.isComplete ? UIImage(named: "chat") : UIImage(named: "sleep") } /// The description for the missing placeholder. var emptyDataSetDescription: NSAttributedString { let rawString = isOnline ? "Noch keine Nachrichten" : "\(messagesProvider.chat.otherUser) ist nicht im Chat" let string = NSMutableAttributedString(string: rawString, attributes: [NSAttributedString.Key.font : UIFont(name: "Futura", size: 16)!]) return string } /// A delegate for the MessagesListViewModel. weak var delegate: MessagesListViewModelDelegate? private let messagesProvider: MessagesProvider init(messagesProvider: MessagesProvider) { self.messagesProvider = messagesProvider self.title = messagesProvider.chat.otherUser super.init(provider: messagesProvider) self.messagesProvider.delegate = self } /// Starts the chat. /// /// - Parameter completion: Called on async call completion with success. func handleStartedChat(completion: @escaping (Bool) -> Void) { messagesProvider.chat.startChat(completion: completion) } /// Leaves the chat. /// /// - Parameter completion: Called on async call completion with success. func handleLeftChat(completion: @escaping (Bool) -> Void) { messagesProvider.chat.leaveChat(completion: completion) } /// Checks if the chat is complete. /// /// - Parameter completion: Called on async call completion with if chat is complete. func checkIfChatComplete(_ completion: ((Bool) -> Void)? = nil) { messagesProvider.chat.checkIfIsComplete { [weak self] complete in completion?(complete) // Indicate that the UI needs to be updated self?.delegate?.updateUINeeded() } } /// Handles a typed letter of the messages text view. /// /// - Parameter text: The text content of the messages text view. func handleTyping(with text: String) { messagesProvider.typeMessage(text: text) } /// Handles a tap on the send button. /// /// - Parameter text: The text content of the messages text view. func handleSendButtonTapped(with text: String) { // Trim the text to remove leading or trailing whitespaces or new lines let trimmedText = text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) // Stop if the trimmed text is empty guard !trimmedText.isEmpty else { return } // Send message with trimmed text messagesProvider.sendMessage(text: trimmedText) } /// Handles a touch down (user holds record button) of the record button. func handleRecordButtonTouchDown() { // Get a reference date to create a unique recording id guard let referenceDate = "01.01.2019".toDate()?.date else { return } // Initialize the AudioPlayingWorker with the id recordingWorker = AudioRecordingWorker(id: Int(Date().timeIntervalSince(referenceDate))) // Start the recording recordingWorker?.record() } /// Handles a touch up (user releases record button) of the record button. func handleRecordButtonTouchUp() { // Stop the recording worker and get its response guard let response = recordingWorker?.stop() else { return } // Send the voice memo with the file url messagesProvider.sendVoiceMemo(id: response.id, fileUrl: response.fileURL) } /// Maps the messages model data to instances of TextMessageCellViewModel or VoiceMemoCellViewModel. private func mapData() { _data = messagesProvider.messages.map({ message -> MessageCellViewModel in switch message { case let textMessage as TextMessage: return TextMessageCellViewModel(data: textMessage) case let voiceMessage as VoiceMemoMessage: return VoiceMemoCellViewModel(data: voiceMessage) default: fatalError() } }) } } // MARK: - MessagesProviderDelegate extension MessagesListViewModel: MessagesProviderDelegate { func didAppend(message: Message) { // Map the new state of data to ViewModels mapData() // Play a matching message sound if message.isEditing { messageEditingAudioPlayingWorker?.play() } else { messageAudioPlayingWorker?.play() } // Indicate that the UI needs to be updated delegate?.updateUINeeded() } func didUpdate(message: Message, at index: Int) { // Map the new state of data to ViewModels mapData() // Play a send sound if the message finished editing if !message.isEditing { messageAudioPlayingWorker?.play() } // Indicate that the UI needs to be updated delegate?.updateUINeeded() } func didRemove(message: Message, at index: Int) { // Map the new state of data to ViewModels mapData() // Indicate that the UI needs to be updated delegate?.updateUINeeded() } func didChangeActiveStatus(username: String) { // Check if the chat is complete checkIfChatComplete { [weak self] _ in // If chat is complete, play online sound, otherwise play offline sound if self?.messagesProvider.chat.otherUserIsActive ?? false { self?.onlineAudioPlayingWorker?.play() } else { self?.offlineAudioPlayingWorker?.play() } } // Indicate that the UI needs to be updated delegate?.updateUINeeded() } }
true
430a6289fae096c4716e6842025156ec9d2f2e43
Swift
goudsmit/SwURL
/Sources/SwURL/RemoteImage/View/Public/RemoteImageView.swift
UTF-8
3,397
3.03125
3
[ "MIT" ]
permissive
// // RemoteImageView.swift // Landmarks // // Created by Callum Trounce on 06/06/2019. // Copyright © 2019 Apple. All rights reserved. // import Foundation import SwiftUI protocol SwURLImageViewType: ImageOutputCustomisable, View {} public protocol ImageOutputCustomisable { mutating func imageProcessing<ProcessedImage: View>( _ processing: @escaping (Image) -> ProcessedImage ) -> Self mutating func progress<T: View>(_ progress: @escaping (CGFloat) -> T) -> Self } public enum SwURLImageView: SwURLImageViewType { case iOS13(iOS13RemoteImageView) case iOS14(iOS14RemoteImageView) init<Base: SwURLImageViewType>(_ base: Base) { if let iOS13 = base as? iOS13RemoteImageView { self = .iOS13(iOS13) } else if #available(iOS 14.0, *), let iOS14 = base as? iOS14RemoteImageView { self = .iOS14(iOS14) } else { fatalError() } } public func imageProcessing<ProcessedImage>(_ processing: @escaping (Image) -> ProcessedImage) -> Self where ProcessedImage : View { switch self { case .iOS13(let view): return SwURLImageView.iOS13(view.imageProcessing(processing)) case .iOS14(var view): if #available(iOS 14.0, *) { return SwURLImageView.iOS14(view.imageProcessing(processing)) } else { fatalError() } } } public func progress<T>(_ progress: @escaping (CGFloat) -> T) -> Self where T : View { switch self { case .iOS13(let view): return SwURLImageView.iOS13(view.progress(progress)) case .iOS14(var view): if #available(iOS 14.0, *) { return SwURLImageView.iOS14(view.progress(progress)) } else { fatalError() } } } public var body: some View { switch self { case .iOS13(let view): return AnyView(view.body) case .iOS14(let view): return AnyView(view.body) } } } public enum RemoteImageView: SwURLImageViewType { case view(SwURLImageView) private var value: SwURLImageView { switch self { case .view(let val): return val } } public init( url: URL, placeholderImage: Image? = nil, transition: ImageTransitionType = .none ) { if #available(iOS 14.0, *) { self = .view(SwURLImageView(iOS14RemoteImageView( url: url, placeholderImage: placeholderImage, transition: transition ))) } else { self = .view(SwURLImageView(iOS13RemoteImageView( url: url, placeholderImage: placeholderImage, transition: transition ))) } } public var body: some View { return value.body } public mutating func imageProcessing<ProcessedImage>(_ processing: @escaping (Image) -> ProcessedImage) -> RemoteImageView where ProcessedImage : View { return .view(value.imageProcessing(processing)) } public mutating func progress<T>(_ progress: @escaping (CGFloat) -> T) -> RemoteImageView where T : View { return .view(value.progress(progress)) } }
true
df5d167392c1dfcbe5b76b7456cfa1834fad4ea4
Swift
doyeongkim/TIL
/Daily_Assignments/Project/19.04.30_(Notification)/19.04.30_(Notification)/SecondViewController.swift
UTF-8
1,630
2.734375
3
[]
no_license
// // SecondViewController.swift // 19.04.30_(Notification) // // Created by Solji Kim on 05/05/2019. // Copyright © 2019 Doyeong Kim. All rights reserved. // import UIKit class SecondViewController: UIViewController { let colorView = UIView() let notiCenter = NotificationCenter.default override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white view.addSubview(colorView) setAutoLayout() } func addNotificationObserver() { notiCenter.addObserver(self, selector: #selector(didReceiveColorNotification(_:)), name: Notification.Name("ColorNotification"), object: nil) } @objc func didReceiveColorNotification(_ sender: Notification) { // guard let mixedColor = sender.object as? UIColor else { return } // colorView.backgroundColor = mixedColor guard let mixedColor = sender.userInfo as? [String : UIColor] else { return } colorView.backgroundColor = mixedColor["colors"] } func setAutoLayout() { let guide = view.safeAreaLayoutGuide colorView.translatesAutoresizingMaskIntoConstraints = false colorView.topAnchor.constraint(equalTo: guide.topAnchor, constant: 10).isActive = true colorView.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 15).isActive = true colorView.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: -15).isActive = true colorView.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: -10).isActive = true } }
true
e0652343b475658c470bcf50089501096ce751ac
Swift
ezefranca/Photos
/Photos/PhotosTests/PhotosTests.swift
UTF-8
6,059
3.03125
3
[ "MIT" ]
permissive
// // PhotosTests.swift // Photos // // Created by Ezequiel on 06/10/16. // Copyright © 2016 Ezequiel França. All rights reserved. // // albumId": 1, // "id": 1, // "title": "accusamus beatae ad facilis cum similique qui sunt", // "url": "http://placehold.it/600/92c952", // "thumbnailUrl": "http://placehold.it/150/30ac17" import Foundation import XCTest import ObjectMapper import SwiftyJSON @testable import Photos class PhotoTests: XCTestCase { let photoMapper = Mapper<Photos>() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testBasicParsing() { let title = "accusamus beatae ad facilis cum similique qui sunt" let url = "http://placehold.it/600/92c952" let internalIdentifier = 1 let thumbnailUrl = "http://placehold.it/150/30ac17" let albumId = 1 let photoJSONString = "{\"albumId\":\(albumId),\"url\":\"\(url)\",\"id\":\(internalIdentifier),\"thumbnailUrl\":\"\(thumbnailUrl)\", \"title\":\"\(title)\"}" print(photoJSONString) let photo = photoMapper.map(photoJSONString) XCTAssertNotNil(photo) XCTAssertEqual(title, photo!.title) XCTAssertEqual(url, photo!.url) XCTAssertEqual(internalIdentifier, photo!.internalIdentifier) XCTAssertEqual(thumbnailUrl, photo!.thumbnailUrl) XCTAssertEqual(albumId, photo!.albumId) } func testInstanceParsing() { let title = "accusamus beatae ad facilis cum similique qui sunt" let url = "http://placehold.it/600/92c952" let internalIdentifier = 1 let thumbnailUrl = "http://placehold.it/150/30ac17" let albumId = 1 let photoJSONString = "{\"albumId\":\(albumId),\"url\":\"\(url)\",\"id\":\(internalIdentifier),\"thumbnailUrl\":\"\(thumbnailUrl)\", \"title\":\"\(title)\"}" let photo = Mapper<Photos>().mapArray(photoJSONString) XCTAssertNotNil(photo) XCTAssertEqual(title, photo!.first!.title) XCTAssertEqual(url, photo!.first!.url) XCTAssertEqual(internalIdentifier, photo!.first!.internalIdentifier) XCTAssertEqual(thumbnailUrl, photo!.first!.thumbnailUrl) XCTAssertEqual(albumId, photo!.first!.albumId) } func testDictionaryParsing() { let title = "accusamus beatae ad facilis cum similique qui sunt" let url = "http://placehold.it/600/92c952" let internalIdentifier = 1 let thumbnailUrl = "http://placehold.it/150/30ac17" let albumId = 1 let json: [String: AnyObject] = ["albumId": albumId, "url": url, "id": internalIdentifier, "thumbnailUrl": thumbnailUrl, "title" : title] let p = Photos() p.title = title let photo = Mapper().map(json, toObject: p) XCTAssertNotNil(photo) XCTAssertEqual(title, photo.title) XCTAssertEqual(url, photo.url) XCTAssertEqual(internalIdentifier, photo.internalIdentifier) XCTAssertEqual(thumbnailUrl, photo.thumbnailUrl) XCTAssertEqual(albumId, photo.albumId) } func testInstanceWithJSON() { let title = "accusamus beatae ad facilis cum similique qui sunt" let url = "http://placehold.it/600/92c952" let internalIdentifier = 1 let thumbnailUrl = "http://placehold.it/150/30ac17" let albumId = 1 let j: JSON = ["albumId": albumId, "url": url, "id": internalIdentifier, "thumbnailUrl": thumbnailUrl, "title" : title] let photo = Photos(json: j) XCTAssertNotNil(photo) XCTAssertEqual(title, photo.title) XCTAssertEqual(url, photo.url) XCTAssertEqual(internalIdentifier, photo.internalIdentifier) XCTAssertEqual(thumbnailUrl, photo.thumbnailUrl) XCTAssertEqual(albumId, photo.albumId) } func testInstanceWithAnyObject() { let title = "accusamus beatae ad facilis cum similique qui sunt" let url = "http://placehold.it/600/92c952" let internalIdentifier = 1 let thumbnailUrl = "http://placehold.it/150/30ac17" let albumId = 1 let j: AnyObject = ["albumId": albumId, "url": url, "id": internalIdentifier, "thumbnailUrl": thumbnailUrl, "title" : title] let photo = Photos(object: j) XCTAssertNotNil(photo) XCTAssertEqual(title, photo.title) XCTAssertEqual(url, photo.url) XCTAssertEqual(internalIdentifier, photo.internalIdentifier) XCTAssertEqual(thumbnailUrl, photo.thumbnailUrl) XCTAssertEqual(albumId, photo.albumId) } func testDictionaryRepresetation() { let title = "accusamus beatae ad facilis cum similique qui sunt" let url = "http://placehold.it/600/92c952" let internalIdentifier = 1 let thumbnailUrl = "http://placehold.it/150/30ac17" let albumId = 1 let json: [String: AnyObject] = ["albumId": albumId, "url": url, "id": internalIdentifier, "thumbnailUrl": thumbnailUrl, "title" : title] let photo = Photos(JSON: json) let dictionary = photo!.dictionaryRepresentation() let photo2 = Photos(JSON: dictionary) XCTAssertNotNil(dictionary) XCTAssertEqual(json as NSObject, dictionary as NSObject) XCTAssertEqual(photo?.title, photo2?.title) XCTAssertEqual(photo?.url, photo2?.url) XCTAssertEqual(photo?.internalIdentifier, photo2?.internalIdentifier) XCTAssertEqual(photo?.thumbnailUrl, photo2?.thumbnailUrl) XCTAssertEqual(photo?.albumId, photo2?.albumId) } }
true
03869f24d51b93138f4213baebd4a51f238ce25a
Swift
cmanciero/KidInfo
/KidInfo/WeightGrowthChartViewController.swift
UTF-8
2,971
2.65625
3
[]
no_license
// // WeightGrowthChartViewController.swift // KidInfo // // Created by i814935 on 6/16/17. // Copyright © 2017 Chris Manciero. All rights reserved. // import UIKit import Charts class WeightGrowthChartViewController: UIViewController { var kid: Kid? = nil; var months: [String]!; var arrKidWeights: [Weight]!; var arrDates: [Date]! = []; var arrWeights: [Double]! = []; var arrWeights2: [Double]! = []; @IBOutlet weak var lineChart: LineChartView! override func viewDidLoad() { super.viewDidLoad(); // Do any additional setup after loading the view. // months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] // let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0] if(kid?.weights != nil){ arrKidWeights = kid!.weights!.array as! [Weight]; } for wt in arrKidWeights{ arrDates.append(wt.date! as Date); arrWeights.append(wt.weight); arrWeights2.append(wt.weight + 0.5); } setChart(dataPoints: arrDates, values: arrWeights); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setChart(dataPoints: [Date], values: [Double]){ lineChart.noDataText = "You need to provide data for the chart"; var dataEntries: [ChartDataEntry] = []; for i in 0..<dataPoints.count { let dataEntry = ChartDataEntry(x: Double(i), y: values[i]); dataEntries.append(dataEntry) } lineChart.backgroundColor = UIColor(red: 189/255, green: 195/255, blue: 199/255, alpha: 1) lineChart.xAxis.labelPosition = .bottom; // display values on xaxis // lineChart.xAxis.valueFormatter = IndexAxisValueFormatter(values: dataPoints); lineChart.animate(xAxisDuration: 1.0, yAxisDuration: 1.0); let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Unites"); let lineChartData = LineChartData(dataSet: lineChartDataSet); // set colors, array of colors to loop through for data point // chartDataSet.colors = [UIColor(red: 230/255, green: 126/255, blue: 34/255, alpha: 1)]; // lineChartDataSet.colors = ChartColorTemplates.material(); lineChart.data = lineChartData; // sets description text in lower right corner lineChart.chartDescription?.text = ""; } /* // 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
31b20e9302e5a72c26536d4645ef3844a7184334
Swift
rjliou/swiftgo_files
/uikit/uicollectionview/ExUICollectionView/ExUICollectionView/ViewController.swift
UTF-8
5,355
3.046875
3
[]
no_license
// // ViewController.swift // ExUICollectionView // // Created by joe feng on 2016/5/20. // Copyright © 2016年 hsin. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { var fullScreenSize :CGSize! override func viewDidLoad() { super.viewDidLoad() // 取得螢幕的尺寸 fullScreenSize = UIScreen.mainScreen().bounds.size // 設置底色 self.view.backgroundColor = UIColor.whiteColor() // 建立 UICollectionViewFlowLayout let layout = UICollectionViewFlowLayout() // 設置 section 的間距 四個數值分別代表 上、左、下、右 的間距 layout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5); // 設置每一行的間距 layout.minimumLineSpacing = 5 // 設置每個 cell 的尺寸 layout.itemSize = CGSizeMake(CGFloat(fullScreenSize.width)/3 - 10.0, CGFloat(fullScreenSize.width)/3 - 10.0) // 設置 header 及 footer 的尺寸 layout.headerReferenceSize = CGSize(width: fullScreenSize.width, height: 40) layout.footerReferenceSize = CGSize(width: fullScreenSize.width, height: 40) // 建立 UICollectionView let myCollectionView = UICollectionView(frame: CGRect(x: 0, y: 20, width: fullScreenSize.width, height: fullScreenSize.height - 20), collectionViewLayout: layout) // 註冊 cell 以供後續重複使用 myCollectionView.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: "Cell") // 註冊 section 的 header 跟 footer 以供後續重複使用 myCollectionView.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header") myCollectionView.registerClass(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer") // 設置委任對象 myCollectionView.delegate = self myCollectionView.dataSource = self // 加入畫面中 self.view.addSubview(myCollectionView) } // 必須實作的方法:每一組有幾個 cell func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 7 } // 必須實作的方法:每個 cell 要顯示的內容 func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // 依據前面註冊設置的識別名稱 "Cell" 取得目前使用的 cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MyCollectionViewCell // 設置 cell 內容 (即自定義元件裡 增加的圖片與文字元件) cell.imageView.image = UIImage(named: "0\(indexPath.item + 1).jpg") cell.titleLabel.text = "0\(indexPath.item + 1)" return cell } // 有幾個 section func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 2 } // 點選 cell 後執行的動作 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { print("你選擇了第 \(indexPath.section + 1) 組的") print("第 \(indexPath.item + 1) 張圖片") } // 設置 reuse 的 section 的 header 或 footer func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { // 建立 UICollectionReusableView var reusableView = UICollectionReusableView() // 顯示文字 let label = UILabel(frame: CGRect(x: 0, y: 0, width: fullScreenSize.width, height: 40)) label.textAlignment = .Center // header if kind == UICollectionElementKindSectionHeader { // 依據前面註冊設置的識別名稱 "Header" 取得目前使用的 header reusableView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", forIndexPath: indexPath) // 設置 header 的內容 reusableView.backgroundColor = UIColor.darkGrayColor() label.text = "Header"; label.textColor = UIColor.whiteColor() } else if kind == UICollectionElementKindSectionFooter { // 依據前面註冊設置的識別名稱 "Footer" 取得目前使用的 footer reusableView = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer", forIndexPath: indexPath) // 設置 footer 的內容 reusableView.backgroundColor = UIColor.cyanColor() label.text = "Footer"; label.textColor = UIColor.blackColor() } reusableView.addSubview(label) return reusableView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
12882ce6d1a485f72a4cc0762050da8c05920393
Swift
QuentinQuero/blackstone-front-ios
/Blackstone Fortress/Model/Starship.swift
UTF-8
517
2.921875
3
[]
no_license
// // Starship.swift // Blackstone Fortress // // Created by Carl on 26/01/2021. // import Foundation struct Starship { var name: String var appui: String var instalations: String var explorateur: String var image: String init(name: String, appui: String, instalations: String, explorateur: String, image: String) { self.name = name self.appui = appui self.instalations = instalations self.explorateur = explorateur self.image = image } }
true
6589d723772669a81fdeac06bba7ae97dcb4db91
Swift
anhquan291/ios-card-scan
/Example/Example/ViewController.swift
UTF-8
2,837
2.671875
3
[ "MIT" ]
permissive
// // ViewController.swift // Example // // Created by Lee Burrows on 20/04/2021. // import UIKit import SharkCardScan final class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() addStartButton() let scannerVC = SharkCardScanViewController(viewModel: CardScanViewModel(noPermissionAction: { [weak self] in self?.showNoPermissionAlert() }, successHandler: { (response) in print("Expiry 💣: \(response.expiry ?? "")") print("Card Number 💳: \(response.number)") print("Holder name 🕺: \(response.holder ?? "")") })) present(scannerVC, animated: true, completion: nil) } private func addStartButton() { let startCameraButton = UIButton(type: .custom, primaryAction: UIAction(title: "Start Card Scanner", image: nil, identifier: nil, discoverabilityTitle: nil, attributes: .destructive, state: .mixed, handler: { _ in let scannerVC = SharkCardScanViewController(viewModel: CardScanViewModel(noPermissionAction: { [weak self] in self?.showNoPermissionAlert() }, successHandler: { (response) in print(response) })) self.present(scannerVC, animated: true, completion: nil) })) view.addSubview(startCameraButton) startCameraButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ startCameraButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), startCameraButton.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) } func showNoPermissionAlert() { showAlert(style: .alert, title: "Oopps, No access", message: "Check settings and ensure the app has permission to use the camera.", actions: [UIAlertAction(title: "OK", style: .default, handler: { (_) in if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) } })]) } func showAlert(style: UIAlertController.Style, title: String?, message: String?, actions: [UIAlertAction]) { let alertController = UIAlertController(title: title, message: message, preferredStyle: style) alertController.view.tintColor = UIColor.black actions.forEach { alertController.addAction($0) } if style == .actionSheet && actions.contains(where: { $0.style == .cancel }) == false { alertController.addAction(UIAlertAction(title: "Close", style: .cancel, handler: nil)) } self.present(alertController, animated: true, completion: nil) } }
true
d2b44d786a3011d2e8e574b527914b3a86f74bf3
Swift
zackshapiro/SmashBrosDemo
/SuperSmash/Common/ImageViewContainer.swift
UTF-8
1,207
3
3
[]
no_license
// // ImageViewContainer.swift // SuperSmash // // Created by Zack Shapiro on 5/27/20. // Copyright © 2020 Zack Shapiro. All rights reserved. // import SwiftUI import Combine struct ImageViewContainer: View { @ObservedObject var remoteImageURL: RemoteImageURL init(imageUrl: String) { remoteImageURL = RemoteImageURL(imageURL: imageUrl) } var body: some View { Image(uiImage: UIImage(data: remoteImageURL.data) ?? UIImage()) .resizable() .scaledToFit() .clipShape(Circle()) .frame(width: 64, height: 64) .foregroundColor(Color(UIColor.secondarySystemFill)) } } // MARK: - RemoteImageURL class RemoteImageURL: ObservableObject { var didChange = PassthroughSubject<Data, Never>() @Published var data = Data() { didSet { didChange.send(data) } } init(imageURL: String) { guard let url = URL(string: imageURL) else { return } URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else { return } DispatchQueue.main.async { self.data = data } }.resume() } }
true
2b385e95ed27983f810be50197b2d52037dcc62a
Swift
20161104573/for1to100
/mxm.playground/Contents.swift
UTF-8
454
3.875
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit //import PlaygroundSupport //一到一百相加 var x=0 for i in 1...100{ x=x+i } //两个数相加 var a = 4; var b = 8; var c = a+b; print(c) // 十个数排序 var n = [4,2,5,12,53,6,46,3,23,35] for i in 0..<n.count { for j in i+1..<n.count { if(n[i]>n[j]){ var temp = n[j] n[j] = n[i] n[i] = temp } } } print(n)
true
c81a8b0d7868a210ed49beda61112454a44eb735
Swift
haspindergill/Xlambton
/xlambton/AddAgentViewController.swift
UTF-8
5,922
2.5625
3
[]
no_license
// // AddAgentViewController.swift // xlambton // // Copyright © 2018 jagdeep. All rights reserved. // import UIKit import SQLite3 class AddAgentViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate{ var db: OpaquePointer? @IBOutlet weak var tName: UITextField! @IBOutlet weak var tMission: UITextField! @IBOutlet weak var tCountry: UITextField! @IBOutlet weak var tDate: UITextField! var selectedField = 1 var pickerView = UIPickerView() let datePicker = UIDatePicker() let missions = ["I","R","P"] let countries = ["Canada","USA","UK","INDIA"] @IBAction func save(_ sender: Any) { var stmt: OpaquePointer? //the insert query let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) .appendingPathComponent("agents.sqlite") if sqlite3_open(fileURL.path, &db) != SQLITE_OK { print("error opening database") }else{ print("perfect") } if sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS Agents (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, country TEXT,mission TEXT,date TEXT)", nil, nil, nil) != SQLITE_OK { let errmsg = String(cString: sqlite3_errmsg(db)!) print("error creating table: \(errmsg)") } let queryString = "INSERT INTO Agents (name, country,mission,date) VALUES ('\(String(describing: UtilityFunctions.createCodeforAlphabet(text: tName.text ?? "")))','\(String(describing: tCountry.text ?? ""))','\(String(describing: tMission.text ?? ""))','\(String(describing: tDate.text ?? ""))')" //preparing the query if sqlite3_prepare(db, queryString, -1, &stmt, nil) != SQLITE_OK{ let errmsg = String(cString: sqlite3_errmsg(db)!) print("error preparing insert: \(errmsg)") return } //executing the query to insert values if sqlite3_step(stmt) != SQLITE_DONE { let errmsg = String(cString: sqlite3_errmsg(db)!) print("failure inserting hero: \(errmsg)") return } self.dismiss(animated: true) {} } override func viewDidLoad() { super.viewDidLoad() pickerView.delegate = self datePicker.datePickerMode = .date datePicker.addTarget(self, action: #selector(dateChanged(_:)), for: .valueChanged) tMission.inputView = pickerView tCountry.inputView = pickerView tDate.inputView = datePicker let toolBar = UIToolbar() toolBar.barStyle = UIBarStyle.default toolBar.isTranslucent = true toolBar.tintColor = UIColor.darkGray toolBar.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action:#selector(self.done)) let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) toolBar.setItems([spaceButton, doneButton], animated: false) toolBar.isUserInteractionEnabled = true tCountry.inputAccessoryView = toolBar tMission.inputAccessoryView = toolBar tDate.inputAccessoryView = toolBar // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func dateChanged(_ sender: UIDatePicker) { let components = Calendar.current.dateComponents([.year, .month, .day], from: sender.date) if let day = components.day, let month = components.month, let year = components.year { print("\(day)\(month)\(year)") tDate.text = "\(day)\(month)\(year)" } } @objc func done() { self.view.endEditing(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. } */ func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch selectedField { case 1: return missions.count case 2: return countries.count default: return missions.count } } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch selectedField { case 1: return missions[row] case 2: return countries[row] default: return missions[row] } } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if let txtField1 = self.view.viewWithTag(selectedField) as? UITextField { switch selectedField { case 1: txtField1.text = missions[row] case 2: txtField1.text = countries[row] default: txtField1.text = missions[row] } } } func textFieldDidEndEditing(_ textField: UITextField) { self.view.endEditing(true) } func textFieldDidBeginEditing(_ textField: UITextField) { selectedField = textField.tag pickerView.reloadAllComponents() pickerView.reloadInputViews() } }
true
406cfe3a5e99aa7b41e93d4c98b0c2bc0eeff75b
Swift
pahmed/TheArabianCenter
/TheArabianCenter/SyncModels.swift
UTF-8
4,771
2.875
3
[ "MIT" ]
permissive
// // SyncModels.swift // TheArabianCenter // // Created by Ahmed Henawey on 2/25/17. // Copyright (c) 2017 Ahmed Henawey. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit import ObjectMapper import CoreLocation struct Sync { struct Save { /// Save Request, it conform Mappable Protocal to Make ObjectMapper able to serialize the object to JSON and vice versa struct Request : Mappable,Hashable{ var title:String var description:String var imageLocation:String? var lat:Double? var long:Double? init(title:String, description:String, imageLocation:String? = nil, location:CLLocation? = nil) { self.title = title self.description = description self.imageLocation = imageLocation lat = location?.coordinate.latitude long = location?.coordinate.longitude } init?(map: Map) { guard let title = map.JSON["title"] as? String, let description = map.JSON["description"] as? String, let imageLocation = map.JSON["imageLocation"] as? String else{ return nil } self.title = title self.description = description self.imageLocation = imageLocation } mutating func mapping(map: Map) { title <- map["title"] description <- map["description"] imageLocation <- map["imageLocation"] lat <- map["location.lat"] long <- map["location.long"] } var hashValue: Int{ get{ return "\(title),\(description),\(lat),\(long)".hashValue } } public static func ==(lhs: Sync.Save.Request, rhs: Sync.Save.Request) -> Bool{ return lhs.hashValue == rhs.hashValue } } } struct Retrieve { struct Request{ var id :String init(id :String) { self.id = id } } } /// Retrieve Response, it conform Mappable Protocal to Make ObjectMapper able to serialize the object to JSON and vice versa struct Response: Mappable{ var id :String var title:String var description:String var imageLocation:String init(id :String, title:String, description:String, imageLocation:String) { self.id = id self.title = title self.description = description self.imageLocation = imageLocation } init?(map: Map) { guard let id = map.JSON["id"] as? String, let title = map.JSON["title"] as? String, let description = map.JSON["description"] as? String, let imageLocation = map.JSON["imageLocation"] as? String else{ return nil } self.id = id self.title = title self.description = description self.imageLocation = imageLocation } mutating func mapping(map: Map) { id <- map["id"] title <- map["title"] description <- map["description"] imageLocation <- map["imageLocation"] } } struct ViewModel { var id :String var title:String var description:String var imageLocation:String } enum Error:Swift.Error { case unknownError case configurationMissing case invalidData case invalidResponse case failure(error:Swift.Error) var localizedDescription: String{ switch self { case .unknownError: return NSLocalizedString("unknownError", comment: "") case .configurationMissing: return NSLocalizedString("configurationMissing", comment: "") case .invalidData: return NSLocalizedString("InvalidData", comment: "") case .invalidResponse: return NSLocalizedString("invalidResponse", comment: "") case let .failure(error): return error.localizedDescription } } } }
true
2c921bfd9e455ea30ecfd65cf5704099fbe03ba0
Swift
awmcclain/CEF.swift
/CEF.swift/Proxies/CEFAuthCallback.swift
UTF-8
759
2.78125
3
[ "BSD-3-Clause" ]
permissive
// // CEFAuthCallback.swift // CEF.swift // // Created by Tamas Lustyik on 2015. 08. 05.. // Copyright © 2015. Tamas Lustyik. All rights reserved. // import Foundation public extension CEFAuthCallback { /// Continue the authentication request. public func doContinue(username: String, password: String) { let cefUserPtr = CEFStringPtrCreateFromSwiftString(username) let cefPassPtr = CEFStringPtrCreateFromSwiftString(password) defer { CEFStringPtrRelease(cefUserPtr) CEFStringPtrRelease(cefPassPtr) } cefObject.cont(cefObjectPtr, cefUserPtr, cefPassPtr) } /// Cancel the authentication request. public func doCancel() { cefObject.cancel(cefObjectPtr) } }
true
c168982424466743dc520035a5512fd7c627a463
Swift
yuri-cavalcanti-git/Swift-Estudos
/Exercicios-Desafios/Modelagem_Supermercado/Modelagem_Supermercado.playground/Contents.swift
UTF-8
2,643
3.546875
4
[]
no_license
import UIKit class Person { var name: String var birthday: String var cpf: Int var address: String var email: String var phone: Int init(name: String, birthday: String, cpf: Int, address: String, email: String, phone: Int) { self.name = name self.birthday = birthday self.cpf = cpf self.address = address self.email = email self.phone = phone } func insertPerson() { print("Pessoa Cadastrada") } func updatePerson() { print("Dados Atualizados") } func deletePerson() { print("Pessoa Deletada") } } class Employee: Person { var salary: Double var department: String var hiringDate: String init(name: String, birthday: String, cpf: Int, address: String, email: String, phone: Int, salary: Double, department: String, hiringDate: String) { self.salary = salary self.department = department self.hiringDate = hiringDate super.init(name: name, birthday: birthday, cpf: cpf, address: address, email: email, phone: phone) } func receiveSalary() { print("Receber salário") } func setShift() { print("Turno definido") } func organizeStock() { print("Estoque Organizado") } } class Client: Person { var cardNumber: Int var purchaseId: Int var paymentMethod: String init(name: String, birthday: String, cpf: Int, address: String, email: String, phone: Int, cardNumber: Int, purchaseId: Int, paymentMethod: String) { self.cardNumber = cardNumber self.purchaseId = purchaseId self.paymentMethod = paymentMethod super.init(name: name, birthday: birthday, cpf: cpf , address: address, email: email, phone: phone) } func makePayment() { print("Pagamento efetado") } func order() { print("Pedido realizado") } } let yuri = Client(name: "Yuri Cavalcanti", birthday: "23-06-1984", cpf: 22682585809, address: "Rua 10 - São Paulo", email: "@.com", phone: 5524-1412, cardNumber: 123456, purchaseId: 5559, paymentMethod: "Cartão de Crédito") print("Nome: \(yuri.name), Data de Nascimento: \(yuri.birthday)") yuri.insertPerson() yuri.order() yuri.makePayment() let dayane = Employee(name: "Dayane Gomes", birthday: "27-01-1988", cpf: 12345678, address: "Rua João - Campinas",email: "@gmail", phone: 5555-1111, salary: 5425.76, department: "ADM", hiringDate: "15-09-2015") print("Nome: \(dayane.name), Departamento: \(dayane.department), Salario R$\(dayane.salary)") dayane.updatePerson() dayane.receiveSalary() dayane.setShift()
true
dbf9702202bca12bc2cf818ee09185d425b7fbb4
Swift
aaku14n/IOSComplete
/completeProject/Extentions/ImageView.swift
UTF-8
928
2.9375
3
[]
no_license
// // ImageView.swift // completeProject // // Created by Aakarsh Yadav on 06/10/20. // import Foundation import UIKit extension UIImageView { func load(url: URL) { DispatchQueue.global().async { [weak self] in if let data = try? Data(contentsOf: url) { if let image = UIImage(data: data) { DispatchQueue.main.async { self?.image = image } } } } } } extension UIImage { class func getImageFrom(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context?.setFillColor(color.cgColor) context!.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } }
true
372ec8dea7bc150ecaa358f41320b874b3bbbfcc
Swift
RyukieSama/BuildTimeAnalyzer-for-Xcode
/BuildTimeAnalyzer/ProcessingState.swift
UTF-8
833
2.9375
3
[ "MIT", "BSD-2-Clause" ]
permissive
// // ProcessingState.swift // BuildTimeAnalyzer // enum ProcessingState { case processing case waiting case completed(didSucceed: Bool, stateName: String) static let cancelledString = "Cancelled" static let completedString = "Completed" static let failedString = "No valid logs found" static let processingString = "Processing log..." static let waitingForBuildString = "Waiting..." } extension ProcessingState : Equatable {} func ==(lhs: ProcessingState, rhs: ProcessingState) -> Bool { switch (lhs, rhs) { case (let .completed(didSucceed1, _), let .completed(didSucceed2, _)): return didSucceed1 == didSucceed2 case (.processing, .processing), (.waiting, .waiting): return true default: return false } }
true
c2b5bc3ff5bdddefe817427e94f60692324853a4
Swift
WhiteHaus/NBAStats
/NBAStats/NBAStats/ViewController.swift
UTF-8
1,917
2.75
3
[]
no_license
// // ViewController.swift // NBAStats // // Created by Andrew Hwang on 9/28/18. // Copyright © 2018 WhiteHaus. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { let teams = ["Bulls", "Wizards", "Lakers", "Nets", "TimberWolves", "Clippers", "Hornets", "Knicks"] var teamsCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewLayout()) let reuseID = "teamCell" func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return teams.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseID, for: indexPath) as! Team cell.teamName.text = teams[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("\(teams[indexPath.item])") } override func viewDidLoad() { super.viewDidLoad() loadData() } override func viewWillAppear(_ animated: Bool) { loadData() } func loadData() { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: view.frame.width, height: 100) teamsCollectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height), collectionViewLayout: layout) teamsCollectionView.delegate = self teamsCollectionView.dataSource = self teamsCollectionView.register(Team.self, forCellWithReuseIdentifier: reuseID) teamsCollectionView.backgroundColor = UIColor.red view.addSubview(teamsCollectionView) } }
true
f1a930801fdcf6b19483904ce0f666b1b69487c3
Swift
eis6aer/Boundaries
/Boundaries/Boundary.swift
UTF-8
3,015
3.0625
3
[ "MIT" ]
permissive
// // Boundary.swift // Boundaries // // Created by Frank Valbuena on 7/05/20. // Copyright © 2020 Frank Valbuena. All rights reserved. // import Foundation /// A boundary is a model for handling the object graph construction of a group of objects. /// Never use this protocol directly instead inherit from Boundary, Adapter, Container or RootBoundary public protocol BoundaryProtocol { associatedtype Dependencies: BoundaryListProtocol } /// A boundary is a class and a protocol, it is meant to handling the object graph construction of a gruop of objects. public typealias Boundary = AnyBoundary & BoundaryProtocol /// An empty boundary having no inputs or external sources. public struct Empty: BoundaryProtocol { public typealias Dependencies = BoundaryList static let empty = Empty() } /// Type erasure for boundary objects. This is the base class for any client extension. This base class /// has a default associated type for dependencies. By default the dependencies list is empty. open class AnyBoundary { /// Default Dependencies associatedtype for BoundaryProtocol. public typealias Dependencies = BoundaryList /// Internal use only struct. This can't be initialized publicly. public struct Internals { let data: Any } fileprivate let internals: Internals /// Required initializer for this class. public required init(internals: Internals) { self.internals = internals } /// Creates an input port based on the passed implementation. InputPorts make your properties /// Accessible to dependents of your boundaries. This method is the only way to create input ports /// The init of the InputPort is internal. This brings cohesion between ports and boundaries. public final func makeInputPort<Interface>(implementation: Interface) -> InputPort<Interface> { return InputPort(implementation: implementation) } } public extension BoundaryProtocol { /// Since Boundary inherits from AnyBoundary, this typealias disambiguate between the associated type /// and the default typealias defined in AnyBoundary. typealias SelfDependencies = Self.Dependencies } public extension BoundaryProtocol where Self: AnyBoundary { /// Resolved type for the Boundary. The instances of Boundary are never exposed to the client. /// Instead resolved wraps the boundary giving access to the input ports and protecting the rest /// of the internal code of the boundary from being used externally. typealias Resolved = Boundaries.Resolved<Self> /// This property brings via dynamic look-up all the input port properties of your dependencies. /// Use it for creating the boundary's objects injecting its dependencies. var dependencies: SelfDependencies { return internals.data as! SelfDependencies } } extension BoundaryProtocol where Self: AnyBoundary { init(dependencies: SelfDependencies) { self.init(internals: .init(data: dependencies)) } }
true
51b132e1b289290bfd5b2491023d6478ff9cb4d7
Swift
TennantShaw/SetsAndOperationals
/SetsAndOptionals20170405/Player.swift
UTF-8
6,115
3.6875
4
[]
no_license
// // Player.swift // SetsAndOptionals20170405 // // Created by Tennant Shaw on 4/6/17. // Copyright © 2017 Tennant Shaw. All rights reserved. // import Foundation enum Symbol { case x case o } enum Location: Int { case zero = 0 case one = 1 case two = 2 case three = 3 case four = 4 case five = 5 case six = 6 case seven = 7 case eight = 8 case nine = 9 } struct Player : Equatable { var name: String let symbol: Symbol public static func == (lhs: Player, rhs: Player) -> Bool { return lhs.name == rhs.name && lhs.symbol == rhs.symbol } } struct Game : Equatable { let playerOne: Player let playerTwo: Player var playerMove: [Move] = [] public static func == (lhs: Game, rhs: Game) -> Bool { return lhs.playerOne == rhs.playerOne && lhs.playerTwo == rhs.playerTwo } } struct Move : Equatable { let location: Location let player: Player public static func == (lhs: Move, rhs: Move) -> Bool { return lhs.location == rhs.location && lhs.player == rhs.player } } // Create Player func func createPlayer(name: String, symbol: Symbol) -> Player? { if name.isEmpty { return nil } else { return Player(name: name, symbol: symbol) } } // Create Game func func createGame(xPlayer: Player, oPlayer: Player) -> Game? { if xPlayer.symbol == oPlayer.symbol { return nil } else { return Game(playerOne: xPlayer, playerTwo: oPlayer, playerMove: []) } } // Create a play func func play(_ player: Player, _ move: Location, _ game: Game) -> Game? { let turn = Move(location: move, player: player) var newTurn = game if game.playerMove.contains(Move(location: move, player: player)) { return nil } else { newTurn.playerMove.append(turn) } return newTurn } // Create a spot checker func func symbol(at location: Location, in game: Game) -> Symbol? { var playerSymbol: Symbol? let emptySpace: Symbol? = nil let spots = game.playerMove for i in spots { switch i.location { case .nine: if playerSymbol != nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .eight: if playerSymbol != nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .seven: if playerSymbol != nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .six: if playerSymbol != nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .five: if playerSymbol != nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .four: if playerSymbol != nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .three: if playerSymbol != nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .two: if playerSymbol != nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .one: if playerSymbol != nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .zero: return emptySpace } } return playerSymbol } func symbol2(at location: Location, in game: Game) -> Symbol? { var playerSymbol: Symbol? let emptySpace: Symbol? = nil let spots = game.playerMove for i in spots { switch i.location { case .nine: if playerSymbol == nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .eight: if playerSymbol == nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .seven: if playerSymbol == nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .six: if playerSymbol == nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .five: if playerSymbol == nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .four: if playerSymbol == nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .three: if playerSymbol == nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .two: if playerSymbol == nil { return playerSymbol } else { playerSymbol = i.player.symbol } fallthrough case .one: if playerSymbol == nil { return playerSymbol } else { playerSymbol = i.player.symbol fallthrough } case .zero: return emptySpace } } return emptySpace }
true
4ca2ab6a45270ea9a18a58fc551dba33454db0b2
Swift
NorbertoVasconcelos/GistViewer
/Domain/Entities/User.swift
UTF-8
1,073
3.203125
3
[]
no_license
// // User.swift // Domain // // Created by Norberto Vasconcelos on 08/11/2018. // Copyright © 2018 Vasconcelos. All rights reserved. // import Foundation public struct User: Codable { public var id: String public var username: String public var avatarUrl: String private enum CodingKeys: String, CodingKey { case id case username = "login" case avatarUrl = "avatar_url" } public init() { self.id = "" self.username = "" self.avatarUrl = "" } public init(id: String, username: String, avatarUrl: String) { self.id = id self.username = username self.avatarUrl = avatarUrl } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let idInt = try container.decode(Int.self, forKey: .id) id = String(idInt) username = try container.decode(String.self, forKey: .username) avatarUrl = try container.decode(String.self, forKey: .avatarUrl) } }
true
442e4d4f3de4fd4ea0e3815fb9b61f976958fd78
Swift
Ankish8/TableTennis
/TableTennis WatchKit Extension/ViewModels/TennisViewModel.swift
UTF-8
3,763
2.859375
3
[]
no_license
// // TennisViewModel.swift // TableTennis WatchKit Extension // // Created by Ankish Khatri on 28/05/21. // import SwiftUI import Foundation class TennisViewModel : ObservableObject { @Published var match: [Matches] = [] { didSet { saveData() } } init() { getData() } let matchKey: String = "match_list" @Published var score1: Int = 0 @Published var score2: Int = 0 @Published var isWon: Bool = false @Published var winner: String = "" @Published var maxPoints: Int = 11 @Published var matchcount: Int = 0 @AppStorage("p1") var playerName1 = "Ankish" @AppStorage("p2") var playerName2 = "Somu" @Published var player1TotalWin: Int = 0 @Published var player2TotalWin: Int = 0 @Published var MatchPoint: Bool = false //Match Point // MARK: UpdateMatch func updateMatch(score1 : Int, score2 : Int, winnerName: String, MatchCount: Int) { let newMatch = Matches(id: UUID().uuidString, player1Score: score1, player2Score: score2, winnerName: winner, MatchCount: matchcount) match.append(newMatch) } // MARK: Delete history func deleteHistory() { match.removeAll() } // MARK: CheckGamePoint func checkGamePoint() { if score1 <= (maxPoints - 1) && score2 <= (maxPoints - 1) { if (score1 == (maxPoints - 1) && score2 == (maxPoints - 1)) { MatchPoint = false } else if (score1 == (maxPoints - 1) || score2 == (maxPoints - 1)) { if !MatchPoint { MatchPoint = true WKInterfaceDevice.current().play(.start) } } } else { if score1 > score2 + 1 { winner = playerName1 matchcount += 1 player1TotalWin += 1 updateMatch(score1: score1, score2: score2, winnerName: winner, MatchCount: matchcount) isWon.toggle() WKInterfaceDevice.current().play(.success) } else if score2 > score1 + 1 { winner = playerName2 player2TotalWin += 1 matchcount += 1 updateMatch(score1: score1, score2: score2, winnerName: winner, MatchCount: matchcount) isWon.toggle() WKInterfaceDevice.current().play(.failure) } else if score1 != score2 { if !MatchPoint { MatchPoint = true WKInterfaceDevice.current().play(.start) } } else { MatchPoint = false } } } // MARK: UpdateScore func updateScore(score: Int, side1: Bool) { if side1 { self.score1 = score + 1 } else { self.score2 = score + 1 } checkGamePoint() } // MARK: Reset func reset() { score1 = 0 score2 = 0 MatchPoint = false isWon = false } // MARK: SaveData in UserDefaults func saveData() { if let encodedData = try? JSONEncoder().encode(match) { UserDefaults.standard.set(encodedData, forKey: matchKey) } } // MARK: GetData from UserDefaults func getData() { guard let data = UserDefaults.standard.data(forKey: matchKey), let savedData = try? JSONDecoder().decode([Matches].self, from: data) else { return } self.match = savedData } }
true
3aab3ba6c8f82778055be9221a9ad98063fc7f34
Swift
K-Y-31/YoutubePlayer-1
/YoutubePlayer/User/ProfileView.swift
UTF-8
2,943
2.640625
3
[]
no_license
// // ProfileView.swift // YoutubePlayer // // Created by 木本瑛介 on 2021/06/18. // import SwiftUI import Firebase struct ProfileView: View { @ObservedObject var fetchuserinfo = FetchLoginUserInfo() @State var ispresented : Bool = false @State var issetting: Bool = false @State var usermodel = UserModel(dic: ["email": "default"]) var body: some View { VStack { HStack(spacing: 20) { Text("Profile") .font(.title) Spacer(minLength: 0) Button(action: { self.ispresented.toggle() }) { Text("Friendを探す") .foregroundColor(.white) .padding(.vertical, 10) .background(Color(.blue)) .cornerRadius(10) }.padding() Button(action: { self.issetting.toggle() }) { Image(systemName: "gearshape.fill") } } .padding() HStack { VStack(alignment: .leading) { URLImageView(viewModel: .init(url: fetchuserinfo.usermodel.profileImageUrl)) .aspectRatio(contentMode: .fill) .frame(width: 100, height: 100) .clipShape(Circle()) .cornerRadius(10) .shadow(color: Color.black.opacity(0.1), radius: 5, x: 8, y: 8) .shadow(color: Color.white.opacity(0.1), radius: 5, x: 8, y: 8) } VStack(alignment: .leading, spacing: 12) { Text(fetchuserinfo.usermodel.username) .font(.title) .foregroundColor(Color.black.opacity(0.8)) Text(fetchuserinfo.usermodel.Role ?? "") .foregroundColor(Color.black.opacity(0.7)) .padding(.top, 8) Text(fetchuserinfo.usermodel.Message ?? "") .font(.title) .foregroundColor(Color.black.opacity(0.7)) } .padding(.leading, 20) Spacer(minLength: 0) } .padding(.horizontal, 20) .padding(.top, 10) Spacer(minLength: 0) } .background(Color("Color1").edgesIgnoringSafeArea(.all)) .fullScreenCover(isPresented: self.$ispresented, content: { SearchUserListView() }) .fullScreenCover(isPresented: self.$issetting, content: { SettingView() }) // .onWillAppear { // self.fetchuserinfo.fetchloginUserInfo() // } } } struct ProfileView_Previews: PreviewProvider { static var previews: some View { ProfileView() } }
true
f30e804fe78ae1d714a24a054c3c1fec46bfc4d4
Swift
Rollerqt/Prenly
/Prenly/CollectionViews/NewsCV.swift
UTF-8
6,497
2.796875
3
[]
no_license
// // NewsCV.swift // Prenly // // Created by Luka Ivkovic on 10/09/2021. // import UIKit class NewsCV: UICollectionView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { var posts = [Post]() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.dataSource = self self.delegate = self } func loadData(urlString: String) { //1. Set URL parameters if let url = URL(string: urlString) { // 2. Create a URLSession let session = URLSession(configuration: .default) // 3. Give the session a task let task = session.dataTask(with: url) { (data, response, error) in if error == nil { let decoder = JSONDecoder() if let safeData = data { do { //print(response) let results = try decoder.decode(Results.self, from: safeData) //print(results) //Update must happen on the main thread, not in the background DispatchQueue.main.async { self.posts = results.articles self.reloadData() } } catch { print(error) } } } } // 4. Start the task task.resume() } } func loadFavorites(){ let userDefaults = UserDefaults.standard var counter = 0 if userDefaults.object(forKey: "counter") != nil { counter = userDefaults.integer(forKey: "counter") } else { return } var post = Post.init() for i in 0 ... counter { let p = counter - i - 1 post.author = userDefaults.string(forKey: "author" + String.init(p)) post.content = userDefaults.string(forKey: "content" + String.init(p)) post.description = userDefaults.string(forKey: "description" + String.init(p)) post.source = Source.init(id: userDefaults.string(forKey: "sourceId" + String.init(p))) post.publishedAt = userDefaults.string(forKey: "publishedAt" + String.init(p))! post.title = userDefaults.string(forKey: "title" + String.init(p))! post.urlToImage = userDefaults.string(forKey: "urlToImage" + String.init(p)) post.url = userDefaults.string(forKey: "url" + String.init(p))! posts.append(post) } self.reloadData() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return posts.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //creating PreviewCell and filling it out with the data let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "previewCell", for: indexPath as IndexPath) as! PreviewCell let post = posts[indexPath.row] cell.post = post cell.labelTitle.text = post.title if !(post.author?.elementsEqual("") ?? true){ //The author string gives back options of authors, I'm choosing the default one cell.labelAuthor.text = String.init(post.author!.split(separator: ",")[0]) } else { cell.labelAuthor.text = "Unknown" } let split = post.publishedAt.split(separator: "T") let date = String.init(split[0]) let now = Date() let formatter = DateFormatter() formatter.timeZone = TimeZone.current formatter.dateFormat = "yyyy-MM-dd" let currentDate = formatter.string(from: now) let time = String(split[1]).split(separator: ":") if date.elementsEqual(currentDate) { cell.labelDate.text = String(time[0] + ":" + time[1]) } else { cell.labelDate.text = date } if !(post.urlToImage?.isEmpty ?? true) { if post.urlToImage!.contains(".jpg") { cell.image.loadFromURL(urlString: post.urlToImage!) } else { cell.image.loadFromURL(urlString: Constants.NO_IMAGE) } } else { cell.image.loadFromURL(urlString: Constants.NO_IMAGE) } cell.layer.borderWidth = 1 cell.layer.borderColor = CGColor.init(red: 211/255, green: 211/255, blue: 211/255, alpha: 1) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.frame.width, height: 150) } } //since there is always a problem with asynchronous loading data with images, //I am using the extension with cache. It also prevents the app from //loading the picture from one item multiple times, it loads it just once, //saving energy and making everything look and work professionally let imageCache = NSCache<NSString, UIImage>() extension UIImageView { func loadFromURL(urlString: String) { let url = URL(string: urlString) image = nil //checks if image is already loaded, preventing unnecessary energy consumption if let imageFromCache = imageCache.object(forKey: urlString as NSString) { self.image = imageFromCache return } if url == nil { return } URLSession.shared.dataTask(with: url!) { (data, response, error) in if error != nil{ print(error!) return } DispatchQueue.main.async { let imageToCache = UIImage(data: data!) //doing this to prevent loading image every time cell is visible imageCache.setObject(imageToCache!, forKey: urlString as NSString) self.image = imageToCache } }.resume() } }
true
4c17be965b09723c7d6d583e486f94bb5f8da1fc
Swift
imberezin/Tehillim
/SwiftUIApp/Shared/ViewModel/TheilimMV.swift
UTF-8
5,965
2.578125
3
[ "MIT" ]
permissive
// // TheilimMV.swift // Tehilim2.0 // // Created by israel.berezin on 01/07/2020. // import SwiftUI import Combine import WidgetKit class TheilimMV: ObservableObject { let menuItem : MenuItem @Published var chapterDivision: ChapterDivisionElement? = nil @AppStorage("WidgetChaptersDivision", store: UserDefaults(suiteName: "group.es.vodafone.ONO")) var widgetChaptersDivisionData: Data = Data(count: 0) // init() { self.menuItem = MenuItem(name: "Widget", prayerMode: .Widget) } init(menuItem : MenuItem) { self.menuItem = menuItem self.dataToWidget() WidgetCenter.shared.reloadAllTimelines() self.prepareThilimList() } func prepareThilimList(){ switch self.menuItem.prayerMode { case .Monthly: print("Monthly") self.prepareMonthly() case .Weekly: print("Weekly") self.prepareWeekly() case .Book: print("Book") self.prepareAllBook() case .Personal: print("Personal") case .Elul: print("Elul") case .Single: print("Single") case .Spaicel: print("Spaicel") default: print("Widget") } } func prepareMonthly(){ let hebDate : String = self.getHebrewDate(date: Date()) print("hebDate = \(hebDate)") let parts: Array = hebDate.components(separatedBy: " ") let selectDay = (Int(parts[0])!) - 1 // our index start form 0 and days start from 1! print("selectDay = \(selectDay)") let chapterDivision = self.loadJson(fileName: "MonthlyThilim") let todayChapterDivision = chapterDivision[selectDay] if (selectDay == 28){ //check if month is 29 or 30 days let hebNextDate : String = self.getHebrewDate(date: self.dateByAddingDays(inDays: 1)) let parts1: Array = hebNextDate.components(separatedBy: " ") print("hebNextDate = \(hebNextDate)") // it 29 days in month need say also missing day let nextDay = (Int(parts1[0])!) - 1 if (nextDay == 0) { let nextChapterDivision = chapterDivision[selectDay+1] self.chapterDivision = ChapterDivisionElement(start: todayChapterDivision.start, end: nextChapterDivision.end) }else{ self.chapterDivision = ChapterDivisionElement(start: todayChapterDivision.start, end: todayChapterDivision.end) } }else{ self.chapterDivision = ChapterDivisionElement(start: todayChapterDivision.start, end: todayChapterDivision.end) } } func prepareWeekly(){ let selectDay = (Date().dayNumberOfWeek()!)-1 let chapterDivision = self.loadJson(fileName: "WeeklyThilim") self.chapterDivision = chapterDivision[selectDay] } func prepareAllBook(){ self.chapterDivision = ChapterDivisionElement(start: "1", end: "149") } func loadJson(fileName: String) -> ChapterDivision { let url = Bundle.main.url(forResource: fileName, withExtension: "json") let data = try? Data(contentsOf: url!) let chapterDivision = try! ChapterDivision(data: data!) print(chapterDivision.count) return chapterDivision // } public func getHebrewDate(date:Date) -> String { let hebrew = NSCalendar(identifier: NSCalendar.Identifier.hebrew) let formatter = DateFormatter() formatter.dateStyle = DateFormatter.Style.short formatter.timeStyle = DateFormatter.Style.short formatter.calendar = hebrew as Calendar? formatter.locale = Locale(identifier: "en") let str:String = formatter.string(from: date as Date) print(str) return (str) } func dateByAddingDays(inDays:NSInteger)->Date{ let today = Date() return Calendar.current.date(byAdding: .day, value: inDays, to: today)! } } extension TheilimMV { func hebTodayDate() -> String{ let hebDate : String = self.getHebrewDate(date: Date()) return hebDate } @discardableResult func dataToWidget() -> [ChapterDivisionStoreElement]{ let hebDate : String = self.getHebrewDate(date: Date()) print("hebDate = \(hebDate)") let parts: Array = hebDate.components(separatedBy: " ") let selectDay = (Int(parts[0])!) - 1 // our index start form 0 and days start from 1! print("selectDay = \(selectDay)") let chapterDivision = self.loadJson(fileName: "MonthlyThilim") let todayChapterDivision: ChapterDivisionElement = chapterDivision[selectDay] let selectWeeklyDay = (Date().dayNumberOfWeek()!)-1 let weeklyChapters = self.loadJson(fileName: "WeeklyThilim") let weeklyChapterDivision: ChapterDivisionElement = weeklyChapters[selectWeeklyDay] let todayChapterDivisionStoreElement = ChapterDivisionStoreElement(todayChapterDivision, storeDate: Date()) let weeklyChapterDivisionStoreElement = ChapterDivisionStoreElement(weeklyChapterDivision, storeDate: Date()) let array = [todayChapterDivisionStoreElement, weeklyChapterDivisionStoreElement] guard let chaptersData = try? JSONEncoder().encode(array) else { return array } self.widgetChaptersDivisionData = chaptersData return array } } //do { // let encodedData = try NSKeyedArchiver.archivedData(withRootObject: array, requiringSecureCoding: false) // self.widgetChaptersDivisionData = encodedData // } catch let error as NSError { // print(error) // }
true
94bc47aaf25e4642fe8567a9d74cc32f897f21ae
Swift
asielcabrera/todus
/todus/Views/Home/BottomView.swift
UTF-8
1,840
2.71875
3
[]
no_license
// // BottomView.swift // todus // // Created by Asiel Cabrera on 8/22/20. // Copyright © 2020 Asiel Cabrera. All rights reserved. // import SwiftUI struct BottomView: View { @Binding var index : Int var body : some View{ HStack{ Button(action: { self.index = 0 }) { Image(systemName: "message.fill") .resizable() .frame(width: 22, height: 22) .foregroundColor(self.index == 0 ? Color.white : Color.white.opacity(0.5)) .padding(.horizontal) } Spacer(minLength: 10) Button(action: { self.index = 1 }) { Image("group") .resizable() .frame(width: 22, height: 22) .foregroundColor(self.index == 1 ? Color.white : Color.white.opacity(0.5)) .padding(.horizontal) } Spacer(minLength: 10) Button(action: { self.index = 2 }) { Image("settings") .resizable() .frame(width: 22, height: 22) .foregroundColor(self.index == 2 ? Color.white : Color.white.opacity(0.5)) .padding(.horizontal) } }.padding(.horizontal, 30) .padding(.bottom, UIApplication.shared.windows.first?.safeAreaInsets.bottom) } }
true
e88108e908ae8b4201d4e95438b2e3e0b204f9bb
Swift
CarsonCooley/Math-a-Mole
/Math-a-Mole-1.0/View Controllers/ModeSelectViewController.swift
UTF-8
2,898
2.75
3
[]
no_license
// // WelcomeViewConntroller.swift // Math-a-Mole-1.0 // // Created by Carson Cooley on 8/5/21. // import UIKit class ModeSelectViewController: UIViewController { @IBOutlet weak var beginnerButton: UIButton! @IBOutlet weak var intermediateButton: UIButton! @IBOutlet weak var advancedButton: UIButton! @IBOutlet weak var expertButton: UIButton! @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var topView: UIView! @IBOutlet weak var middleView: UIView! @IBOutlet weak var bottomView: UIView! var difficultyButtons: [UIButton] = [] var views: [UIView] = [] var activeDifficultySelected: String = "" override func viewDidLoad() { super.viewDidLoad() nextButton.alpha = 0.0 difficultyButtons = [beginnerButton, intermediateButton, advancedButton, expertButton] for button in difficultyButtons { button.layer.cornerRadius = 10 button.clipsToBounds = true } nextButton.layer.cornerRadius = 10 nextButton.clipsToBounds = true navigationController?.navigationBar.tintColor = UIColor.white views = [topView, middleView, bottomView] for view in views { view.backgroundColor = UIColor.clear } descriptionLabel.text = "" } override func viewDidDisappear(_ animated: Bool) { nextButton.isHidden = true descriptionLabel.text = "" for button in difficultyButtons { button.alpha = 1.0 } } @IBAction func difficultySelected(_ sender: UIButton) { nextButton.isHidden = false nextButton.alpha = 1.0 for button in difficultyButtons { button.alpha = 0.33 } sender.alpha = 1.0 activeDifficultySelected = sender.currentTitle! self.updateDescriptionLabel() } @IBAction func nextPressed(_ sender: UIButton) { performSegue(withIdentifier: K.Segues.advanceToGamePlay, sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let vc = segue.destination as! GameplayViewController vc.gameDifficulty = self.activeDifficultySelected } func updateDescriptionLabel() { if self.activeDifficultySelected == "Beginner" { self.descriptionLabel.text = K.Descriptions.beginner } else if self.activeDifficultySelected == "Intermediate" { self.descriptionLabel.text = K.Descriptions.intermediate } else if self.activeDifficultySelected == "Advanced" { self.descriptionLabel.text = K.Descriptions.advanced } else if self.activeDifficultySelected == "Expert" { self.descriptionLabel.text = K.Descriptions.expert } } }
true
86a797946ccb74bed160305ac1f53830ca424c72
Swift
Parrot-Developers/groundsdk-ios
/groundsdk/GroundSdk/Device/Peripheral/Gimbal.swift
UTF-8
20,312
2.640625
3
[]
permissive
// Copyright (C) 2019 Parrot Drones SAS // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the Parrot Company nor the names // of its contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // PARROT COMPANY BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS // OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED // AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. import Foundation /// Gimbal axis. @objc(GSGimbalAxis) public enum GimbalAxis: Int, CustomStringConvertible { /// Yaw axis of the gimbal. case yaw /// Pitch axis of the gimbal. case pitch /// Roll axis of the gimbal. case roll /// Debug description. public var description: String { switch self { case .yaw: return "yaw" case .pitch: return "pitch" case .roll: return "roll" } } /// Set containing all axes. public static let allCases: Set<GimbalAxis> = [.yaw, .pitch, .roll] } /// Gimbal frame of reference. @objc(GSFrameOfReference) public enum FrameOfReference: Int, CustomStringConvertible { /// Absolute frame of reference. case absolute /// Relative frame of reference. case relative /// Debug description. public var description: String { switch self { case .absolute: return "absolute" case .relative: return "relative" } } /// Set containing all frame of reference. public static let allCases: Set<FrameOfReference> = [.absolute, .relative] } /// Gimbal error. @objc(GSGimbalError) public enum GimbalError: Int, CustomStringConvertible { /// Calibration error. /// /// May happen during manual or automatic calibration. /// /// Application should inform the user that the gimbal is currently inoperable and suggest to verify that /// nothing currently hinders proper gimbal movement. /// /// The device will retry calibration regularly; after several failed attempts, it will escalate the current /// error to `.critical` level, at which point the gimbal becomes inoperable until both the issue /// is fixed and the device is restarted. case calibration /// Overload error. /// /// May happen during normal operation of the gimbal. /// /// Application should inform the user that the gimbal is currently inoperable and suggest to verify that /// nothing currently hinders proper gimbal movement. /// /// The device will retry stabilization regularly; after several failed attempts, it will escalate the current /// error to `.critical` level, at which point the gimbal becomes inoperable until both the issue /// is fixed and the device is restarted. case overload /// Communication error. /// /// Communication with the gimbal is broken due to some unknown software and/or hardware issue. /// /// Application should inform the user that the gimbal is currently inoperable. /// However, there is nothing the application should recommend the user to do at that point: either the issue /// will hopefully resolve itself (most likely a software issue), or it will escalate to critical level /// (probably hardware issue) and the application should recommend the user to send back the device for repair. /// /// The device will retry stabilization regularly; after several failed attempts, it will escalate the current /// error to `.critical` level, at which point the gimbal becomes inoperable until both the issue /// is fixed and the device is restarted. case communication /// Critical error. /// /// May occur at any time; in particular, occurs when any of the other errors persists after /// multiple retries from the device. /// /// Application should inform the user that the gimbal has become completely inoperable until the issue is /// fixed and the device is restarted, as well as suggest to verify that nothing currently hinders proper gimbal /// movement and that the gimbal is not damaged in any way. case critical /// Debug description. public var description: String { switch self { case .calibration: return "calibration" case .overload: return "overload" case .communication: return "communication" case .critical: return "critical" } } /// Set containing all axes. public static let allCases: Set<GimbalError> = [.calibration, .overload, .communication, critical] } /// Way of controlling the gimbal. @objc(GSGimbalControlMode) public enum GimbalControlMode: Int, CustomStringConvertible { /// Control the gimbal giving position targets. case position /// Control the gimbal giving velocity targets. case velocity /// Debug description. public var description: String { switch self { case .position: return "position" case .velocity: return "velocity" } } } /// Gimbal calibration process state. @objc(GSGimbalCalibrationProcessState) public enum GimbalCalibrationProcessState: Int, CustomStringConvertible { /// No ongoing calibration process. case none /// Calibration process in progress. case calibrating /// Calibration was successful. /// /// This result is transient, calibration state will change back to `.none` immediately after success is notified. case success /// Calibration failed. /// /// This result is transient, calibration state will change back to `.none` immediately after failure is notified. case failure /// Calibration was canceled. /// /// This result is transient, calibration state will change back to `.none` immediately after canceled is notified. case canceled /// Debug description. public var description: String { switch self { case .none: return "none" case .calibrating: return "calibrating" case .success: return "success" case .failure: return "failure" case .canceled: return "canceled" } } } /// Gimbal offsets manual correction process. @objcMembers @objc(GSGimbalOffsetsCorrectionProcess) public class GimbalOffsetsCorrectionProcess: NSObject { /// Set of axes that can be manually corrected. /// /// If a given axis can be corrected, calibrationOffsets of this axis will return a non-nil object when correction /// is started. internal(set) public var correctableAxes = Set<GimbalAxis>() /// Offsets correction applied to the gimbal. /// /// Only contains correctable axes. public var offsetsCorrection: [GimbalAxis: DoubleSetting] { return _offsetsCorrection } var _offsetsCorrection = [GimbalAxis: DoubleSettingCore]() /// Internal constructor. override init() {} } /// The gimbal is the peripheral "holding" and orientating the camera. It can be a real mechanical gimbal, or a software /// one. /// /// The gimbal can act on one or multiple axes. It can stabilize a given axis, meaning that the movement on this axis /// will be following the horizon (for `.roll` and `.pitch`) or the North (for the `.yaw`). /// /// Two frames of reference are used to control the gimbal with the `.position` mode, and to retrieve the gimbal /// attitude /// Relative frame of reference: /// - yaw: given angle is relative to the heading of the drone. /// Positive yaw values means a right orientation when seeing the gimbal from above. /// - pitch: given angle is relative to the body of the drone. /// Positive pitch values means an orientation of the gimbal towards the top of the drone. /// - roll: given angle is relative to the body of the drone. /// Positive roll values means an clockwise rotation of the gimbal. /// Absolute frame of reference: /// - yaw: given angle is relative to the magnetic North (clockwise). /// - pitch: given angle is relative to the horizon. /// Positive pitch values means an orientation towards sky. /// - roll: given angle is relative to the horizon line. /// Positive roll values means an orientation to the right when seeing the gimbal from behind. /// /// This peripheral can be retrieved by: /// ``` /// device.getPeripheral(Peripherals.gimbal) /// ``` public protocol Gimbal: Peripheral { /// Set of supported axes, i.e. axis that can be controlled. var supportedAxes: Set<GimbalAxis> { get } /// Set of current errors. /// /// When empty, the gimbal can be operated normally, otherwise, it is currently inoperable. /// In case the returned set contains the `.critical` error, then gimbal has become completely inoperable /// until both all other reported errors are fixed and the device is restarted. var currentErrors: Set<GimbalError> { get } /// Set of currently locked axes. /// While an axis is locked, you cannot set a speed or a position. /// /// An axis can be locked because the drone is controlling this axis on itself, thus it does not allow the /// controller to change its orientation. This might be the case during a FollowMe or when the /// `PointOfInterestPilotingItf` is active. /// /// Only contains supported axes. var lockedAxes: Set<GimbalAxis> { get } /// Bounds of the attitude by axis. /// Only contains supported axes. var attitudeBounds: [GimbalAxis: Range<Double>] { get } /// Max speed by axis. /// Only contains supported axes. var maxSpeedSettings: [GimbalAxis: DoubleSetting] { get } /// Whether the axis is stabilized. /// Only contains supported axes. var stabilizationSettings: [GimbalAxis: BoolSetting] { get } /// Current gimbal attitude. /// Empty when not connected. var currentAttitude: [GimbalAxis: Double] { get } /// Offset correction process. /// Not nil when offset correction is started (see `startOffsetsCorrectionProcess()` and /// `stopOffsetsCorrectionProcess()`). var offsetsCorrectionProcess: GimbalOffsetsCorrectionProcess? { get } /// Whether the gimbal is calibrated. var calibrated: Bool { get } /// Calibration process state. /// See `startCalibration()` and `cancelCalibration()` var calibrationProcessState: GimbalCalibrationProcessState { get } /// Controls the gimbal. /// /// Unit of the `yaw`, `pitch`, `roll` values depends on the value of the `mode` parameter: /// - `.position`: axis value is in degrees and represents the desired position of the gimbal on the given axis. /// - `.velocity`: axis value is in max speed (`maxSpeedSettings[thisAxis].value`) ratio (from -1 to 1). /// /// If mode is `.position`, frame of reference of a given axis depends on the value of the stabilization on /// this axis. If this axis is stabilized (i.e. `stabilizationSettings[thisAxis].value == true`), the .absolute /// frame of reference is used. Otherwise .relative frame of reference is used. /// - Parameters: /// - mode: the mode that should be used to move the gimbal. This parameter will change the unit of the following /// parameters /// - yaw: target on the yaw axis. `nil` if you want to keep the current value. /// - pitch: target on the pitch axis. `nil` if you want to keep the current value. /// - roll: target on the roll axis. `nil` if you want to keep the current value. func control(mode: GimbalControlMode, yaw: Double?, pitch: Double?, roll: Double?) /// Starts the offsets correction process. /// /// When offset correction is started, `offsetsCorrectionProcess` is not nil and correctable offsets can be /// corrected. func startOffsetsCorrectionProcess() /// Stops the offsets correction process. /// /// `offsetsCorrectionProcess` will be set to nil. func stopOffsetsCorrectionProcess() /// Starts calibration process. /// Does nothing when `calibrationProcessState` is `calibrating`. func startCalibration() /// Cancels the current calibration process. /// Does nothing when `calibrationProcessState` is not `calibrating`. func cancelCalibration() /// Gets the current attitude for a given frame of reference. /// /// - Parameter frameOfReference: the frame of reference /// - Returns: the current attitude as an array of axis. func currentAttitude(frameOfReference: FrameOfReference) -> [GimbalAxis: Double] } /// Objective-C version of Gimbal. /// /// The gimbal is the peripheral "holding" and orientating the camera. It can be a real mechanical gimbal, or a software /// one. /// /// The gimbal can act on one or multiple axes. It can stabilize a given axis, meaning that the movement on this axis /// will be following the horizon (for `.roll` and `.pitch`) or the North (for the `.yaw`). /// /// - Note: This class is for Objective-C only and must not be used in Swift. @objc public protocol GSGimbal: Peripheral { /// Offset correction process. /// Not nil when offset correction is started (see `startOffsetsCorrectionProcess()` and /// `stopOffsetsCorrectionProcess()`). var offsetsCorrectionProcess: GimbalOffsetsCorrectionProcess? { get } /// Whether the gimbal is calibrated. var calibrated: Bool { get } /// Calibration process state. /// See `startCalibration()` and `cancelCalibration()` var calibrationProcessState: GimbalCalibrationProcessState { get } /// Tells whether a given axis is supported /// /// - Parameter axis: the axis to query /// - Returns: `true` if the axis is supported, `false` otherwise func isAxisSupported(_ axis: GimbalAxis) -> Bool /// Tells whether the gimbal currently has the given error. /// /// - Parameter error: the error to query /// - Returns: `true` if the error is currently happening func hasError(_ error: GimbalError) -> Bool /// Tells whether a given axis is currently locked. /// /// While an axis is locked, you cannot set a speed or a position. /// /// An axis can be locked because the drone is controlling this axis on itself, thus it does not allow the /// controller to change its orientation. This might be the case during a FollowMe or when the /// `PointOfInterestPilotingItf` is active. /// /// - Parameter axis: the axis to query /// - Returns: `true` if the axis is supported and locked, `false` otherwise func isAxisLocked(_ axis: GimbalAxis) -> Bool /// Gets the lower bound of the attitude on a given axis. /// /// - Parameter axis: the axis /// - Returns: a double in an NSNumber. `nil` if axis is not supported. func attitudeLowerBound(onAxis axis: GimbalAxis) -> NSNumber? /// Gets the upper bound of the attitude on a given axis. /// /// - Parameter axis: the axis /// - Returns: a double in an NSNumber. `nil` if axis is not supported. func attitudeUpperBound(onAxis axis: GimbalAxis) -> NSNumber? /// Gets the max speed setting on a given axis. /// /// - Parameter axis: the axis /// - Returns: the max speed setting or `nil` if the axis is not supported. func maxSpeed(onAxis axis: GimbalAxis) -> DoubleSetting? /// Gets the stabilization setting on a given axis /// /// - Parameter axis: the axis /// - Returns: the stabilization setting or `nil` if the axis is not supported func stabilization(onAxis axis: GimbalAxis) -> BoolSetting? /// Gets the current attitude on a given axis. /// /// - Parameter axis: the axis /// - Returns: the current attitude as a double in an NSNumber. `nil` if axis is not supported. func currentAttitude(onAxis axis: GimbalAxis) -> NSNumber? /// Gets the current attitude on a given axis and frame of reference /// /// - Parameters: /// - axis: the axis /// - frameOfReference: the frame of reference /// - Returns: the current attitude as a double in an NSNumber. `nil` if axis is not supported. func currentAttitude(onAxis axis: GimbalAxis, frameOfReference: FrameOfReference) -> NSNumber? /// Controls the gimbal. /// /// Unit of the `yaw`, `pitch`, `roll` values depends on the value of the `mode` parameter: /// - `.position`: axis value is in degrees and represents the desired position of the gimbal on the given axis. /// - `.velocity`: axis value is in max speed (`maxSpeedSettings[thisAxis].value`) ratio (from -1 to 1). /// /// If mode is `.position`, frame of reference of a given axis depends on the value of the stabilization on /// this axis. If this axis is stabilized (i.e. `stabilizationSettings[thisAxis].value == true`), the .absolute /// frame of reference is used. Otherwise .relative frame of reference is used. /// - Parameters: /// - mode: the mode that should be used to move the gimbal. This parameter will change the unit of the following /// parameters /// - yaw: target on the yaw axis as a Double in an NSNumber. `nil` if you want to keep the current value. /// - pitch: target on the pitch axis as a Double in an NSNumber. `nil` if you want to keep the current value. /// - roll: target on the roll axis as a Double in an NSNumber. `nil` if you want to keep the current value. func control(mode: GimbalControlMode, yaw: NSNumber?, pitch: NSNumber?, roll: NSNumber?) /// Starts the offsets correction process. /// /// When offset correction is started, `offsetsCorrectionProcess` is not nil and correctable offsets can be /// corrected. func startOffsetsCorrectionProcess() /// Stops the offsets correction process. /// /// `offsetsCorrectionProcess` will be set to nil. func stopOffsetsCorrectionProcess() /// Starts calibration process. func startCalibration() /// Cancels the current calibration process. func cancelCalibration() } /// Extension of the GimbalOffsetsCorrectionProcess that adds Objective-C missing vars and functions support. extension GimbalOffsetsCorrectionProcess { /// Tells whether a given axis can be manually corrected. /// /// - Parameter axis: the axis to query /// - Returns: `true` if the axis can be corrected /// - Note: This method is for Objective-C only. Swift must use `correctableAxes` public func isAxisCorrectable(_ axis: GimbalAxis) -> Bool { return correctableAxes.contains(axis) } /// Gets the manual offset correction on a given axis. /// /// - Parameter axis: the axis /// - Returns: the manual offset correction setting if the axis is correctable. /// - Note: This method is for Objective-C only. Swift must use `offsetsCorrection` public func offsetCorrection(onAxis axis: GimbalAxis) -> DoubleSetting? { return offsetsCorrection[axis] } } /// :nodoc: /// Gimbal description @objc(GSGimbalDesc) public class GimbalDesc: NSObject, PeripheralClassDesc { public typealias ApiProtocol = Gimbal public let uid = PeripheralUid.gimbal.rawValue public let parent: ComponentDescriptor? = nil }
true
24dd464f31d53c00aeeba8c6a73e63864e1fc9b3
Swift
mohsinalimat/GMCalendar
/GMCalendar/Classes/Extensions/UIView+Round.swift
UTF-8
413
2.625
3
[ "MIT" ]
permissive
// // UIView+Round.swift // CalendarView // // Created by Gianpiero Mode on 20/02/2020. // Copyright © 2020 Gianpiero Mode. All rights reserved. // import Foundation import UIKit extension UIView{ func roundBourdersUntilCircle(){ self.clipsToBounds = true self.layer.cornerRadius = self.bounds.width / 2 self.layer.borderWidth = 1 self.layer.borderColor = UIColor.clear.cgColor } }
true
789cb368be76048f7b75da1f0654197076ade4a2
Swift
kylebshr/wooly
/Wooly/Sources/Extensions/URL+Extensions.swift
UTF-8
129
2.578125
3
[]
no_license
import Foundation extension URL { init(staticString: StaticString) { self = URL(string: "\(staticString)")! } }
true
79d218dcfaa67ed72b8b89f6efe960425a4328a4
Swift
Stratagem-Studios/Stratagem
/Stratagem/UI Views/Pregame/JoinGameView.swift
UTF-8
1,913
2.625
3
[]
no_license
import SwiftUI import SpriteKit public struct JoinGameView: View { @EnvironmentObject var playerVariables: PlayerVariables @EnvironmentObject var staticGameVariables: StaticGameVariables @State var enteredCode: String = "" public var body: some View { VStack() { TitleText(text: "STRATAGEM") .padding(.top, 10) Spacer() Button(action: { if enteredCode != "" { Global.lfGameManager!.joinGameWithCode(code: enteredCode) } }) { Text("PLAY") }.buttonStyle(BasicButtonStyle()) .padding(.bottom, 10) ZStack { TextField("CODE", text: $enteredCode) .onReceive(enteredCode.publisher.collect()) { enteredCode = String($0.prefix(4)) } .multilineTextAlignment(.center) .frame(width: 85, height: 40) .background(Color.gray) .cornerRadius(5) .font(.custom("Montserrat-Bold", size: 20)) RoundedRectangle(cornerRadius: 5) .stroke(Color("ButtonBackground")) .frame(width: 85, height: 40) } .padding(.bottom, 10) Button(action: { playerVariables.currentView = .TitleScreenView }) { Text("BACK") }.buttonStyle(BasicButtonStyle()) .padding(.bottom, 10) }.statusBar(hidden: true) } } struct JoinGameView_Preview: PreviewProvider { static var previews: some View { JoinGameView() // .environmentObject(GameVariables()) .previewLayout(.fixed(width: 896, height: 414)) } }
true
2cc1a65ecf452cffdb20c737b016adabc37bdf16
Swift
mcamara/Napkin
/Example/Napkin/SimpleArrayStoredModel.swift
UTF-8
847
2.828125
3
[ "MIT" ]
permissive
// // SimpleArrayStoredModel.swift // Napkin // // Created by Daniel Green on 22/07/2015. // Copyright © 2015 CocoaPods. All rights reserved. // import Foundation class SimpleArrayStoredModel: NSObject { static var collection = [SimpleArrayStoredModel]() let uuid = NSUUID().UUIDString class func all() -> [SimpleArrayStoredModel] { return collection } func instanceClass() -> SimpleArrayStoredModel.Type { return object_getClass(self) as! SimpleArrayStoredModel.Type } func save(callback: ()->()) { for o in instanceClass().collection { if o.uuid == self.uuid { return } } instanceClass().collection.append(self) // A callback is used here to help demonstrate the usage with an // asynronous save. callback() } }
true
791d1012f1add27ef0affc74f8c1de5303c8bc4a
Swift
AnisaEbadi/FlashCard
/FlashCard/FlashCard/Model/Collection.swift
UTF-8
435
2.84375
3
[]
no_license
// // Collection.swift // FlashCard // // Created by Anisa Ebadi on 2/19/18. // Copyright © 2018 NikanSoft. All rights reserved. // import Foundation struct Collection { // var title: String! // var cards : [Card]? private(set) public var title: String private(set) public var titleImage: String init(title: String, titleImage: String) { self.title = title self.titleImage = titleImage } }
true
649536ef2afc47bc6c5071a0e20f41972490ee8f
Swift
lolsmh/oop
/lab3/Racing/Broom.swift
UTF-8
361
3.125
3
[]
no_license
// // Broom.swift // Racing // // Created by Даниил Апальков on 23.10.2020. // class Broom: AirTransport { var _name: String = "Broom" var _speed: Double = 20 func DistanceReducer(distance: Double) -> Double { let reducer = (distance / 1000).rounded(FloatingPointRoundingRule.down) / 100 return distance - distance * reducer } }
true
5f8cf042ba302344535c205fd2e2f0789a46d33c
Swift
joser1996/refresh
/Refresh/Controller/AnimeInfoController.swift
UTF-8
3,905
2.5625
3
[]
no_license
// // AnimeInfoController.swift // Refresh // // Created by Jose Torres-Vargas on 7/18/21. // import UIKit class AnimeInfoController: UIViewController { let scrollView = UIScrollView() let animeInfoView = AnimeInfoView() var animeData: MediaItem? { didSet { let title: String = animeData?.title.romaji ?? "No Title" let imageURL: String? = animeData?.coverImage.large let syn: String? = animeData?.description ?? nil let airingAt = animeData?.nextAiringEpisode?.airingAt var nextDateString: String = "Next: " if airingAt != nil { let nextDate = Alarm.airingDay(seconds: airingAt!) let formatter = DateFormatter() formatter.timeStyle = .short formatter.dateStyle = .short nextDateString += formatter.string(from: nextDate) } else { nextDateString += "N/A" } //set date label animeInfoView.nextAiringDate.text = nextDateString //set title animeInfoView.titleView.text = title //set image if let imageUrl = imageURL { animeInfoView.thumbNail.loadImageUsing(urlString: imageUrl) { image in self.animeInfoView.thumbNail.image = image } } else { //place generic image here for when not found self.animeInfoView.thumbNail.image = nil } //set synopsis if let synopsis = syn { //clean up text let clean = synopsis.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) animeInfoView.synopsis.text = clean } else { animeInfoView.synopsis.text = "No Snyopis Provided." } } } var imageURLString: String? var alarms: [Int: Date] = [:] override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.isHidden = false navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addAction)) setUpScrollView() } @objc func addAction() { print("Add button was pressed") } override func viewWillDisappear(_ animated: Bool) { animeInfoView.thumbNail.image = nil } private func setUpScrollView() { scrollView.translatesAutoresizingMaskIntoConstraints = false animeInfoView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) scrollView.addSubview(animeInfoView) scrollView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true scrollView.widthAnchor.constraint(equalTo: view.widthAnchor).isActive = true scrollView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true animeInfoView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true animeInfoView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true animeInfoView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true animeInfoView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true } override func viewWillAppear(_ animated: Bool) { DispatchQueue.main.async { var sum = CGFloat(0) for subView in self.animeInfoView.subviews { sum += subView.frame.height } self.scrollView.contentSize = CGSize(width: UIScreen.main.bounds.width, height: sum + 100) } } }
true
29a6150ab78962045815ac5288073a597e6693ef
Swift
Rajeshgandru/ThorChat
/ThorChat/ThorChat/UISupportClass.swift
UTF-8
5,624
2.546875
3
[ "MIT" ]
permissive
// // UISupportClass.swift // ThorChat // // Created by admin on 4/15/21. // import Foundation import UIKit extension UITextField { func showDoneButtonOnKeyboard() { let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(resignFirstResponder)) var toolBarItems = [UIBarButtonItem]() toolBarItems.append(flexSpace) toolBarItems.append(doneButton) let doneToolbar = UIToolbar() doneToolbar.items = toolBarItems doneToolbar.sizeToFit() inputAccessoryView = doneToolbar } } extension UIView { @IBInspectable var cornerRadiusV: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } @IBInspectable var borderWidthV: CGFloat { get { return layer.borderWidth } set { layer.borderWidth = newValue } } @IBInspectable var borderColorV: UIColor? { get { return UIColor(cgColor: layer.borderColor!) } set { layer.borderColor = newValue?.cgColor } } } extension UIView { @IBInspectable var shadowColor: UIColor?{ set { guard let uiColor = newValue else { return } layer.shadowColor = uiColor.cgColor } get{ guard let color = layer.shadowColor else { return nil } return UIColor(cgColor: color) } } @IBInspectable var shadowOpacity: Float{ set { layer.shadowOpacity = newValue } get{ return layer.shadowOpacity } } @IBInspectable var shadowOffset: CGSize{ set { layer.shadowOffset = newValue } get{ return layer.shadowOffset } } @IBInspectable var shadowRadius: CGFloat{ set { layer.shadowRadius = newValue } get{ return layer.shadowRadius } } } class REView: UIView { override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() if isCircle{ layer.cornerRadius = (self.frame.height) / 2 // layer.masksToBounds = true } if isBottomShadow{ layer.shadowColor = setShadowColor.cgColor layer.borderColor = UIColor(named: "D3CDCD")?.cgColor //layer.cornerRadius = cornerRadius layer.shadowOffset = CGSize(width: 1, height: 2) layer.shadowOpacity = 0.5 layer.shadowRadius = 2.0 } if isimgShadow{ layer.shadowColor = setShadowColor.cgColor layer.borderColor = UIColor(named: "D3CDCD")?.cgColor //layer.cornerRadius = cornerRadius layer.shadowOffset = CGSize(width: 0, height: 5) layer.shadowOpacity = 0.5 layer.shadowRadius = 5.0 layer.shouldRasterize = true layer.masksToBounds = false } } @IBInspectable var isCircle: Bool = false { didSet { layoutSubviews() } } @IBInspectable var setShadowColor: UIColor = UIColor.red { didSet { layer.shadowColor = setShadowColor.cgColor } } @IBInspectable var isBottomShadow: Bool = false { didSet { layer.borderColor = UIColor(named: "D3CDCD")?.cgColor // layer.cornerRadius = cornerRadius layer.shadowOffset = CGSize(width: 3, height: 3) layer.shadowOpacity = 5.0 layer.shadowRadius = 1.0 } } @IBInspectable var isimgShadow: Bool = false { didSet { layer.shadowColor = setShadowColor.cgColor layer.borderColor = UIColor(named: "D3CDCD")?.cgColor //layer.cornerRadius = cornerRadius layer.shadowOffset = CGSize(width: 0, height: 5) layer.shadowOpacity = 0.5 layer.shadowRadius = 5.0 layer.shouldRasterize = true layer.masksToBounds = false } } } extension UIView { func roundCorners(corners: UIRectCorner, radius: CGFloat) { let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let mask = CAShapeLayer() mask.path = path.cgPath layer.mask = mask } } class REImageView: UIImageView { override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() if isCircle{ layer.cornerRadius = ( self.frame.height) / 2 layer.masksToBounds = true } } @IBInspectable var isCircle: Bool = false { didSet { layoutSubviews() } } @IBInspectable var tintImage: UIImage? { didSet { if tintImage != nil { let imgTintImage = tintImage?.withRenderingMode(.alwaysTemplate) self.image = imgTintImage } } } }
true
485203df00eb86130cdde9f0aeb371412f95c83b
Swift
jason156/WimoOrder
/WimoOrder/Class/ViewController/SideMenu/MenuViewController.swift
UTF-8
2,815
2.6875
3
[]
no_license
// // MenuViewController.swift // WimoOrder // // Created by ELSAGA-MACOS on 8/16/20. // Copyright © 2020 ELSAGA-MACOS. All rights reserved. // import UIKit enum TypeMenu : String,CaseIterable { case trangChu = "Trang chủ" case thongTin = "Thông tin cá nhân" case lichSu = "Lịch sử thanh toán" case dangXuat = "Đăng xuất" var image : UIImage? { switch self { case .trangChu: return UIImage.init(named: "icons8-home-24") case .thongTin: return UIImage.init(named: "icons8-person-24") case .lichSu: return UIImage.init(named: "icons8-time-machine-24") case .dangXuat: return UIImage.init(named: "icons8-shutdown-48") } } } class MenuViewController: UIViewController { @IBOutlet weak var imgAvata: UIImageView! @IBOutlet weak var lbName: UILabel! @IBOutlet weak var lbPosition: UILabel! @IBOutlet weak var myTable: UITableView! @IBOutlet weak var viewBooth: UIView! let menuItem : [TypeMenu] = [.trangChu,.thongTin,.lichSu,.dangXuat] var onSelectedType: ((TypeMenu)->Void)? override func viewDidLoad() { super.viewDidLoad() myTable.register(UINib.init(nibName: "MenuCell", bundle: nil), forCellReuseIdentifier: "MenuCell") conFig() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } //MARK: Function func conFig(){ //bo tron anh imgAvata.layer.cornerRadius = imgAvata.frame.height / 2 imgAvata.clipsToBounds = true //View booth viewBooth.layer.cornerRadius = 10 viewBooth.clipsToBounds = true viewBooth.layer.borderWidth = 1 viewBooth.layer.borderColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) } //MARK: Button @IBAction func chooseBooth(_ sender: Any) { } } extension MenuViewController: UITableViewDelegate,UITableViewDataSource{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItem.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MenuCell", for: indexPath) as! MenuCell cell.menuType = menuItem[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let type = TypeMenu.allCases[indexPath.row] onSelectedType?(type) } }
true
a765f08dfba0a27f26d1357150892a5db90eb832
Swift
JoeHolt/JHTools
/JHTools/TableViewCells/JHStatisticsCollectionCell.swift
UTF-8
1,550
2.65625
3
[ "MIT" ]
permissive
// // UIClassDisplayStatisticsCell.swift // WiscEnroll // // Created by Joe Holt on 3/27/19. // Copyright © 2019 Joe Holt. All rights reserved. // import UIKit /** Cell holding a collection of statistics to be displayed in large font */ public class JHStatisticsCollectionCell: UITableViewCell { // MARK: Instance Variables private var stackView: UIStackView! // MARK: Init public init(statView views: [JHStatDisplayLabel]) { super.init(style: .default, reuseIdentifier: nil) selectionStyle = .none setUpStackView() for view in views { stackView.addArrangedSubview(view) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Other Functions /** Sets up the stack view */ private func setUpStackView() { stackView = UIStackView() stackView.translatesAutoresizingMaskIntoConstraints = false stackView.distribution = .equalCentering addSubview(stackView) stackView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -JHTableViewCellConstants.rightSpacing * 2.5).isActive = true stackView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: JHTableViewCellConstants.leftSpacing * 2.5).isActive = true stackView.topAnchor.constraint(equalTo: self.topAnchor, constant: -10).isActive = true stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true } }
true
b627531b9315c89ec7ad01070eda8876e7dc2098
Swift
kormic/Rocket.Chat.iOS
/Rocket.Chat.iOS/Models/User.swift
UTF-8
2,499
3
3
[ "MIT" ]
permissive
// // User.swift // Rocket.Chat.iOS // // Created by Mobile Apps on 8/5/15. // Copyright © 2015 Rocket.Chat. All rights reserved. // import Foundation import CoreData class User : NSManagedObject { /// Status of the `User` /// This uses raw values, in order to facilitate CoreData enum Status : Int16{ case ONLINE = 0 case AWAY = 1 case BUSY = 2 case INVISIBLE = 3 } @NSManaged dynamic var id : String @NSManaged dynamic var username : String @NSManaged dynamic var password : String? //Password is only for the local user, not remote /// Avatar url or image name. /// In case this is not a url the code calling must know how to construct the url @NSManaged dynamic var avata : NSData! /// This is to make CoreData work, since it doesn't support enums /// We store this private int to CoreData and use `status` for public usage @NSManaged dynamic private var statusVal : NSNumber var status : Status { get { return Status(rawValue: statusVal.shortValue) ?? .ONLINE } set { //self.statusVal = NSNumber(short: newValue.rawValue) setValue(NSNumber(short: newValue.rawValue), forKey: "statusVal") } } @NSManaged dynamic var statusMessage : String? @NSManaged dynamic private var timezoneVal : String var timezone : NSTimeZone { get { return NSTimeZone(name: timezoneVal) ?? NSTimeZone.systemTimeZone() } set { self.timezoneVal = newValue.name } } convenience init(context: NSManagedObjectContext, id:String, username:String, avatar:UIImage!, status : Status, timezone : NSTimeZone){ let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: context)! self.init(entity: entity, insertIntoManagedObjectContext: context) self.id = id self.username = username self.avata = UIImagePNGRepresentation(avatar)! //TODO: Setting status hear will cause an exception, come back later and check why (probably swift/compiler bug) //self.status = status setValue(NSNumber(short: status.rawValue), forKey: "statusVal") self.timezoneVal = timezone.name } //For Hashable override var hashValue : Int { return id.hashValue } } //For Equalable (part of Hashable) func == (left : User, right: User) -> Bool { return left.id == right.id }
true
852614627e6b05bbe2f4e57adb616f0b82677356
Swift
jabudhii/ad-dController
/ad&dController/Combat.swift
UTF-8
2,250
3.328125
3
[]
no_license
// // Combat.swift // ad&dController // // Created by mattkimball on 5/14/20. // Copyright © 2020 matthewKimball. All rights reserved. // import Foundation func attack(attacker: theCharacter, defender: theEnemy, roller: Int) -> Bool{ // Thaco - roll < enemy AC // (thaco - enemyAC) <= roll if((roller + 1) == 1){ return false } else if((roller + 1) == 20){ return true } else{ if((attacker.thacAc[0]-defender.thacAc[1]) <= (roller + 1)){ return true } else{ return false } } } func displayAttackResults(attacker: theCharacter, defender: theEnemy, roller: Int) -> String{ var returnString = "" returnString.append(attacker.name + " has a Thac0 of: " + String(attacker.thacAc[0]) + "\n") returnString.append(defender.name + " has an AC of: " + String(defender.thacAc[1]) + "\n") returnString.append("To hit " + defender.name + ", " + attacker.name + " Needs to roll at least a: " + String(attacker.thacAc[0]-defender.thacAc[1]) + "\n") returnString.append(attacker.name + " Rolled a: " + String(roller + 1) + "\n") return returnString } // End displayAttackResults func defend(attacker: theEnemy, defender: theCharacter, roller: Int) -> Bool{ // Thaco - roll < enemy AC // (thaco - enemyAC) <= roll if((roller + 1) == 1){ return false } else if((roller + 1) == 20){ return true } else{ if((attacker.thacAc[0]-defender.thacAc[1]) <= (roller + 1)){ return true } else{ return false } } } func displayDefendResults(attacker: theEnemy, defender: theCharacter, roller: Int) -> String{ var returnString = "" returnString.append(attacker.name + " has a Thac0 of: " + String(attacker.thacAc[0]) + "\n") returnString.append(defender.name + " has an AC of: " + String(defender.thacAc[1]) + "\n") returnString.append("To hit " + defender.name + ", " + attacker.name + " Needs to roll at least a: " + String(attacker.thacAc[0]-defender.thacAc[1]) + "\n") returnString.append(attacker.name + " Rolled a: " + String(roller + 1) + "\n") return returnString } // End displayDefendResults
true
8dcf7b743226f0d0f3b5f9e3457506d732cc928b
Swift
soaltomas/SoalIP
/SoalIP/Core/Network/Error/AbstractErrorParser.swift
UTF-8
585
2.875
3
[]
no_license
import Foundation //---Error handling protocol protocol AbstractErrorParser { /// Converts errors to a single format /// /// - Parameter error: original error /// - Returns: internal app error func parse(_ error: Error) -> Error /// Analyzes the http response for errors /// /// - Parameters: /// - response: server response /// - data: server response data /// - error: network or server error in response /// - Returns: internal app error func parse(_ response: HTTPURLResponse?, _ data: Data?, _ error: Error?) -> Error? }
true
615c67fb0ea9f8646714e06a5324a8ec9070587d
Swift
petinartur/HomeWork1.2
/HomeWork1.2/ViewController.swift
UTF-8
932
2.578125
3
[]
no_license
// // ViewController.swift // HomeWork1.2 // // Created by Артур Петин on 24.03.2021. // import UIKit class ViewController: UIViewController { @IBOutlet weak var redSign: UIView! @IBOutlet weak var yellowSign: UIView! @IBOutlet weak var greenSign: UIView! @IBOutlet weak var buttonSwitch: UIButton! override func viewDidLoad() { super.viewDidLoad() redSign.layer.cornerRadius = redSign.frame.size.width/2 redSign.alpha = 0.3 yellowSign.layer.cornerRadius = yellowSign.frame.size.width/2 yellowSign.alpha = 0.3 greenSign.layer.cornerRadius = greenSign.frame.size.width/2 greenSign.alpha = 0.3 buttonSwitch.layer.cornerRadius = 3 // Do any additional setup after loading the view. } @IBAction func buttonSwitchPressed() { redSign.alpha = 0.3 } }
true
01283a657e4b4cb1eb659818bec654be626aa323
Swift
crenelle/OrderedDictionary
/Sources/OrderedDictionary/OrderedDictionarySlice.swift
UTF-8
3,318
3.140625
3
[ "MIT" ]
permissive
public struct OrderedDictionarySlice<Key: Hashable, Value>: RandomAccessCollection, MutableCollection { // ============================================================================ // // MARK: - Type Aliases // ============================================================================ // /// The type of the underlying ordered dictionary. public typealias Base = OrderedDictionary<Key, Value> /// The type of the contiguous subrange of the ordered dictionary's elements. public typealias SubSequence = Self // ============================================================================ // // MARK: - Initialization // ============================================================================ // public init(base: Base, bounds: Base.Indices) { self.base = base self.startIndex = bounds.lowerBound self.endIndex = bounds.upperBound } // ============================================================================ // // MARK: - Base // ============================================================================ // /// The underlying ordered dictionary. public private(set) var base: Base // ============================================================================ // // MARK: - Indices // ============================================================================ // /// The start index. public let startIndex: Base.Index /// The end index. public let endIndex: Base.Index // ============================================================================ // // MARK: - Subscripts // ============================================================================ // public subscript( position: Base.Index ) -> Base.Element { get { base[position] } set(newElement) { base[position] = newElement } } public subscript( bounds: Range<Int> ) -> OrderedDictionarySlice<Key, Value> { get { base[bounds] } set(newElements) { base[bounds] = newElements } } // ============================================================================ // // MARK: - Reordering Methods Overloads // ============================================================================ // public mutating func sort( by areInIncreasingOrder: (Base.Element, Base.Element) throws -> Bool ) rethrows { try base._sort( in: indices, by: areInIncreasingOrder ) } public mutating func reverse() { base._reverse(in: indices) } public mutating func shuffle<T>( using generator: inout T ) where T: RandomNumberGenerator { base._shuffle( in: indices, using: &generator ) } public mutating func partition( by belongsInSecondPartition: (Base.Element) throws -> Bool ) rethrows -> Index { return try base._partition( in: indices, by: belongsInSecondPartition ) } public mutating func swapAt(_ i: Base.Index, _ j: Base.Index) { base.swapAt(i, j) } }
true
85a0d79d9a721ea8f155818e6571927a8d76a9c7
Swift
WaterSource/tech
/swift 算法基础 链表.playground/Pages/删除链表中的节点.xcplaygroundpage/Contents.swift
UTF-8
394
3.46875
3
[]
no_license
//: [Previous](@previous) import Foundation // 删除链表节点 // 注意前置节点和后续节点的连接 func deleteNode(_ node: ListNode) { let next = node.next node.val = next?.val node.next = next?.next } let list = ListNodeList(1) list.insert(2) list.insert(3) list.insert(4) let test = list.head list.insert(5) deleteNode(test!) list.printAll() //: [Next](@next)
true
21add23f4d011892e4278729db0df04847d1b3ef
Swift
willieLjohnson/mob-3
/02-UserDefaults-Keychain-NSCoding/nscoding/nscoding/User.swift
UTF-8
803
3.1875
3
[]
no_license
// // User.swift // nscoding // // Created by Willie Johnson on 10/01/2018. // Copyright © 2018 Willie Johnson. All rights reserved. // import Foundation class User: NSObject, NSCoding { var username: String! var password: String! init(username: String, password: String) { self.username = username self.password = password } required convenience init?(coder aDecoder: NSCoder) { guard let username = aDecoder.decodeObject(forKey: "username") as? String else { return nil } guard let password = aDecoder.decodeObject(forKey: "password") as? String else { return nil } self.init(username: username, password: password) } func encode(with aCoder: NSCoder) { aCoder.encode(self.username, forKey: "username") aCoder.encode(self.password, forKey: "password") } }
true
434992795739db672d2aec64008fbf8397d2fd2f
Swift
DimmyMaenhout/LitePay2
/LitePay2/ViewControllers/CurrencyRateViewController.swift
UTF-8
4,142
3.09375
3
[]
no_license
import Foundation import UIKit class CurrencyRateViewController : UIViewController { @IBOutlet weak var currencyRateTableView: UITableView! var sv = UIView() var timer = Timer() var currencyRates : [String: String]? { // This is a property observer. // The willSet and didSet observers provide a way to observe (and to respond appropriately) when the value of a variable or property is being set. // Observers aren't called when the or property is first initialized, they are only called when the value is set outside of an initialization context // didSet is called immediatly after the new value is set didSet { scheduledTimerInterval() print("\n\nCurrency rates view controller line 15, var currencyRate didSet: \(String(describing: currencyRates))\n\n") currencyRateTableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() currencyRateTableView.dataSource = self getCurrencyRates() // removes the unwanted space between the navbar and first cell self.automaticallyAdjustsScrollViewInsets = false // Stores the view that is created sv = UIViewController.displaySpinner(onView: self.view) } @objc func getCurrencyRates(){ print("Currency rate view controller line 32, got here") CoinbaseAPIService.getExchangeRates(completion: ({ response in UIViewController.removeSpinner(spinner: self.sv) // print("Currency rate view controller line 35, response: \(response!)") self.currencyRates = response! // print("Currency rate view controller line 38, self.currencyRates: \(String(describing: self.currencyRates))") })) } // Repeat getCurrencyRates every 900 seconds (15 min) (to get new data, currencyRates could have changed from 120 seconds ago func scheduledTimerInterval(){ timer = Timer.scheduledTimer(timeInterval: 900, target: self, selector: #selector(self.getCurrencyRates), userInfo: nil, repeats: true) // currencyRateTableView.reloadData() } } extension CurrencyRateViewController : UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // all elements in currencyRates need to be showed, if currencyRates = nil return 0 return currencyRates?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = currencyRateTableView.dequeueReusableCell(withIdentifier: "currencyRateCell", for: indexPath) as! KoersCell // show the key and value at indexPath.row, to show every key and value we use Array(key/value)[ at this position ] cell.codeCurrencyLbl.text = Array(currencyRates!.keys)[indexPath.row] print("Currency rates view controller line 72, currencyRates.keys[indexpath.row]: \(Array(currencyRates!.keys)[indexPath.row])") cell.valueCurrencyLabel.text = Array(currencyRates!.values)[indexPath.row] return cell } } // To show the spinner I used this tutorial: http://brainwashinc.com/2017/07/21/loading-activity-indicator-ios-swift/ extension UIViewController { class func displaySpinner(onView: UIView) -> UIView { let spinnerView = UIView.init(frame: onView.bounds) spinnerView.backgroundColor = UIColor.init(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5) let ai = UIActivityIndicatorView.init(activityIndicatorStyle: .whiteLarge) ai.startAnimating() ai.center = spinnerView.center DispatchQueue.main.async { spinnerView.addSubview(ai) onView.addSubview(spinnerView) } return spinnerView } class func removeSpinner(spinner: UIView) { DispatchQueue.main.async { spinner.removeFromSuperview() } } }
true
5406aa1fd5a5e1c812ea3f9a658313865810a277
Swift
jaysalvador/butterfly-systems
/Butterfly SystemsTests/DataHelper.swift
UTF-8
1,276
2.53125
3
[]
no_license
// // DataHelper.swift // Butterfly SystemsTests // // Created by Jay Salvador on 11/5/20. // Copyright © 2020 Jay Salvador. All rights reserved. // import Foundation import CoreData import Butterfly_Systems class DataHelper { class func getData(completion: HttpCompletionClosure<[Order]>?) { let dataPath = Bundle(for: DataHelper.self).path(forResource: "data", ofType: "json") ?? "" do { guard let codingUserInfoKeyManagedObjectContext = CodingUserInfoKey.managedObjectContext else { completion?(.failure(HttpError.coredata)) return } let managedObjectContext = CoreDataStack.persistentContainer.viewContext let data = try Data(contentsOf: URL(fileURLWithPath: dataPath)) let decoder = JSONDecoder() decoder.userInfo[codingUserInfoKeyManagedObjectContext] = managedObjectContext decoder.dateDecodingStrategy = .formatted(.dateAndTime) let decoded = try decoder.decode([Order].self, from: data) completion?(.success(decoded)) } catch { completion?(.failure(HttpError.decoding(error))) } } }
true
6b35dac6f30e877d7c69112280377785b76808c7
Swift
foolishlionel/OMPToolKit
/OMPToolKit/OMPToolKit/Vendor/OMPDataPickerView/OMPDataPickerTitleBarButtonItem.swift
UTF-8
3,954
2.578125
3
[]
no_license
// // OMPDataPickerTitleBarButtonItem.swift // OMPToolKit // // Created by flion on 2018/10/31. // Copyright © 2018 flion. All rights reserved. // import UIKit class OMPDataPickerTitleBarButtonItem: UIBarButtonItem { public var font: UIFont? = UIFont.systemFont(ofSize: 14) { didSet { guard let titleFont = font else { return } titleButton.titleLabel?.font = titleFont } } public var titleColor: UIColor? = UIColor.lightGray { didSet { guard let color = titleColor else { titleButton.setTitleColor(UIColor.lightGray, for: .disabled) return } titleButton.setTitleColor(color, for: .disabled) } } fileprivate let titleView: UIView = { let view = UIView() view.backgroundColor = UIColor.clear return view }() fileprivate let titleButton: UIButton = { let button = UIButton(type: .custom) button.isEnabled = false button.titleLabel?.numberOfLines = 3 button.titleLabel?.textAlignment = .center button.titleLabel?.font = UIFont.systemFont(ofSize: 13.0) button.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), for: .normal) button.setTitleColor(UIColor.lightGray, for: .disabled) button.backgroundColor = .clear return button }() override var title: String? { didSet { titleButton.setTitle(title, for: .normal) } } override init() { super.init() _setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _setupUI() } convenience init(title: String?) { self.init() self.title = title } } fileprivate extension OMPDataPickerTitleBarButtonItem { func _setupUI() { titleView.addSubview(titleButton) _layoutViews() customView = titleView } func _layoutViews() { if #available(iOS 11.0, *) { titleView.translatesAutoresizingMaskIntoConstraints = false titleView.setContentHuggingPriority(UILayoutPriority.defaultLow - 1, for: .vertical) titleView.setContentHuggingPriority(UILayoutPriority.defaultLow - 1, for: .horizontal) titleView.setContentHuggingPriority(UILayoutPriority.defaultHigh - 1, for: .vertical) titleView.setContentHuggingPriority(UILayoutPriority.defaultHigh - 1, for: .horizontal) titleButton.translatesAutoresizingMaskIntoConstraints = false titleButton.setContentHuggingPriority(UILayoutPriority.defaultLow - 1, for: .vertical) titleButton.setContentHuggingPriority(UILayoutPriority.defaultLow - 1, for: .horizontal) titleButton.setContentHuggingPriority(UILayoutPriority.defaultHigh - 1, for: .vertical) titleButton.setContentHuggingPriority(UILayoutPriority.defaultHigh - 1, for: .horizontal) let top = NSLayoutConstraint(item: titleButton, attribute: .top, relatedBy: .equal, toItem: titleView, attribute: .top, multiplier: 1, constant: 0) let bottom = NSLayoutConstraint(item: titleButton, attribute: .bottom, relatedBy: .equal, toItem: titleView, attribute: .bottom, multiplier: 1, constant: 0) let leading = NSLayoutConstraint(item: titleButton, attribute: .leading, relatedBy: .equal, toItem: titleView, attribute: .leading, multiplier: 1, constant: 0) let trailing = NSLayoutConstraint(item: titleButton, attribute: .trailing, relatedBy: .equal, toItem: titleView, attribute: .trailing, multiplier: 1, constant: 0) titleView.addConstraints([top, bottom, leading, trailing]) } else { titleButton.autoresizingMask = [.flexibleWidth, .flexibleHeight] titleView.autoresizingMask = [.flexibleWidth, .flexibleHeight] } } }
true
edf437c3103f8fa4be95e71cf66a9caf81c0c95c
Swift
mohsinalimat/ZBMetal
/ZBMetal/ZBMetalView.swift
UTF-8
2,840
2.625
3
[ "MIT" ]
permissive
// // ZBMetalView.swift // ZBMetal // // Created by DongSoo Lee on 2017. 2. 3.. // Copyright © 2017년 zigbang. All rights reserved. // import UIKit import MetalKit class ZBMetalView: MTKView { var vertexBuffer: MTLBuffer! var rps: MTLRenderPipelineState! = nil var uniformBuffer: MTLBuffer! required init(coder: NSCoder) { super.init(coder: coder) self.device = MTLCreateSystemDefaultDevice() self.createBuffer() self.registerShaders() } func createBuffer() { let vertexData = [Vertex(position: [-1.0, -1.0, 0.0, 1.0], color: [1, 0, 0, 1]), Vertex(position: [1.0, -1.0, 0.0, 1.0], color: [0, 1, 0, 1]), Vertex(position: [0.0, 1.0, 0.0, 1.0], color: [0, 0, 1, 1])] let dataSize = vertexData.count * MemoryLayout<Vertex>.size self.vertexBuffer = self.device?.makeBuffer(bytes: vertexData, length: dataSize, options: []) self.uniformBuffer = self.device?.makeBuffer(length: MemoryLayout<Float>.size * 16, options: []) let bufferPointer = self.uniformBuffer.contents() memcpy(bufferPointer, Matrix().modelMatrix(Matrix()).m, MemoryLayout<Float>.size * 16) } func registerShaders() { guard let library = self.device?.newDefaultLibrary() else { return } let vertexFunc = library.makeFunction(name: "vertex_func") let fragFunc = library.makeFunction(name: "fragment_func") let rpld = MTLRenderPipelineDescriptor() rpld.vertexFunction = vertexFunc rpld.fragmentFunction = fragFunc rpld.colorAttachments[0].pixelFormat = .bgra8Unorm do { self.rps = try self.device?.makeRenderPipelineState(descriptor: rpld) } catch let error { print("\(error)") } } override func draw(_ rect: CGRect) { super.draw(rect) guard let rpd = self.currentRenderPassDescriptor else { return } guard let drawable = self.currentDrawable else { return } let bleen = MTLClearColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1) // rpd.colorAttachments[0].texture = drawable.texture rpd.colorAttachments[0].clearColor = bleen // rpd.colorAttachments[0].loadAction = .clear let commandBuffer = self.device?.makeCommandQueue().makeCommandBuffer() let encoder = commandBuffer?.makeRenderCommandEncoder(descriptor: rpd) encoder?.setRenderPipelineState(self.rps) encoder?.setVertexBuffer(self.vertexBuffer, offset: 0, at: 0) encoder?.setVertexBuffer(self.uniformBuffer, offset: 0, at: 1) encoder?.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 3, instanceCount: 1) encoder?.endEncoding() commandBuffer?.present(drawable) commandBuffer?.commit() } }
true
c6ecd0c4a72bc4483d4c3e92b91e8f6f1d5619d7
Swift
combes/swift
/practice/Playgrounds/ConstantsAndVariables.playground/Contents.swift
UTF-8
2,829
4.125
4
[]
no_license
//: Playground - noun: a place where people can play // Excerpt From: Apple Inc. “The Swift Programming Language (Swift 3).” iBooks. https://itun.es/us/jEUH0.l // Constant let maximumNumberOfLoginAttempts = 10 // Variable var currentLoginAttempt = 0 // Multiple variables on a single line var x = 0.0, y = 1.0, z = 2.0 // Type Annotations var welcomeMessage: String welcomeMessage = "Hello" // Multiple related variables var red, green, blue: Double // Naming constants and variables let π = 3.14159265358979323846 let 😀 = "Happy!" enum MonkeyState: Int { case 🐵, 🙈, 🙉, 🙊 func description() -> String { switch self { case .🐵: return "None" case .🙈: return "See no evil" case .🙉: return "Hear no evil" case .🙊: return "Speak no evil" } } } var monkeyState = MonkeyState.🙊 monkeyState.description() // It's possible to use Swift keywords as variable names but is best avoided for obvious reasons var `var` = "Value" // Changing value var friendlyWelcome = "Hello!" friendlyWelcome = "Bonjour!" // Constants are immutable let languageName = "Swift" // languageName = "C#" // Error // Printing constants and variables print(friendlyWelcome) print([friendlyWelcome, monkeyState], separator: " | ", terminator: "\n") print([friendlyWelcome, monkeyState], separator: " | ", terminator: "") // String interpolation print("The current value of friendlyWelcome is \(friendlyWelcome)") // Comments // Single-line comment. /* This is a comment written over multiple lines. */ /* Here is the start of a multiline comment. /* This is a second, nested multiline comment. */ This is the end of the first multiline comment. */ // Semicolons let cat = "🐱"; print(cat) // required to separate statements // Integers let minValue8 = UInt8.min let maxValue8 = UInt8.max let minValue16 = UInt16.min let maxValue16 = UInt16.max let minValue32 = UInt32.min let maxValue32 = UInt32.max let minValue64 = UInt64.min let maxValue64 = UInt64.max Int.min Int.max Int8.min Int8.max Int16.min Int16.max Int32.min Int32.max Int64.min Int64.max // Numeric literals let decimalInteger = 17 let binaryInteger = 0b10001 // 17 in binary notation let octalInteger = 0o21 // 17 in octal notation let hexademinalInteger = 0x11 // 17 in hexadecimal notation let exponentValue = 1.25e2 let smallExponent = 1.25e-2 let exponentHex = 0xFp2 let smallHex = 0xFp-2 let decimalDouble = 12.1875 let exponentDouble = 1.21875e1 let hexadecimalDouble = 0xC.3p0 // Both integers and floats can be padded with extra zero and can contain underscores to help with readability let paddedDouble = 000123.456 let oneMillion = 1_000_000 let justOverOneMillion = 1_000_000.000_000_1
true
a0e27bfc7739218094e9a12cdedf32cbb67b5644
Swift
ninty90/NTYPomeloKit
/PomeloDemo/PomeloDemo/HTTPClient.swift
UTF-8
7,186
2.6875
3
[ "MIT" ]
permissive
// // HTTPClient.swift // PomeloDemo // // Created by little2s on 16/3/14. // Copyright © 2016年 Ninty. All rights reserved. // import Foundation // MARK: HTTPMethod enum HTTPMethod: String { case GET = "GET" case POST = "POST" } extension HTTPMethod: CustomStringConvertible { var description: String { return self.rawValue } } // MARK: HTTPResource struct HTTPResource<T> { let baseURL: NSURL let path: String let method: HTTPMethod let requestBody: NSData? let headers: [String: String] let parse: NSData -> Result<T> } extension HTTPResource: CustomStringConvertible { var description: String { var decodeRequestBody: String? = nil if let requestBody = requestBody { decodeRequestBody = String(data: requestBody, encoding: NSUTF8StringEncoding) } let unwrappedBequestBody = decodeRequestBody ?? "" return "HTTPResource<Method: \(method), path: \(path), headers: \(headers), requestBody: \(unwrappedBequestBody)>" } } // MARK: HTTPError enum HTTPError: ErrorType { case NoResponse case NoData case ParseDataFailed } extension HTTPError { var description: String { switch self { case .NoResponse: return "No response" case .NoData: return "No data" case .ParseDataFailed: return "Parse data failed" } } } // MARK: HTTPClient protocol HTTPClientProtocol { func requestResource<T>(resource: HTTPResource<T>, modifyRequest: (NSMutableURLRequest -> Void)?, completionHandler: (Result<T> -> Void)?) -> NSURLSessionTask } class HTTPClient: HTTPClientProtocol { class SessionDelegate: NSObject, NSURLSessionDelegate { func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) { completionHandler(.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)) } } static let sharedClient: HTTPClient = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() return HTTPClient(configuration: configuration) }() let session: NSURLSession let delegate: SessionDelegate init(configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: SessionDelegate = SessionDelegate()) { self.delegate = delegate self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) } // MARK: HTTPClientProtocol func requestResource<T>( resource: HTTPResource<T>, modifyRequest: (NSMutableURLRequest -> Void)? = nil, completionHandler: (Result<T> -> Void)? = nil) -> NSURLSessionTask { let URL = resource.baseURL.URLByAppendingPathComponent(resource.path) let request = NSMutableURLRequest(URL: URL) request.HTTPMethod = resource.method.rawValue // URL encode func needEncodesParametersForMethod(method: HTTPMethod) -> Bool { switch method { case .GET: return true default: return false } } func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value: AnyObject! = parameters[key] components += queryComponents(key, value: value) } return (components.map{"\($0)=\($1)"} as [String]).joinWithSeparator("&") } func handleParameters() { if needEncodesParametersForMethod(resource.method) { guard let URL = request.URL else { fatalError("Invalid URL of request: \(request)") } if let requestBody = resource.requestBody { if let URLComponents = NSURLComponents(URL: URL, resolvingAgainstBaseURL: false) { URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parseJSON(requestBody)!) request.URL = URLComponents.URL } } } else { request.HTTPBody = resource.requestBody } } handleParameters() // set headers for (key, value) in resource.headers { request.setValue(value, forHTTPHeaderField: key) } // hook request by caller modifyRequest?(request) // create data task let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in if let error = error { completionHandler?(.Failure(error)) return } guard let _ = response as? NSHTTPURLResponse else { completionHandler?(.Failure(HTTPError.NoResponse)) return } guard let data = data else { completionHandler?(.Failure(HTTPError.NoData)) return } let result = resource.parse(data) completionHandler?(result) } task.resume() return task } } // MARK: JSON resource helper func jsonResource<T>(baseURL: NSURL, path: String, method: HTTPMethod, parameters: JSONObject, parse: JSONObject -> Result<T>) -> HTTPResource<T> { let jsonParse: NSData -> Result<T> = { data in if let json = parseJSON(data) { return parse(json) } return .Failure(HTTPError.ParseDataFailed) } let jsonBody = dumpJSON(parameters) let headers = [ "Content-Type": "application/json", ] return HTTPResource(baseURL: baseURL, path: path, method: method, requestBody: jsonBody, headers: headers, parse: jsonParse) } // MARK: Private helpers private func queryComponents(key: String, value: AnyObject) -> [(String, String)] { func escape(string: String) -> String { let legalURLCharactersToBeEscaped: String = ":/?&=;+!@#$()',*" return (string as NSString).stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString: legalURLCharactersToBeEscaped))! } var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value: value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value: value) } } else { components.appendContentsOf([(escape(key), escape("\(value)"))]) } return components }
true
d6924d8e2ff5a44ed8032c937904e25e5d159ac6
Swift
zdeneksejcek/BabyWhisperer
/BabyWhisperer/FirstViewController.swift
UTF-8
2,468
2.59375
3
[]
no_license
// // FirstViewController.swift // BabyWhisperer // // Created by Zdenek Sejcek on 13/10/14. // Copyright (c) 2014 Zdenek Sejcek. All rights reserved. // import UIKit import AVFoundation; class FirstViewController: UIViewController { var recorder : AVAudioRecorder; var audioPlayer : AVAudioPlayer; var timer: NSTimer = NSTimer(); @IBOutlet weak var playStopButton: UIButton! @IBOutlet weak var decibelsLabel: UILabel! @IBAction func buttonTouchedDown(sender: UIButton) { if (audioPlayer.playing) { audioPlayer.stop() sender.setTitle("Start playing", forState: UIControlState.Normal) // playStopButton.setTitle("Start playing", forState: UIControlState.Normal) } else { audioPlayer.currentTime = 0; audioPlayer.prepareToPlay(); audioPlayer.play() sender.setTitle("Stop playing", forState: UIControlState.Normal) // playStopButton.setTitle("Stop playing", forState: UIControlState.Normal) } } required init(coder aDecoder: NSCoder) { AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil) var recordSettings = [ AVFormatIDKey: kAudioFormatAppleLossless, AVEncoderAudioQualityKey : AVAudioQuality.Low.toRaw(), AVNumberOfChannelsKey: 1, AVSampleRateKey : 44100.0 ] var url: NSURL = NSURL.URLWithString(NSTemporaryDirectory().stringByAppendingPathComponent("tmp.caf")) self.recorder = AVAudioRecorder(URL:url, settings:recordSettings, error:nil) self.recorder.meteringEnabled = true; self.recorder.record() var mp3Path = NSBundle.mainBundle().pathForResource("lullaby", ofType: "mp3") var mp3Url = NSURL.URLWithString(mp3Path!); audioPlayer = AVAudioPlayer(contentsOfURL: mp3Url, error: nil) super.init(coder: aDecoder) timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateMeters", userInfo: nil, repeats: true) } func updateMeters() { recorder.updateMeters(); decibelsLabel.text = NSString(format:"%.2f", recorder.peakPowerForChannel(0)); } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
true
efbde2e713686a42b4900d07e4261de5c4a3be6a
Swift
yoko-hashimoto/SlideshowApp
/SlideshowApp/ViewController.swift
UTF-8
2,759
2.625
3
[]
no_license
// // ViewController.swift // SlideshowApp // // Created by 橋本養子 on 2017/08/21. // Copyright © 2017年 kotokotokoto. All rights reserved. // import UIKit class ViewController: UIViewController { let imageNames = ["image4.jpg", "image5.jpg", "image6.jpg"] var imageIndex = 0 @IBOutlet weak var startStopButton: UIButton! @IBOutlet weak var imageView: UIImageView! var timer: Timer! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. imageView.image = UIImage(named: imageNames[imageIndex]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func next(_ sender: Any) { imageIndex += 1 if imageNames.count - 1 < imageIndex { imageIndex = 0 } imageView.image = UIImage(named: imageNames[imageIndex]) } @IBOutlet weak var nextButton: UIButton! @IBAction func back(_ sender: Any) { imageIndex -= 1 if imageIndex < 0 { imageIndex = imageNames.count - 1 } imageView.image = UIImage(named: imageNames[imageIndex]) } @IBOutlet weak var backButton: UIButton! @IBAction func startStop(_ sender: Any) { if(timer != nil) { //停止する timer.invalidate() timer = nil; nextButton.isEnabled = true backButton.isEnabled = true startStopButton.setTitle("再生", for: .normal) } else { //再生する timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) nextButton.isEnabled = false backButton.isEnabled = false startStopButton.setTitle("停止", for: .normal) } } func updateTimer() { imageIndex += 1 if imageNames.count - 1 < imageIndex { imageIndex = 0 } imageView.image = UIImage(named: imageNames[imageIndex]) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let resultViewController:ResultViewController = segue.destination as! ResultViewController resultViewController.image = imageView.image! } @IBAction func unwind(_ segue: UIStoryboardSegue) { } }
true
51e89da8d97422fd5c9de8ecc4b12ec17fb12036
Swift
Gerochka88/DailyFit
/DailyFit/CustomViews/GradientBackGroundColor.swift
UTF-8
735
2.75
3
[]
no_license
// // GradientBackGroundColor.swift // DailyFit // // Created by Taras Vitoshko on 3/20/19. // Copyright © 2019 Taras Vitoshko. All rights reserved. // import Foundation import UIKit extension UIView{ func setGradientBackgroundColor(colorOne: UIColor, colorTwo: UIColor, colorThree: UIColor, colorFour: UIColor){ let gradientLayer = CAGradientLayer() gradientLayer.frame = bounds gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor, colorThree.cgColor, colorFour.cgColor] gradientLayer.locations = [0.0, 0.3, 0.9, 1] gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.0) gradientLayer.endPoint = CGPoint(x: 0.5, y: 1.0) layer.insertSublayer(gradientLayer, at: 0) } }
true
68c3b2d789328ef81b1d48a274c5195dc576f2b3
Swift
davarda/RestaurantList
/TestAppRestaurants/DataManager/RestaurantServices.swift
UTF-8
1,310
2.828125
3
[]
no_license
// // RestaurantServices.swift // DataManager // // Created by David V on 3/12/20. // Copyright © 2020 davidv. All rights reserved. // import Foundation public final class RestaurantServices { private static var services: [Any] = [] public static func setup() { registerFavoriteService() registerRestaurantsListService() } static private func registerFavoriteService() { let favoriteService = FavoriteService() RestaurantServices.register(service: favoriteService) } static private func registerRestaurantsListService() { let restaurantsListService = RestaurantsListService() RestaurantServices.register(service: restaurantsListService) } public static func get<T>() -> T { let service = services.first(where: { $0 is T }) if let currentResult = service as? T { return currentResult } else { fatalError("Couldn't find registered service \(T.self)") } } static public func deleteAll() { services.removeAll() } static public func register<T: ExpressibleByNilLiteral>(service: T) { fatalError("Couldn't register service \(T.self)") } static public func register<T>(service: T) { return services.append(service) } }
true
e949e899101d0b710980c74dba5694d44d71b532
Swift
thuongvanbui39/CoderSchool_TipsCalculator
/TipsCalculator/ChangeBackground.swift
UTF-8
1,972
2.5625
3
[ "Apache-2.0" ]
permissive
// // ChangeBackground.swift // TipsCalculator // // Created by Lon on 5/28/17. // Copyright © 2017 Lon. All rights reserved. // import UIKit class ChangeBackGround:UIViewController{ // // @IBOutlet weak var sysCurrentcyLB: UILabel! // @IBOutlet weak var DollaCurrentcyLB: UILabel! // @IBOutlet weak var CurrentcyLB: UILabel! // @IBOutlet weak var sysCurrentcyLB: UILabel! @IBOutlet weak var CurrentcyLB: UILabel! @IBOutlet weak var DollaCurrentcy: UILabel! let currency: [String] = ["VietNam(Dong)", "Eurozone(EUR)", "United Kingdom(GBP)", "Japanese Yên(JPY)", "China(PNY)","Australia(AUD)","Indonesia(IDR)","Hong Kong(HKD)","Korea(KRW)"] let sysbol: [String] = ["VND", "€", "£", "¥", "¥","؋","Rp","$","₩"] let Country: [String] = ["flag_vietnam", "flag_EU", "flag_english", "flag_japanese", "flag_china", "flag_australia","flag_indonesia","flag_hongkong","flag_korea"] var total = Double() @IBOutlet weak var tableCountry: UITableView! // @IBOutlet weak var tableCountry: UITableView! override func viewDidLoad() { super .viewDidLoad() self.tableCountry.register(UITableViewCell.self, forCellReuseIdentifier: "ChangeBackGround") CurrentcyLB.text = String(format:"%.2f",(total)) DollaCurrentcy.text = String(format:"%.2f",(total)) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.currency.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { //create a new cell if needed or reuse an old one let cell:UITableViewCell = self.tableCountry.dequeueReusableCell(withIdentifier: "ChangeBackGround") as UITableViewCell! // set the text from the data model cell.textLabel?.text = self.currency[indexPath.row] cell.imageView?.image = UIImage(named: self.Country[indexPath.row]) return cell } //let// } }
true
6e579c4a95562e474bddaeeea25e52199a4131a9
Swift
emilia98/Swift-Training
/Test 2/Task 1/GetUniqueCharacters.swift
UTF-8
1,618
3.9375
4
[ "MIT" ]
permissive
func getUnique(_ text1 : String, _ text2 : String) -> [String] { let first = Array(text1) let second = Array(text2) let firstCount = first.count let secondCount = second.count var arr = [String]() if (firstCount < secondCount) { arr = getContainedUniqueCharacters(first, second) } else { arr = getContainedUniqueCharacters(second, first) } return arr } func isContained(_ arr : [String], _ char : String) -> Bool { for ch in arr { if (ch == char) { return true } } return false } func getContainedUniqueCharacters(_ shorterText: Array<Character>, _ longerText: Array<Character>) -> [String]{ var arr = [String]() let shorterCount = shorterText.count let longerCount = longerText.count for i in 0..<shorterCount { let currentCharShorter = shorterText[i] for j in 0..<longerCount { let currentCharLonger = longerText[j] if (currentCharShorter == currentCharLonger) { if (!isContained(arr, String(currentCharShorter))) { arr.append(String(currentCharShorter)) } break } } } return arr } var characters = getUnique("Hello", "BellowH") print(characters) characters = getUnique("Hello", "BellowH") print(characters) characters = getUnique("BellowH", "Hello") print(characters) characters = getUnique("AbCdE", "ABCDEFEA") print(characters) characters = getUnique("AbC", "aB") print(characters)
true
d50e4d4c8c2d722bc2cf2ff1345ed0b82228dede
Swift
stxnext/STXImageCache
/Source/Task.swift
UTF-8
1,380
2.671875
3
[ "MIT", "Apache-2.0" ]
permissive
// // Task.swift // STXImageCache // // Created by Norbert Sroczyński on 09.02.2017. // Copyright © 2017 STX Next Sp. z o.o. All rights reserved. // import Foundation final class Task: Operation { let url: URL let forceRefresh: Bool let provider: Providing let progress: STXImageCacheProgress? let completion: STXImageOperationCompletion var urlSessionTask: URLSessionTask? init(url: URL, forceRefresh: Bool, provider: Providing, progress: STXImageCacheProgress?, completion: @escaping STXImageOperationCompletion) { self.url = url self.forceRefresh = forceRefresh self.provider = provider self.progress = progress self.completion = completion } override func main() { if isCancelled { return } let semaphore = DispatchSemaphore(value: 0) urlSessionTask = provider.get(fromURL: url, forceRefresh: forceRefresh, progress: progress) { [weak self] data, error in guard let strongSelf = self else { semaphore.signal() return } if !strongSelf.isCancelled { strongSelf.completion(data, error) } semaphore.signal() } semaphore.wait() } override func cancel() { urlSessionTask?.cancel() super.cancel() } }
true
3dd7407baff934d0bc3f4c95898984d18b496c65
Swift
PetrosTepoyan/GRPC_test_app
/GRPC_test_app/RestNetwork/Entitys/ProfileModels/SetProfileLanguage.swift
UTF-8
729
2.984375
3
[]
no_license
// // File.swift // // // Created by Anton Yaroshchuk on 30.07.2021. // import Foundation public struct SetProfileLanguage: Codable { public var language: [String] public init(language: [String]) { self.language = language } public enum CodingKeys: String, CodingKey { case language } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) language = try container.decode([String].self, forKey: .language) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(language, forKey: .language) } }
true
4e058cd128f4758d99d65cb0068d07f64cac5b04
Swift
lukan98/iOS-Vjestina-QuizApp
/QuizApp/PresentationLayer/Presenters/Login/LoginPresenter.swift
UTF-8
1,409
2.875
3
[]
no_license
// // LoginPresenter.swift // QuizApp // // Created by Luka Namačinski on 11.05.2021.. // import Foundation class LoginPresenter: LoginPresenterProtocol { weak var coordinator: LoginCoordinator? private let userUseCase: UserUseCaseProtocol = UserUseCase() weak var delegate: LoginDelegate? init(delegate ld: LoginDelegate, coordinator lc: LoginCoordinator) { self.delegate = ld self.coordinator = lc } func handleLogin(username: String, password: String) { self.userUseCase.handleLogin(username: username, password: password, completionHandler: { [weak self] (loginResult: Result<User, RequestError>) -> Void in guard let self = self else { return } switch loginResult { case .failure(let requestError): DispatchQueue.main.async { switch requestError { case .networkError: self.delegate?.handleSignInError(errorMessage: requestError.localizedDescription) default: self.delegate?.handleSignInError(errorMessage: "Username or password incorrect!") } } case .success: DispatchQueue.main.async { self.coordinator?.handleLogin() } } }) } }
true
1acdc1277260b9859b95991da5502f7c4cbed0c3
Swift
bjray/Escape
/Escape/Ghost.swift
UTF-8
1,829
2.96875
3
[]
no_license
// // Ghost.swift // Escape // // Created by B.J. Ray on 8/25/15. // Copyright (c) 2015 Bj Ray. All rights reserved. // import SpriteKit class Ghost:SKSpriteNode, GameSprite { var textureAtlas:SKTextureAtlas = SKTextureAtlas(named: "enemies.atlas") var fadeAnimation = SKAction() func spawn(parentNode: SKNode, position: CGPoint, size: CGSize = CGSize(width: 30, height: 44)) { parentNode.addChild(self) createAnimations() self.size = size self.position = position self.physicsBody = SKPhysicsBody(circleOfRadius: size.width / 2) self.physicsBody?.affectedByGravity = false self.physicsBody?.categoryBitMask = PhysicsCategory.enemy.rawValue self.physicsBody?.collisionBitMask = ~PhysicsCategory.damagedPenguin.rawValue self.texture = textureAtlas.textureNamed("ghost-frown.png") self.runAction(fadeAnimation) self.alpha = 0.8 } func onTap() { // not implemented } func createAnimations() { // Fade ghost out action group let fadeOutGroup = SKAction.group([ SKAction.fadeAlphaTo(0.3, duration: 2), SKAction.scaleTo(0.8, duration: 2), SKAction.colorizeWithColor(UIColor.greenColor(), colorBlendFactor: 0.8, duration: 2) ]) let fadeInGroup = SKAction.group([ SKAction.fadeAlphaTo(0.8, duration: 2), SKAction.scaleTo(1, duration: 2), SKAction.colorizeWithColor(UIColor.lightGrayColor(), colorBlendFactor: 0.8, duration: 2) ]) // Sequence the actions let fadeSequence = SKAction.sequence([fadeOutGroup, fadeInGroup]) fadeAnimation = SKAction.repeatActionForever(fadeSequence) } }
true
6bb74fdbc5ec3ab8a3c36f444d8a20c6ce30661f
Swift
fordee/RemoteHome
/RemoteHome/Cells/TemperatureCell.swift
UTF-8
690
2.625
3
[]
no_license
// // TemperatureCell.swift // RemoteHome // // Created by John Forde on 13/10/18. // Copyright © 2018 4DWare. All rights reserved. // import UIKit import Stevia class TemperatureCell: UICollectionViewCell { let roomTemperatureView = RoomTemperatureView() var device: IoTDevice? { didSet(value) { roomTemperatureView.device = device } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder)} override init(frame: CGRect) { super.init(frame: frame) sv( roomTemperatureView ) // Here we layout the cell. layout( 4, |-4-roomTemperatureView-4-|, >=4 ) // Configure visual elements backgroundColor = UIColor.backgroundColor } }
true
fe1a612b67f3af85fe1dfab7ea2e8b1d7d7ba626
Swift
zwvista/LogicPuzzlesSwift
/LogicPuzzlesSwift/Puzzles/Galaxies/GalaxiesDocument.swift
UTF-8
690
2.5625
3
[]
no_license
// // GalaxiesDocument.swift // LogicPuzzlesSwift // // Created by 趙偉 on 2016/09/18. // Copyright © 2016年 趙偉. All rights reserved. // import UIKit class GalaxiesDocument: GameDocument<GalaxiesGameMove> { static var sharedInstance = GalaxiesDocument() override func saveMove(_ move: GalaxiesGameMove, to rec: MoveProgress) { (rec.row, rec.col) = move.p.unapply() rec.intValue1 = move.dir rec.intValue2 = move.obj.rawValue } override func loadMove(from rec: MoveProgress) -> GalaxiesGameMove { GalaxiesGameMove(p: Position(rec.row, rec.col), dir: rec.intValue1, obj: GridLineObject(rawValue: rec.intValue2)!) } }
true
a03281d4b993fa3a4401c18f1d40dcc548ce00db
Swift
jessgates/Brew_Buddy
/BreweryDBConvenience.swift
UTF-8
9,059
2.546875
3
[ "MIT" ]
permissive
// // BreweryDBConvenience.swift // Brew_Buddy // // Created by Jess Gates on 1/6/17. // Copyright © 2017 Jess Gates. All rights reserved. // import UIKit extension BreweryDBClient { // Get the paginated beer list from BreweryDB func getBeerList( _ completionHandlerForGetBeers: @escaping (_ success: Bool, _ data: [[String: AnyObject]]?, _ error: NSError?) -> Void) { let apiPath = BreweryDBClient.BreweryDB.APIPathBeers let paramaters: [String: Any?] = [BreweryDBClient.BreweryDBParameterKeys.APIKey: BreweryDBClient.BreweryDBParameterValues.APIKey, BreweryDBClient.BreweryDBParameterKeys.ResponseFormat: BreweryDBClient.BreweryDBParameterValues.ResponseFormat, BreweryDBClient.BreweryDBBeersParameterKeys.AvailableID: BreweryDBClient.BreweryDBBeersParameterValues.AvailableID, BreweryDBClient.BreweryDBBeersParameterKeys.WithBreweries: BreweryDBClient.BreweryDBBeersParameterValues.WithBreweries, BreweryDBClient.BreweryDBBeersParameterKeys.Page: pageNumber] taskForGETMethod(paramaters as [String : AnyObject], apiPath: apiPath) { (result, error) -> Void in if let error = error { completionHandlerForGetBeers(false, nil, error) } else { guard let numberOfPages = result?["numberOfPages"] as? Int else { completionHandlerForGetBeers(false, nil, error) return } guard let pageNumber = result?["currentPage"] as? Int else { completionHandlerForGetBeers(false, nil, error) return } guard let beerDictionary = result?[BreweryDBClient.BreweryDBResponseKeys.Data] as? [[String: AnyObject]] else { completionHandlerForGetBeers(false, nil, error) return } self.numberOfPages = numberOfPages self.pageNumber = pageNumber completionHandlerForGetBeers(true, beerDictionary, nil) } } } // Get brewery list from BreweryDB func getNearbyBreweries(lat: Double, lon: Double, _ completionHandlerForGetBreweries: @escaping (_ success: Bool, _ data: [Brewery]?, _ error: NSError?) -> Void) { let apiPath = BreweryDBClient.BreweryDB.APIPathSearchBreweries let paramaters: [String: Any?] = [BreweryDBClient.BreweryDBParameterKeys.APIKey: BreweryDBClient.BreweryDBParameterValues.APIKey, BreweryDBBreweryParameterKeys.Latitude: lat, BreweryDBBreweryParameterKeys.Longitude: lon, BreweryDBBreweryParameterKeys.Radius: BreweryDBBreweryParameterValues.Radius, BreweryDBBreweryParameterKeys.Unit: BreweryDBBreweryParameterValues.Unit, BreweryDBClient.BreweryDBParameterKeys.ResponseFormat: BreweryDBClient.BreweryDBParameterValues.ResponseFormat] taskForGETMethod(paramaters as [String : AnyObject], apiPath: apiPath) { (result, error) -> Void in if let error = error { completionHandlerForGetBreweries(false, nil, error) } else { guard let breweryDictionary = result?[BreweryDBClient.BreweryDBResponseKeys.Data] as? [[String: AnyObject]] else { completionHandlerForGetBreweries(false, nil, error) return } let breweries = Brewery.breweriesFromResults(breweryDictionary) BreweryAnnotation.sharedInstance().breweries = breweries let annotations = BreweryAnnotation.sharedInstance().getBreweryAnnotations(breweries) BreweryAnnotation.sharedInstance().annotations = annotations completionHandlerForGetBreweries(true, breweries, nil) } } } // Search the breweryDB for beer based search text func getBeerFromSearch(queryString: String, _ completionHandlerForGetBeers: @escaping (_ success: Bool, _ data: [[String: AnyObject]]?, _ error: NSError?) -> Void) { let apiPath = BreweryDBClient.BreweryDB.APIPathSearch let paramaters: [String: Any?] = [BreweryDBClient.BreweryDBParameterKeys.APIKey: BreweryDBClient.BreweryDBParameterValues.APIKey, BreweryDBClient.BreweryDBParameterKeys.ResponseFormat: BreweryDBClient.BreweryDBParameterValues.ResponseFormat, BreweryDBClient.BreweryDBBeersParameterKeys.WithBreweries: BreweryDBClient.BreweryDBBeersParameterValues.WithBreweries, BreweryDBBeersParameterKeys.QueryString: queryString, BreweryDBBeersParameterKeys.SearchType: BreweryDBBeersParameterValues.SearchType] taskForGETMethod(paramaters as [String : AnyObject], apiPath: apiPath) { (result, error) -> Void in if let error = error { completionHandlerForGetBeers(false, nil, error) } else { guard let beerDictionary = result?[BreweryDBClient.BreweryDBResponseKeys.Data] as? [[String: AnyObject]] else { completionHandlerForGetBeers(false, nil, error) return } completionHandlerForGetBeers(true, beerDictionary, nil) } } } // Get list of beers for a brewery based on the style func getBeerStyleFromSearch(styleID: Double, _ completionHandlerForGetBeers: @escaping (_ success: Bool, _ data: [[String: AnyObject]]?, _ error: NSError?) -> Void) { let apiPath = BreweryDBClient.BreweryDB.APIPathBeers let paramaters: [String: Any?] = [BreweryDBClient.BreweryDBParameterKeys.APIKey: BreweryDBClient.BreweryDBParameterValues.APIKey, BreweryDBClient.BreweryDBParameterKeys.ResponseFormat: BreweryDBClient.BreweryDBParameterValues.ResponseFormat, BreweryDBClient.BreweryDBBeersParameterKeys.WithBreweries: BreweryDBClient.BreweryDBBeersParameterValues.WithBreweries, BreweryDBBeersParameterKeys.StyleID: styleID, BreweryDBClient.BreweryDBBeersParameterKeys.Order: BreweryDBClient.BreweryDBBeersParameterValues.Order, BreweryDBBeersParameterKeys.RandCount: BreweryDBBeersParameterValues.RandCount] taskForGETMethod(paramaters as [String : AnyObject], apiPath: apiPath) { (result, error) -> Void in if let error = error { completionHandlerForGetBeers(false, nil, error) } else { guard let beerDictionary = result?[BreweryDBClient.BreweryDBResponseKeys.Data] as? [[String: AnyObject]] else { completionHandlerForGetBeers(false, nil, error) return } completionHandlerForGetBeers(true, beerDictionary, nil) } } } // Get list of beers for a brewery based on the brewery ID func getBreweryBeersFromSearch(_ completionHandlerForGetBreweryBeers: @escaping (_ success: Bool, _ data: [[String: AnyObject]]?, _ error: NSError?) -> Void) { let apiPath = BreweryDB.APIPathBreweryID.replacingOccurrences(of: "<breweryId>", with: breweryID) let paramaters: [String: Any?] = [BreweryDBClient.BreweryDBParameterKeys.APIKey: BreweryDBClient.BreweryDBParameterValues.APIKey, BreweryDBClient.BreweryDBParameterKeys.ResponseFormat: BreweryDBClient.BreweryDBParameterValues.ResponseFormat] taskForGETMethod(paramaters as [String : AnyObject], apiPath: apiPath) { (result, error) -> Void in if let error = error { completionHandlerForGetBreweryBeers(false, nil, error) } else { guard let beerDictionary = result?[BreweryDBClient.BreweryDBResponseKeys.Data] as? [[String: AnyObject]] else { completionHandlerForGetBreweryBeers(false, nil, error) return } completionHandlerForGetBreweryBeers(true, beerDictionary, nil) } } } // Download images asynchronously func downloadImage( imagePath:String, completionHandler: @escaping (_ imageData: NSData?, _ errorString: String?) -> Void){ DispatchQueue.global(qos: .userInitiated).async { let session = URLSession.shared let imgURL = NSURL(string: imagePath) let request: NSURLRequest = NSURLRequest(url: imgURL! as URL) let task = session.dataTask(with: request as URLRequest) {data, response, downloadError in if downloadError != nil { completionHandler(nil, "Could not download image \(imagePath)") } else { completionHandler(data as NSData?, nil) } } task.resume() } } }
true
ab654f42b5f07397441d099398251ba712456ed0
Swift
M-Hamed/weatherHistory
/Weather History/Weather History/Core/Network/Base/Constants.swift
UTF-8
1,173
2.859375
3
[ "MIT" ]
permissive
// // Constants.swift // Weather History // // Created by Mohamed Hamed on 12/28/17. // Copyright © 2017 Hamed. All rights reserved. // import Foundation enum Environment { case debug case release static var current: Environment { return .debug } } struct Constants { private init() {} static let environment = Environment.current static var baseURL: String { switch environment { case .debug: return "http://api.openweathermap.org" case .release: return "http://api.openweathermap.org" } } static var baseApiURL: String { switch environment { case .debug: return baseURL + "/\(namespace)/\(APIVersion.v25.rawValue)" case .release: return baseURL + "/\(namespace)/\(APIVersion.v25.rawValue)" } } } extension Constants { static var namespace: String { return "data" } public enum APIVersion: String { case v25 = "2.5" } } extension Constants { static var weatherAPIKEY: String { return "be41eee34a0fcd23293be278c0333f88" } }
true
53639803453baf01221431e5c573a0d89dbb18e5
Swift
apple/swift-lldb
/packages/Python/lldbsuite/test/lang/swift/clangimporter/objcmain_conflicting_dylibs/Bar.swift
UTF-8
187
2.65625
3
[ "NCSA", "Apache-2.0", "LLVM-exception" ]
permissive
import CBar import Foundation func use<T>(_ t: T) {} @objc public class Bar : NSObject { @objc public func f() { let baz = Baz(i_am_from_Bar: 42) use(baz) // break here } }
true
2e63f5b5d2d2521bf0f41d3b1028a4274e6172e6
Swift
rogertalk/reactioncam
/ReactionCam/ComposerLayer.swift
UTF-8
592
2.578125
3
[ "MIT" ]
permissive
import CoreGraphics class ComposerLayer: CustomDebugStringConvertible { let name: String var frame: CGRect var isHidden = false var isOpaque = false var layout = ComposerLayout.coverCenter var provider: TextureProvider var transform = CGAffineTransform.identity init(_ name: String, frame: CGRect, provider: TextureProvider) { self.name = name self.frame = frame self.provider = provider } // MARK: - CustomDebugStringConvertible var debugDescription: String { return "<ComposerLayer \"\(self.name)\">" } }
true
60f0ba9057c9fec00904d47d85b9ff8d6b086ee5
Swift
Frenor/Hundevurdering
/Hundevurdering/Dog.swift
UTF-8
629
3.328125
3
[]
no_license
// // Dog.swift // Hundevurdering // // Created by Fredrik Nordmoen on 03.10.14. // Copyright (c) 2014 Fredrik Nordmoen. All rights reserved. // import Foundation struct Dog { let name: String let age: Int let score1: Int let score2: Int var totalScore: Int { return score1 + score2 } init(name: String, age: Int) { self.name = name self.age = age self.score1 = 0 self.score2 = 0 } init(name: String, age: Int, score1: Int, score2: Int) { self.name = name self.age = age self.score1 = score1 self.score2 = score2 } }
true
1b825c4cc1d0690fb102fdb283912f7f1ed4b1b5
Swift
Zyoma108/HeadsAndHandsTest
/HeadsAndHandsTest/Network/WeatherService.swift
UTF-8
588
2.53125
3
[]
no_license
// // WeatherService.swift // HeadsAndHandsTest // // Created by Roman Sentsov on 18/01/2019. // Copyright © 2019 Roman Sentsov. All rights reserved. // import Foundation import Alamofire class WeatherService: APIService { typealias T = Weather var url: String { return "https://api.apixu.com/v1/current.json" } var method: HTTPMethod { return .get } var parameters: [String : Any] { return [ "key": Constants.apixApiKey, "q": city ] } let city: String init(city: String) { self.city = city } }
true
ce0b489eb5888f829e531fb4f69215f3d55c95f7
Swift
garretthead00/RepHub
/RepHub/Views/Activity/ActivityLogsView.swift
UTF-8
2,146
2.53125
3
[]
no_license
// // ActivityLogsView.swift // RepHub // // Created by Garrett Head on 1/30/20. // Copyright © 2020 Garrett Head. All rights reserved. // import UIKit class ActivityLogsView: UITableViewCell { @IBOutlet weak var collectionView: UICollectionView! var logs : [NutritionLog]? { didSet { updateView() } } override func awakeFromNib() { super.awakeFromNib() // Initialization code collectionView.delegate = self collectionView.dataSource = self } private func updateView(){ print("got logs \(logs?.count)") collectionView.reloadData() } } extension ActivityLogsView : UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return logs!.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LogView", for: indexPath) as! HydrationLogView cell.log = logs![indexPath.row] return cell } } extension ActivityLogsView : UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 192.0, height: 148.0) } // func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { // return UIEdgeInsets(top: 8, left: 2, bottom: 8, right: 2) // } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 16 } }
true
b408040d0f7e1c69e0bdb7f148a5b89b92dab2ce
Swift
InnaLabynskaya/Foodzie
/Foodzie/Services/Location/PermissionHandler/LocationPermissionHandler.swift
UTF-8
834
2.671875
3
[]
no_license
// // LocationPermissionHandler.swift // Foodzie // // Created by Inna Kuts on 08.07.2021. // import Foundation import CoreLocation class LocationPermissionHandler: LocationPermissionHandlerProtocol { var authorizationStatus: CLAuthorizationStatus { return CLLocationManager.authorizationStatus() } var isLocationEnabled: Bool { return CLLocationManager.locationServicesEnabled() } var needAccessToLocation: Bool { return authorizationStatus == .notDetermined || authorizationStatus == .denied } var isLocationAuthorized: Bool { return authorizationStatus == .authorizedWhenInUse || authorizationStatus == .authorizedAlways } var isLocationEnabledAndAuthorized: Bool { return isLocationEnabled && isLocationAuthorized } }
true
a3cfa16abe8483653dd6344209bb881d5e4d0871
Swift
JianglunPro/Blog
/JS-Native/JS-Native/WK/WKController.swift
UTF-8
1,371
2.65625
3
[]
no_license
// // WKController.swift // JS-Native // // Created by 姜伦 on 2018/7/13. // Copyright © 2018年 JianglunPro. All rights reserved. // import UIKit import WebKit class WKController: UIViewController { var wkweb: WKWebView! let handlerName = "App" override func viewDidLoad() { super.viewDidLoad() let config = WKWebViewConfiguration() config.userContentController.add(self, name: handlerName) wkweb = WKWebView(frame: view.bounds, configuration: config) let url = Bundle.main.url(forResource: "wk", withExtension: "html")! let request = URLRequest(url: url) view.addSubview(wkweb) wkweb.load(request) } @objc func callNative(_ parameter: String) { print(parameter) } } extension WKController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { if message.name == handlerName { if let body = message.body as? [String: Any], let method = body["method"] as? String, let parameter = body["parameter"] as? String { let selector = Selector(method) if responds(to: selector) { self.perform(selector, with: parameter) } } } } }
true
47a471a9bd733ec482479ead181d2ab9795c32fd
Swift
dat1010/ActivityMaps
/ActivityMaps/SignUpLogin.swift
UTF-8
1,910
2.546875
3
[]
no_license
// // SignUpLogin.swift // ActivityMaps // // Created by David Tanner Jr on 6/6/15. // Copyright (c) 2015 David Tanner Jr. All rights reserved. // import UIKit import Parse import ParseUI class SignUpLogin: UIViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate { override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if PFUser.currentUser() == nil { var loginCtrl = PFLogInViewController() loginCtrl.fields = PFLogInFields.UsernameAndPassword | PFLogInFields.LogInButton loginCtrl.delegate = self var signupCtrl = PFSignUpViewController() signupCtrl.delegate = self loginCtrl.signUpController = signupCtrl self.presentViewController(loginCtrl ,animated:true,completion:nil) } } func logInViewController(logInController: PFLogInViewController, shouldBeginLogInWithUsername username: String, password: String) -> Bool { if count(username) > 0 && count(password) > 0{ return true }else{ var alert = UIAlertView(title: "Missing login info", message: "Make sure you fill in the username and password", delegate: nil, cancelButtonTitle: "OK") alert.show() return false } } func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) { self.dismissViewControllerAnimated(true, completion: nil) } func logInViewController(logInController: PFLogInViewController, didFailToLogInWithError error: NSError?) { println("Login Failed") } func logInViewControllerDidCancelLogIn(logInController: PFLogInViewController) { println("Login canceled by user") } }
true
c9eb58de6cafe1b5cf0c28214960ea766dae3d2b
Swift
game-platform-awaresome/GamerSky
/GamerSky/Classes/Module/News/Detail/Controller/ContentDetailViewController.swift
UTF-8
3,450
2.59375
3
[ "Apache-2.0" ]
permissive
// // NewsDetailViewController.swift // GamerSky // // Created by Insect on 2018/4/2. // Copyright © 2018年 QY. All rights reserved. // import UIKit import WebKit import URLNavigator class ContentDetailViewController: ViewController { private var contentID = 0 // MARK: - Lazyload private lazy var webView: WKWebView = { let webView = WKWebView(frame: UIScreen.main.bounds) webView.navigationDelegate = self return webView }() // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() view.addSubview(webView) setUpRefresh() } // MARK: - init init(ID: Int) { contentID = ID super.init(nibName: nil, bundle: nil) webView.backgroundColor = .clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension ContentDetailViewController { // MARK: - 设置刷新 private func setUpRefresh() { let nightMode = QYUserDefaults.getUserPreference()?.currentTheme == .night ? 1 : 0 webView.scrollView.qy_header = QYRefreshHeader { [weak self] in guard let `self` = self else {return} guard let URL = URL(string: "\(AppHostIP)/v1/ContentDetail/\(self.contentID)/1?fontSize=0&nullImageMode=1&tag=news&deviceid=\(deviceID)&platform=ios&nightMode=\(nightMode)&v=") else {return} self.webView.load(URLRequest(url: URL)) } webView.scrollView.qy_header.beginRefreshing() } } // MARK: - WKUIDelegate extension ContentDetailViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { webView.evaluateJavaScript("$('#gsTemplateContent_AD1').css('display', 'none');", completionHandler: nil) webView.evaluateJavaScript("$('#gsTemplateContent_AD2').css('display', 'none');", completionHandler: nil) webView.scrollView.qy_header.endRefreshing() } // func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { // // print("\(navigationAction.request)") // decisionHandler(.allow) // } } // MARK: - 与 JS 交互方法 extension ContentDetailViewController { // MARK: - 无图模式 private func setNullImageMode(_ isNull: Bool) { let jsString = isNull ? "gsSetNullImageMode(0);" : "gsSetNullImageMode(1);" webView.evaluateJavaScript(jsString, completionHandler: nil) } // MARK: - 设置字体大小 private func setFontSize(_ size: FontSizeType) { webView.evaluateJavaScript("gsSetFontSize(\(size.rawValue));", completionHandler: nil) } // MARK: - 获取网页中所有图片 private func getImages(info: ((_ images: [WebViewImage]) -> ())?) { webView.evaluateJavaScript("imageInfos;") { (result, error) in if let result = result { do { let images = try JSONDecoder().decode([WebViewImage].self, from: try JSONSerialization.data(withJSONObject: result, options: .prettyPrinted)) info?(images) } catch { print(error) } } } } }
true
786eb1a4e8e9d66d3e76ebe8f322065e74602efd
Swift
wxpasta/SwiftUI-learning
/Designcode.io/SwiftUI iOS 14/DesignCodeUniversal/Shared/Content/TutorialContent.swift
UTF-8
1,230
2.875
3
[ "Apache-2.0" ]
permissive
// // TutorialContent.swift // iOS // // Created by Meng To on 7/8/20. // import SwiftUI struct TutorialContent: View { @State var show = false var body: some View { LazyVGrid( columns: [GridItem(.adaptive(minimum: 240), spacing: 16, alignment: .top)], spacing: 0) { ForEach(tutorialSections) { section in #if os(iOS) NavigationLink(destination: TutorialSectionDetail(section: section)) { TutorialSectionRow(section: section) .padding(.all, 8) .frame(maxHeight: 78) } #else TutorialSectionRow(section: section) .padding(.all, 8) .frame(maxHeight: 78) .onTapGesture { show.toggle() } .sheet(isPresented: $show) { TutorialSectionDetail(section: section) } #endif } } .padding(16) } } struct TutorialContent_Previews: PreviewProvider { static var previews: some View { TutorialContent() } }
true
5742661ff21b03c622c07e13f426c8021659ca60
Swift
GeorgeWS/Intuitive-Math
/IntuitiveMath.swift
UTF-8
10,121
4
4
[]
no_license
// // Created by George Woodliff-Stanley on 12/31/15. // Copyright (c) 2015 George Woodliff-Stanley. // import Darwin /// Create a random number generator whose outputs are within a given range. func random(var from from: Double, var to: Double) -> Void -> Double { if to < from { swap(&to, &from) } return { _ in (((Double(arc4random()) % (Double(UInt32.max) + 1)) / Double(UInt32.max)) * (to - from)) + from } } /// Transform a mathematical function `f` into a new mathematical function using /// standard transformation parameters (`a`, `b`, `d`, and `h`). /// /// As few as none and as many as all of the parameters may be specified. At /// least one must be specified for the transformation to have any effect; the /// default parameters leave `f` untransformed. /// /// - parameters: /// - f: function to transform /// - a: vertical scale factor /// - b: horizontal scale factor (behavior varies between functions) /// - h: horizontal shift /// - d: vertical shift /// func transform(f: (Double -> Double), a: Double = 1, b: Double = 1, h: Double = 0, d: Double = 0) -> Double -> Double { return { x in a * f(b * (x - h)) + d } } /// Returns the number a given percentage from one number to another. /// /// - parameter percentage: The percentage specifying where in the given range /// the desired value is located. /// func scale(from from: Double, to: Double, by percentage: Double) -> Double { return from + percentage * (to - from) } /// A structure encapsulating the parameters and application of a hyperbolic /// tangent curve, useful for smooth animation or difficulty curves. An /// untransformed hyperbolic tangent curve looks like a smooth, continuously /// increasing "S" with a horizontal asymptote on each end. /// /// An `IntuitiveCurve` allows you to specify such a curve in terms of its /// "apparent" start and end points, where the function appears to depart from /// its two horizontal asymptotes. These points are defined as the locations of /// the function values at a customizable percentage (defaulting to 1%) inside /// the function's upper and lower bounds (i.e. using the default percentage, /// the x-values of the intersections between the function and two horizontal /// lines: one 1% below the function's upper limit, the other 1% above its lower /// limit). /// /// In addition to specifying the x-values of these intersections and optionally /// modifying the percent by which these intersections are inset from the upper /// and lower bounds of the curve, an `IntuitiveCurve` can also have a /// customized range. This is achieved by supplying any unique pair of /// "y-handles", defined by `IntuitiveCurve`'s `YHandle` enum. Each y-handle /// specifies a conceptual vertical customization point for the curve, as if /// attaching a draggable handle to the curve at the place indicated by the enum /// case, as well as an associated value for that handle, as if specifying /// where, vertically, that handle is dragged. A unique pair of y-handles is /// both necessary and sufficient to specify the range of the curve, which is /// why y-handles can only be specified as a tuple of two handles. Passing the /// same handle for both members of the tuple will cause an exception. /// /// Once an `IntuitiveCurve` is initialized, its parameters can be accessed but /// not modified, and function values can be obtained by passing x-inputs into /// the `apply` closure. (This closure is generated once when it is first /// accessed and can be saved into a variable, further transformed, and used as /// needed once it is generatated.) /// /// **Examples:** /// /// Create a curve which equals 0.01 at x = 0 and 0.99 at x = 100, with default /// limits of exactly 0 and 1: /// /// let curve1 = IntuitiveCurve(from: 0, to: 100) /// /// Create a curve which equals 0 at x = 0 and 1 at x = 100, with limits /// slightly below 0 and above 1: /// /// let curve2 = IntuitiveCurve(from: 0, to: 100, /// yHandles: (.BottomIntercept(0), .TopIntercept(1))) /// /// Create a curve which equals 0.1 at x = 0 and 0.9 at x = 100, with default /// limits of exactly 0 and 1: /// /// let curve3 = IntuitiveCurve(from: 0, to: 100, insetByPercent: 0.1) /// /// Create a curve which equals very slightly above 0 at x = 5 and exactly 4 at /// x = 10 at with a left limit of exactly 0 and a right limit very slightly /// above 4: /// /// let curve4 - IntuitiveCurve(from: 5, to: 10, /// yHandles: (.LeftLimit(0), .TopIntercept(4)), insetByPercent: 0.002) /// /// - note: To create a decreasing curve, specify a `from` value greater than /// the `to` value. /// struct IntuitiveCurve { /// The different "handles" that can be controlled vertically in an /// `IntuitiveCurve`. Cases are listed in decreasing order of where they /// would be located vertically on an untransformed `IntuitiveCurve`. enum YHandle: Equatable { /// The limit of the right asymptote (as x → ∞) case RightLimit(Double) /// The y value of the intersection between the curve and a horizontal /// line located `percentInset` percent in (down if increasing, up if /// decreasing) from the right limit. case RightIntercept(Double) /// The y value of the intersection between the curve and a horizontal /// line located `percentInset` percent in (up if increasing, down if /// decreasing) from the left limit. case LeftIntercept(Double) /// The limit of the left asymptote (as x → -∞) case LeftLimit(Double) } let rightLimit: Double let rightIntersection: (x: Double, y: Double) let leftIntersection: (x: Double, y: Double) let leftLimit: Double let percentInset: Double // The base function used to make the curve. Might want to allow base // functions other than tanh to be specified in future. let baseFunction: Double -> Double = tanh let inverseBaseFunction: Double -> Double = atanh let apply: Double -> Double let applyInverse: Double -> Double init(from: Double, to: Double, withYHandles yHandles: (YHandle, YHandle) = (.LeftLimit(0), .RightLimit(1)), insetByPercent percentInset: Double = 0.01) { let (handle1, handle2) = yHandles guard handle1 != handle2 else { fatalError("The same case cannot be used for both y-handles of an IntuitiveCurve") } self.percentInset = percentInset var leftLimit: Double?, leftIntercept: Double?, rightIntercept: Double?, rightLimit: Double? switch handle1 { case .RightLimit(let a): rightLimit = a case .RightIntercept(let a): rightIntercept = a case .LeftIntercept(let a): leftIntercept = a case .LeftLimit(let a): leftLimit = a } switch handle2 { case .RightLimit(let a): rightLimit = a case .RightIntercept(let a): rightIntercept = a case .LeftIntercept(let a): leftIntercept = a case .LeftLimit(let a): leftLimit = a } // Derive remaining two vertical parameters from supplied y-handles: switch (leftLimit, leftIntercept, rightIntercept, rightLimit) { case (let leftLimit?, _, _, let rightLimit?): leftIntercept = scale(from: leftLimit, to: rightLimit, by: percentInset) rightIntercept = scale(from: leftLimit, to: rightLimit, by: 1 - percentInset) case (let leftLimit?, _, let rightIntercept?, _): rightLimit = scale(from: leftLimit, to: rightIntercept, by: 1 / (1 - percentInset)) leftIntercept = scale(from: leftLimit, to: rightLimit!, by: percentInset) case (let leftLimit?, let leftIntercept?, _, _): rightLimit = scale(from: leftLimit, to: leftIntercept, by: 1 / percentInset) rightIntercept = scale(from: leftLimit, to: rightLimit!, by: 1 - percentInset) case (_, let leftIntercept?, _, let rightLimit?): leftLimit = scale(from: rightLimit, to: leftIntercept, by: 1 / (1 - percentInset)) rightIntercept = scale(from: leftLimit!, to: rightLimit, by: 1 - percentInset) case (_, let leftIntercept?, let rightIntercept?, _): rightLimit = scale(from: leftIntercept, to: rightIntercept, by: (1 - percentInset) / (1 - 2 * percentInset)) leftLimit = scale(from: rightLimit!, to: leftIntercept, by: 1 / (1 - percentInset)) case (_, _, let rightIntercept?, let rightLimit?): leftLimit = scale(from: rightLimit, to: rightIntercept, by: 1 / percentInset) leftIntercept = scale(from: leftLimit!, to: rightLimit, by: percentInset) default: break } self.rightLimit = rightLimit! self.rightIntersection = (x: to, y: rightIntercept!) self.leftIntersection = (x: from, y: leftIntercept!) self.leftLimit = leftLimit! // Derive vertical transformation constants (a = scale, d = shift): let a = (self.rightLimit - self.leftLimit) / 2 let d = self.rightLimit - a // Use inverse function to get x-positions of desired y-intercepts // on curve without horizontal transformations: let unscaledX1 = self.inverseBaseFunction((self.leftIntersection.y - d) / a) let unscaledX2 = self.inverseBaseFunction((self.rightIntersection.y - d) / a) // Derive horizontal scale factor: let unscaledXRange = unscaledX2 - unscaledX1 let desiredXRange = self.rightIntersection.x - self.leftIntersection.x let b = unscaledXRange / desiredXRange // Get scaled (but still unshifted) x-positions of desired y-intercepts: let scaledButUnshiftedX1 = unscaledX1 / b let scaledButUnshiftedX2 = unscaledX2 / b // Derive horizontal shift: let scaledXRange = scaledButUnshiftedX2 - scaledButUnshiftedX1 let h = scaledXRange / 2 + self.leftIntersection.x // Construct desired function (and its inverse) with derived parameters: let function = transform(self.baseFunction, a: a, b: b, h: h, d: d) let inverseFunction = transform(self.inverseBaseFunction, a: 1 / b, b: 1 / a, h: d, d: h) self.apply = function self.applyInverse = inverseFunction } } /// Two YHandles are considered equal iff their cases match (i.e. regardless of /// their associated values). func ==(lhs: IntuitiveCurve.YHandle, rhs: IntuitiveCurve.YHandle) -> Bool { switch (lhs, rhs) { case (.RightLimit, .RightLimit): return true case (.RightIntercept, .RightIntercept): return true case (.LeftIntercept, .LeftIntercept): return true case (.LeftLimit, .LeftLimit): return true default: return false } }
true
e624446302b32c60fd68604036e04498e80ba442
Swift
teddysot/SwiftIOS
/RPGStore/RPGStore/Weapon.swift
UTF-8
257
2.625
3
[]
no_license
// // Item.swift // RPGStore // // Created by Teddy Nasahachart on 2019-08-09. // Copyright © 2019 Teddy Nasahachart. All rights reserved. // import Foundation struct Weapon : Decodable { let name : String let cost : Int let damage : Int let icon : URL }
true
ff316e3e00bb2b1e792e04044ca48833f477b5a9
Swift
mike976/HolyBibleDailyScriptures_IOS
/HolyBibleDailyScriptures/View/DailyScripturesViewController.swift
UTF-8
4,136
2.5625
3
[]
no_license
// // FirstViewController.swift // HolyBibleDailyScriptures // // Created by Michael Bullock on 21/07/2020. // Copyright © 2020 Michael Bullock. All rights reserved. // import UIKit class DailyScripturesViewController: UIViewController { @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var tableView: UITableView! private var loadingScriptures = false; private var newTestamentVerse: Verse? private var psalmVerse: Verse? private var proverbVerse: Verse? var categories = ["New Testament", "Psalms", "Proverbs"] override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.backgroundColor self.navigationBar.barTintColor = UIColor.navBarBackgroundColor self.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] self.navigationBar.delegate = self self.tableView.allowsSelection = false self.tableView.separatorColor = UIColor.clear self.tableView.backgroundColor = UIColor.backgroundColor self.tableView.register(UINib(nibName: "DailyScriptureCell", bundle: nil), forCellReuseIdentifier: "DailyScriptureCell") self.tableView.dataSource = self self.tableView.delegate = self self.loadScriptures() } var bibleViewModel: BibleViewModelProtocol? { didSet { self.loadScriptures() } } func loadScriptures() { if self.loadingScriptures == true { return } self.loadingScriptures = true if bibleViewModel != nil { let dispatchQueue = DispatchQueue.global(qos: .background) dispatchQueue.async { self.getNewTestamentVerse() self.getPsalmVerse() self.getProverbVerse() } } } private func getNewTestamentVerse(){ if let verse = self.bibleViewModel?.getNewTestamentVerse(){ DispatchQueue.main.async { self.newTestamentVerse = verse self.tableView.reloadData() } } } private func getPsalmVerse(){ if let verse = self.bibleViewModel?.getPsalmVerse() { DispatchQueue.main.async { self.psalmVerse = verse self.tableView.reloadData() } } } private func getProverbVerse(){ if let verse = self.bibleViewModel?.getProverbVerse() { DispatchQueue.main.async { self.proverbVerse = verse self.tableView.reloadData() } } } } //MARK: - TableViewController section extension DailyScripturesViewController : UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 5 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "DailyScriptureCell", for: indexPath) as! DailyScriptureCell var verse: Verse? if indexPath.section == 0 { verse = self.newTestamentVerse } else if indexPath.section == 2 { verse = self.psalmVerse } else if indexPath.section == 4 { verse = self.proverbVerse } if verse != nil { cell.verseLabel?.text = verse?.Text cell.verseInfoLabel?.text = verse?.Reference cell.translationLabel?.text = verse?.TranslationName } return cell } } extension DailyScripturesViewController: UINavigationBarDelegate { func position(for bar: UIBarPositioning) -> UIBarPosition { return UIBarPosition.topAttached } }
true
24ab0415212dd5a1903617e966a4f8c863ef68f5
Swift
brandon-beekeeper/Geofencing
/Geofencing/APICalls.swift
UTF-8
2,529
2.703125
3
[]
no_license
// // APICalls.swift // Geofencing // // Created by Brandon Vasquez on 6/17/18. // Copyright © 2018 Brandon Vasquez. All rights reserved. // import Foundation class Backend { // API setup__________________________________________________________________________ // This creates a post request that mutes notificaitons for 12 hours func muteNotifications() { let url = URL(string: "https://usecasedev.us.beekeeper.io/api/2/users/me/settings/notifications")! var request = URLRequest(url: url) request.httpMethod = "POST" // Adding Headers request.addValue("application/json", forHTTPHeaderField: "content-type") request.addValue("Token a32b1b34-ed58-44fe-b1c5-aa2cc815ae88", forHTTPHeaderField: "Authorization") request.addValue("application/json", forHTTPHeaderField: "Accept") // Setting up post body let post = ["mute_group_chats": "12", "mute_push_notifications": "12"] do { let jsonBody = try JSONSerialization.data(withJSONObject: post, options: []) request.httpBody = jsonBody } catch {} // Setting up data task let task = URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data else { return } do { let json = try JSONSerialization.jsonObject(with: data, options: []) print(json) } catch {} } task.resume() } // This function createss a post request that unmutes notifications func unmuteNotifications() { let url = URL(string: "https://usecasedev.us.beekeeper.io/api/2/users/me/settings/notifications")! var request = URLRequest(url: url) request.httpMethod = "POST" // Adding Headers request.addValue("application/json", forHTTPHeaderField: "content-type") request.addValue("Token a32b1b34-ed58-44fe-b1c5-aa2cc815ae88", forHTTPHeaderField: "Authorization") request.addValue("application/json", forHTTPHeaderField: "Accept") // Setting up post body let post = ["mute_group_chats": "0", "mute_push_notifications": "0"] do { let jsonBody = try JSONSerialization.data(withJSONObject: post, options: []) request.httpBody = jsonBody } catch {} // Setting up data task let task = URLSession.shared.dataTask(with: request) { (data, response, error) in guard let data = data else { return } do { let json = try JSONSerialization.jsonObject(with: data, options: []) print(json) } catch {} } task.resume() } }
true
547c8b0c6081a4685cef4452b8750f57b36cd2e7
Swift
evelyngonzalez/Acoustic
/AppAcoustic/AppAcoustic/Location.swift
UTF-8
416
2.90625
3
[]
no_license
import UIKit import Alamofire import AlamofireObjectMapper import ObjectMapper class Location: Mappable { required init?(map: Map) { } var lat: Double? var lon: Double? init(latX: Double, latY: Double){ self.lat = latX self.lon = latY } func mapping(map: Map) { self.lat <- map["lat"] self.lon <- map ["lon"] } }
true
fefa8ce3f02b553f394b08ec4fd60ddf3ddc4067
Swift
VeronikaBabii/GettingActiveApp
/GettingActiveApp/ViewControllers/ProgressTreeViewController.swift
UTF-8
5,496
2.625
3
[]
no_license
// // ProgressTreeViewController.swift // GettingActiveApp // // Created by Veronika Babii on 12.06.2020. // Copyright © 2020 GettingActiveApp. All rights reserved. // import UIKit import Firebase import FirebaseAuth import FirebaseFirestore class ProgressTreeViewController: UIViewController { var db = Firestore.firestore() @IBOutlet weak var treeImage: UIImageView! @IBOutlet weak var progressLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() setBadges() checkForCountUpdates() } func setBadges() { let userID = Auth.auth().currentUser!.uid let archiveCollRef = db.collection("users").document(userID).collection("archive") archiveCollRef.getDocuments { (queryShapshot, error) in if let error = error { print("\(error.localizedDescription)") } else { // count snapshots in a collection - number of tasks in archive var count = 0 for _ in queryShapshot!.documents { count += 1 } // count number of tasks, badges = count * 5 // switch for different number of tasks and set appropriate images switch count { case 0: print("0") self.progressLabel.text = "Ти на 0 рівні :(" self.treeImage.image = UIImage(named: "tree-0") case 1: print("\nLevel 1: 5-20 points") self.progressLabel.text = "Ти на 1 рівні!" self.treeImage.image = UIImage(named: "tree-1") case 4: print("\nLevel 2: 25-40 points") self.progressLabel.text = "Ти на 2 рівні!" self.treeImage.image = UIImage(named: "tree-2") case 8: print("\nLevel 3: 45-60 points") self.progressLabel.text = "Ти на 3 рівні!" self.treeImage.image = UIImage(named: "tree-3") case 12: print("\nLevel 4: 65-80 points") self.progressLabel.text = "Ти на 4 рівні!" self.treeImage.image = UIImage(named: "tree-4") case 16: print("\nLevel 5: 85-100 points") self.progressLabel.text = "Ти на 5 рівні! Вітаю!" self.treeImage.image = UIImage(named: "tree-5") default: print("Default") } } } } func checkForCountUpdates() { let userID = Auth.auth().currentUser!.uid let archiveCollRef = db.collection("users").document(userID).collection("archive") archiveCollRef.getDocuments { (queryShapshot, error) in if let error = error { print("\(error.localizedDescription)") } else { // listen to archive collection archiveCollRef.addSnapshotListener() { querySnapshot, error in guard let snapshot = querySnapshot else {return} snapshot.documentChanges.forEach { diff in // if action is addition - count number of done tasks again if diff.type == .added { var count = 0 for _ in querySnapshot!.documents { count += 1 } switch count { case 1: print("\nLevel 1: 5-20 points") self.progressLabel.text = "Ти на 1 рівні!" self.treeImage.image = UIImage(named: "tree-1") case 4: print("\nLevel 2: 25-40 points") self.progressLabel.text = "Ти на 2 рівні!" self.treeImage.image = UIImage(named: "tree-2") case 8: print("\nLevel 3: 45-60 points") self.progressLabel.text = "Ти на 3 рівні!" self.treeImage.image = UIImage(named: "tree-3") case 12: print("\nLevel 4: 65-80 points") self.progressLabel.text = "Ти на 4 рівні!" self.treeImage.image = UIImage(named: "tree-4") case 16: print("\nLevel 5: 85-100 points") self.progressLabel.text = "Ти на 5 рівні! Вітаю!" self.treeImage.image = UIImage(named: "tree-5") default: print("Default") } } } } } } } }
true
69d2ac77f6271780c5ad555a8773df6e9772dc4f
Swift
arvindcc/iOS-Application
/AppSlash/AppSlash/ViewController.swift
UTF-8
3,256
2.59375
3
[]
no_license
// // ViewController.swift // AppSlash // // Created by Arvind Chawdhary on 30/10/18. // Copyright © 2018 private. All rights reserved. // import UIKit import WebKit class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate { @IBOutlet var webView: WKWebView! let webPageSpinner = UIActivityIndicatorView() override func loadView() { webView = WKWebView() webView.navigationDelegate = self webView.uiDelegate = self view = webView } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.hidesBackButton = true let newBackButton = UIBarButtonItem(title: "Back", style: UIBarButtonItem.Style.plain, target: self, action: #selector(self.onBackPressed(_:))) self.navigationItem.leftBarButtonItem = newBackButton; let url = URL(string:"http://www.appslash.org")! webView.load(URLRequest(url: url)) webView.allowsBackForwardNavigationGestures = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) /* To init Spinner initSpinner() */ } @IBAction func onBackPressed(_ sender: Any) { if(webView.canGoBack) { webView.goBack() } } // this handles target=_blank links by opening them in the same view func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { if Reachability().isConnectedToNetwork() == true{ UIApplication.shared.isNetworkActivityIndicatorVisible = true if navigationAction.targetFrame == nil { webView.load(navigationAction.request) } UIApplication.shared.isNetworkActivityIndicatorVisible = false }else{ performSegue(withIdentifier: "loadLaunchScreen", sender: nil) } return nil } func initSpinner() { webPageSpinner.style = .whiteLarge webPageSpinner.color = #colorLiteral(red: 0.7450980544, green: 0.1568627506, blue: 0.07450980693, alpha: 1) webPageSpinner.frame = CGRect(x: self.view.center.x, y: self.view.center.y, width: 48, height: 48) view.addSubview(webPageSpinner) view.bringSubviewToFront(webPageSpinner) webPageSpinner.isHidden = true } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { webPageSpinner.stopAnimating() webPageSpinner.isHidden = true UIApplication.shared.isNetworkActivityIndicatorVisible = false } func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { webPageSpinner.stopAnimating() webPageSpinner.isHidden = true UIApplication.shared.isNetworkActivityIndicatorVisible = true } func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { webPageSpinner.isHidden = false webPageSpinner.startAnimating() UIApplication.shared.isNetworkActivityIndicatorVisible = true } }
true
442a2b67a842e181b612a5eae95fcff2edc0b50b
Swift
OussefFersi/think-it-smartyHomeIos
/smartyhome/smartyhome/View/HomeViewController.swift
UTF-8
2,686
2.8125
3
[]
no_license
// // HomeViewController.swift // smartyhome // // Created by Oussef Fersi on 18/3/2021. // import UIKit class HomeViewController: UIViewController { @IBOutlet weak var homeWelcomeLabel: UILabel! @IBOutlet weak var currentDateLabel: UILabel! @IBOutlet weak var tableView: UITableView! var data = [ Room(name: "Living Room",numberOfDevices: 4,image: "livingroom"), Room(name: "Media Room",numberOfDevices: 6,image: "mediaroom"), Room(name: "Bathroom",numberOfDevices: 1,image: "bathroom"), Room(name: "Bedroom",numberOfDevices: 3,image: "bedroom") ] override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = MStyle.backgroundColor self.tableView.delegate = self self.tableView.dataSource = self self.tableView.register(UINib(nibName: "RoomTableViewCell", bundle: nil), forCellReuseIdentifier: RoomTableViewCell.identifier) let currentDate = Date() let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_EN") formatter.dateStyle = .long currentDateLabel?.text = formatter.string(from: currentDate) currentDateLabel?.textColor = MStyle.grayColor let userName = UserDefaults.standard.string(forKey: MainViewController.USER_NAME_KEY) ?? "Unkown"//"Oussef" homeWelcomeLabel?.text = "Welcome, \(userName)!" homeWelcomeLabel?.textColor = MStyle.textColor } /* // 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 HomeViewController : UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 160.0 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: RoomTableViewCell.identifier, for: indexPath) as? RoomTableViewCell{ cell.roomViewModel = RoomViewModel(data[indexPath.row]) return cell } return UITableViewCell() } }
true
fd0dbf450c8cdc17b69071e1ce21fb06e5c15287
Swift
audreywelch/ios-sprint4-challenge
/MyMovies/MyMovies/View Controllers/MovieSearchTableViewCell.swift
UTF-8
1,742
3.09375
3
[]
no_license
import UIKit extension NSNotification.Name { static let shouldShowMovieAdded = NSNotification.Name("ShouldShowMovieAdded") } protocol MovieSearchTableViewCellDelegate: class { func addMovie(cell: MovieSearchTableViewCell, movie: MovieRepresentation) } class MovieSearchTableViewCell: UITableViewCell { // Holds the reference to our delegate weak var delegate: MovieSearchTableViewCellDelegate? static let reuseIdentifier = "MovieCell" @IBOutlet weak var movieTitleLabel: UILabel! @IBOutlet weak var movieButtonOutlet: UIButton! @IBAction func addMovieButton(_ sender: Any) { // Make sure we have a movie guard let movieRepresentation = movieRepresentation else { return } // When tapped, call the delegate's function with the cell that was tapped (self), and the movie delegate?.addMovie(cell: self, movie: movieRepresentation) // Change the title of the button to "Saved" movieButtonOutlet.setTitle("Saved", for: .normal) // Deactivate the button movieButtonOutlet.isEnabled = false // Post a notification when button is tapped indicating a movie has been saved NotificationCenter.default.post(name: .shouldShowMovieAdded, object: self) } var movieRepresentation: MovieRepresentation? { didSet { updateViews() } } func updateViews() { // Set the cell's text to the passed movie title movieTitleLabel.text = movieRepresentation?.title movieButtonOutlet.isEnabled = true movieButtonOutlet.setTitle("Add Movie", for: .normal) } }
true
3294880b93f72ea4a0e245a1ad72639bb13ddca3
Swift
jotape26/ND-Budget
/Budget/View Controller/ExpensesHomeViewController.swift
UTF-8
3,874
2.546875
3
[]
no_license
// // ExpensesHomeViewController.swift // Budget // // Created by João Leite on 05/02/19. // Copyright © 2019 João Leite. All rights reserved. // import UIKit import FirebaseFirestore import GoogleSignIn class ExpensesHomeViewController: UIViewController { @IBOutlet weak var headerView: UIView! @IBOutlet weak var expensesTable: UITableView! @IBOutlet weak var lbBudget: UILabel! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var budgetHeight: NSLayoutConstraint! @IBOutlet weak var budgetLabel: UILabel! @IBOutlet weak var smileyImage: UIImageView! let form = NumberFormatter() var expenses: [Expense] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. expensesTable.register(UINib(nibName: "ExpensesCell", bundle: nil), forCellReuseIdentifier: "ExpensesCell") expensesTable.delegate = self expensesTable.dataSource = self headerView.backgroundColor = APPCOLOR.DARK_GREEN form.numberStyle = .currencyAccounting } override func viewDidAppear(_ animated: Bool) { activityIndicator.isHidden = false lbBudget.text = "" activityIndicator.startAnimating() getExpenses() } } //MARK: - Custom Functions extension ExpensesHomeViewController { func getExpenses() { FirebaseService.retrieveUserExpenses { (retrievedExpenses) in self.expenses = retrievedExpenses if !self.expenses.isEmpty { self.smileyImage.isHidden = true } var monthlyExpenses = 0.0 self.expenses.forEach({ (t) in if Calendar.current.isDate(t.expenseDate!, equalTo: Date(), toGranularity: .month){ monthlyExpenses = monthlyExpenses + t.expenseValue! } }) let formattetExpense = self.form.string(from: monthlyExpenses as NSNumber)! self.lbBudget.text = "You've spent \(formattetExpense) this month." self.activityIndicator.isHidden = true self.activityIndicator.stopAnimating() if let userBudget = UserDefaults.standard.value(forKey: "userBudget") as? Double { if monthlyExpenses > userBudget { UIView.animate(withDuration: 1.5, animations: { self.budgetHeight.constant = 30 self.budgetLabel.backgroundColor = APPCOLOR.ORANGE }) } } self.expensesTable.reloadData() } } } extension ExpensesHomeViewController : UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print(self.expenses.count) return self.expenses.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ExpensesCell") as! ExpensesCell cell.lbExpenseName.text = expenses[indexPath.row].expenseName cell.lbExpenseValue.text = form.string(from: expenses[indexPath.row].expenseValue! as NSNumber) let df = DateFormatter() df.dateFormat = "dd/MM/yyyy" if let expense = expenses[indexPath.row].expenseDate { cell.lbDateExpense.text = df.string(from: expense) } else { cell.lbDateExpense.text = "" } if let category = expenses [indexPath.row].category { cell.expenseText.text = category } return cell } }
true
0846faeb2b372cfb018086b027b5b3cb9314d612
Swift
rptang/SQLiteDemo
/SQLiteDemo/SQLiteDemo/ViewController.swift
UTF-8
1,725
2.9375
3
[ "Apache-2.0" ]
permissive
// // ViewController.swift // SQLiteDemo // // Created by Mac on 16/12/5. // Copyright © 2016年 Mac. All rights reserved. // import UIKit let statuText = "当前状态:" class ViewController: UIViewController { let CellIdentifier = "CellIdentifier_ViewController" @IBOutlet weak var tableView: UITableView! var datas :[Person]?{ didSet{ tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: CellIdentifier) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) datas = Person.loadPersons() } } extension ViewController: UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return datas?.count ?? 0 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as! TableViewCell cell.p = datas![indexPath.row] return cell } } /* override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { //插入数据测试 one() //取出数据测试 two() } //取出 func two(){ let dicts = SQLManager.shareInstance().selectSQL(sql: "SELECT * FROM T_Person;") for dict in dicts { for (key,value) in dict { print(key) print(value) } } } //插入 func one(){ let p = Person(dict: ["name":"first", "age":15, "money":125.5]) print(p.insertSQL()) } */
true
91c92fefecb1827b7707658fe564bf152074ab85
Swift
yasuohasegawa/SimpleRssReaderWithSwiftUI
/RssReaderWithSwiftUI/FeedData.swift
UTF-8
530
2.515625
3
[]
no_license
// // FeedData.swift // RssReaderWithSwiftUI // // Created by Yasuo Hasegawa on 2020/03/06. // Copyright © 2020 Yasuo Hasegawa. All rights reserved. // import Foundation struct Feed: Codable { var items:[Item] } struct Item: Hashable, Codable { var title:String var link:String var guid:String var description:String var pubDate:String } struct ListItem: Hashable, Identifiable { var id = UUID() var title:String var link:String var guid:String var description:String var pubDate:String }
true
d6d306879f135184aa481e73883775102b6d5693
Swift
tifoaudii/GoPlay
/GoPlay/Scenes/MovieList/Cell/Popular/PopularMovieItemCell.swift
UTF-8
2,114
2.71875
3
[]
no_license
// // PopularMovieItemCell.swift // GoPlay // // Created by Tifo Audi Alif Putra on 30/06/21. // import UIKit final class PopularMovieItemCell: UICollectionViewCell { // MARK:- Static Cell Identifier static let identifier: String = "PopularMovieItemCellIdentifier" // MARK:- UI Components private lazy var movieImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.layer.cornerRadius = 4.0 imageView.backgroundColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1) imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() private lazy var movieTitleLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFont(ofSize: 14, weight: .bold) label.textAlignment = .left return label }() // MARK:- Initializer override init(frame: CGRect) { super.init(frame: frame) configureView() } required init?(coder: NSCoder) { super.init(coder: coder) configureView() } // MARK:- Internal functions func bindViewWith(movie: Movie) { movieImageView.sd_setImage(with: movie.posterURL, completed: nil) movieTitleLabel.text = movie.title } // MARK:- Private functions private func configureView() { let stackView = UIStackView( arrangedSubviews: [ movieImageView, movieTitleLabel ] ) .setAxis(.vertical) .setMargins(10) .setSpacing(6) movieTitleLabel.setContentHuggingPriority( UILayoutPriority(rawValue: 252), for: .vertical ) movieTitleLabel.setContentCompressionResistancePriority( UILayoutPriority(rawValue: 751), for: .vertical ) contentView.addSubview(stackView) stackView.fillSuperview() } }
true
12a180eeb923e2864f3ac7872c1be72c7174ac44
Swift
javb99/CocoaTouchAdditions
/CocoaTouchAdditions/NavigationBarConfiguration.swift
UTF-8
2,017
2.734375
3
[]
no_license
// // NavigationBarConfiguration.swift // CocoaTouchAdditions // // Created by Joseph Van Boxtel on 11/20/18. // Copyright © 2018 Joseph Van Boxtel. All rights reserved. // import UIKit extension UINavigationBar { public func apply(_ config: NavBarConfiguration) { if let v = config.barStyle { barStyle = v } if let v = config.isTranslucent { isTranslucent = v } if let v = config.prefersLargeTitles { prefersLargeTitles = v } if let v = config.tintColor { tintColor = v } if let v = config.barTintColor { barTintColor = v } if let v = config.titleTextAttributes { titleTextAttributes = v } if let v = config.largeTitleTextAttributes { largeTitleTextAttributes = v } if let v = config.shadowImage { shadowImage = v } if let v = config.backgroundImage { setBackgroundImage(v, for: .default)} } public var currentConfig: NavBarConfiguration { var config = NavBarConfiguration() config.barStyle = barStyle config.isTranslucent = isTranslucent config.prefersLargeTitles = prefersLargeTitles config.tintColor = tintColor config.barTintColor = barTintColor config.titleTextAttributes = titleTextAttributes config.largeTitleTextAttributes = largeTitleTextAttributes config.shadowImage = shadowImage config.backgroundImage = backgroundImage(for: .default) return config } } /// Leave a field nil to leave it unchanged. public struct NavBarConfiguration { public var barStyle: UIBarStyle? = nil public var isTranslucent: Bool? = nil public var prefersLargeTitles: Bool? = nil public var tintColor: UIColor? = nil public var barTintColor: UIColor?? = nil public var titleTextAttributes: [NSAttributedString.Key : Any]?? = nil public var largeTitleTextAttributes: [NSAttributedString.Key : Any]?? = nil public var shadowImage: UIImage?? = nil public var backgroundImage: UIImage?? = nil public init() {} }
true
ec65a62f936922ac08c03e4e248cf2e67079103b
Swift
konshinyg/steps
/urSteps/ClientControl.swift
UTF-8
5,111
2.828125
3
[]
no_license
// // Client.swift // urSteps // // Created by Core on 24.10.17. // Copyright © 2017 Cornelius. All rights reserved. // import Foundation let stringURL = "https://yoursteps.ru/api/users/" class ClientControl { static var currentClient = ClientControl() func requestToken(url: URL, email: String, password: String) { userDefClean() print("ClientControl: requesting for new access token") let bodyData = "email=\(email)&password=\(password)" var request = URLRequest(url: url) request.httpMethod = "Post" request.httpBody = bodyData.data(using: String.Encoding.utf8) URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in if let error = error { let errString = error.localizedDescription print(errString) } else if data != nil { if let dictionary = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary { let accessToken = dictionary?["id"] as! String let id = dictionary?["userId"] as! Int // -- Запись результатов в dictionary // var results = [String: AnyObject]() // results = ["at": accessToken as AnyObject, "id": id as AnyObject] // print("results: \(results)") UserDefaults.standard.set(accessToken, forKey: "access_token") UserDefaults.standard.set(id, forKey: "userID") UserDefaults.standard.synchronize() } } ClientControl.currentClient.requestJSON() }.resume() } // requestToken ends func requestJSON(/*infoView: UIViewController*/) { print("ClientControl: ok, we have access token, trying to request for JSON data") guard let accessToken = UserDefaults.standard.object(forKey: "access_token") as? String else { print("did't pass guard accessToken") return } guard let id = UserDefaults.standard.object(forKey: "userID") as? Int else { print("did't pass guard userID") return } print("id: ", id, ", access_token: ", accessToken) guard let url = URL(string: stringURL + String(describing: id)) else { return } var request = URLRequest(url: url) print("request: ", request) request.addValue(accessToken, forHTTPHeaderField: "Authorization") URLSession.shared.dataTask(with: request) { data, response, error in if let response = response as? HTTPURLResponse { print("response status: \(response.statusCode)") if response.statusCode == 401 { UserDefaults.standard.removeObject(forKey: "access_token") print("ClientControl: failed to get JSON data. Bad access token removed") return } } if let error = error { let errString = error.localizedDescription print(errString) } else if data != nil { let user = User(data: data!) User.currentUser = user if let dictionary = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary { print("dictionary: ", dictionary) } } }.resume() } // requestJSON ends func searchOldToken() { print("searchOldToken") let id = UserDefaults.standard.object(forKey: "userID") as! Int let accessToken = UserDefaults.standard.object(forKey: "access_token") as! String let urlString = stringURL + String(describing: id) + "/accessTokens" var request = URLRequest(url: URL(string: urlString)!) request.httpMethod = "Get" request.addValue(accessToken, forHTTPHeaderField: "Authorization") print("request", request) URLSession.shared.dataTask(with: request) { (data, response, error) in if let error = error { print("error", error) } else if let response = response { print("response", response) } if data != nil { if let dictionary = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary { print("dictionary: ", dictionary) } } }.resume() } func userDefClean() { print("\(#function)") for key in UserDefaults.standard.dictionaryRepresentation().keys { UserDefaults.standard.removeObject(forKey: key) } User.currentUser = nil } }
true
7cc55f7864e75957268b210e9f41461a9ccc35e7
Swift
bkostjens/Turnstile
/Sources/Turnstile/Core/Turnstile.swift
UTF-8
606
2.9375
3
[ "Apache-2.0" ]
permissive
// // Turnstile.swift // Turnstile // // Created by Edward Jiang on 7/26/16. // // /** Turnstile is the object that manages all components used in Turnstile, and allows them to interoperate. */ public class Turnstile { /// The session manager backing Turnstile. public let sessionManager: SessionManager /// The realm backing Turnstile public let realm: Realm /// Initialize Turnstile with a compatible session manager and realm. public init(sessionManager: SessionManager, realm: Realm) { self.sessionManager = sessionManager self.realm = realm } }
true
e4b50beb38abeab33c94d1498999bb221e67b30c
Swift
cmcclatchey/ChicagoBlackhawksColinM.playground
/Contents.swift
UTF-8
2,868
3.671875
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit var nameOfPlayers: [Int: String] = [15: "Anisimov", 39: "Baun", 29: "Bickell", 56: "Dano", 11: "Desjardins", 28: "Garbutt", 62: "Haggerty", 38: "Hartman", 48: "Hinostroza", 81: "Hossa", 88: "Kane", 67: "Kero", 58: "Knott", 16: "Kruger", 46: "Liambas", 53: "Mashinter", 41: "Mcneill", 27: "Morin", 72: "Panarin", 70: "Rasmussen", 61: "Ross", 65: "Shaw", 86: "Teravainen", 14: "Tikhonov", 19: "Toews", 25: "Tropp", 63: "Brisebois", 6: "Daley", 45: "Fournier", 52: "Gustafsson", 4: "Hjalmarsson", 2: "Keith", 17: "Pokka", 42: "Robertson", 32: "Rozsival", 5: "Rundblad", 47: "Schilling", 7: "Seabrook", 43: "Svedberg", 75: "Valleau", 57: "Van Riemsdyk", 50: "Crawford", 33: "Darling", 49: "Leighton"] println("There are currently \(nameOfPlayers.count) players on the team.") println("") let names = nameOfPlayers.values let numbers = nameOfPlayers.keys for (numbers, names) in nameOfPlayers { print("Name of player: \(names) #\(numbers)") println("") } println("") var ageOfPlayers: [String] = ["18: Knott", "20: Dano", "21: Hartman, Hinostroza, Teravainen, Fournier, Pokka", "22: Haggerty, Mcneill, Valleau", "23: Baun, Kerom, Panarin Brisebois", "24: Morin, Shaw, Robertson, Runblad, Svedberg, Riemsdyk", "25: Kruger, Rasmussen", "26: Kane, Liambas, Schilling, Darling", "27: Anisimov, Mashinter, Tikhonov, Toews", "28: Hjalmarsson", "29: Bickell, Desjardins", "30: Garbutt, Seabrook, Crawford", "31: Daley", "32: Keith", "34: Leighton", "37: Rozsival"] println("Age of players") println("") for (age) in ageOfPlayers { print("Age \(age)") println("") } println("") println("Country of players") println("") var countryOfPlayers: [String] = ["Russia: Anisimov, Panarin", "Canada: Baun, Bickell, Desjardins, Garbutt, Knott, Liambas, Mashinter, Mcneill, Shaw, Toews, Brisebois, Daley, Fournier, Keith, Rovertson, Seabrook, Crawford, Leighton", "Austria: Dano", "USA: Hartman, Hinostroza, Kane, Kero, Morin, Ross, Tropp, Schilling, Riemsdyk, Darling", "Slovakia: Hossa", "Sweden: Kruger, Rasmussen, Gustafsson, Hjamarsson, Rundblad, Svedberg", "Finland: Teravainen, Pokka", "Latvia: Tikhonov", "Czech Republic: Rozsival"] for (country) in countryOfPlayers { print("\(country)") println("") } println("") println("Average age of players:") var averageAge = ((18 + 20 + (21 * 5) + (22 * 3) + (23 * 4) + (24 * 6) + (25 * 2) + (26 * 4) + (27 * 4) + 28 + (29 * 2) + (30 * 3) + 31 + 32 + 34 + 37) / 42) print(averageAge) println("\n") println("Average height of players:") var averageHeight = ((76 + 74 + 76 + 71 + 73 + 72 + 71 + 69 + 73 + 71 + 72 + 71 + 75 + 72 + 71 + 71 + 74 + 74 + 71 + 71 + 72 + 75 + 73 + 73 + 74 + 75 + 80 + 74 + 74 + 78 + 75) / 31) print("\(averageHeight) inches or 6'1\"") println("\n") var averageMonth = "May" println("Average birthday month: ") print(averageMonth)
true
35f3685c29855be1eba3c9ce3c5fce0bb7b192b0
Swift
jesse99/gym-planner
/gym-planner/gym-plannerTests/storableTests.swift
UTF-8
2,892
3.078125
3
[ "MIT" ]
permissive
import XCTest @testable import gym_planner class storableTests: XCTestCase { struct Data: Storable { let x: Double let n: Int let title: String init(x: Double, n: Int, title: String) { self.x = x self.n = n self.title = title } init(from store: Store) { self.x = store.getDbl("x") self.n = store.getInt("n") self.title = store.getStr("title") } func save(_ store: Store) { store.addDbl("x", x) store.addInt("n", n) store.addStr("title", title) } } struct Nested: Storable { let a: Data let b: Data init(first: String, second: String) { self.a = Data(x: 10.0, n: 2, title: first) self.b = Data(x: 20.0, n: 3, title: second) } init(from store: Store) { self.a = store.getObj("a") self.b = store.getObj("b") } func save(_ store: Store) { store.addObj("a", a) store.addObj("b", b) } } func testPrimitives() { let old = Data(x: 3.14, n: 10, title: "some data") let store = Store() store.addObj("data", old) let new: Data = store.getObj("data") XCTAssert((old.x - new.x) < 0.001) XCTAssertEqual(old.n, new.n) XCTAssertEqual(old.title, new.title) } func testIntArray() { let old: [Int] = [1, 3, 5, 7] let store = Store() store.addIntArray("data", old) let new = store.getIntArray("data") XCTAssertEqual(old.count, new.count) for i in 0..<min(old.count, new.count) { XCTAssertEqual(old[i], new[i]) } } func testObjArray() { let old: [Data] = [Data(x: 3.14, n: 10, title: "some data"), Data(x: 2.718, n: 33, title: "more data")] let store = Store() store.addObjArray("data", old) let new: [Data] = store.getObjArray("data") XCTAssertEqual(old.count, new.count) for i in 0..<min(old.count, new.count) { XCTAssert((old[i].x - new[i].x) < 0.001) XCTAssertEqual(old[i].n, new[i].n) XCTAssertEqual(old[i].title, new[i].title) } } func testNested() { let old = Nested(first: "one", second: "two") let store = Store() store.addObj("data", old) let new: Nested = store.getObj("data") XCTAssert((old.a.x - new.a.x) < 0.001) XCTAssertEqual(old.a.n, new.a.n) XCTAssertEqual(old.a.title, new.a.title) XCTAssert((old.b.x - new.b.x) < 0.001) XCTAssertEqual(old.b.n, new.b.n) XCTAssertEqual(old.b.title, new.b.title) } }
true
5b7f74bba732bc7fdd717c75ac3ddf1cca337b32
Swift
jaredmpayne/SwiftArg
/Sources/SwiftArg/Option.swift
UTF-8
527
3.421875
3
[ "Apache-2.0" ]
permissive
internal class Option { public init(names: [String], maxValueCount: UInt = 0) { self.names = names self.maxValueCount = maxValueCount } public let names: [String] public let maxValueCount: UInt public var isRaised: Bool = false public private(set) var values: [String] = [] public func add(value: String) -> Bool { guard self.values.count < self.maxValueCount else { return false } self.values.append(value) return true } }
true