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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
3b0ded7ca2f5ca2a36d4e2cc43198b0d71a4a5d0
|
Swift
|
wsmurphy/WeatherApp
|
/WeatherApp/ViewModel/ForecastWeatherViewModel.swift
|
UTF-8
| 1,447
| 3.109375
| 3
|
[] |
no_license
|
//
// ForecastWeatherViewModel.swift
// WeatherApp
//
// Created by Murphy, Stephen - William S on 7/19/19.
// Copyright © 2019 Murphy. All rights reserved.
//
import Foundation
protocol ForecastWeatherViewModelDelegate {
func forecastDidUpdate()
}
class ForecastWeatherViewModel {
var delegate: ForecastWeatherViewModelDelegate?
var forecast: Forecast?
var formatter: DateFormatter
init() {
formatter = DateFormatter()
formatter.dateFormat = "EEEE"
}
//Presentation variables
var numberOfForecastRows: Int {
return forecast?.list.count ?? 0
}
func getLatestForecast() {
//Get latest Weather
WeatherConnections.loadForecast(zip: "28146") { [weak self] (newForecast) in
guard let strongSelf = self else { return }
strongSelf.forecast = newForecast
//Indicate successful completion
strongSelf.delegate?.forecastDidUpdate()
}
}
func configureCellForRow(row: Int, cell: ForecastWeatherTableViewCell) -> ForecastWeatherTableViewCell {
guard let forecastDay = forecast?.list[row] else {
return cell
}
let date = Date(timeIntervalSince1970: forecastDay.dt)
cell.dayLabel.text = formatter.string(from: date)
cell.highTempLabel.text = "\(forecastDay.temp.max)"
cell.lowTempLabel.text = "\(forecastDay.temp.min)"
return cell
}
}
| true
|
fa1ede1dbfea235ef920dfc25ee3340f4514f076
|
Swift
|
autoreleasefool/legacy-hive-mind-client
|
/HiveAI/HiveAI/Source/Sections/Game/GameplayViewController.swift
|
UTF-8
| 4,754
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// GameplayViewController.swift
// HiveAI
//
// Created by Joseph Roque on 2019-02-27.
// Copyright © 2019 Joseph Roque. All rights reserved.
//
import UIKit
import HiveEngine
import FunctionalTableData
class GameplayViewController: FunctionalTableDataViewController {
struct State {
let aiPlayer: Player
var gameState: GameState = GameState(options: [.ladyBug, .mosquito, .pillBug, .disableMovementValidation, .allowSpecialAbilityAfterYoink, .restrictedOpening])
var lastAiMove: Movement?
var availableMoves: [Movement] = []
var selectedMovementCategory: MovementCategory?
var selectedUnit: HiveEngine.Unit?
var inputEnabled: Bool
var isPlayerTurn: Bool {
return gameState.currentPlayer != aiPlayer
}
var isAiTurn: Bool {
return isPlayerTurn == false
}
init(playerIsFirst: Bool) {
self.aiPlayer = playerIsFirst ? .black : .white
self.inputEnabled = playerIsFirst ? true : false
}
mutating func clearSelection() {
selectedMovementCategory = nil
selectedUnit = nil
}
}
private let api: HiveAPI
private var state: State
init(api: HiveAPI, playerIsFirst: Bool) {
self.api = api
self.state = State(playerIsFirst: playerIsFirst)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupNavigation()
view.backgroundColor = Colors.primary
state.inputEnabled = false
updateTitle()
refresh()
api.newGame(playerIsFirst: state.isPlayerTurn, delegate: self)
}
private func setupNavigation() {
navigationItem.hidesBackButton = true
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Reset", style: .plain, target: self, action: #selector(promptFinishGame))
}
private func updateTitle() {
self.title = state.gameState.isEndGame ? "Game over!" : (state.isPlayerTurn ? "Your Move" : "AI's Move")
}
override func render() -> [TableSection] {
return GameplayBuilder.sections(aiName: api.name, state: state, actionable: self)
}
private func resolvePlayerMovement(_ movement: Movement) {
state.clearSelection()
state.inputEnabled = false
state.gameState.apply(movement)
updateTitle()
if state.gameState.isEndGame {
// Do nothing
} else if state.isAiTurn {
api.play(movement, delegate: self)
} else {
state.inputEnabled = true
}
refresh()
}
private func resolveAiMovement(_ movement: Movement) {
state.gameState.apply(movement)
state.clearSelection()
state.lastAiMove = nil
if state.isAiTurn {
state.inputEnabled = false
api.play(nil, delegate: self)
} else {
state.inputEnabled = true
}
updateTitle()
refresh()
}
@objc private func promptFinishGame() {
DispatchQueue.main.async { [weak self] in
let alert = UIAlertController(title: "Finish game?", message: "Are you sure you want to end this game? You'll lose all your progress.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .default) { _ in })
alert.addAction(UIAlertAction(title: "Finish", style: .destructive) { _ in
self?.api.endGame()
self?.navigationController?.popViewController(animated: true)
})
self?.present(alert, animated: true)
}
}
}
extension GameplayViewController: GameplayActionable {
func confirmAiMove() {
guard let aiMovement = state.lastAiMove else { return }
resolveAiMovement(aiMovement)
}
func select(category: MovementCategory) {
guard state.inputEnabled else { return }
if state.selectedMovementCategory == category {
state.clearSelection()
} else {
state.selectedMovementCategory = category
}
if state.selectedMovementCategory == .pass {
resolvePlayerMovement(.pass)
}
refresh()
}
func select(unit: HiveEngine.Unit) {
guard state.inputEnabled else { return }
if state.selectedUnit == unit {
state.selectedUnit = nil
} else {
state.selectedUnit = unit
}
refresh()
}
func select(movement: Movement) {
guard state.inputEnabled else { return }
resolvePlayerMovement(movement)
}
}
extension GameplayViewController: HiveAPIDelegate {
func didBeginGame(api: HiveAPI) {
if state.isAiTurn {
api.play(nil, delegate: self)
} else {
state.inputEnabled = true
}
updateTitle()
refresh()
}
func didPlay(api: HiveAPI, move: Movement) {
state.lastAiMove = move
state.inputEnabled = true
refresh()
}
func didReceiveError(api: HiveAPI, error: Error) {
DispatchQueue.main.async { [weak self] in
print(error)
let alert = UIAlertController(title: "Error!", message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
self?.present(alert, animated: true)
}
}
}
| true
|
949f724898bedf269acdc14b46bb2435bc21124c
|
Swift
|
peter1001136/IOS_final2
|
/IOS_final2/Music/Feature/FeaturesDetail.swift
|
UTF-8
| 2,104
| 2.5625
| 3
|
[] |
no_license
|
//
// FeaturesDetail.swift
// IOS_final2
//
// Created by 陳政沂 on 2021/1/13.
//
import SwiftUI
struct FeaturesDetail: View {
@StateObject var trackviewmodel = TrackViewModel()
var featuresId: FeatureInfo
@State private var showsheet = false
var body: some View {
NavigationView {
List {
ScrollView(.vertical) {
HStack {
Button(action: {
showsheet = true
}){
NetworkImage(url: featuresId.images[1].url)
.scaledToFill()
.frame(width: 200, height: 200)
Text(featuresId.title)
.bold()
}.sheet(isPresented: $showsheet){
FeatureplaylistWidget(song: featuresId)
}
}
HStack {
ForEach (trackviewmodel.featuretracks) { index in
NavigationLink(
destination: /*@START_MENU_TOKEN@*/Text("Destination")/*@END_MENU_TOKEN@*/,
label: {
VStack {
NetworkImage(url: index.album.images[0].url)
.scaledToFill()
.frame(width: 100, height: 100)
Text(index.name)
.bold()
}
})
}
}
}
}
.onAppear(perform: {
trackviewmodel.fetchfeauretracks(id: featuresId.id)
})
}
}
}
struct FeaturesDetail_Previews: PreviewProvider {
static var previews: some View {
/*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/
}
}
| true
|
bf3d052f9602cf097155e243581a964c7e5ee81b
|
Swift
|
barisakkaya/ShoppingList-Realm
|
/Shopping List/ShoppingViewController.swift
|
UTF-8
| 3,851
| 2.90625
| 3
|
[] |
no_license
|
//
// ShoppingViewController.swift
// Shopping List
//
// Created by Barış Can Akkaya on 25.06.2021.
//
import UIKit
import RealmSwift
class ShoppingViewController: UITableViewController {
let localRealm = try! Realm()
var shoppingList = [Shopping]()
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
@IBAction func addButtonClicked(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add a new product!", message: "", preferredStyle: .alert)
let saveAction = UIAlertAction(title: "Save", style: .default) { alertAction in
if let text = textField.text {
let shop = Shopping()
shop.product = text
self.shoppingList.append(Shopping(product: text))
self.saveNewData(data: Shopping(product: text))
}
}
alert.addTextField { UITextField in
UITextField.placeholder = "Product"
textField = UITextField
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert, animated: true, completion: nil)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return shoppingList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ShoppingCell", for: indexPath)
let shop = localRealm.objects(Shopping.self)[indexPath.row]
cell.textLabel?.text = shop.product
cell.accessoryType = shop.isSelected ? .checkmark : .none
return cell
}
@objc func bos(){
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
try! localRealm.write {
localRealm.delete(shoppingList[indexPath.row])
}
shoppingList.remove(at: indexPath.row)
tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let shopToUpdate = localRealm.objects(Shopping.self)[indexPath.row]
print(shopToUpdate.isSelected)
try! localRealm.write {
shopToUpdate.isSelected = !shopToUpdate.isSelected
}
tableView.cellForRow(at: indexPath)?.accessoryType = shopToUpdate.isSelected ? .checkmark : .none
}
}
extension ShoppingViewController {
func saveNewData(data: Shopping) {
do {
try localRealm.write{
localRealm.add(data)
}
} catch {
print(error.localizedDescription)
}
tableView.reloadData()
}
func loadData() {
shoppingList.removeAll()
let shopping = localRealm.objects(Shopping.self)
for shop in shopping {
shoppingList.append(shop)
}
tableView.reloadData()
}
}
| true
|
f9cbc509a0f36196480a7aac81d4b7f2405edd79
|
Swift
|
asselborn/IZGuide
|
/InformatikzentrumGuide/Overlay/MapOverlay.swift
|
UTF-8
| 1,092
| 2.671875
| 3
|
[] |
no_license
|
//
// MapOverlay.swift
// InformatikzentrumGuide
//
// Created by David Asselborn on 02.01.18.
// Copyright © 2018 David Asselborn. All rights reserved.
//
import UIKit
import MapKit
// Defines position and dimensions of an overlay
class MapOverlay: NSObject, MKOverlay {
var coordinate: CLLocationCoordinate2D
var boundingMapRect: MKMapRect
override init() {
let topLeft = CLLocationCoordinate2D(latitude: 50.779817, longitude: 6.058315)
let topRight = CLLocationCoordinate2D(latitude: 50.779822, longitude: 6.061283)
let bottomLeft = CLLocationCoordinate2D(latitude: 50.777923, longitude: 6.058065)
self.coordinate = CLLocationCoordinate2D(latitude: 50.77885, longitude: 6.05975)
let origin = MKMapPointForCoordinate(topLeft)
let size = MKMapSize(width: fabs(MKMapPointForCoordinate(topLeft).x - MKMapPointForCoordinate(topRight).x),
height: fabs(MKMapPointForCoordinate(topLeft).y - MKMapPointForCoordinate(bottomLeft).y))
self.boundingMapRect = MKMapRect(origin: origin, size: size)
}
}
| true
|
a6a9b45024a3978bdbea9554254587baf69661d4
|
Swift
|
usedesk/UseDeskSwift
|
/Core/UDLocalizeManager.swift
|
UTF-8
| 19,402
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// UDLocalizeManager.swift
// UseDesk_SDK_Swift
import Foundation
class UDLocalizeManager {
var languages: [String : Any] = [:]
private var enLocale: [String:String] = [:]
private var ruLocale: [String:String] = [:]
private var ptLocale: [String:String] = [:]
private var esLocale: [String:String] = [:]
init() {
enLocale = getEnLocale()
ruLocale = getRuLocale()
ptLocale = getPtLocale()
esLocale = getEsLocale()
languages = [
"en" : enLocale,
"ru" : ruLocale,
"pt" : ptLocale,
"es" : esLocale
]
}
func getLocaleFor(localeId: String) -> [String:String]? {
if let locale = languages[localeId] as? [String:String] {
return locale
} else {
if localeId.count >= 2 {
let shorhLocaleId: String = String(localeId[localeId.startIndex..<localeId.index(localeId.startIndex, offsetBy: 2)])
if let locale = languages[shorhLocaleId] as? [String:String] {
return locale
}
}
return nil
}
}
// MARK: - Russia
private func getRuLocale() -> [String:String] {
let ruLocale: [String:String] = [
"Copy" : "Копировать",
"Yesterday" : "Вчера",
"Today" : "Сегодня",
"Close" : "Закрыть",
"GoToSettings" : "Перейти в настройки",
"AllowMedia" : "Разрешите доступ к фото и видео в настройках",
"AllowCamera" : "Разрешите доступ к камере в настройках",
"ToSendMedia" : "Для отправки фото или видео",
"Article" : "Статья",
"Category" : "Категория",
"KnowlengeBase" : "База знаний",
"Search" : "Введите свой запрос",
"SearchFail" : "Ничего не найдено",
"Cancel" : "Отменить",
"ArticleReviewForSubject" : "Отзыв о статье",
"KnowlengeBaseTag" : "БЗ",
"OnlineChat" : "Онлайн-чат",
"Chat" : "Чат",
"File" : "файл",
"File2" : "файла",
"File3" : "файлов",
"Attach" : "Прикрепить",
"AttachFile" : "Прикрепить файл",
"Write" : "Написать",
"AttachmentLimit" : "Прикреплено максимальное количество файлов",
"Ok" : "ОК",
"Done" : "Готово",
"Gallery" : "Галерея",
"ErrorLoading" : "Ошибка загрузки",
"Loading" : "Загрузка",
"DeleteMessage" : "Удалить сообщение",
"SendAgain" : "Отправить повторно",
"CSIReviewLike" : "Оценка: отлично",
"CSIReviewDislike" : "Оценка: плохо",
"LimitIsExceeded" : "Превышен лимит",
"ThisFileSize" : "Этот файл размером",
"B" : "Б",
"KB" : "КБ",
"MB" : "МБ",
"GB" : "ГБ",
"ExceededMaximumSize" : "превышает максимальный размер файла в",
"NotInternet" : "Нет интернета",
"NotInternetCheck" : "Попробуйте отключить режим полета, включить Wi-FI или мобильный интернет и проверить уровень сигнала сети",
"Sended" : "Отправлено",
"NotSelected" : "Не выбрано",
//Knowledge
"Send" : "Отправить",
"ArticleReviewTitle" : "Что не так?",
"PositiveReviewButton" : "Да, была",
"NegativeReviewButton" : "Не совсем",
"ArticleReviewFirstTitle" : "Была ли статья полезна?",
"ArticleReviewSendedTitle" : "Спасибо за отзыв!",
"ArticleReviewPlaceholder" : "Ваш комментарий",
"Comment" : "Комментарий:",
"ReviewTagsTitle" : "Что не так:",
//Feedback form
"Message" : "Сообщение",
"Email" : "Почта",
"ErrorEmail" : "Неправильно введена почта",
"MandatoryField" : "Обязательное поле",
"Name" : "Имя",
"TopicTitle" : "Тема обращения",
"CustomField" : "Дополнительное поле",
"Error" : "Ошибка",
"ServerError" : "Сервер не отвечает. Проверьте соединение и попробуйте еще раз.",
"Understand" : "Понятно",
"FeedbackSendedMessage" : "Сообщение отправлено! \n Ответим вам в течение 1 рабочего дня.",
"FeedbackText" : "Все операторы заняты. Оставьте сообщение, мы ответим вам на почту в течение 1 рабочего дня."
]
return ruLocale
}
// MARK: - English
private func getEnLocale() -> [String:String] {
let enLocale: [String:String] = [
"Copy" : "Copy",
"Yesterday" : "Yesterday",
"Today" : "Today",
"Close" : "Close",
"GoToSettings" : "Go to settings",
"AllowMedia" : "Allow access to digital media and files",
"AllowCamera" : "Allow access to the camera",
"ToSendMedia" : "To send photo/video",
"Article" : "Article",
"Category" : "Category",
"KnowlengeBase" : "Knowledge Base",
"Search" : "Enter your query",
"SearchFail" : "Nothing found",
"Cancel" : "Cancel",
"ArticleReviewForSubject" : "Article review",
"KnowlengeBaseTag" : "Knowlenge Base",
"OnlineChat" : "Online-chat",
"Chat" : "Chat",
"File" : "File",
"File2" : "File",
"File3" : "File",
"Attach" : "Attach",
"AttachFile" : "Прикрепить файл",
"Write" : "Text",
"AttachmentLimit" : "Attachment limit reached",
"Ok" : "OK",
"Done" : "Done",
"Gallery" : "Gallery",
"ErrorLoading" : "Error loading",
"Loading" : "Loading",
"DeleteMessage" : "Delete message",
"SendAgain" : "Resend",
"CSIReviewLike" : "Rating: excellent",
"CSIReviewDislike" : "Rating: poor",
"LimitIsExceeded" : "Limit is exceeded",
"ThisFileSize" : "This file size",
"B" : "B",
"KB" : "KB",
"MB" : "MB",
"GB" : "GB",
"ExceededMaximumSize" : "exceeded maximum file size",
"NotInternet" : "No Internet",
"NotInternetCheck" : "Try turning off airplane mode, turning on Wi-Fi or mobile internet and checking the network signal strength",
"Sended" : "Sent",
"NotSelected" : "Not selected",
//Knowledge
"Send" : "Send",
"ArticleReviewTitle" : "What's goes wrong?",
"PositiveReviewButton" : "Yes, it was",
"NegativeReviewButton" : "No, it wasn't",
"ArticleReviewFirstTitle" : "Was this article helpful?",
"ArticleReviewSendedTitle" : "Thanks for review!",
"ArticleReviewPlaceholder" : "Your comment",
"Comment" : "Comment:",
"ReviewTagsTitle" : "What's wrong:",
//Feedback form
"Message" : "Message",
"Email" : "Mail",
"ErrorEmail" : "Invalid login",
"MandatoryField" : "Mandatory field",
"Name" : "Name",
"TopicTitle" : "Subject of appeal",
"CustomField" : "Additional field",
"Error" : "Error",
"ServerError" : "The server isn't responding. Check your connection and try again.",
"Understand" : "OK",
"FeedbackSendedMessage" : "Your message has been sent. We will reply to you within one business day.",
"FeedbackText" : "All agents are busy at this time. Leave your message and we'll answer withing one working day."
]
return enLocale
}
// MARK: - Spanish
private func getEsLocale() -> [String:String] {
let esLocale: [String:String] = [
"Copy" : "Copiar",
"Yesterday" : "Ayer",
"Today" : "Hoy",
"Close" : "Cerrar",
"GoToSettings" : "Ir a la configuración",
"AllowMedia" : "Permitir el acceso a medios digitales y archivos",
"AllowCamera" : "Permitir el acceso a la cámara",
"ToSendMedia" : "Para enviar foto / video",
"Article" : "Artículo",
"Category" : "Categoría",
"KnowlengeBase" : "Base de conocimientos",
"Search" : "Ingresa tu consulta",
"SearchFail" : "Nada Encontrado",
"Cancel" : "Cancelar",
"ArticleReviewForSubject" : "Revisión del artículo",
"KnowlengeBaseTag" : "Base de conocimiento",
"OnlineChat" : "Chat en línea",
"Chat" : "Charla",
"File" : "Archivo",
"File2" : "Archivo",
"File3" : "Archivo",
"Attach" : "Adjuntar",
"AttachFile" : "Прикрепить файл",
"Write" : "Escribir",
"AttachmentLimit" : "Se alcanzó el límite de archivos adjuntos",
"Ok" : "OK",
"Done" : "Hecho",
"Gallery" : "Galería",
"ErrorLoading" : "Error al cargar",
"Loading" : "Cargando",
"DeleteMessage" : "Borrar mensaje",
"SendAgain" : "Reenviar",
"CSIReviewLike" : "Satisfacción: Excelente",
"CSIReviewDislike" : "Satisfacción: Pobre",
"LimitIsExceeded" : "Limite foi excedido",
"ThisFileSize" : "Tamanho do arquivo",
"B" : "B",
"KB" : "KB",
"MB" : "MB",
"GB" : "GB",
"ExceededMaximumSize" : "excedeu o tamanho máximo do arquivo",
"NotInternet" : "Sin conexión al internet",
"NotInternetCheck" : "Intente apagar el modo avión, encienda Wi-FI o Internet móvil y verifique la intensidad de la señal de la red",
"Sended" : "Enviado",
"NotSelected" : "No seleccionado",
//Knowledge
"Send" : "Enviar",
"ArticleReviewTitle" : "¿Qué va mal?",
"PositiveReviewButton" : "Sí, lo era",
"NegativeReviewButton" : "No, no fue",
"ArticleReviewFirstTitle" : "¿Te resultó útil este artículo",
"ArticleReviewSendedTitle" : "¡Gracias por revisar!",
"ArticleReviewPlaceholder" : "Tu comentario",
"Comment" : "Сomentario:",
"ReviewTagsTitle" : "Que sucede:",
//Feedback form
"Message" : "Mensaje",
"Email" : "Correo",
"ErrorEmail" : "Ingreso invalido",
"MandatoryField" : "Campo obligatorio",
"Name" : "Nombre",
"TopicTitle" : "El tema de la solicitud",
"CustomField" : "Campo adicional",
"Error" : "Error",
"ServerError" : "El servidor no responde. Verifique su conexión y vuelva a intentarlo.",
"Understand" : "OK",
"FeedbackSendedMessage" : "Tu mensaje ha sido enviado. Le responderemos dentro de un día hábil.",
"FeedbackText" : "Todos los agentes están ocupados en este momento. Deje su mensaje que te responderemos en un día hábil. "
]
return esLocale
}
// MARK: - Portugal
private func getPtLocale() -> [String:String] {
let ptLocale: [String:String] = [
"Copy" : "Copiar",
"Yesterday" : "Ontem",
"Today" : "Hoje",
"Close" : "Fechar",
"GoToSettings" : "Ir para as configurações",
"AllowMedia" : "Permitir o acesso a arquivos e media digital ",
"AllowCamera" : "Permitir acesso à câmera",
"ToSendMedia" : "Para enviar foto / vídeo",
"Article" : "Artigo",
"Category" : "Categoria",
"KnowlengeBase" : "Base de Conhecimento",
"Search" : "Digite sua consulta",
"SearchFail" : "Nada encontrado",
"Cancel" : "Cancelar",
"ArticleReviewForSubject" : "Avaliação do artigo",
"KnowlengeBaseTag" : "Base de Conhecimento",
"OnlineChat" : "Chat online",
"Chat" : "Chat",
"File" : "Arquivo",
"File2" : "Arquivo",
"File3" : "Arquivo",
"Attach" : "Anexar",
"AttachFile" : "Прикрепить файл",
"Write" : "Escrever",
"AttachmentLimit" : "Limite de anexos atingido",
"Ok" : "OK",
"Done" : "Feito",
"Gallery" : "Galeria",
"ErrorLoading" : "Erro ao carregar",
"Loading" : "Carregando",
"DeleteMessage" : "Apagar mensagem",
"SendAgain" : "Reenviar",
"CSIReviewLike" : "Avaliação: Excelente",
"CSIReviewDislike" : "Avaliação: Ruim",
"LimitIsExceeded" : "Se supera el límite",
"ThisFileSize" : "Tamaño del archivo",
"B" : "B",
"KB" : "KB",
"MB" : "MB",
"GB" : "GB",
"ExceededMaximumSize" : "superó el tamaño máximo de archivo",
"NotInternet" : "Sem internet",
"NotInternetCheck" : "Tente desligar o modo avião, ligue o Wi-Fi ou a internet móvel e verifique a força do sinal da rede",
"Sended" : "Enviado",
"NotSelected" : "Não selecionado",
//Knowledge
"Send" : "Enviar",
"ArticleReviewTitle" : "O que há de errado?",
"PositiveReviewButton" : "Sim, foi",
"NegativeReviewButton" : "Não, não foi",
"ArticleReviewFirstTitle" : "Esse artigo foi útil?",
"ArticleReviewSendedTitle" : "Obrigado por nos avaliar!",
"ArticleReviewPlaceholder" : "Seu comentário",
"Comment" : "Сomentário:",
"ReviewTagsTitle" : "O que há de errado:",
//Feedback form
"Message" : "Mensagem",
"Email" : "Enviar",
"ErrorEmail" : "Login inválido",
"MandatoryField" : "Campo obrigatório",
"Name" : "Nome",
"TopicTitle" : "Tema da solicitação ",
"CustomField" : "Campo adicional",
"Error" : "Erro",
"ServerError" : "O servidor não está respondendo. Verifique sua conexão e tente novamente.",
"Understand" : "OK",
"FeedbackSendedMessage" : "Sua mensagem foi enviada. Nós responderemos dentro de um dia útil.",
"FeedbackText" : "Todos os atendentes estão ocupados neste momento. Deixe sua mensagem que nós te responderemos em até um dia útil."
]
return ptLocale
}
}
| true
|
6d2d0f215185611a12aee79d0450bb709f5ce291
|
Swift
|
chaosuperduan/Youker_Enterprise
|
/Youker_Enterprise/Classes/Hotel/Cell/RoomTableViewCell.swift
|
UTF-8
| 2,345
| 2.515625
| 3
|
[] |
no_license
|
//
// RoomTableViewCell.swift
// youke
//
// Created by keelon on 2018/6/26.
// Copyright © 2018年 M2Micro. All rights reserved.
//
import UIKit
class RoomTableViewCell: UITableViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var roomLabel: UILabel!
@IBOutlet weak var bedLabel: UILabel!
@IBOutlet weak var areaLabel: UILabel!
@IBOutlet weak var priceLabel: UILabel!
@IBOutlet weak var breakfeastLabel: UILabel!
@IBOutlet weak var windowLabel: UILabel!
@IBOutlet weak var discountLabel: UILabel!
var callBack:((_ room:Room)->())?
var price:NSInteger = 0
var room:Room?{
didSet{
if room?.has_Window == 1 {
self.windowLabel.text = "有窗"
}else{
self.windowLabel.text = "有窗"
}
roomLabel.text = room?.room_Name
if (room?.pictures.count)!>0 {
iconImageView.kf.setImage(with: URL.init(string: (room?.pictures[0])!))
}
if room?.has_Breakfast == 1 {
self.breakfeastLabel.text = "含早餐"
}else{
self.breakfeastLabel.text = "不含早餐"
}
let priceString = NSMutableAttributedString.init(string:"原价:" + "\(String(describing: room!.original_Price))")
priceString.addAttribute(NSAttributedStringKey.strikethroughStyle, value: NSNumber.init(value: 1), range: NSRange(location: 0, length: priceString.length))
discountLabel.text = "¥" + "\(price)" + "/天"
priceLabel.attributedText = priceString
areaLabel.text = "房间面积:"+"\(room!.area)"+"㎡"
bedLabel.text = "床的尺寸" + "\(room!.bed_Length)"+"x"+"\(room!.bed_Width)"+"m"
}
}
@IBAction func book(_ sender: Any) {
if (callBack != nil) != nil {
callBack!(room!)
}
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| true
|
fd578cbafcad8936c734ade914643ff3aaa0dc46
|
Swift
|
Kopezaur/ParkinCare
|
/ParkinCare/EvaluationSetViewModel.swift
|
UTF-8
| 4,421
| 2.875
| 3
|
[] |
no_license
|
//
// EvaluationSetViewModel.swift
// ParkinCare
//
// Created by Kopezaur on 3/29/18.
// Copyright © 2018 Kopezaur. All rights reserved.
//
import Foundation
import CoreData
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
// MARK: -
/// Delegate to simulate reactive programming to change of Evaluation set
protocol EvaluationSetViewModelDelegate {
// MARK: -
/// called when set globally changes
func dataSetChanged()
/// called when a Evaluation is deleted from set
///
/// - Parameter indexPath: (section,row) of deletion
func evaluationDeleted(at indexPath: IndexPath)
/// called when a Evaluation is updated in set
///
/// - Parameter indexPath: (section, row) of updating
func evaluationUpdated(at indexPath: IndexPath)
/// called when a Evaluation is added to set
///
/// - Parameter indexPath: (section,row) of add
func evaluationAdded(at indexPath: IndexPath)
}
//----------------------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------------------
// MARK: -
class EvaluationSetViewModel : EvaluationTableViewModel{
// MARK: -
let modelset : EvaluationSet = EvaluationSet()
/// NSFetchResultsController manage the set of Evaluations that are persistents
fileprivate lazy var evaluationsFetched : NSFetchedResultsController<Evaluation> = {
// prepare a request
let request : NSFetchRequest<Evaluation> = Evaluation.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(key:#keyPath(Evaluation.dateTime),ascending:true)]
let fetchResultController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: CoreDataManager.context, sectionNameKeyPath: nil, cacheName: nil)
guard let fetchResultControllerDelegate = self.delegate as? NSFetchedResultsControllerDelegate else{
fatalError("delegate of EvaluationSetViewModel should also be a NSFetchedResultsControllerDelegate")
}
fetchResultController.delegate = fetchResultControllerDelegate
return fetchResultController
}()
var pdelegate : EvaluationSetViewModelDelegate?
var delegate : EvaluationSetViewModelDelegate?{
get{
return self.pdelegate
}
set{
self.pdelegate = newValue
do{
try self.evaluationsFetched.performFetch()
}
catch let error as NSError{
fatalError(error.description)
}
}
}
init() {
}
convenience init(delegate : EvaluationSetViewModelDelegate) {
self.init()
self.delegate = delegate
}
//-------------------------------------------------------------------------------------------------
// MARK: EvaluationTableViewModel function
/// numbers of rows for a given section
///
/// - Parameter section: section we want the number of rows
/// - Returns: number of rows for section
func rowsCount(inSection section : Int) -> Int{
guard let section = self.evaluationsFetched.sections?[section] else { fatalError("Unexpected Section") }
return section.numberOfObjects
}
/// return Evaluation at indexPath
///
/// - Parameter indexPath: indexPath of Evaluation to be returned
/// - Returns: Evaluation if there is one at this indexPath, else returns nil
public func getEvaluation(at indexPath: IndexPath) -> Evaluation?{
return self.evaluationsFetched.object(at: indexPath)
}
//-------------------------------------------------------------------------------------------------
// MARK: View Model functions
/// add a new Evaluation in set of Evaluations
///
/// - Parameter Evaluation: Evaluation to be added
public func add(evaluation: Evaluation){
self.modelset.add(evaluation: evaluation)
}
//-------------------------------------------------------------------------------------------------
// MARK: Convenience functions
}
| true
|
0a317cc88c7ceb4794267ae51092c2e3d60e69a9
|
Swift
|
Sridharan15/Intern_works
|
/print the key when ele present.swift
|
UTF-8
| 676
| 2.84375
| 3
|
[] |
no_license
|
let productGroups = ["1000": "/1/2/3/4/5",
"1002": "1/2/4" ,
"1004": "/5/2/4/"]
let productDetails = [["id": 0, "Name": "Boost", "Parent": 1],
["id": 1, "Name": "Horlicks", "Parent": 0],
["id": 2, "Name": "Complan", "Parent": 1],
["id": 3, "Name": "Bournvita", "Parent": 2],
["id": 4, "Name": "Moltovo", "Parent": 3]]
let input = 1
for (key,values) in productGroups{
let productValues = values.split(separator : "/")
for each in productValues{
if each == "\(input)"{
print(key)
}
}
}
| true
|
3320549a26c0f52e1ce041fc52396b39ec636fc1
|
Swift
|
BenEmdon/Swift-iOS-Workshop
|
/Tour of Swift.playground/Pages/Simple Values.xcplaygroundpage/Contents.swift
|
UTF-8
| 1,366
| 5.125
| 5
|
[
"MIT"
] |
permissive
|
/*:
# Simple Values
## Variables and Constants
*/
// Use `var` to make a variable
var myVariable = 42
myVariable = 50
// `let` to make a constant
let myConstant = 42
//: ## Types and Type Inference
// All values have a type (like in Java and C/C++).
// While you didn't explicitly specify the type of the variable and constant above ☝️ the type was INFERED by the compiler
// ☝️ Above the compiler infered that the types of `myVariable` and `myConstant` were of type Int
// You can also explicitly delcare a variables type
// Heres an example of the difference between explicit and implicit:
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
//: ## Strings
// You can also convert one type to another type:
let dogsAge = 4
let dogDescription = "Jozi is " + String(dogsAge) + " years old."
// You can also do String interpolation:
let dogDescription2 = "Jozi is \(dogsAge) years old."
//: ## Arrays and Dictionaries
let shoppingList = ["apples", "pears", "milk"]
shoppingList[0]
let namesAndAge = ["Ben": 20, "Rico": 22]
namesAndAge["Rico"]
// How to create an empty array:
let emptyArrayInferred = [String]()
let emptyArrayExplicit: [String] = []
// How to create an empty dictionary:
let emptyDictionaryInferred = [String: Int]()
let emptyDictionaryExplicit: [String: Int] = [:]
//: [👉 continue the tour](@next)
| true
|
25f51b7e642ac8922972889129d10dea5ba2e57d
|
Swift
|
jlorencelim/EagleQuote
|
/EagleQuote/Authentication/Controllers/EQLoginViewController.swift
|
UTF-8
| 2,640
| 2.5625
| 3
|
[] |
no_license
|
//
// EQLoginViewController.swift
// EagleQuote
//
// Created by Lorence Lim on 26/08/2018.
// Copyright © 2018 Lorence Lim. All rights reserved.
//
import UIKit
import SwifterSwift
class EQLoginViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
// MARK: - Actions
@IBAction func onSignInButtonPressed(_ sender: UIButton) {
let email = self.emailTextField.text!
let password = self.passwordTextField.text!
if email == "" {
// check if email field has value
let alert = UIAlertController(title: "Email required", message: "Please enter your email.")
alert.show()
} else if !EQUtils.isValidEmail(email) {
// ckeck if email is valid
let alert = UIAlertController(title: "Email not valid", message: "Please check the email that you entered.")
alert.show()
} else if password == "" {
// check if passwrod field has value
let alert = UIAlertController(title: "Password required", message: "Please enter a password.")
alert.show()
} else {
// show alert
let alert = EQUtils.loadingAlert()
alert.show()
EQAPIAuthentication.login(email: email, password: password) { (response) in
alert.dismiss(animated: true, completion: {
if let error = response!["error"] as? String {
// show error message
let alert = UIAlertController(title: "Sign-in Attempt", message: error)
alert.show()
} else {
// go to dashboard
self.present(R.storyboard.home().instantiateInitialViewController()!, animated:true, completion:nil)
}
})
}
}
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.emailTextField.delegate = self
self.passwordTextField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension EQLoginViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| true
|
7af04afdf7cd0a319ca6ad247c18dcca126864f6
|
Swift
|
chriseidhof/ViaAlpina
|
/ViaAlpina/KMLParser.swift
|
UTF-8
| 3,444
| 3.0625
| 3
|
[] |
no_license
|
//
// KMLParser.swift
// ViaAlpina
//
// Created by Chris Eidhof on 28/06/15.
// Copyright © 2015 objc.io. All rights reserved.
//
import Foundation
import CoreLocation
struct Coordinate {
let location: CLLocation
let altitudeInMeters: Int
}
private func parseCoordinate(s: String) -> Coordinate? {
let parts = s.componentsSeparatedByString(",")
guard parts.count == 3,
let lon = Double(parts[0]),
let lat = Double(parts[1]),
let altitude = Int(parts[2])
else { return nil }
let loc = CLLocation(latitude: lat, longitude: lon)
return Coordinate(location: loc, altitudeInMeters: altitude)
}
private func parseCoordinates(s: String) -> [Coordinate] {
let lines = s.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
return lines.flatMap(parseCoordinate)
}
@objc private class KMLDelegate: NSObject, NSXMLParserDelegate {
var inPlaceMark = false
var inName = false
var inCoordinates = true
var nameString = ""
var coordinates = ""
@objc func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
if elementName == "Placemark" {
inPlaceMark = true
} else if elementName == "name" && inPlaceMark {
inName = true
} else if elementName == "coordinates" {
inCoordinates = true
}
}
@objc func parser(parser: NSXMLParser, foundCharacters string: String) {
if inName {
nameString += string
} else if inCoordinates {
coordinates += string
}
}
@objc func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == "Placemark" {
inPlaceMark = false
} else if elementName == "name" && inName {
inName = false
} else if elementName == "coordinates" {
inCoordinates = false
}
}
}
struct KMLInfo {
let name: String
let coordinates: [Coordinate]
}
func parseKML(filePath: String) -> KMLInfo? {
let url = NSURL(fileURLWithPath: filePath)
if let parser = NSXMLParser(contentsOfURL: url)
{
let delegate = KMLDelegate()
parser.delegate = delegate
parser.parse()
let name = delegate.nameString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
return KMLInfo(name: name, coordinates: parseCoordinates(delegate.coordinates))
}
return nil
}
typealias AltitudeAndLocation = (distance: CLLocationDistance, altitude: Int, location: CLLocation)
typealias AltitudeProfile = [AltitudeAndLocation]
extension KMLInfo {
var altitudeProfile: AltitudeProfile {
let result = coordinates.reduce((coordinates[0], CLLocationDistance(0), AltitudeProfile())) { (intermediateResult, coord) in
let previousCoord = intermediateResult.0
var distances = intermediateResult.2
let distance = coord.location.distanceFromLocation(previousCoord.location)
let totalDistance = intermediateResult.1 + distance
distances.append((distance: totalDistance, altitude: coord.altitudeInMeters, location: coord.location))
return (coord, totalDistance, distances)
}
return result.2
}
}
| true
|
22007d137e36df77bb2f3f352961cb9e7f4a05dd
|
Swift
|
MckennaBrew/MckennaBrewer_AdvancedMobileAppDev
|
/Lab 3/BooksToRead/BooksToRead/BookDataLoader.swift
|
UTF-8
| 1,363
| 3.40625
| 3
|
[] |
no_license
|
//
// BookDataLoader.swift
// BooksToRead
//
// Created by Mckenna Brewer on 2/14/21.
//
import Foundation
class BookDataLoader{
var bookData = [BookData]()
func loadBooks(filename: String){
if let pathURL = Bundle.main.url(forResource: filename, withExtension: "plist"){
//creates a property list decoder object
let plistdecoder = PropertyListDecoder()
do {
let data = try Data(contentsOf: pathURL)
//decodes the property list
bookData = try plistdecoder.decode([BookData].self, from: data)
}
catch {
// handle error
print(error)
}
}
}
// Get Book Data Methods
func getGenres() -> [String]{
var genres = [String]()
for item in bookData{
genres.append(item.genre)
}
return genres
}
func getBooks(index: Int) -> [String]{
return bookData[index].books
}
// Add and Delete Book Methods
func addBook(index:Int, newBook:String, newIndex:Int){
bookData[index].books.insert(newBook, at: newIndex)
}
func deleteBook(index:Int, bookIndex: Int){
bookData[index].books.remove(at: bookIndex)
}
}
| true
|
25ff6de848618f7c79178b65c2d897d046997277
|
Swift
|
handeebrar/Gezginler-app
|
/Gezginler/Modules/BaseViewController.swift
|
UTF-8
| 2,176
| 2.515625
| 3
|
[] |
no_license
|
import UIKit
// bu extension metotları kullanıyor
class BaseViewController: UIViewController {
fileprivate var internalScrollView: UIScrollView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func showMessage(_ message: String?, withTitle title: String?) {
let errorController = UIAlertController(title: title, message: message, preferredStyle: .alert)
errorController.addAction(UIAlertAction(title: "Tamam", style: .default, handler: nil))
present(errorController, animated: true, completion: nil)
}
func showError(_ errorMessage: String?) {
let errorController = UIAlertController(title: "Hata", message: errorMessage, preferredStyle: .alert)
errorController.addAction(UIAlertAction(title: "Tamam", style: .default, handler: nil))
present(errorController, animated: true, completion: nil)
}
//
func setupKeyboardNotifications(with scrollView: UIScrollView?) {
internalScrollView = scrollView
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
guard let info = notification.userInfo,
let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size else { return }
let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height + 15.0, right: 0.0)
internalScrollView?.contentInset = contentInsets
internalScrollView?.scrollIndicatorInsets = contentInsets
}
@objc func keyboardWillBeHidden(notification: NSNotification) {
let contentInsets = UIEdgeInsets.zero
internalScrollView?.contentInset = contentInsets
internalScrollView?.scrollIndicatorInsets = contentInsets
}
}
| true
|
9f3bb852001e10622e5fcd81b89a4fd01ef778ad
|
Swift
|
jasoneliann/StateMachineEssImplementation
|
/StateMachine-Before/StateMachine/Main/Components/ShimmerTextDescription.swift
|
UTF-8
| 665
| 3.328125
| 3
|
[] |
no_license
|
//
// ShimmerTextDescription.swift
// StateMachine
//
// Created by Jason Elian on 07/11/20.
//
import SwiftUI
struct ShimmerTextDescription: View {
let state: ShimmerType
let text: String
var body: some View {
switch state {
case .start:
ShimmerView(size: CGSize(width: 200, height: 50))
case .stop:
Text(text)
.font(.body)
.multilineTextAlignment(.leading)
}
}
}
struct ShimmerTextDescription_Previews: PreviewProvider {
static var previews: some View {
ShimmerTextDescription(state: .stop, text: "Hello")
}
}
| true
|
f539cfba7673a09dd106f5832e060e118934c6b8
|
Swift
|
philhenson/TriggerWork
|
/TriggerWork/Athlete.swift
|
UTF-8
| 637
| 2.65625
| 3
|
[] |
no_license
|
//
// Athlete.swift
// TriggerWork
//
// Created by Phil Henson on 3/17/16.
// Copyright © 2016 Lost Nation R&D. All rights reserved.
//
import UIKit
class Athlete {
var id: String
var name: String
var email: String
var password: String
var shootingDays: [String:String]
convenience init(id: String) {
self.init(id: id, name: "", email: "", password: "")
}
init(id: String, name: String, email: String, password: String) {
self.id = id
self.name = name
self.email = email
self.password = password
self.shootingDays = [String:String]()
}
}
| true
|
1dfd4069b879940d8895fb8e86051be0316f1c63
|
Swift
|
PacktPublishing/Machine-Learning-with-Core-ML
|
/Chapter05/Start/ObjectDetection/ObjectDetection/Extensions/CGPoint+Extension.swift
|
UTF-8
| 852
| 3.40625
| 3
|
[
"MIT"
] |
permissive
|
//
// CGPoint+Extension.swift
// ObjectDetection
//
// Created by Joshua Newnham on 17/05/2018.
// Copyright © 2018 Joshua Newnham. All rights reserved.
//
import UIKit
extension CGPoint{
var length : CGFloat{
get{
return sqrt(self.x * self.x + self.y * self.y)
}
}
var normalised : CGPoint{
get{
return CGPoint(x: self.x/self.length, y: self.y/self.length)
}
}
func distance(other:CGPoint) -> CGFloat{
let dx = (self.x - other.x)
let dy = (self.y - other.y)
return sqrt(dx*dx + dy*dy)
}
func dot(other:CGPoint) -> CGFloat{
return (self.x * other.x) + (self.y * other.y)
}
static func -(left: CGPoint, right: CGPoint) -> CGPoint{
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
}
| true
|
71d131610eb44bc5f7c27d3bfd45be6bc261c0dc
|
Swift
|
remuty/SenshuApp
|
/SenshuApp/View/TaskBoardView.swift
|
UTF-8
| 1,781
| 3.078125
| 3
|
[] |
no_license
|
//
// TaskBoardView.swift
// SenshuApp
//
// Created by remuty on 2020/04/10.
// Copyright © 2020 remuty. All rights reserved.
//
import SwiftUI
struct TaskBoardView: View {
@ObservedObject var user:User
var body: some View {
HStack {
TaskBoard(user: self.user, i: 0, title: "ToDo")
TaskBoard(user: self.user, i: 1,title: "Done")
}.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct TaskBoard: View {
@ObservedObject var user:User
var i:Int
var title:String
var body: some View {
VStack {
VStack(spacing: 0) {
Text(title)
.font(.headline)
.fontWeight(.semibold)
.padding(10.0)
List {
ForEach(0..<self.user.toDo[i].count, id: \.self){j in
TaskCard(user: self.user, data: self.user.toDo[self.i][j])
.padding(.horizontal, 10.0)
.padding(.bottom, 7)
.contentShape(Rectangle())
.onTapGesture {
self.user.moveToDo(i: self.i, j: j)
}
}.onDelete(perform: delete)
}
}.frame(maxWidth: .infinity)
.background(Color.accentColor)
.cornerRadius(10)
}.padding(.vertical, 10.0)
.padding(10.0)
}
private func delete(at indexSet: IndexSet) {
self.user.toDo[i].remove(atOffsets: indexSet)
}
}
struct TaskBoardView_Previews: PreviewProvider {
static var previews: some View {
TaskBoardView(user: User()).previewLayout(.fixed(width: 600, height: 450))
}
}
| true
|
ccc2e48e744a5cceb4395ee23427bcfc07443ecc
|
Swift
|
pj4533/MobileFarmInfo
|
/MobileFarmInfo/FarmsViewController.swift
|
UTF-8
| 1,980
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// FarmsViewController.swift
// MobileFarmInfo
//
// Created by PJ Gray on 10/3/20.
//
import UIKit
class FarmsViewController: UIViewController {
@IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "📱🚜"
}
/*
// 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 FarmsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let vc = storyboard.instantiateViewController(withIdentifier: "FarmViewController") as? FarmViewController {
let datasource = PickleDataSource()
datasource.loadABI(withSuccess: {
vc.datasource = datasource
DispatchQueue.main.async {
self.navigationController?.pushViewController(vc, animated: true)
}
}, failure: nil)
}
}
}
extension FarmsViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
// hardcording pickle for now, making the farm VC generic
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = "Pickle"
return cell
}
}
| true
|
ad0f2f338bd69315fc99dc99582d3d807376503d
|
Swift
|
hackersatcambridge/hac-website
|
/Sources/HaCWebsiteLib/Location.swift
|
UTF-8
| 349
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
struct Location {
let latitude : Double
let longitude : Double
let address : String?
let venue : String?
init(latitude: Double, longitude: Double, address: String? = nil, venue: String? = nil) {
self.latitude = latitude
self.longitude = longitude
self.address = address
self.venue = venue
}
}
| true
|
ddebdca9be371102fc12226b13bac1eeb4859fc4
|
Swift
|
fredlim/canvas
|
/packages/canvas/src-native/canvas-ios/CanvasNative/Source/HowToClear.swift
|
UTF-8
| 373
| 2.6875
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
//
// HowToClear.swift
// CanvasNative
//
// Created by Osei Fortune on 02/09/2020.
//
import Foundation
enum HowToClear {
// Skip clearing the backbuffer.
case Skipped
// Clear the backbuffer.
case JustClear
// Combine webgl.clear() API with the backbuffer clear, so webgl.clear()
// doesn't have to call glClear() again.
case CombinedClear
}
| true
|
57e7f4dd96d5abbc5de92145f4c4b0f6316dccfc
|
Swift
|
alexpezzi/LiquidKit
|
/Tests/LiquidKitTests/LexerTests.swift
|
UTF-8
| 1,290
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// LexerTests.swift
// Liquid
//
// Created by YourtionGuo on 28/06/2017.
//
//
import XCTest
@testable import LiquidKit
class LexerTests: XCTestCase {
func testCreateToken() {
let lexer = Lexer(templateString: "")
let variable = lexer.createToken(string: "{{ a }}")
XCTAssertEqual(variable, .variable(value: "a"))
let tag = lexer.createToken(string: "{% b %}")
XCTAssertEqual(tag, .tag(value: "b"))
}
func testTokenize() {
let lexer = Lexer(templateString: "aab {{ a }} cc{%d%}{{ e}}")
let tokens = lexer.tokenize()
XCTAssertEqual(tokens.count, 5)
XCTAssertEqual(tokens[0], .text(value: "aab "))
XCTAssertEqual(tokens[1], .variable(value: "a"))
XCTAssertEqual(tokens[2], .text(value: " cc"))
XCTAssertEqual(tokens[3], .tag(value: "d"))
XCTAssertEqual(tokens[4], .variable(value: "e"))
let empty = Lexer(templateString: "{{ a").tokenize()
XCTAssertEqual(empty.count, 1)
XCTAssertEqual(empty[0], .text(value: ""))
}
func testTokenizePerformance() {
let lexer = Lexer(templateString: "aab {{ a }} cc{%d%}")
measure {
_ = lexer.tokenize()
}
}
}
| true
|
6b53a7a1dc488c5eedcc00ad66e1e31b5e4b3f79
|
Swift
|
moguonyanko/moglabo
|
/lang/swift/PracticeSwift/PracticeSwift/PracticeSwift/properties.swift
|
UTF-8
| 5,355
| 4
| 4
|
[] |
no_license
|
//
// properties.swift
// PracticeSwift
//
// Properties practices
//
import Foundation
//Lazy Stored Properties
private struct TargetImage {
var imageName: String
}
private class ImageLoader {
//lazyが指定されたプロパティは常にvarで宣言しなければならない。
lazy var target = TargetImage(imageName: "sample.jpg")
var options:[String] = []
}
func displayLazyProperties() {
let loader = ImageLoader()
loader.options.append("force")
loader.options.append("recursive")
print("loader options = \(loader.options.description)")
print("loader target = \(loader.target.imageName)")
}
//Computed Properties
private struct Point {
var x = 0, y = 0, z = 0
}
private struct Size {
var x = 0, y = 0, z = 0
}
private struct Cube {
var origin = Point()
var size = Size()
private func getCenter(origin: Int, size: Int) -> Int {
return origin + (size / 2)
}
private func getOrigin(center: Int, size: Int) -> Int {
return center - (size / 2)
}
var center: Point {
get {
let x = getCenter(origin: origin.x, size: size.x)
let y = getCenter(origin: origin.y, size: size.y)
let z = getCenter(origin: origin.z, size: size.z)
return Point(x: x, y: y, z: z)
}
set {
origin.x = getCenter(origin: newValue.x, size: size.x)
origin.y = getCenter(origin: newValue.y, size: size.y)
origin.z = getCenter(origin: newValue.z, size: size.z)
}
}
//Computed propertyは読み込み専用だとしてもletで宣言できない。
var volume: Int {
return size.x * size.y * size.z
}
}
func accessStructProperties() {
var cube = Cube(origin: Point(x: 0, y: 0, z: 0),
size: Size(x: 10, y: 10, z: 10))
//cubeがletで宣言されているとプロパティが可変でも変更できなくなる。
cube.center = Point(x: 10, y: 15, z: 5)
//読み込み専用プロパティに値を設定しようとするとコンパイルエラーになる。
//cube.volume = 10
print("Cube origin = (\(cube.origin.x), \(cube.origin.y), \(cube.origin.z))")
print("Cubic volume = \(cube.volume)")
}
//Property Observers
private class NumberQuiz {
static let name = "Observer Quiz"
//読み取り専用でもcomputed propertyをletでは宣言できない。
static var version: Double {
return 1.0
}
static var history = [String]()
//classを指定するとオーバーライドできるtype propertyになる。
//オーバーライド可能なtype propertyにはwillSetとdidSetを定義することができない。
class var memo: String {
get {
return history.joined(separator: ",")
}
set {
//historyにstaticが無い,つまりインスタンスなメンバだったらコンパイルエラー
history.append(newValue)
}
}
static var info: String = "" {
willSet {
print("Change info to \(newValue)")
}
didSet {
NumberQuiz.memo = oldValue
print("Changed info from \(oldValue)")
}
}
var rightAnswer = 0
//プロパティに初期値が設定されていない場合,Initializerがないとコンパイルエラーになる。
var answer: Int = 0 {
willSet(newAnswer) {
print("New answer = \(newAnswer)")
}
didSet {
//oldValueはsetterで更新される前の値になっている。
let oldDelta = abs(rightAnswer - oldValue)
let nowDelta = abs(rightAnswer - answer)
print("Old \(oldDelta) to right answer")
print("Now \(nowDelta) to right answer")
}
}
}
func checkActionOfObservers() {
let quiz = NumberQuiz()
NumberQuiz.memo = "foo"
NumberQuiz.memo = "bar"
NumberQuiz.memo = "baz"
print("Quiz name: \(NumberQuiz.name)")
print("Quiz version: \(NumberQuiz.version)")
print("Quiz memo: \(NumberQuiz.memo)")
quiz.rightAnswer = 50
quiz.answer = 10
quiz.answer = 55
quiz.answer = 50
NumberQuiz.info = "Hello"
NumberQuiz.info = "Good morning"
NumberQuiz.info = "さようなら"
print("One more quiz memo: \(NumberQuiz.memo)")
}
//Querying and Setting Type Properties
private struct Player {
//このような設定値をこの手のクラスに持たせることは普通しない。あくまでもサンプル。
static let limitScore = 100
static var currentMaxScoreOfAllPlayers = 0
var score: Int = 0 {
didSet {
if Player.limitScore < score {
score = Player.limitScore
}
if Player.currentMaxScoreOfAllPlayers < score {
Player.currentMaxScoreOfAllPlayers = score
}
}
}
}
func changeTypeProperties() {
var p1 = Player()
var p2 = Player()
p1.score = 10
p2.score = 30
print("Current max score: \(Player.currentMaxScoreOfAllPlayers)")
p1.score = 120
p2.score = 90
print("Current max score: \(Player.currentMaxScoreOfAllPlayers)")
}
| true
|
b8c67b3c08a59426fc5db4537f86616515b7f190
|
Swift
|
danieljstvincent/Instagram-Clone---iOS-APP-
|
/BinaryTreePractice.playground/Contents.swift
|
UTF-8
| 1,125
| 4.09375
| 4
|
[] |
no_license
|
import UIKit
// 10
// / \
// 5 14
// / / \
// 1 11 20
class Node {
let value: Int
var leftChild: Node?
var rightChild: Node?
init(value: Int, leftChild: Node?, rightChild: Node?) {
self.value = value
self.leftChild = leftChild
self.rightChild = rightChild
}
}
//left branch
let oneNode = Node(value: 1, leftChild: nil, rightChild: nil)
let fiveNode = Node(value: 5, leftChild: oneNode, rightChild: nil)
//right branch
let elevenNode = Node(value: 11, leftChild: nil, rightChild: nil)
let twentyNode = Node(value: 20, leftChild: nil, rightChild: nil)
let fourteenNode = Node(value: 14, leftChild: elevenNode, rightChild: twentyNode)
let tenRootNode = Node(value: 10, leftChild: fiveNode , rightChild: fourteenNode)
func search(node: Node?, searchValue: Int) -> Bool {
if node?.value == searchValue {
return true
} else {
// recursion
return search(node: node?.leftChild, searchValue: searchValue)
}
return false
}
search(node: tenRootNode, searchValue: 14)
let Arr = [12,421,32,12,5,2]
| true
|
a214e01c3919e8c6d00060afc36754c05b7b04f0
|
Swift
|
Aoxian/algorithm-workshop-examples
|
/swift/Tests/AlgorithmsTests/Factorial/IFactorialTests.swift
|
UTF-8
| 659
| 2.765625
| 3
|
[] |
no_license
|
//
// IFactorialTests.swift
// AlgorithmsTests
//
// Created by Brian Gerstle on 11/10/19.
//
@testable import Algorithms
import XCTest
class IFactorialTests: XCTestCase {
func testZero() {
XCTAssertEqual(try! 0.ifactorial(), 0)
}
func testOne() {
XCTAssertEqual(try! 1.ifactorial(), 1)
}
func testTwo() {
XCTAssertEqual(try! 2.ifactorial(), 2)
}
func testThree() {
XCTAssertEqual(try! 3.ifactorial(), 6)
}
func testTen() {
XCTAssertEqual(try! 10.ifactorial(), 3628800)
}
func testThrowsOnOverflow() {
XCTAssertThrowsError(try (100 as UInt8).ifactorial())
}
}
| true
|
7fb126be5badc7e2b288ff7c84212b9547f4fe0c
|
Swift
|
pcannon67/swift-chat-bot
|
/ChatBot/Bot.swift
|
UTF-8
| 4,023
| 2.75
| 3
|
[] |
no_license
|
//
// Bot.swift
// ChatBot
//
// Created by Rene Argento on 2/3/16.
// Copyright © 2016 Rene Argento. All rights reserved.
//
import Foundation
class Bot {
func getUpdates() {
let restAPIManager = RestAPIManager.restAPIManagerInstance
let requestURL = "\(Constants.botToken)\(RestAPIManager.getUpdatesUrl)"
let parameters = [String:AnyObject]()
restAPIManager.getRequest(requestURL, parameters: parameters,
completionHandler: { (data, response, error) -> Void in
do {
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
let messageService = MessageService()
let ok = jsonDictionary.valueForKey(RestAPIManager.okKey) as! Bool
if(ok){
let result = jsonDictionary.valueForKey(RestAPIManager.resultKey) as! NSArray
var messageList = messageService.getMessagesFromResponse(result as! [NSDictionary])
messageService.orderMessagesBasedOnId(&messageList)
let lastMessage = messageList.last
if let messageId = lastMessage?.messageId {
if messageService.checkIfANewMessageArrived(messageId) {
//Store the last message ID read
UserDefaultsUtil.writeInt(messageId, key: UserDefaultsUtil.lastMessageIdReadKey)
if let lastMessageValue = lastMessage {
self.handleMessage(lastMessageValue)
}
} else {
//No new messages
}
}
} else {
print("An exception occurred when getting the messages")
}
} catch {
print("An exception occurred when parsing the get messages response")
}
})
}
private func handleMessage(message: Message) {
var response = BotResponses.defaultResponse
if let text = message.text {
if text.lowercaseString.rangeOfString(Constants.bestText) != nil
&& text.lowercaseString.rangeOfString(Constants.companyText) != nil {
response = BotResponses.companyResponse
} else if text.lowercaseString.rangeOfString(Constants.fkBestText) != nil
&& text.lowercaseString.rangeOfString(Constants.areaText) != nil {
response = BotResponses.areaResponse
}
}
sendMessage(response)
}
private func sendMessage(response: String) {
let restAPIManager = RestAPIManager.restAPIManagerInstance
let restAPIRequestService = RestAPIRequestService()
let requestURL = "\(Constants.botToken)\(RestAPIManager.sendMessageUrl)"
var requestParameters = [String:AnyObject]()
requestParameters[Message.chatIdKey] = Constants.chatId
requestParameters[Message.textKey] = response
restAPIManager.postRequest(requestURL, parameters: requestParameters) { (data, response, error) -> Void in
if error == nil {
let statusCode = restAPIRequestService.getStatusCode(response!)
if statusCode == ResponseEnum.OKResponse.rawValue {
print("ChatBot just answered the message!")
}
} else {
print("An exception occurred when sending the message")
}
}
}
}
| true
|
35870ccd18e8b98267e68bec4e7cb5a41ef42c8a
|
Swift
|
akshdeepkaur2/Chippy-assignment1
|
/Chippy/Extensions.swift
|
UTF-8
| 306
| 2.8125
| 3
|
[] |
no_license
|
//
// Extensions.swift
// Chippy Game
//
// Created by TED Komputer on 10/7/19.
// Copyright © 2019 Lars Bergqvist. All rights reserved.
//
import Foundation
extension Int {
var degreesToRadians: Double { return Double(self) * .pi / 180 }
var radiansToDegrees: Double { return Double(self) * 180 / .pi }
}
| true
|
046affb197bf123e792330e9a16e23ba6ddc85be
|
Swift
|
leroncier/BoutonBit
|
/BoutonBit/ViewController.swift
|
UTF-8
| 1,968
| 2.578125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// BoutonBit
//
// Created by Charles Roncier on 11/01/2016.
// Copyright © 2016 Charles Roncier. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var makeItBlue: UIButton!
@IBOutlet weak var fireTheLasers: UIButton!
@IBOutlet weak var imageOnlyButton: UIButton!
@IBOutlet weak var alternativeImageButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func makeItBluePressed(sender: UIButton) {
view.backgroundColor = UIColor.blueColor()
makeItBlue.setTitle("C'est bleu !", forState: UIControlState.Normal)
makeItBlue.backgroundColor = UIColor.grayColor()
makeItBlue.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
}
@IBAction func fireTheLasersPressed(sender: UIButton) {
fireTheLasers.enabled = false
fireTheLasers.setTitle("Run to the escape pod !", forState: UIControlState.Normal)
fireTheLasers.titleLabel!.adjustsFontSizeToFitWidth = true
fireTheLasers.backgroundColor = UIColor.orangeColor()
}
@IBAction func imageOnlyButtonTapped(sender: AnyObject) {
imageOnlyButton.setImage(UIImage(named: "nextButtonAlternative"), forState: UIControlState.Normal)
}
@IBAction func alternativeImageButtonTapped(sender: UIButton) {
alternativeImageButton.setImage(nil, forState: UIControlState.Normal)
alternativeImageButton.setBackgroundImage(UIImage(named: "greenOval"), forState: UIControlState.Normal)
alternativeImageButton.setTitle("Ok", forState: UIControlState.Normal)
}
}
| true
|
e0770b2da26897d12d14ce1bc411e58ebbd91d6d
|
Swift
|
Banck/Weather-VIPER-example
|
/Weather VIPER Example/Extensions/Extension+UIVIewController.swift
|
UTF-8
| 1,707
| 2.71875
| 3
|
[] |
no_license
|
//
// Extension+UIVIewController.swift
// Weather VIPER Example
//
// Created by Egor Sakhabaev on 15.07.2018.
// Copyright © 2018 Egor Sakhabaev. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
func showAlert(title: String? = nil, message: String?) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let close = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(close)
present(alert, animated: true, completion: nil)
}
func showAlert(title: String? = nil, message: String?, handler: @escaping ((UIAlertAction) -> Void)) {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let close = UIAlertAction(title: "OK", style: .cancel, handler: handler)
alert.addAction(close)
present(alert, animated: true, completion: nil)
}
func showAlert(title: String? = nil, message: String?, cancel: String? = nil, textField: Bool = false, completion: ((UIAlertController, UIAlertAction) -> Void)? = nil) {
let alert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let cancelTitle: String = cancel ?? "Done"
let action: UIAlertAction = UIAlertAction(title: cancelTitle, style: .cancel, handler: { (alertAction) in
if completion != nil {
completion!(alert, alertAction)
}
})
alert.addAction(action)
if textField {
alert.addTextField(configurationHandler: nil)
}
present(alert, animated: true, completion: nil)
}
}
| true
|
ccc7a716ab3affc10fb9fca4e913c679e5bb8e55
|
Swift
|
anggasenna/DotaHeroes
|
/DotaHeroes/Modules/HeroList/HeroModel.swift
|
UTF-8
| 726
| 2.6875
| 3
|
[] |
no_license
|
//
// HeroModel.swift
// DotaHeroes
//
// Created by Angga on 03/10/20.
// Copyright © 2020 Angga. All rights reserved.
//
import Foundation
import CoreData
struct Hero: Codable {
let id: Int?
let localized_name: String?
let primary_attr: String?
let attack_type: String?
let roles: [HeroRole]?
let img: String?
let base_health: Int?
let base_mana: Int?
let base_attack_max: Int?
let move_speed: Int?
enum CodingKeys: CodingKey {
case id
case localized_name
case primary_attr
case attack_type
case roles
case img
case base_health
case base_mana
case base_attack_max
case move_speed
}
}
| true
|
223f51122fc70f46e70f1ddae453728a4c379515
|
Swift
|
LiveUI/Hagrid
|
/Classes/View controllers/GridViewController.swift
|
UTF-8
| 904
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// GridViewController.swift
// Hagrid
//
// Created by Ondrej Rafaj on 29/05/2018.
// Copyright © 2018 LiveUI. All rights reserved.
//
#if os(iOS) || os(tvOS)
@_exported import Foundation
@_exported import UIKit
/// Grid view view controller
open class GridViewController: UIViewController {
/**
Grid view
- important: Replaces default `view`
*/
public internal(set) var gridView: GridView!
/// Original view (removed)
@available(*, unavailable, message: "This property is unavailable", renamed: "gridView")
open override var view: ViewAlias! {
get { return super.view }
set { super.view = newValue }
}
// MARK: View lifecycle
@available(*, unavailable, message: "This method is unavailable")
open override func loadView() {
gridView = GridView()
super.view = gridView
}
}
#endif
| true
|
767b7bf7602eb93e69b84d80ade198da082d954c
|
Swift
|
sahinyyurt/OMDBClient
|
/OMDBClient/Views/MovieDetailView.swift
|
UTF-8
| 3,660
| 2.96875
| 3
|
[] |
no_license
|
//
// MovieDetailView.swift
// OMDBClient
//
// Created by Sahin Yesilyurt on 16.06.2020.
// Copyright © 2020 sahiny. All rights reserved.
//
import SwiftUI
import SDWebImageSwiftUI
struct MovieDetailView: View {
let id:String
let title:String
@State private var isLoading = true;
@State private var movieDetail:MovieDetail?;
var body: some View {
OmdbApiService.getMovie(self.id){ movie in
if let movieDetail = movie {
self.movieDetail = movieDetail
} else {
print("Movie Not Found")
}
self.isLoading = false;
}
return ZStack {
ActivityIndicator(isAnimating: isLoading).zIndex(1)
VStack {
ScrollView(.vertical, showsIndicators: true) {
if self.movieDetail != nil {
PosterView(image: self.movieDetail!.poster)
TitleView(title: self.movieDetail!.title)
FilmInfoView(duration: self.movieDetail!.runtime, genre: self.movieDetail!.genre, release: self.movieDetail!.released)
RatingsView(rating: self.movieDetail!.imdbRating)
PlotView(plot: self.movieDetail!.plot)
} else {
}
}
}.onAppear {
FirebaseService.sendMovieAnalytics(id:self.id, name:self.title)
}
}
.navigationBarTitle(Text(title))
}
}
struct MovieDetailView_Previews: PreviewProvider {
static var previews: some View {
MovieDetailView(id:"1",title:"Movie Detail")
}
}
struct PosterView: View {
let image:String
var body: some View {
WebImage(url: URL(string: image))
.renderingMode(.original)
.resizable()
.placeholder(Image(systemName: "questionmark.video.fill"))
.aspectRatio(contentMode: .fit)
.cornerRadius(12)
.padding()
}
}
struct TitleView: View {
let title:String
var body: some View {
HStack {
Text(title)
.fontWeight(.heavy)
.padding(.leading)
Spacer()
}
}
}
struct FilmInfoView: View {
let duration:String
let genre:String
let release:String
var body: some View {
HStack {
Text("\(duration) | \(genre) | \(release)")
.foregroundColor(.secondary)
.padding(.leading)
Spacer()
}
}
}
struct RatingsView: View {
let rating:String
var body: some View {
let ratingNumber = Float(rating) ?? 0
let unfillStar = 10 - Int(ratingNumber)
return HStack {
ForEach(0 ..< Int(ratingNumber)) { item in
Image(systemName: "star.fill")
}
if(ratingNumber.truncatingRemainder(dividingBy: 1) > 0.5) {
Image(systemName: "star.lefthalf.fill")
}
ForEach(0 ..< unfillStar) { item in
Image(systemName: "star")
}
Text("(\(rating))")
.bold()
.font(.system(size: 14))
}
.foregroundColor(.yellow)
}
}
struct PlotView: View {
let plot:String
var body: some View {
VStack {
HStack {
Text("Storyline")
.fontWeight(.bold)
Spacer()
}
.padding(.bottom)
Text(plot)
}
.padding()
}
}
| true
|
cc0341fcc5ac0df101cda07678ec57df1c499510
|
Swift
|
beretis/SwipeToDeleteCollectionView
|
/Example Project/CollectionViewSwipeToDelete/Model.swift
|
UTF-8
| 696
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// Model.swift
// CollectionViewSwipeToDelete
//
// Created by Jozef Matus on 09/05/2017.
// Copyright © 2017 o2. All rights reserved.
//
import Foundation
import RxDataSources
struct ItemModel {
var title: String
var image: String = "BMW-2-series"
var subtitle: String
init() {
self.title = randomString(length: 10)
self.subtitle = randomString(length: 13)
}
}
struct SectionOfItemModels {
var header: String
var items: [ItemCellVM]
}
extension SectionOfItemModels: SectionModelType {
typealias Item = ItemCellVM
init(original: SectionOfItemModels, items: [Item]) {
self = original
self.items = items
}
}
| true
|
83939cfbde4e8f22c43369e127c76311cbbba671
|
Swift
|
adya/TSKit
|
/Sources/TSKit.Core/Extensions/Collections/Sequence+Mapping.swift
|
UTF-8
| 3,668
| 3.4375
| 3
|
[] |
no_license
|
// - Since: 01/20/2018
// - Author: Arkadii Hlushchevskyi
// - Copyright: © 2022. Arkadii Hlushchevskyi.
// - Seealso: https://github.com/adya/TSKit.Core/blob/master/LICENSE.md
public extension Sequence {
/// Maps `Sequence` to a `Dictionary` using `key` and `value` closures to build resulting `dictionary`.
///
/// This method is mostly obsoleted by `map(key:value:)` alternative based on `KeyPath`.
/// The only meaningful usage of closure-based method is when there is some logic for `key` or `value`
/// that might throw an `Error` for elements that should be ignored.
/// - Parameter key: A closure that provides a property of `Sequence`'s element to be used as a dictioanry key.
/// - Parameter value: A closure that provides a property of `Sequence`'s element to be used as a dictioanry value.
/// - Important: Elements for which either `key` or `value` throws an `Error` will be ignored and not included in the resulting dictionary.
/// - Note: `key` must be unique in order to avoid collisions.
/// In cases when `key` may be not unique consider using `group(by:)` method to preserve all elements.
/// - Returns: `Dictionary` containing key-value pairs.
/// - Seealso: `compactMap(key:value:)`.
func map<KeyType, ValueType>(key: (Iterator.Element) throws -> KeyType,
value: (Iterator.Element) throws -> ValueType) -> [KeyType : ValueType] where KeyType : Hashable {
reduce(into: [:]) {
guard let key = try? key($1),
let value = try? value($1) else { return }
$0[key] = value
}
}
/// Maps `Sequence` to a `Dictionary` using `key` and `value` closures to build resulting `dictionary`.
///
/// - Parameter key: A closure that provides a property of `Sequence`'s element to be used as a dictionary key.
/// - Parameter value: A closure that provides a property of `Sequence`'s element to be used as a dictionary value.
/// - Important: Elements for which either `key` or value evaluates to `nil` or throws an `Error` will be ignored and not included in the resulting dictionary.
/// - Note: `key` must be unique in order to avoid collisions.
/// In cases when `key` may be not unique consider using `group(by:)` method to preserve all elements.
/// - Returns: `Dictionary` containing key-value pairs.
/// - Seealso: `map(key:value:)`.
func compactMap<KeyType, ValueType>(key: (Iterator.Element) throws -> KeyType?,
value: (Iterator.Element) throws -> ValueType?) -> [KeyType: ValueType] where KeyType : Hashable {
reduce(into: [:]) {
guard let key = try? key($1),
let value = try? value($1) else { return }
$0[key] = value
}
}
/// Maps `Sequence` to a `Dictionary` using `key` and `value` *KeyPath*s to build resulting `dictionary`.
///
/// - Note: `key` must be unique in order to avoid collisions.
/// In cases when `key` may be not unique consider using `group(by:)` method to preserve all elements.
/// - Note: You can use `\.self` notation of the *KeyPath* to reference the element itself.
/// - Returns: `Dictionary` containing key-value pairs.
/// - Seealso: `compactMap(key:value:)`.
func map<KeyType, ValueType>(key: KeyPath<Element, KeyType>,
value: KeyPath<Element, ValueType>) -> [KeyType : ValueType] where KeyType : Hashable {
reduce(into: [:]) {
let key = $1[keyPath: key]
let value = $1[keyPath: value]
$0[key] = value
}
}
}
| true
|
512a1134b16ac472955f33755666718d3f140fca
|
Swift
|
sofiadechiara/EcoTips
|
/EcoTips/QuestionOneViewController.swift
|
UTF-8
| 1,546
| 2.640625
| 3
|
[] |
no_license
|
//
// QuestionOneViewController.swift
// EcoTips
//
// Created by Sofia De Chiara on 7/29/20.
// Copyright © 2020 Sofia De Chiara. All rights reserved.
//
import UIKit
class QuestionOneViewController: UIViewController {
var choicesArray = [String]()
@IBOutlet weak var questionOneLabel: UITextView!
@IBOutlet weak var instructionLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func veganButton(_ sender: UIButton) {
choicesArray.append("Make sure other products that you use are also vegan")
}
@IBAction func vegetarianButton(_ sender: UIButton) {
choicesArray.append("Avoid plastic and styrofoam packaging")
}
@IBAction func pescetarianButton(_ sender: UIButton) {
choicesArray.append("Reduce consumption of larger fish")
}
@IBAction func meatButton(_ sender: UIButton) {
choicesArray.append("Eat other proteins such as beans, nuts, dairy instead")
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do alittle preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vs = segue.destination as? QuestionTwoViewController
vs?.choicesArray = choicesArray
}
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
| true
|
002641b99aeeff7a37c2361257ce1f0bb79d12f5
|
Swift
|
musicandtech00/OpenWeatherAppService
|
/OpenWeatherAppService/UserDefaults.swift
|
UTF-8
| 914
| 3.203125
| 3
|
[] |
no_license
|
//
// UserDefaults.swift
// OpenWeatherAppService
//
// Created by Curtis Wiseman on 12/9/20.
//
import Foundation
struct UserDefaultsKeys {
static let temperatureKey = "temperatureKey"
static let cityKey = "cityKey"
}
extension UserDefaults {
static func temperatureNotation() -> Double? {
let storedValue = UserDefaults.standard.double(forKey: UserDefaultsKeys.temperatureKey)
guard !storedValue.isZero else { return nil }
return storedValue
}
static func setTemperatureNotation(temperature: Double) {
UserDefaults.standard.set(temperature, forKey: UserDefaultsKeys.temperatureKey)
}
static func cityNotation() -> String? {
return UserDefaults.standard.string(forKey: UserDefaultsKeys.cityKey)
}
static func setCityNotation(city: String) {
UserDefaults.standard.setValue(city, forKey: UserDefaultsKeys.cityKey)
}
}
| true
|
ea9cd235e3bfbdd2be502c9235ed5d38e1f20f30
|
Swift
|
Hitendra95/BasisTest
|
/BasisTest/ViewControllers/CustomView.swift
|
UTF-8
| 2,361
| 2.78125
| 3
|
[] |
no_license
|
//
// CustomView.swift
// BasisTest
//
// Created by Hitendra Dubey on 27/06/20.
// Copyright © 2020 Hitendra Dubey. All rights reserved.
//
import Foundation
import UIKit
class CustomCardView : UIView{
let CardFrameView: UIView = {
let card = UIView()
card.backgroundColor = UIColor(red: 226/255, green: 243/255, blue: 243/255, alpha: 1)
card.layer.shadowColor = UIColor.black.cgColor
card.layer.shadowOpacity = 1
card.layer.shadowOffset = .zero
card.layer.shadowRadius = 10
card.layer.borderWidth = 0.8
card.layer.cornerRadius = 6
card.clipsToBounds = true
card.layer.masksToBounds = true
return card
}()
let Text : UILabel = {
let lb = UILabel()
lb.text = ""
lb.textColor = .black
lb.textAlignment = .justified
lb.font = UIFont(name: "Helvetica", size: 15)//UIFont.boldSystemFont(ofSize: 12)
lb.numberOfLines = 0
lb.backgroundColor = .clear
return lb
}()
let Tracklabel : UILabel = {
let lb = UILabel()
lb.text = ""
lb.textColor = .black
lb.font = UIFont(name: "Helvetica-Bold", size: 15)
lb.backgroundColor = .clear
return lb
}()
//MARK: Add views
override init(frame: CGRect) {
super.init(frame: frame)
CardFrameView.addSubview(Tracklabel)
CardFrameView.addSubview(Text)
addSubview(CardFrameView)
addConstraints()
}
//MARK: Add constraints
fileprivate func addConstraints() {
CardFrameView.setAnchors(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, height: 0, width: 0)
Tracklabel.setAnchors(top: CardFrameView.topAnchor, left: nil, bottom: nil, right: CardFrameView.rightAnchor, paddingTop: 20, paddingLeft: 0, paddingBottom: 0, paddingRight: 20, height: 22, width: 0)
Text.setAnchors(top: CardFrameView.topAnchor, left: CardFrameView.leftAnchor, bottom: CardFrameView.bottomAnchor, right: CardFrameView.rightAnchor, paddingTop: 50, paddingLeft: 20, paddingBottom: 50, paddingRight: 20, height: 0, width: 0)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
7c305301d529543ba30767cae02c5cbd10cfe07d
|
Swift
|
haitaowu/ST
|
/ST/GRDB/GRDB/Core/RowAdapter.swift
|
UTF-8
| 12,125
| 3.3125
| 3
|
[
"MIT"
] |
permissive
|
#if !USING_BUILTIN_SQLITE
#if os(OSX)
import SQLiteMacOSX
#elseif os(iOS)
#if (arch(i386) || arch(x86_64))
import SQLiteiPhoneSimulator
#else
import SQLiteiPhoneOS
#endif
#elseif os(watchOS)
#if (arch(i386) || arch(x86_64))
import SQLiteWatchSimulator
#else
import SQLiteWatchOS
#endif
#endif
#endif
/// ConcreteColumnMapping is a type that supports the RowAdapter protocol.
public struct ConcreteColumnMapping {
let columns: [(Int, String)] // [(baseRowIndex, adaptedColumn), ...]
let lowercaseColumnIndexes: [String: Int] // [adaptedColumn: adaptedRowIndex]
/// Creates an ConcreteColumnMapping from an array of (index, name)
/// pairs. In each pair:
///
/// - index is the index of a column in an original row
/// - name is the name of the column in an adapted row
///
/// For example, the following ConcreteColumnMapping defines two
/// columns, "foo" and "bar", that load from the original columns at
/// indexes 1 and 2:
///
/// ConcreteColumnMapping([(1, "foo"), (2, "bar")])
///
/// Use it in your custom RowAdapter type:
///
/// struct FooBarAdapter : RowAdapter {
/// func concreteRowAdapter(with statement: SelectStatement) throws -> ConcreteRowAdapter {
/// return ConcreteColumnMapping([(1, "foo"), (2, "bar")])
/// }
/// }
///
/// // <Row foo:"foo" bar: "bar">
/// Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
public init(columns: [(Int, String)]) {
self.columns = columns
self.lowercaseColumnIndexes = Dictionary(keyValueSequence: columns.enumerated().map { ($1.1.lowercased(), $0) }.reversed())
}
var count: Int {
return columns.count
}
func baseColumIndex(adaptedIndex index: Int) -> Int {
return columns[index].0
}
func columnName(adaptedIndex index: Int) -> String {
return columns[index].1
}
func adaptedIndexOfColumn(named name: String) -> Int? {
if let index = lowercaseColumnIndexes[name] {
return index
}
return lowercaseColumnIndexes[name.lowercased()]
}
}
/// ConcreteColumnMapping adopts ConcreteRowAdapter
extension ConcreteColumnMapping : ConcreteRowAdapter {
/// Part of the ConcreteRowAdapter protocol; returns self.
public var concreteColumnMapping: ConcreteColumnMapping {
return self
}
/// Part of the ConcreteRowAdapter protocol; returns the empty dictionary.
public var scopes: [String: ConcreteRowAdapter] {
return [:]
}
}
/// ConcreteRowAdapter is a protocol that supports the RowAdapter protocol.
///
/// GRBD ships with a ready-made type that adopts this protocol:
/// ConcreteColumnMapping.
///
/// It is unlikely that you need to write your custom type that adopts
/// this protocol.
public protocol ConcreteRowAdapter {
/// A ConcreteColumnMapping that defines how to map a column name to a
/// column in an original row.
var concreteColumnMapping: ConcreteColumnMapping { get }
/// A dictionary of scopes
var scopes: [String: ConcreteRowAdapter] { get }
}
/// RowAdapter is a protocol that helps two incompatible row interfaces working
/// together.
///
/// GRDB ships with three concrete types that adopt the RowAdapter protocol:
///
/// - ColumnMapping: renames row columns
/// - SuffixRowAdapter: hides the first columns of a row
/// - ScopeAdapter: groups several adapters together to define named scopes
///
/// If the built-in adapters don't fit your needs, you can implement your own
/// type that adopts RowAdapter.
///
/// To use a row adapter, provide it to any method that fetches:
///
/// let adapter = SuffixRowAdapter(fromIndex: 2)
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
///
/// // <Row baz:3>
/// Row.fetchOne(db, sql, adapter: adapter)
public protocol RowAdapter {
/// You never call this method directly. It is called for you whenever an
/// adapter has to be applied.
///
/// The result is a value that adopts ConcreteRowAdapter, such as
/// ConcreteColumnMapping.
///
/// For example:
///
/// // An adapter that turns any row to a row that contains a single
/// // column named "foo" whose value is the leftmost value of the
/// // original row.
/// struct FirstColumnAdapter : RowAdapter {
/// func concreteRowAdapter(with statement: SelectStatement) throws -> ConcreteRowAdapter {
/// return ConcreteColumnMapping(columns: [(0, "foo")])
/// }
/// }
///
/// // <Row foo:1>
/// Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
func concreteRowAdapter(with statement: SelectStatement) throws -> ConcreteRowAdapter
}
extension RowAdapter {
/// Returns an adapter based on self, with added scopes.
///
/// If self already defines scopes, the added scopes replace
/// eventual existing scopes with the same name.
///
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter {
return ScopeAdapter(mainAdapter: self, scopes: scopes)
}
}
/// ColumnMapping is a row adapter that maps column names.
///
/// let adapter = ColumnMapping(["foo": "bar"])
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
///
/// // <Row foo:"bar">
/// Row.fetchOne(db, sql, adapter: adapter)
public struct ColumnMapping : RowAdapter {
/// The column names mapping, from adapted names to original names.
let mapping: [String: String]
/// Creates a ColumnMapping with a dictionary that maps adapted column names
/// to original column names.
public init(_ mapping: [String: String]) {
self.mapping = mapping
}
/// Part of the RowAdapter protocol
public func concreteRowAdapter(with statement: SelectStatement) throws -> ConcreteRowAdapter {
let columns = try mapping
.map { (mappedColumn, baseColumn) -> (Int, String) in
guard let index = statement.index(ofColumn: baseColumn) else {
throw DatabaseError(code: SQLITE_MISUSE, message: "Mapping references missing column \(baseColumn). Valid column names are: \(statement.columnNames.joined(separator: ", ")).")
}
return (index, mappedColumn)
}
.sorted { $0.0 < $1.0 }
return ConcreteColumnMapping(columns: columns)
}
}
/// SuffixRowAdapter is a row adapter that hides the first columns in a row.
///
/// let adapter = SuffixRowAdapter(fromIndex: 2)
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
///
/// // <Row baz:3>
/// Row.fetchOne(db, sql, adapter: adapter)
public struct SuffixRowAdapter : RowAdapter {
/// The suffix index
let index: Int
/// Creates a SuffixRowAdapter that hides all columns before the
/// provided index.
///
/// If index is 0, the adapted row is identical to the original row.
public init(fromIndex index: Int) {
GRDBPrecondition(index >= 0, "Negative column index is out of range")
self.index = index
}
/// Part of the RowAdapter protocol
public func concreteRowAdapter(with statement: SelectStatement) throws -> ConcreteRowAdapter {
GRDBPrecondition(index <= statement.columnCount, "Column index is out of range")
return ConcreteColumnMapping(columns: statement.columnNames.suffix(from: index).enumerated().map { ($0 + index, $1) })
}
}
/// ScopeAdapter is a row adapter that lets you define scopes on rows.
///
/// // Two adapters
/// let fooAdapter = ColumnMapping(["value": "foo"])
/// let barAdapter = ColumnMapping(["value": "bar"])
///
/// // Define scopes
/// let adapter = ScopeAdapter([
/// "foo": fooAdapter,
/// "bar": barAdapter])
///
/// // Fetch
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
/// let row = Row.fetchOne(db, sql, adapter: adapter)!
///
/// // Scoped rows:
/// if let fooRow = row.scoped(on: "foo") {
/// fooRow.value(named: "value") // "foo"
/// }
/// if let barRow = row.scopeed(on: "bar") {
/// barRow.value(named: "value") // "bar"
/// }
public struct ScopeAdapter : RowAdapter {
/// The main adapter
let mainAdapter: RowAdapter
/// The scope adapters
let scopes: [String: RowAdapter]
/// Creates a scoped adapter.
///
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
public init(_ scopes: [String: RowAdapter]) {
self.mainAdapter = SuffixRowAdapter(fromIndex: 0) // Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
self.scopes = scopes
}
init(mainAdapter: RowAdapter, scopes: [String: RowAdapter]) {
self.mainAdapter = mainAdapter
self.scopes = scopes
}
/// Part of the RowAdapter protocol
public func concreteRowAdapter(with statement: SelectStatement) throws -> ConcreteRowAdapter {
let mainConcreteAdapter = try mainAdapter.concreteRowAdapter(with: statement)
var concreteAdapterScopes = mainConcreteAdapter.scopes
for (name, adapter) in scopes {
try concreteAdapterScopes[name] = adapter.concreteRowAdapter(with: statement)
}
return ConcreteScopeAdapter(
concreteColumnMapping: mainConcreteAdapter.concreteColumnMapping,
scopes: concreteAdapterScopes)
}
}
/// The concrete row adapter for ScopeAdapter
struct ConcreteScopeAdapter : ConcreteRowAdapter {
let concreteColumnMapping: ConcreteColumnMapping
let scopes: [String: ConcreteRowAdapter]
}
extension Row {
/// Creates a row from a base row and a statement adapter
convenience init(baseRow: Row, concreteRowAdapter: ConcreteRowAdapter) {
self.init(impl: AdapterRowImpl(baseRow: baseRow, concreteRowAdapter: concreteRowAdapter))
}
/// Returns self if adapter is nil
func adaptedRow(adapter: RowAdapter?, statement: SelectStatement) throws -> Row {
guard let adapter = adapter else {
return self
}
return try Row(baseRow: self, concreteRowAdapter: adapter.concreteRowAdapter(with: statement))
}
}
struct AdapterRowImpl : RowImpl {
let baseRow: Row
let concreteRowAdapter: ConcreteRowAdapter
let concreteColumnMapping: ConcreteColumnMapping
init(baseRow: Row, concreteRowAdapter: ConcreteRowAdapter) {
self.baseRow = baseRow
self.concreteRowAdapter = concreteRowAdapter
self.concreteColumnMapping = concreteRowAdapter.concreteColumnMapping
}
var count: Int {
return concreteColumnMapping.count
}
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
return baseRow.value(atIndex: concreteColumnMapping.baseColumIndex(adaptedIndex: index))
}
func dataNoCopy(atUncheckedIndex index:Int) -> Data? {
return baseRow.dataNoCopy(atIndex: concreteColumnMapping.baseColumIndex(adaptedIndex: index))
}
func columnName(atUncheckedIndex index: Int) -> String {
return concreteColumnMapping.columnName(adaptedIndex: index)
}
func index(ofColumn name: String) -> Int? {
return concreteColumnMapping.adaptedIndexOfColumn(named: name)
}
func scoped(on name: String) -> Row? {
guard let concreteRowAdapter = concreteRowAdapter.scopes[name] else {
return nil
}
return Row(baseRow: baseRow, concreteRowAdapter: concreteRowAdapter)
}
var scopeNames: Set<String> {
return Set(concreteRowAdapter.scopes.keys)
}
func copy(_ row: Row) -> Row {
return Row(baseRow: baseRow.copy(), concreteRowAdapter: concreteRowAdapter)
}
}
| true
|
af4bf36a0f30c6ea2308a6fbcb841a64778f7f5d
|
Swift
|
JeanVinge/ifood-mobile-test
|
/TwitterSentiment/Scenes/Sentiment/View/SentimentView.swift
|
UTF-8
| 2,544
| 2.5625
| 3
|
[] |
no_license
|
//
// SentimentView.swift
// TwitterSentiment
//
// Created by Jean Vinge on 26/12/18.
// Copyright © 2018 Jean Vinge. All rights reserved.
//
import UIKit
import Utility
import Domain
import Resources
class SentimentView: View {
// MARK: Var
lazy var indicator = UIActivityIndicatorView(style: .gray)
lazy var container = View(with: Customization().backgroundColor(.clear))
lazy var background = UIVisualEffectView(backgroundColor: .white, alpha: 0.9)
lazy var emojiLabel = Label(with: Customization().font(.systemFont(ofSize: 70)).numberOfLines(0).alignment(.center))
lazy var titleLabel = Label(with: Customization().titleColor(.black).font(.systemFont(ofSize: 12)).numberOfLines(0).alignment(.center))
lazy var closeButton = Button(with: Customization().image(Asset.iconCloseX.image))
// MARK: Init
func configure(with output: SentimentOutput) {
self.animate(output)
}
override func initSubviews() {
self.addSubview(background)
self.addSubview(container)
container.addSubview(emojiLabel)
container.addSubview(titleLabel)
self.addSubview(closeButton)
container.addSubview(indicator)
self.indicator.hidesWhenStopped = true
}
override func initConstraints() {
self.container.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.left.right.equalToSuperview().inset(40)
}
self.closeButton.snp.makeConstraints { (make) in
make.top.left.equalToSuperview().inset(20)
make.height.width.equalTo(50)
}
self.emojiLabel.snp.makeConstraints { (make) in
make.top.left.right.equalToSuperview()
}
self.titleLabel.snp.makeConstraints { (make) in
make.top.equalTo(emojiLabel.snp.bottom).offset(10)
make.left.right.bottom.equalToSuperview()
}
self.indicator.snp.makeConstraints { (make) in
make.top.left.right.bottom.equalToSuperview()
}
self.background.snp.makeConstraints { (make) in
make.top.left.right.bottom.equalToSuperview()
}
}
// MARK: Animation
func animate(_ output: SentimentOutput) {
UIView.animate(withDuration: 0.2) { [weak self] in
guard let self = self else { return }
self.background.backgroundColor = output.color
self.emojiLabel.text = output.emoji
self.titleLabel.text = output.text
}
}
}
| true
|
defcd8e77d4e5b977a4bf5b284d1af019fed818b
|
Swift
|
ValeFCF/adventOfCode2020
|
/day08.playground/Contents.swift
|
UTF-8
| 2,989
| 3.296875
| 3
|
[] |
no_license
|
import UIKit
let input = InputHelper.input
let miniInput = """
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6
"""
typealias TupleData = (stopped: Bool, acc: Int)
func knowTuple(instructions: [String]) -> TupleData {
var accumulator = 0
var stopProgram = false
var positionToRead = 0
var savedPositions: [Int] = []
while !stopProgram && positionToRead < instructions.count {
let instruction = instructions[positionToRead]
let words = instruction.split(separator: " ")
let operation = words[0]
let argument = Int(words[1])
switch operation {
case "acc":
if let argument = argument {
accumulator += argument
}
positionToRead += 1
case "jmp":
if let argument = argument {
positionToRead += argument
}
case "nop":
positionToRead += 1
default:
stopProgram = true
}
if savedPositions.contains(positionToRead) {
stopProgram = true
} else {
savedPositions.append(positionToRead)
}
}
return (stopProgram, accumulator)
}
func firstPart() {
let instructions = input.components(separatedBy: .newlines)
let acc = knowTuple(instructions: instructions).acc
print("first part \(acc)")
}
firstPart()
func getIndexArray(instructions: [String]) -> [Int] {
var JMPorNOPIndex: [Int] = []
for (index, element) in instructions.enumerated() {
if element.contains("jmp") || element.contains("nop") {
JMPorNOPIndex.append(index)
}
}
return JMPorNOPIndex
}
func changeInstructions(_ instructions: [String], position: Int) -> [String] {
var instructions = instructions
if instructions[position].contains("jmp") {
instructions[position] = instructions[position].replacingOccurrences(of: "jmp", with: "nop")
} else {
instructions[position] = instructions[position].replacingOccurrences(of: "nop", with: "jmp")
}
return instructions
}
func fixInstructionsStep(_ instructions: [String], JMPorNOPIndex: [Int]) -> Int {
var accumulator = 0
var counterWhile = 0
while counterWhile < JMPorNOPIndex.count {
let instructionsModified = changeInstructions(instructions,
position: JMPorNOPIndex[counterWhile])
let tuple = knowTuple(instructions: instructionsModified)
if tuple.stopped {
counterWhile += 1
} else {
accumulator = tuple.acc
break
}
}
return accumulator
}
func secondPart() {
let instructions = input.components(separatedBy: .newlines)
let JMPorNOPIndex = getIndexArray(instructions: instructions)
let instructionsFixed = fixInstructionsStep(instructions, JMPorNOPIndex: JMPorNOPIndex)
print("second part \(instructionsFixed)")
}
secondPart()
| true
|
e80d4111667102d3b3da2e96b087cfb6b346f975
|
Swift
|
tiagoln/VirtusApp
|
/VirtusApp/ShowCaseItem.swift
|
UTF-8
| 452
| 2.671875
| 3
|
[] |
no_license
|
//
// ShowCase.swift
// VirtusApp
//
// Created by Tiago Leite Da Nóbrega on 14/07/17.
// Copyright © 2017 Virtus. All rights reserved.
//
import Foundation
struct ShowCaseItem {
let title: String?
let description: String?
let imageURL: String?
init(json: [String: Any]) {
title = json["Title"] as? String ?? ""
description = json["Description"] as? String ?? ""
imageURL = json["ImageURL"] as? String ?? ""
}
}
| true
|
d3183b5cb27b5303ee6debbee7413cf97f13ffad
|
Swift
|
FilipeNobrega/FilipeNobrega
|
/FilipeNobrega/Views/TileSection/SimpleText/FreeTextCollectionViewCell.swift
|
UTF-8
| 681
| 2.515625
| 3
|
[] |
no_license
|
//
// FreeTextCollectionViewCell.swift
// FilipeNobrega
//
// Created by Filipe Nobrega on 10/06/18.
// Copyright © 2018 Filipe. All rights reserved.
//
import UIKit
final class FreeTextCollectionViewCell: UICollectionViewCell, TilableViewProtocol {
@IBOutlet weak private var descriptionLabel: UILabel!
@IBOutlet weak private var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
titleLabel.textColor = StyleGuides.primaryTextColor
descriptionLabel.textColor = StyleGuides.primaryTextColor
roundedCorners()
}
func prepare(with tile: Tile) {
descriptionLabel.text = tile.shortDescription
titleLabel.text = tile.title
}
}
| true
|
566ee941ce286a704fce1f9f9de5b2a63a16340c
|
Swift
|
robertmukhtarov-kfu/LearnersDictionary
|
/LearnersDictionary/Modules/Entry/Views/EntryToolbar.swift
|
UTF-8
| 1,290
| 2.65625
| 3
|
[] |
no_license
|
//
// EntryToolbar.swift
// LearnersDictionary
//
// Created by Robert Mukhtarov on 12.03.2021.
//
import UIKit
class EntryToolbar: UIView, EntryToolbarView {
let segmentedControl = UISegmentedControl(items: [])
override init(frame: CGRect) {
super.init(frame: frame)
setupToolbar()
setupFakeNavbarShadow()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configureSegmentedControl(with items: [String]) {
for (index, title) in items.enumerated() {
segmentedControl.insertSegment(withTitle: title, at: index, animated: false)
}
segmentedControl.selectedSegmentIndex = 0
}
// MARK: - Private Methods
private func setupToolbar() {
backgroundColor = .background
addSubview(segmentedControl)
segmentedControl.snp.makeConstraints { make in
make.top.equalToSuperview()
make.centerX.equalToSuperview()
make.height.equalTo(32)
make.width.equalToSuperview().offset(-32)
}
}
private func setupFakeNavbarShadow() {
let fakeNavbarShadow = UIView(frame: .zero)
fakeNavbarShadow.backgroundColor = .navigationBarShadow
addSubview(fakeNavbarShadow)
fakeNavbarShadow.snp.makeConstraints { make in
make.top.equalTo(snp.bottom)
make.left.right.equalToSuperview()
make.height.equalTo(0.25)
}
}
}
| true
|
56336d340644a042377ea33c12f506b0e1afa467
|
Swift
|
OTPio/LibToken
|
/Tests/LibTokenTests/LibTokenTests.swift
|
UTF-8
| 9,015
| 2.734375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
import XCTest
#if canImport(Base32)
import Base32
#else
import SwiftBase32
#endif
@testable import LibToken
final class LibTokenTests: XCTestCase {
// MARK: - Success Cases: creation
/// Should successfully create a TOTP token using maximum options without throwing
func testValidTotpToken() {
let url = URL(string: "otpauth://totp/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios&algorithm=md5&digits=8&period=50")
do {
let token = try Token(url)
if case .totp(let period) = token.generator.type {
XCTAssertTrue(period == 50, "Got incorrect period")
} else { XCTFail("Incorrect type initialized") }
XCTAssertTrue(token.issuer == "Matrix Studios", "Got incorrect issuer")
XCTAssertTrue(token.label == "MatrixSenpai", "Got incorrect label")
XCTAssertTrue(token.generator.algorithm == .md5, "Got incorrect algorithm")
XCTAssertTrue(token.generator.digits == 8, "Got incorrect digits")
let secret = token.generator.secret.base32EncodedString
XCTAssertTrue(secret == "FEEDFACE", "Incorrectly encoded/decoded or wrong secret")
} catch {
XCTFail(error.localizedDescription)
}
}
/// Should successfully create a HOTP token using maximum options without throwing
func testValidHotpToken() {
let url = URL(string: "otpauth://hotp/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios&algorithm=sha512&digits=7&counter=70")
do {
let token = try Token(url)
if case .hotp(let counter) = token.generator.type {
XCTAssertTrue(counter == 70, "Got incorrect counter")
} else { XCTFail("Incorrect type initialized") }
XCTAssertTrue(token.issuer == "Matrix Studios", "Got incorrect issuer")
XCTAssertTrue(token.label == "MatrixSenpai", "Got incorrect label")
XCTAssertTrue(token.generator.algorithm == .sha512, "Got incorrect algorithm")
XCTAssertTrue(token.generator.digits == 7, "Got incorrect digits")
let secret = token.generator.secret.base32EncodedString
XCTAssertTrue(secret == "FEEDFACE", "Incorrectly encoded/decoded or wrong secret")
} catch {
XCTFail(error.localizedDescription)
}
}
// MARK: - Success Cases: functionality
/// Should successfully create a TOTP token and return its time
func testTokenTime() {
let url = URL(string: "otpauth://totp/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios&algorithm=sha1&digits=6&period=30")
let date = Date(timeIntervalSince1970: 1576035350)
do {
let token = try Token(url)
let remaining = token.timeRemaining(at: date)
XCTAssert(remaining == 10)
let reversed = token.timeRemaining(at: date, reversed: true)
XCTAssert(reversed == 20)
} catch {
XCTFail(error.localizedDescription)
}
}
/// Should successfully create a TOTP token and return the digits
func testTotpTokenOutput() {
let url = URL(string: "otpauth://totp/MatrixSenpai?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Matrix%20Studios&algorithm=sha1&digits=6&period=30")
let date = Date(timeIntervalSince1970: 1576034678)
do {
let token = try Token(url)
let password = token.password(at: date)
XCTAssert(password == "187979")
} catch {
XCTFail(error.localizedDescription)
}
}
/// Should successfully create a HOTP token and return the digits
func testHotpTokenOutput() {
let url = URL(string: "otpauth://hotp/MatrixSenpai?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Matrix%20Studios&algorithm=sha1&digits=6&counter=4778929323")
do {
let token = try Token(url)
let password = token.password()
XCTAssert(password == "331727")
} catch {
XCTFail(error.localizedDescription)
}
}
func testNextHotpTokenOutput() {
let url = URL(string: "otpauth://hotp/MatrixSenpai?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=Matrix%20Studios&algorithm=sha1&digits=6&counter=4778929323")
do {
var token = try Token(url)
token = token.nextToken()
let password = token.password()
XCTAssert(password == "494109")
} catch {
XCTFail(error.localizedDescription)
}
}
// MARK: - Success Cases: missing components
/// Should successfully create with algorithm 'sha1'
func testMissingAlgorithm() {
let url = URL(string: "otpauth://totp/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios&digits=6&period=30")
do {
let token = try Token(url)
XCTAssertTrue(token.generator.algorithm == .sha1)
} catch {
XCTFail(error.localizedDescription)
}
}
/// Should successfully create with digits '6'
func testMissingDigits() {
let url = URL(string: "otpauth://totp/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios&algorithm=sha1&period=30")
do {
let token = try Token(url)
XCTAssertTrue(token.generator.digits == 6)
} catch {
XCTFail(error.localizedDescription)
}
}
/// Should successfully create with period '30'
func testMissingPeriod() {
let url = URL(string: "otpauth://totp/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios&algorithm=sha1&digits=6")
do {
let token = try Token(url)
if case .totp(let period) = token.generator.type {
XCTAssertTrue(period == 30)
} else { XCTFail("Missing or wrong type") }
} catch {
XCTFail(error.localizedDescription)
}
}
/// Should successfully create token
func testMissingTotpOptionalComponents() {
let url = URL(string: "otpauth://totp/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios")
do {
let token = try Token(url)
if case .totp(let period) = token.generator.type {
XCTAssertTrue(period == 30, "Got incorrect period")
} else { XCTFail("Incorrect type initialized") }
XCTAssertTrue(token.generator.algorithm == .sha1, "Got incorrect algorithm")
XCTAssertTrue(token.generator.digits == 6, "Got incorrect digits")
} catch {
XCTFail(error.localizedDescription)
}
}
/// Should successfully create HOTP token
func testMissingHotpOptionalComponents() {
let url = URL(string: "otpauth://hotp/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios&counter=30")
do {
let token = try Token(url)
XCTAssertTrue(token.generator.algorithm == .sha1, "Got incorrect algorithm")
XCTAssertTrue(token.generator.digits == 6, "Got incorrect digits")
} catch {
XCTFail(error.localizedDescription)
}
}
// MARK: - Failure Cases
/// Should throw 'incorrect schema'
func testIncorrectScheme() {
let url = URL(string: "http://totp/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios&algorithm=sha1&digits=6&period=30")
XCTAssertThrowsError(try Token(url))
}
/// Should throw 'missing type'
func testMissingType() {
let url = URL(string: "otpauth://%20/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios&algorithm=sha1&digits=6&period=30")
XCTAssertThrowsError(try Token(url))
}
/// Should throw 'missing type'
func testIncorrectType() {
let url = URL(string: "otpauth://asdf/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios&algorithm=sha1&digits=6&period=30")
XCTAssertThrowsError(try Token(url))
}
/// Should throw 'missing label'
func testMissingLabel() {
let url = URL(string: "otpauth://totp/?secret=FEEDFACE&issuer=Matrix%20Studios&algorithm=sha1&digits=6&period=30")
XCTAssertThrowsError(try Token(url))
}
/// Should throw 'missing secret'
func testMissingSecret() {
let url = URL(string: "otpauth://totp/MatrixSenpai?issuer=Matrix%20Studios&algorithm=sha1&digits=6&period=30")
XCTAssertThrowsError(try Token(url))
}
/// Should throw 'missing issuer'
func testMissingIssuer() {
let url = URL(string: "otpauth://totp/MatrixSenpai?secret=FEEDFACE&algorithm=sha1&digits=6&period=30")
XCTAssertThrowsError(try Token(url))
}
/// Should throw 'missing counter'
func testMissingCounter() {
let url = URL(string: "otpauth://hotp/MatrixSenpai?secret=FEEDFACE&issuer=Matrix%20Studios&algorithm=sha1&digits=6")
XCTAssertThrowsError(try Token(url))
}
}
| true
|
013372dcb2d3838817bfb5ba4357d842f75557b5
|
Swift
|
Scrill21/MapKit-Test-App
|
/MapKit-Test/MapKit-Test/Models/Location.swift
|
UTF-8
| 345
| 2.84375
| 3
|
[] |
no_license
|
//
// Location.swift
// MapKit-Test
//
// Created by anthony byrd on 6/15/21.
//
import Foundation
import CoreLocation
class Location {
let title: String
let coordinates: CLLocationCoordinate2D?
init(title: String, coordinates: CLLocationCoordinate2D?) {
self.title = title
self.coordinates = coordinates
}
}
| true
|
82dd6ebf70c6192751ced8f20f26efc3b5ccfa29
|
Swift
|
asgeY/Apple-Card
|
/Apple Card/Cells/CollectionViewCells/SupportMessagesCell.swift
|
UTF-8
| 2,276
| 2.671875
| 3
|
[] |
no_license
|
//
// SupportMessagesCell.swift
// Apple Card
//
// Created by Richard Witherspoon on 4/1/19.
// Copyright © 2019 Richard Witherspoon. All rights reserved.
//
import UIKit
class SupportMessagesCell: BaseCollectionViewCell {
var isSender : Bool!{
didSet{
if self.isSender{
updateCell(image: SupportMessagesCell.sendingBubble, textColor: .white, backgroundColor: .gray)
} else {
updateCell(image: SupportMessagesCell.receivingBubble, textColor: .black, backgroundColor: UIColor.init(white: 0.95, alpha: 1))
}
}
}
let cellID = "SupportMessagesCell"
static let sendingBubble = #imageLiteral(resourceName: "bubbleSent").resizableImage(withCapInsets: UIEdgeInsets(top: 22, left: 26, bottom: 22, right: 26), resizingMode: .stretch).withRenderingMode(.alwaysTemplate)
static let receivingBubble = #imageLiteral(resourceName: "bubbleReceived").resizableImage(withCapInsets: UIEdgeInsets(top: 22, left: 26, bottom: 22, right: 26), resizingMode: .stretch).withRenderingMode(.alwaysTemplate)
let messageView : UITextView = {
let view = UITextView()
view.font = UIFont.systemFont(ofSize: 18)
view.backgroundColor = .clear
view.isEditable = false
return view
}()
let textBubbleView : UIView = {
let view = UIView()
return view
}()
let bubbleImageView : UIImageView = {
let view = UIImageView()
view.image = SupportMessagesCell.receivingBubble
view.tintColor = UIColor(white: 0.95, alpha: 1)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
override func layoutSubviews() {
textBubbleView.roundCorners(radius: 15)
}
override func setupViews() {
backgroundColor = .white
addSubview(textBubbleView)
addSubview(messageView)
textBubbleView.addSubview(bubbleImageView)
bubbleImageView.fillSuperview()
}
func updateCell(image: UIImage, textColor: UIColor, backgroundColor: UIColor) {
bubbleImageView.image = image
messageView.textColor = textColor
bubbleImageView.tintColor = backgroundColor
}
}
| true
|
c2f20a1b628036c0c54995cf9c195f64b7bfd82f
|
Swift
|
sayleepradhan/ContactManagerSwift
|
/ContactManagerSwift/Model/Contact/ContactDBModel+CoreDataProperties.swift
|
UTF-8
| 1,788
| 2.65625
| 3
|
[] |
no_license
|
//
// ContactDBModel+CoreDataProperties.swift
// ContactManagerSwift
//
// Created by Saylee Pradhan on 8/22/17.
// Copyright © 2017 Saylee Pradhan. All rights reserved.
//
import Foundation
import CoreData
extension ContactDBModel {
@nonobjc public class func fetchRequest() -> NSFetchRequest<ContactDBModel> {
return NSFetchRequest<ContactDBModel>(entityName: "ContactDBModel")
}
@NSManaged public var firstName: String?
@NSManaged public var lastName: String?
@NSManaged public var dateOfBirth: String?
@NSManaged public var phone: String?
@NSManaged public var zipCode: String?
static func fetchAllContacts() -> [ContactDBModel]? {
var contacts: [ContactDBModel] = []
let moc = DataManager.sharedInstance.context()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ContactDBModel")
do {
guard let contactList = try moc.fetch(fetchRequest) as? [ContactDBModel] else {
return nil
}
contacts = contactList
} catch {
fatalError("Failed to fetch events: \(error)")
}
return contacts
}
static func initWith(firstName: String, lastName: String,
dateOfBirth: String?, phone: String,
zipCode: String?) {
guard let contact: ContactDBModel = NSEntityDescription.insertNewObject(forEntityName: "ContactDBModel",into: DataManager.sharedInstance.context()) as? ContactDBModel else {
return
}
contact.firstName = firstName
contact.lastName = lastName
contact.dateOfBirth = dateOfBirth
contact.phone = phone
contact.zipCode = zipCode
DataManager.sharedInstance.saveContext()
}
}
| true
|
6d201721709905c5bdb84546dea0dd8f38924474
|
Swift
|
ronanrodrigo/CocoaHeadsApp
|
/CocoaHeadsApp/Classes/Base/Extensions/Unbox+Extensions.swift
|
UTF-8
| 642
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
import Unbox
/**
Allow NSDate fields inside Unboxable models
*/
public class UnboxNSDateTransformer: UnboxTransformer {
public typealias RawType = Double
public typealias TransformedType = NSDate
public static func transformUnboxedValue(unboxedValue: RawType) -> TransformedType? {
let seconds = unboxedValue / 1000
let tempo = Tempo(unixOffset: seconds)
return tempo.date
}
public static func fallbackValue() -> TransformedType {
return NSDate()
}
}
extension NSDate: UnboxableByTransform {
public typealias UnboxTransformerType = UnboxNSDateTransformer
}
| true
|
495fefb344d56642735ebbd4d5787a487ea1386c
|
Swift
|
msgpo/swiftSVG
|
/Tests/swiftSVGTests/CircleTests.swift
|
UTF-8
| 1,013
| 3
| 3
|
[
"Apache-2.0"
] |
permissive
|
import XCTest
import swiftSVG
class CircleTests: XCTestCase {
func testMakeCircle() {
let svg = SVG(width: 100, height: 100)
let circle = Circle(centerX: 50, centerY: 50, radius: 40)
svg.add(circle)
let result = svg.render()
let expectedResult =
"""
<svg width="100" height="100">
\t<circle cx="50" cy="50" r="40" />
</svg>
"""
XCTAssertEqual(result, expectedResult)
}
func testGiveCircleAnID() {
let svg = SVG(width: 100, height: 100)
let circle = Circle(centerX: 50, centerY: 50, radius: 40)
svg.add(circle)
circle.id = "myCircle"
let result = svg.render()
let expectedResult =
"""
<svg width="100" height="100">
\t<circle cx="50" cy="50" r="40" id="myCircle" />
</svg>
"""
XCTAssertEqual(result, expectedResult)
}
static var allTests = [
("Create a Circle", testMakeCircle)
]
}
| true
|
ae85e14974d1353244f861b288c37e45c45abe59
|
Swift
|
rizumita/Combine-DiffableDataSource-Sample
|
/DiffableSample/Presentation/ViewModel.swift
|
UTF-8
| 1,920
| 2.59375
| 3
|
[] |
no_license
|
//
// ViewModel.swift
// DiffableSample
//
// Created by 長田卓馬 on 2019/09/25.
// Copyright © 2019 Takuma Osada. All rights reserved.
//
import Foundation
import Combine
final class ViewModel: ObservableObject {
private let urlString = "https://qiita.com/api/v2/items?page=1&per_page=20"
private let urlSession = URLSession.shared
private let jsonDecoder = JSONDecoder()
private var subscriptions = Set<AnyCancellable>()
func fetchArticles(with filter: String? = nil) -> AnyPublisher<[Article], QiitaAPIError> {
guard let url = URL(string: urlString) else {
return Fail<[Article], QiitaAPIError>(error: .urlError(URLError(URLError.unsupportedURL))).eraseToAnyPublisher()
}
return urlSession.dataTaskPublisher(for: url)
.tryMap { (data, response) -> Data in
guard let httpResponse = response as? HTTPURLResponse, 200...299 ~= httpResponse.statusCode else {
throw QiitaAPIError.responseError((response as? HTTPURLResponse)?.statusCode ?? 500)
}
return data
}
.decode(type: [Post].self, decoder: jsonDecoder)
.mapError { (error) -> QiitaAPIError in
switch error {
case let urlError as URLError:
return .urlError(urlError)
case let decodingError as DecodingError:
return .decodingError(decodingError)
case let apiError as QiitaAPIError:
return apiError
default:
return .genericError
}
}
.map { (posts) -> [Article] in
posts.map { (post) -> Article in
let title = post.title
let url = post.url
return Article(title: title, url: url)
}
}
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
}
| true
|
dc30ef332bbf43899b1374a3c167424b5486b44c
|
Swift
|
algolia/instantsearch-ios
|
/Tests/InstantSearchCoreTests/Unit/SelectableListInteractorFilterConnectorsTests.swift
|
UTF-8
| 4,430
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// SelectableListInteractorFilterConnectorsTests.swift
// InstantSearchCore
//
// Created by Vladislav Fitc on 21/05/2019.
// Copyright © 2019 Algolia. All rights reserved.
//
import Foundation
@testable import InstantSearchCore
import XCTest
class SelectableListInteractorFilterConnectorsTests: XCTestCase {
func testConstructors() {
let facetFilterListInteractor = FilterListInteractor<Filter.Facet>()
XCTAssertEqual(facetFilterListInteractor.selectionMode, .multiple)
let numericFilterListInteractor = FilterListInteractor<Filter.Numeric>()
XCTAssertEqual(numericFilterListInteractor.selectionMode, .single)
let tagFilterListInteractor = FilterListInteractor<Filter.Tag>()
XCTAssertEqual(tagFilterListInteractor.selectionMode, .multiple)
}
func testFilterStateConnector() {
let interactor = FilterListInteractor<Filter.Tag>()
interactor.items = [
"tag1", "tag2", "tag3"
]
let filterState = FilterState()
filterState.notify(.add(filter: Filter.Tag(value: "tag3"), toGroupWithID: .or(name: "", filterType: .tag)))
interactor.connectFilterState(filterState, operator: .or)
// FilterState -> Interactor preselection
XCTAssertEqual(interactor.selections, ["tag3"])
// FilterState -> Interactor
filterState.notify(.add(filter: Filter.Tag(value: "tag1"), toGroupWithID: .or(name: "", filterType: .tag)))
XCTAssertEqual(interactor.selections, ["tag1", "tag3"])
// Interactor -> FilterState
interactor.computeSelections(selectingItemForKey: "tag2")
XCTAssertTrue(filterState.contains(Filter.Tag(value: "tag2"), inGroupWithID: .or(name: "", filterType: .tag)))
}
class TestController<F: FilterType>: SelectableListController {
typealias Item = F
var onClick: ((F) -> Void)?
var didReload: (() -> Void)?
var selectableItems: [(item: F, isSelected: Bool)] = []
func setSelectableItems(selectableItems: [(item: F, isSelected: Bool)]) {
self.selectableItems = selectableItems
}
func reload() {
didReload?()
}
func clickOn(_ item: F) {
onClick?(item)
}
}
func testControllerConnector() {
let interactor = FilterListInteractor<Filter.Tag>()
let controller = TestController<Filter.Tag>()
interactor.items = ["tag1", "tag2", "tag3"]
interactor.selections = ["tag2"]
interactor.connectController(controller)
// Test preselection
XCTAssertEqual(controller.selectableItems.map { $0.0 }, [
Filter.Tag(value: "tag1"),
Filter.Tag(value: "tag2"),
Filter.Tag(value: "tag3")
])
XCTAssertEqual(controller.selectableItems.map { $0.1 }, [
false,
true,
false
])
// Items change
let itemsChangedReloadExpectation = expectation(description: "items changed reload expectation")
controller.didReload = {
XCTAssertEqual(controller.selectableItems.map { $0.0 }, [
Filter.Tag(value: "tag1"),
Filter.Tag(value: "tag2"),
Filter.Tag(value: "tag3"),
Filter.Tag(value: "tag4")
])
XCTAssertEqual(controller.selectableItems.map { $0.1 }, [
false,
true,
false,
false
])
itemsChangedReloadExpectation.fulfill()
}
interactor.items = ["tag1", "tag2", "tag3", "tag4"]
waitForExpectations(timeout: 2, handler: nil)
// Selection change
let selectionsChangedReloadExpectation = expectation(description: "selections changed reload expectation")
controller.didReload = {
XCTAssertEqual(controller.selectableItems.map { $0.0 }, [
Filter.Tag(value: "tag1"),
Filter.Tag(value: "tag2"),
Filter.Tag(value: "tag3"),
Filter.Tag(value: "tag4")
])
XCTAssertEqual(controller.selectableItems.map { $0.1 }, [
false,
false,
true,
true
])
selectionsChangedReloadExpectation.fulfill()
}
interactor.selections = ["tag3", "tag4"]
waitForExpectations(timeout: 2, handler: nil)
// Selection computation on click
let selectionsComputedExpectation = expectation(description: "selections computed")
interactor.onSelectionsComputed.subscribe(with: self) { _, selectedTags in
XCTAssertEqual(selectedTags, ["tag1", "tag3", "tag4"])
selectionsComputedExpectation.fulfill()
}
controller.clickOn("tag1")
waitForExpectations(timeout: 2, handler: nil)
}
}
| true
|
ee4c53a79d8a0f4115ed2b3f52f5003b167709c5
|
Swift
|
SoftwareVerde/utopia-ios
|
/Utopia/Utopia/JavaUtil.swift
|
UTF-8
| 616
| 2.859375
| 3
|
[] |
no_license
|
import Foundation
open class JavaUtil {
open static func toJavaInteger(_ int: Int) -> JavaLangInteger {
return JavaLangInteger(value: Int32(int))
}
open static func toJavaIntegerPrimitive(_ int: Int) -> jint {
return Int32(int)
}
open static func toSwiftBool(_ bool: JavaLangBoolean) -> Bool {
return bool.booleanValue()
}
open static func toJavaBoolean(_ bool: Bool) -> JavaLangBoolean {
return JavaLangBoolean(boolean: bool)
}
open static func toSwiftInt(_ integer: JavaLangInteger) -> Int {
return Int(integer.intValue())
}
}
| true
|
e678f769270739ab9814953c5a29090d8c6ad16c
|
Swift
|
deirdresm/RayTracer
|
/RayTracer/Vector.swift
|
UTF-8
| 501
| 2.8125
| 3
|
[] |
no_license
|
//
// Vector.swift
// RayTracer
//
// Created by Deirdre Saoirse Moen on 2/26/19.
// Copyright © 2019 Deirdre Saoirse Moen. All rights reserved.
//
import Foundation
// swiftlint:disable identifier_name
public class Vector: Tuple {
required init(_ x: CGFloat, _ y: CGFloat, _ z: CGFloat, _ w: CGFloat) {
super.init(x, y, z, 0.0)
}
init(_ x: CGFloat, _ y: CGFloat, _ z: CGFloat) {
super.init(x, y, z, 0.0)
}
public override var description: String {
return("Vector: x: \(x), y: \(y), z: \(z), w: \(w)")
}
}
| true
|
bb36884c4e443e7b1b4dfbc5a1af7c9123157468
|
Swift
|
artemsmikh/SwiftMVVMExample
|
/SwiftMVVMExample/GooglePlacesConfig.swift
|
UTF-8
| 877
| 2.640625
| 3
|
[] |
no_license
|
//
// GooglePlacesConfig.swift
// SwiftMVVMExample
//
// Created by Artem Mikhailov on 06/02/17.
// Copyright © 2017 Artem Mikhailov. All rights reserved.
//
import Foundation
final class GooglePlacesConfig {
let maxImageSize: Int = 600
private(set) var apiKey: String = ""
init(plistName name: String) {
// Check for both default and example paths (just in case
// when someone hasn't renamed example .plist file)
let defaultPath = Bundle.main.path(forResource: name, ofType: "plist")
let examplePath = Bundle.main.path(forResource: name, ofType: "plist.example")
if let path = defaultPath ?? examplePath {
let config = NSDictionary(contentsOfFile: path)
if let value = config?.object(forKey: "apiKey") as? String {
apiKey = value
}
}
}
}
| true
|
f8757d61b88ddffa437b47bd5ab4131a67d2ba56
|
Swift
|
lcs-oyousufi/TortoiseGraphics
|
/Playground/Playground.playground/Pages/Line art 3.xcplaygroundpage/Contents.swift
|
UTF-8
| 419
| 2.78125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
import PlaygroundSupport
import TortoiseGraphics
import CoreGraphics
let myFrame = CGRect(x: 0, y: 0, width: 500, height: 500)
let canvas = PlaygroundCanvas(frame: myFrame)
canvas.frameRate = 300
canvas.color = .white
PlaygroundPage.current.liveView = canvas
canvas.drawing { turtle in
for s in stride(from: 250.0, to: 25.0, by: -25.0) {
turtle.square(withSize: s)
}
turtle.hideTortoise()
}
| true
|
8a49afa6c59702270c9ebf16f132821a40c0c5e4
|
Swift
|
KYang646/kimball-repo
|
/Aug27/Aug27/episodes.swift
|
UTF-8
| 848
| 3
| 3
|
[] |
no_license
|
//
// episodes.swift
// Aug27
//
// Created by Kimball Yang on 8/27/19.
// Copyright © 2019 Kimball Yang. All rights reserved.
//
import Foundation
enum JSONError: Error {
case decodingError(Error)
}
struct Episode: Codable {
let name: String
let summary: String
let number: Int
let runtime: Int
let image: ImageWrapper
private enum CodingKeys: String CodingKey {
case name, summary, number, runtime, image, link = "_links.self.href"
}
static func getEpisodes(from data: Data) throws -> [Episode] {
do {
let episodes = try JSONDecoder().decode([Episode].self, from: data)
return episodes
} catch {
throw JSONError.decodingError(<#T##Error#>)
}
}
}
struct ImageWrapper {
let medium = String
let original = String
}
| true
|
081fe20106a56fd82867594095da5455acb017e9
|
Swift
|
s4cha/ReduxApp
|
/TestRedux/LikeUser.swift
|
UTF-8
| 1,256
| 3.140625
| 3
|
[] |
no_license
|
//
// LikeUser.swift
// TestRedux
//
// Created by Sacha Durand Saint Omer on 04/02/16.
// Copyright © 2016 s4cha. All rights reserved.
//
import Foundation
enum LikeUserAction:Action {
case success(user:User)
case failed(user:User)
}
func LikeUser(_ user:User) -> ActionCreator {
return { dispatch in
//Optimistic
dispatch(LikeUserAction.success(user: user))
api.latestUsers().onError { _ in
dispatch(LikeUserAction.failed(user: user))
}
}
}
func likeUserReducer(_ state:MyState, action:LikeUserAction) -> MyState {
var state = state
switch action {
case .success(let aUser):
return likeUser(state, aUser: aUser)
case .failed(let aUser):
state.likingUserFailed = true
state.users = state.users?.map({ user in
var user = user
if user.name == aUser.name {
user.isLiked = false
}
return user
})
}
return state
}
func likeUser(_ state:MyState, aUser:User) -> MyState {
var state = state
state.users = state.users?.map({ user in
var user = user
if user.name == aUser.name {
user.isLiked = true
}
return user
})
return state
}
| true
|
702dba8ff508ec205b8d2d171006494ecc9a75cd
|
Swift
|
mredig/VectorExtor
|
/Tests/VectorExtorTests/CGVectorExtensionsTests.swift
|
UTF-8
| 6,535
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
import VectorExtor
class CGVectorExtensionsTests: XCTestCase {
override func 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.
}
func testCGVectorUtilities() {
let vec = CGVector(dx: 34, dy: 8.432)
let point = vec.point
XCTAssertEqual(vec.dx, point.x)
XCTAssertEqual(vec.dy, point.y)
let notNormal = CGVector(dx: 1, dy: 1)
XCTAssertEqual(notNormal.isNormal, false)
let normalized = notNormal.normalized
XCTAssertEqual(normalized.isNormal, true)
let normalVec = CGVector(dx: 0.7071067, dy: 0.7071067)
XCTAssertEqual(normalVec.isNormal, true)
let one = CGVector(dx: 1, dy: 1)
let two = CGVector(dx: 2, dy: 2)
let three = one + two
XCTAssertEqual(three, CGVector(dx: 3, dy: 3))
let six = two * 3
XCTAssertEqual(six, CGVector(dx: 6, dy: 6))
let inverted = notNormal.inverted
XCTAssertEqual(inverted, CGVector(dx: -1, dy: -1))
var rotationVector = CGVector(fromDegree: 0)
XCTAssertEqual(rotationVector.dx, 1, accuracy: 0.0000001)
XCTAssertEqual(rotationVector.dy, 0, accuracy: 0.0000001)
rotationVector = CGVector(fromDegree: 45)
XCTAssertEqual(rotationVector.dx, 0.7071067811865476, accuracy: 0.0000001)
XCTAssertEqual(rotationVector.dy, 0.7071067811865476, accuracy: 0.0000001)
rotationVector = CGVector(fromDegree: 90)
XCTAssertEqual(rotationVector.dx, 0, accuracy: 0.0000001)
XCTAssertEqual(rotationVector.dy, 1, accuracy: 0.0000001)
rotationVector = CGVector(fromDegree: 180)
XCTAssertEqual(rotationVector.dx, -1, accuracy: 0.0000001)
XCTAssertEqual(rotationVector.dy, 0, accuracy: 0.0000001)
rotationVector = CGVector(fromDegree: 270)
XCTAssertEqual(rotationVector.dx, 0, accuracy: 0.0000001)
XCTAssertEqual(rotationVector.dy, -1, accuracy: 0.0000001)
rotationVector = CGVector(fromDegree: 360)
XCTAssertEqual(rotationVector.dx, 1, accuracy: 0.0000001)
XCTAssertEqual(rotationVector.dy, 0, accuracy: 0.0000001)
rotationVector = CGVector(fromRadian: 0)
XCTAssertEqual(rotationVector.dx, 1, accuracy: 0.0000001)
XCTAssertEqual(rotationVector.dy, 0, accuracy: 0.0000001)
rotationVector = CGVector(fromRadian: CGFloat.pi / 2)
XCTAssertEqual(rotationVector.dx, 0, accuracy: 0.0000001)
XCTAssertEqual(rotationVector.dy, 1, accuracy: 0.0000001)
rotationVector = CGVector(fromRadian: CGFloat.pi)
XCTAssertEqual(rotationVector.dx, -1, accuracy: 0.0000001)
XCTAssertEqual(rotationVector.dy, 0, accuracy: 0.0000001)
rotationVector = CGVector(fromRadian: CGFloat.pi * 1.5)
XCTAssertEqual(rotationVector.dx, 0, accuracy: 0.0000001)
XCTAssertEqual(rotationVector.dy, -1, accuracy: 0.0000001)
rotationVector = CGVector(fromRadian: CGFloat.pi * 2)
XCTAssertEqual(rotationVector.dx, 1, accuracy: 0.0000001)
XCTAssertEqual(rotationVector.dy, 0, accuracy: 0.0000001)
let scalar3 = CGVector(scalar: 3)
let scalar35 = CGVector(scalar: 3.5)
XCTAssertEqual(scalar3, CGVector(dx: 3, dy: 3))
XCTAssertEqual(scalar35, CGVector(dx: 3.5, dy: 3.5))
}
func testCGVectorHashing() {
let point0 = CGVector.zero
let point1 = CGVector(dx: 1, dy: 0)
let point2 = CGVector(dx: 0, dy: 1)
let hash0 = point0.hashValue
let hash1 = point1.hashValue
let hash2 = point2.hashValue
XCTAssertNotEqual(hash0, hash1)
XCTAssertNotEqual(hash0, hash2)
XCTAssertNotEqual(hash1, hash2)
}
func testCGVectorOperands() {
let vectorA = CGVector(dx: 5, dy: 7)
let vectorB = CGVector(dx: 2.5, dy: 5)
// test negate
XCTAssertEqual(-vectorA, CGVector(dx: -5, dy: -7))
// cgvector with cgvector compuation tests
XCTAssertEqual(vectorA + vectorB, CGVector(dx: 7.5, dy: 12))
var sizeAB = vectorA
sizeAB += vectorB
XCTAssertEqual(sizeAB, CGVector(dx: 7.5, dy: 12))
XCTAssertEqual(vectorA - vectorB, CGVector(dx: 2.5, dy: 2))
sizeAB = vectorA
sizeAB -= vectorB
XCTAssertEqual(sizeAB, CGVector(dx: 2.5, dy: 2))
XCTAssertEqual(vectorA * vectorB, CGVector(dx: 12.5, dy: 35))
sizeAB = vectorA
sizeAB *= vectorB
XCTAssertEqual(sizeAB, CGVector(dx: 12.5, dy: 35))
XCTAssertEqual(vectorA / vectorB, CGVector(dx: 2, dy: 1.4))
sizeAB = vectorA
sizeAB /= vectorB
XCTAssertEqual(sizeAB, CGVector(dx: 2, dy: 1.4))
// cgvector with cgsize computation tests
let bSize = vectorB.size
XCTAssertEqual(vectorA + bSize, CGVector(dx: 7.5, dy: 12))
sizeAB = vectorA
sizeAB += bSize
XCTAssertEqual(sizeAB, CGVector(dx: 7.5, dy: 12))
XCTAssertEqual(vectorA - bSize, CGVector(dx: 2.5, dy: 2))
sizeAB = vectorA
sizeAB -= bSize
XCTAssertEqual(sizeAB, CGVector(dx: 2.5, dy: 2))
XCTAssertEqual(vectorA * bSize, CGVector(dx: 12.5, dy: 35))
sizeAB = vectorA
sizeAB *= bSize
XCTAssertEqual(sizeAB, CGVector(dx: 12.5, dy: 35))
XCTAssertEqual(vectorA / bSize, CGVector(dx: 2, dy: 1.4))
sizeAB = vectorA
sizeAB /= bSize
XCTAssertEqual(sizeAB, CGVector(dx: 2, dy: 1.4))
// cgvector with cgpoint computation tests
let bPoint = vectorB.point
XCTAssertEqual(vectorA + bPoint, CGVector(dx: 7.5, dy: 12))
sizeAB = vectorA
sizeAB += bPoint
XCTAssertEqual(sizeAB, CGVector(dx: 7.5, dy: 12))
XCTAssertEqual(vectorA - bPoint, CGVector(dx: 2.5, dy: 2))
sizeAB = vectorA
sizeAB -= bPoint
XCTAssertEqual(sizeAB, CGVector(dx: 2.5, dy: 2))
XCTAssertEqual(vectorA * bPoint, CGVector(dx: 12.5, dy: 35))
sizeAB = vectorA
sizeAB *= bPoint
XCTAssertEqual(sizeAB, CGVector(dx: 12.5, dy: 35))
XCTAssertEqual(vectorA / bPoint, CGVector(dx: 2, dy: 1.4))
sizeAB = vectorA
sizeAB /= bPoint
XCTAssertEqual(sizeAB, CGVector(dx: 2, dy: 1.4))
// cgfloat computation tests
let cgFloatValue: CGFloat = 5
XCTAssertEqual(vectorA + cgFloatValue, CGVector(dx: 10, dy: 12))
var pointCGFloat = vectorA
pointCGFloat += cgFloatValue
XCTAssertEqual(pointCGFloat, CGVector(dx: 10, dy: 12))
XCTAssertEqual(vectorA - cgFloatValue, CGVector(dx: 0, dy: 2))
pointCGFloat = vectorA
pointCGFloat -= cgFloatValue
XCTAssertEqual(pointCGFloat, CGVector(dx: 0, dy: 2))
XCTAssertEqual(vectorA * cgFloatValue, CGVector(dx: 25, dy: 35))
pointCGFloat = vectorA
pointCGFloat *= cgFloatValue
XCTAssertEqual(pointCGFloat, CGVector(dx: 25, dy: 35))
XCTAssertEqual(vectorA / cgFloatValue, CGVector(dx: 1, dy: 1.4))
pointCGFloat = vectorA
pointCGFloat /= cgFloatValue
XCTAssertEqual(pointCGFloat, CGVector(dx: 1, dy: 1.4))
}
}
| true
|
aa416e33456d5b1dfce41e540bb7e18da5c77472
|
Swift
|
doquanghuy/StreamingVideo
|
/StreamingVideo/Model/CustomModel/Video/Video+CoreDataClass.swift
|
UTF-8
| 2,000
| 2.65625
| 3
|
[] |
no_license
|
//
// Video+CoreDataClass.swift
// StreamingVideo
//
// Created by huydoquang on 10/31/17.
// Copyright © 2017 huydoquang. All rights reserved.
//
//
import Foundation
import CoreData
import SwiftyJSON
public class Video: NSManagedObject {
var isDownloaded: Bool {
return self.localURL != nil
}
static func createOrUpdateVideo(with json: JSON, context: NSManagedObjectContext? = nil) -> Video {
let id = json["id"].int32!
let manageObjContext = CoreDataStack.shared.managedContext
let video = self.video(with: id) ?? Video(context: manageObjContext)
if let backgroundImageURL = json["background_image_url"].string {
video.backgroundImageURL = backgroundImageURL
}
video.id = id
if let streamURL = json["stream_url"].string {
video.streamURL = streamURL
}
if let offlineURL = json["offline_url"].string {
video.offlineURL = offlineURL
}
if let name = json["name"].string {
video.name = name
}
return video
}
static func createOrUpdateMultiVideo(with json: JSON, context: NSManagedObjectContext? = nil) -> [Video] {
let manageObjContext = CoreDataStack.shared.managedContext
var videos = [Video]()
for json in json.arrayValue {
let video = self.createOrUpdateVideo(with: json, context: manageObjContext)
videos.append(video)
}
do {
try context?.save()
} catch let error as NSError {
print(error.localizedDescription)
}
return videos
}
static func video(with id: Int32) -> Video? {
let fetchRequest: NSFetchRequest<Video> = Video.fetchRequest()
let predicateID = NSPredicate(format: "id == %@", String(id))
fetchRequest.predicate = predicateID
return (try? CoreDataStack.shared.managedContext.fetch(fetchRequest).first) as? Video
}
}
| true
|
93edac685119a4c71853382c2a8beca82b6d2402
|
Swift
|
Dornhoth/adventOfCode2015
|
/day3/day3.swift
|
UTF-8
| 2,471
| 3.703125
| 4
|
[] |
no_license
|
//
// day3.swift
//
//
// Created by Dornhoth on 14.07.19.
//
import Foundation
struct House {
var x: Int;
var y: Int;
}
class DeliveryGuy {
static var visited = [House(x: 0, y: 0)]
static func reset() {
DeliveryGuy.visited = [House]()
}
var location: House;
init() {
self.location = House(x: 0, y: 0);
}
func goTo(house: House) {
let alreadyVisited = DeliveryGuy.visited.filter {$0.x == house.x && $0.y == house.y}
if alreadyVisited.count == 0 {
DeliveryGuy.visited.append(house);
}
location = house;
}
func goNorth() {
goTo(house: House(x: location.x, y: location.y + 1));
}
func goSouth() {
goTo(house: House(x: location.x, y: location.y - 1));
}
func goEast() {
goTo(house: House(x: location.x - 1, y: location.y));
}
func goWest() {
goTo(house: House(x: location.x + 1, y: location.y));
}
func followInstruction(instruction: String) {
switch(instruction) {
case "^":
goNorth();
case "v":
goSouth();
case ">":
goEast();
case "<":
goWest();
default:
goWest();
}
}
}
func getVisitedHousesWithOneDeliveryGuy(input: String) -> Int{
let santa = DeliveryGuy();
let instructions = Array(input);
for instruction in instructions {
santa.followInstruction(instruction: String(instruction));
}
return DeliveryGuy.visited.count;
}
func getVisitedHousesWithTwoDeliveryGuys(input: String) -> Int{
let santa = DeliveryGuy();
let roboSanta = DeliveryGuy();
let instructions = Array(input);
for i in 0..<instructions.count {
let instruction = instructions[i];
if i % 2 == 0 {
santa.followInstruction(instruction: String(instruction));
} else {
roboSanta.followInstruction(instruction: String(instruction));
}
}
return DeliveryGuy.visited.count;
}
print("Enter input file path:");
if let path = readLine() {
let input = try String(contentsOfFile: path, encoding: .utf8);
let resultPart1 = getVisitedHousesWithOneDeliveryGuy(input: input);
DeliveryGuy.reset();
let resultPart2 = getVisitedHousesWithTwoDeliveryGuys(input: input);
print("Result part 1 : \(resultPart1)");
print("Result part 2 : \(resultPart2)");
}
| true
|
ee31cb6b1f9ecbb582af5e9909a8615c29bab842
|
Swift
|
ultimate-deej/ResizeCrop-for-iOS
|
/ResizeCrop/ResizeCrop.swift
|
UTF-8
| 6,766
| 3.765625
| 4
|
[
"MIT"
] |
permissive
|
import UIKit
/**
Functions for resizing an image to fill a specific `CGSize` or `UIView`'s frame.
- Important: Aspect ratio is always maintained.
**Examples**
````
ResizeCrop.resize(
image: myImage,
toFillView: myView,
gravity: .bottom)
````
````
ResizeCrop.resize(
image: cgImage,
toPixelSize: CGSize(width: 100, height: 100),
gravity: .center,
quality: .default)
````
Generally, you provide two things besides the image:
- *Gravity*: determines which part of the image will be cropped
- *Target*: an area the image should fill
There are a couple of other resizing options:
- *Scale* (e.g. 1x, 2x). Implied or specified explicitly
- *Interpolation quality*. `.high` by default
---------------------------------------------------------------
- Note: As the name of the library implies, images are cropped.
Specifically, the library does almost the same thing as `UIImageView`
with content mode set to **Aspect Fill** except that *you can choose
which part of the image to crop*, and the image is actually resampled
therefore consuming less memory.
*/
public struct ResizeCrop {
public enum Gravity {
case center
case left
case top
case right
case bottom
}
private init() {}
// MARK: - Low Level Functions
/**
Resizes an image to the specified size in pixels
- Parameters:
- image: Source image
- pixelSize: Desired size of the resulting image in pixels
- gravity: Which part of the `image` to crop
- quality: Interpolation quality for a graphics context
*/
public static func resize(image: CGImage, toPixelSize pixelSize: CGSize, gravity: Gravity, quality: CGInterpolationQuality = .high) -> CGImage {
assert(pixelSize.width != 0, "zero width")
assert(pixelSize.height != 0, "zero height")
let sourceRatio = ratio(width: CGFloat(image.width), height: CGFloat(image.height))
let drawLocation = calculateDrawLocation(sourceRatio: sourceRatio, rectToFill: pixelSize, gravity: gravity)
let context = CGContext(data: nil, width: Int(pixelSize.width), height: Int(pixelSize.height), bitsPerComponent: image.bitsPerComponent, bytesPerRow: 0, space: image.colorSpace!, bitmapInfo: image.bitmapInfo.rawValue)!
context.interpolationQuality = quality
context.draw(image, in: drawLocation)
return context.makeImage()!
}
/**
Resizes an image to the specified size in pixels
- Parameters:
- image: Source image
- pixelSize: Desired size of the resulting image in pixels
- gravity: Which part of the `image` to crop
- quality: Interpolation quality for a graphics context
*/
public static func resize(image: UIImage, toPixelSize pixelSize: CGSize, gravity: Gravity, quality: CGInterpolationQuality = .high) -> UIImage {
let resized = resize(image: image.cgImage!, toPixelSize: pixelSize, gravity: gravity, quality: quality)
return UIImage(cgImage: resized)
}
// MARK: - High Level Functions
/**
Resizes an image given a target size in points and a scaleFactor
- Parameters:
- image: Source image
- size: Desired size of the resulting image in points
- scaleFactor: Scale factor of the resulting image. Used in conjunction with `size` to determine the size of the result
- gravity: Which part of the `image` to crop
*/
public static func resize(image: UIImage, toSize size: CGSize, scaleFactor: CGFloat, gravity: Gravity) -> UIImage {
let pixelSize = CGSize(width: size.width * scaleFactor, height: size.height * scaleFactor)
let resized = resize(image: image.cgImage!, toPixelSize: pixelSize, gravity: gravity)
return UIImage(cgImage: resized, scale: scaleFactor, orientation: image.imageOrientation)
}
/**
Resizes an image to the specified size
- Parameters:
- image: Source image
- size: Desired size of the resulting image. Units depend on the `image` scale
- gravity: Which part of the `image` to crop
*/
public static func resize(image: UIImage, toSize size: CGSize, gravity: Gravity) -> UIImage {
return resize(image: image, toSize: size, scaleFactor: image.scale, gravity: gravity)
}
/**
Resizes an image to the size of a view's frame
- Parameters:
- image: Source image
- view: The view whose size is used for the result
- gravity: Which part of the `image` to crop
- Requires:
`view.window != nil`
- Note:
Pixel size of the result is determined by the scale factor the `view`'s screen
*/
public static func resize(image: UIImage, toFillView view: UIView, gravity: Gravity) -> UIImage {
return resize(image: image, toSize: view.frame.size, scaleFactor: view.window!.screen.scale, gravity: gravity)
}
// MARK: - Calculations
private static func calculateDrawLocation(sourceRatio: CGFloat, rectToFill: CGSize, gravity: Gravity) -> CGRect {
let targetRatio = ratio(width: rectToFill.width, height: rectToFill.height)
if sourceRatio == targetRatio {
return CGRect(origin: .zero, size: rectToFill)
}
let (drawWidth, drawHeight) = sourceRatio > targetRatio
? (rectToFill.height * sourceRatio, rectToFill.height)
: (rectToFill.width, rectToFill.width / sourceRatio)
switch gravity {
case .center:
return CGRect(x: (rectToFill.width - drawWidth) / 2,
y: (rectToFill.height - drawHeight) / 2,
width: drawWidth,
height: drawHeight)
case .left:
return CGRect(x: 0,
y: (rectToFill.height - drawHeight) / 2,
width: drawWidth,
height: drawHeight)
case .top:
return CGRect(x: (rectToFill.width - drawWidth) / 2,
y: rectToFill.height - drawHeight,
width: drawWidth,
height: drawHeight)
case .right:
return CGRect(x: rectToFill.width - drawWidth,
y: (rectToFill.height - drawHeight) / 2,
width: drawWidth,
height: drawHeight)
case .bottom:
return CGRect(x: (rectToFill.width - drawWidth) / 2,
y: 0,
width: drawWidth,
height: drawHeight)
}
}
private static func ratio(width: CGFloat, height: CGFloat) -> CGFloat {
return width / height
}
}
| true
|
3f90c33a519b8e696c30f2ecd6cf9d52a9347f47
|
Swift
|
ignasiperez/SWIFT-Swift_org-The_Swift_programming_language-Language_guide
|
/SW-01-Swift_Language_Guide -Swift5.4/Swift_language_Guide -Swift5_4.playground/Pages/06-FUNCTIONS-Sec03 Ex01 - Parameter Names.xcplaygroundpage/Contents.swift
|
UTF-8
| 676
| 3.421875
| 3
|
[] |
no_license
|
//: # [ ](@previous) [ ](_Cover%20page) [ ](@next)
/*:
### 06 - Section 3 - Example 01
# FUNCTIONS
# Function Argument Labels and Parameter Names
## Parameter Names
---
*/
import Foundation
// ******************** 06-Sec03-Ex01 ********************
func someFunction(firstParameterName: Int,
secondParameterName: Int) {
// In the function body, firstParameterName and secondParameterName
// refer to the argument values for the first and second parameters.
}
someFunction(firstParameterName: 1, secondParameterName: 2)
//: # [ ](@previous) [ ](_Cover%20page) [ ](@next)
| true
|
57d90a64821e03f4d30df99d53e1013585019a01
|
Swift
|
mark33699/nihongo
|
/NiHonGo/View/GrammarView.swift
|
UTF-8
| 1,374
| 2.96875
| 3
|
[] |
no_license
|
//
// GrammarView.swift
// NiHonGo
//
// Created by MarkHsieH on 2021/3/29.
//
import SwiftUI
struct GrammarView: NiHonGoView {
@State var partsOfSpeechIndex = 1
@State var listSelection = Set<String>()
@State private var showingSheet = false
var body: some View {
NavigationView {
VStack {
Picker("", selection: $partsOfSpeechIndex, content: {
Text("動詞").tag(0)
Text("形容詞").tag(1)
Text("名詞").tag(2)
}).pickerStyle(SegmentedPickerStyle())
List(verbs, selection: $listSelection ) { word in
Button(word.hiraganas) {
showingSheet.toggle()
}
.sheet(isPresented: $showingSheet) {
SheetView()
}
}
.navigationBarTitle("文法")
}
}
}
}
struct SheetView: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
Button("Press to dismiss") {
presentationMode.wrappedValue.dismiss()
}
.font(.title)
.padding()
}
}
struct GrammarView_Previews: PreviewProvider {
static var previews: some View {
GrammarView()
}
}
| true
|
140e2e0b3e52137305c81a6fd9240add72cb1a72
|
Swift
|
hades0803/DouYuTVCode
|
/DouYuTV/DouYuTV/Classes/Tools/Extension/UIColor-Extension.swift
|
UTF-8
| 336
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// UIColor-Extension.swift
// DouYuTV
//
// Created by 段忠明 on 2020/4/8.
// Copyright © 2020 段忠明. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(r : CGFloat, g : CGFloat, b : CGFloat) {
self.init(red : r / 255.0, green : g / 255.0, blue : b / 255.0, alpha : 1.0)
}
}
| true
|
3af7ee4d652ac44a76ded88456e037748e190ce9
|
Swift
|
adrian-barbu/GiftLog
|
/iOS/GiftLogApp/Managers/Helpers/SSHelperManager.swift
|
UTF-8
| 15,017
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// SSHelper.swift
//
// Created by Serhii Kharauzov on 12/23/15.
// Copyright © 2015 Webs The Word. All rights reserved.
//
import Foundation
import MessageUI
import CoreLocation
typealias AlertViewConfirmCompletionHandler = () -> Void
typealias AlertViewConfirmCancelHandler = () -> Void
//MARK: iOS System constants
private enum UIUserInterfaceIdiom : Int {
case unspecified
case phone
case pad
}
struct ScreenSize {
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
struct DeviceType {
static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
static let IS_IPHONE_5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
static let IS_IPHONE_6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
static let IS_IPHONE_6P = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad
}
/** This class created for gathering and using some popular methods, that help to make development process easy. */
class SSHelperManager:NSObject {
// MARK: Properties
static let shared = SSHelperManager()
var mailComposerVC: MFMailComposeViewController!
var messageComposerVC: MFMessageComposeViewController!
override init() {
if MFMessageComposeViewController.canSendText() {
messageComposerVC = MFMessageComposeViewController()
}
if MFMailComposeViewController.canSendMail() {
mailComposerVC = MFMailComposeViewController()
}
}
func makeShakeAnimationOfView(_ view: UIView) {
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.07
animation.repeatCount = 4
animation.autoreverses = true
animation.fromValue = NSValue(cgPoint: CGPoint(x: view.center.x - 10, y: view.center.y))
animation.toValue = NSValue(cgPoint: CGPoint(x: view.center.x + 10, y: view.center.y))
view.layer.add(animation, forKey: "position")
}
/** Count flexible height for cell depending on its content. */
func heightForViewWithContentString(_ content:String, viewWidth width:CGFloat, font fontSize:CGFloat, minimuSize:CGFloat) -> CGFloat {
let fontSize:CGFloat = fontSize
let viewContentWidth:CGFloat = width
let viewContentMargin:CGFloat = 10.0 // 5.0 - default
let text = content
let constraint:CGSize = CGSize(width: viewContentWidth - (viewContentMargin * 2), height: 20000.0)
let attributedText:NSAttributedString = NSAttributedString(string: text, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: fontSize)])
let rect:CGRect = attributedText.boundingRect(with: constraint, options:NSStringDrawingOptions.usesLineFragmentOrigin, context: nil)
let size:CGSize = rect.size
let height:CGFloat = max(size.height,minimuSize)
return height
}
/** Make call from device on phone number. */
func makeCallOnPhoneNumber(_ phoneNumber:String) {
if DeviceType.IS_IPAD {
UIAlertController.showAlertWithTitle("Error", message: phoneNumber)
} else {
var number = phoneNumber
number = number.replacingOccurrences(of: "+", with: "")
number = number.replacingOccurrences(of: "(", with: "")
number = number.replacingOccurrences(of: ")", with: "")
number = number.replacingOccurrences(of: "-", with: "")
number = number.replacingOccurrences(of: " ", with: "")
if let url = URL(string: "tel://\(number)") {
UIApplication.shared.openURL(url) // calling
}
}
}
func showShareActionSheetFromController(_ controller: UIViewController, withText text: String) {
let sharedObjects = ["\(text)\nDownload the app: " as AnyObject, Constants.appStoreLink as AnyObject] as [AnyObject]
let activityController = UIActivityViewController(activityItems: sharedObjects, applicationActivities: nil)
if let popoverController = activityController.popoverPresentationController {
popoverController.sourceView = controller.view
popoverController.sourceRect = CGRect(x: controller.view.center.x, y: UIScreen.main.bounds.height, width: 1, height: 10)
}
controller.present(activityController, animated: true, completion: nil)
}
/** Check if email is valid */
func isValidEmail(_ email:String) -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return emailTest.evaluate(with: email)
}
/* Use this method for textFields only */
func areAllTextFieldsEnteredInView(_ view: UIView) -> Bool {
for subview in view.subviews {
if subview is UITextField {
if (subview as! UITextField).text!.isEmpty {
return false
}
}
}
return true
}
func isPasswordValid(_ password: String) -> Bool {
if password.characters.count < Constants.minPasswordLength {
return false
}
return true
}
func getBoldAttributedStringFromString(_ initialString: String, stringToMakeBold: String, color: UIColor, fontSize: CGFloat) -> NSMutableAttributedString {
let stringToMakeBold = stringToMakeBold
let initialString = initialString
let fontSize: CGFloat = fontSize
let attributes = [NSFontAttributeName:UIFont.systemFont(ofSize: fontSize), NSForegroundColorAttributeName: color]
let boldAttribute = [NSFontAttributeName:UIFont.boldSystemFont(ofSize: fontSize), NSForegroundColorAttributeName: color]
// For Facebook
let string = initialString.appending(stringToMakeBold)
let attributedString = NSMutableAttributedString(string: string, attributes: attributes)
let nsString = NSString(string: string)
let range = nsString.range(of: stringToMakeBold)
if range.length > 0 { attributedString.setAttributes(boldAttribute, range: range) }
return attributedString
}
func setUnderlinedAttributed(_ string: String, with color: UIColor, fontSize: CGFloat, font: String?) -> NSMutableAttributedString {
var fontToUse = UIFont.systemFont(ofSize: fontSize)
if font != nil {
fontToUse = UIFont(name: font!, size: fontSize)!
}
let stringAttributes : [String: Any] = [
NSFontAttributeName : fontToUse,
NSForegroundColorAttributeName : color,
NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue
]
return NSMutableAttributedString(string: string, attributes: stringAttributes)
}
func setEmptyBackNavigationButtonIn(_ controller: UIViewController) {
let backItem = UIBarButtonItem()
backItem.title = ""
controller.navigationItem.backBarButtonItem = backItem
}
}
extension UIViewController {
/** Get last visible window */
static func lastWindow() -> UIWindow? {
return UIApplication.shared.windows.last ?? nil
}
/** Get visible viewcontroller from any class . */
static func getVisibleViewController(_ rootViewController: UIViewController?) -> UIViewController? {
var rootViewController = rootViewController
if rootViewController == nil { rootViewController = UIApplication.shared.delegate!.window!!.rootViewController }
if let nav = rootViewController as? UINavigationController {
return getVisibleViewController(nav.visibleViewController)
}
if let tab = rootViewController as? UITabBarController {
let moreNavigationController = tab.moreNavigationController
if let top = moreNavigationController.topViewController , top.view.window != nil {
return getVisibleViewController(top)
} else if let selected = tab.selectedViewController {
return getVisibleViewController(selected)
}
}
if let presented = rootViewController?.presentedViewController {
return getVisibleViewController(presented)
}
return rootViewController
}
}
extension UIAlertController {
/** Show alertView with two options : 'Confirm' and 'Cancel' . */
static func showAlertWithTitle(_ titleText:String, message messageText:String, cancelButtonText cancelText:String, confirmButtonText confirmText:String , confirmCancelHandler:AlertViewConfirmCancelHandler?, confirmCompletionHandler:AlertViewConfirmCompletionHandler?) {
let alert = UIAlertController(title: titleText, message: messageText, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: cancelText, style: UIAlertActionStyle.cancel, handler: { (action) -> Void in
if let handler = confirmCancelHandler {
handler()
}
}))
alert.addAction(UIAlertAction(title: confirmText, style: .default, handler: { (action) -> Void in
if let handler = confirmCompletionHandler {
handler()
}
}))
let currentController = UIViewController.getVisibleViewController(nil)
if let controller = currentController {
controller.present(alert, animated: true, completion: nil)
}
}
/** Show alertView with one option : 'Ok' . */
static func showAlertWithTitle(_ titleText:String, message messageText:String) {
let alert = UIAlertController(title: titleText, message: messageText, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .cancel, handler: nil))
// Must not search needed controller in all view hierarchy, beacause of possible issues
let currentController = UIViewController.getVisibleViewController(nil)
if let controller = currentController {
controller.present(alert, animated: true, completion: nil)
}
}
//FIXME: Remove in production this code
static func showErrorAlert() {
let alert = UIAlertController(title: "Error", message: "Debug mode", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay", style: .cancel, handler: nil))
// Must not search needed controller in all view hierarchy, beacause of possible issues
let currentController = UIViewController.getVisibleViewController(nil)
if let controller = currentController {
controller.present(alert, animated: true, completion: nil)
}
}
}
// MARK: MFMailComposeViewController
extension SSHelperManager: MFMailComposeViewControllerDelegate {
func showMailComposerFor(recipients: [String], withText text: String, withFile file: Data? = nil) {
if MFMailComposeViewController.canSendMail() {
let mailComposeViewController = configuredMailComposeViewController(recipients: recipients, withText: text, withFile: file)
let currentController = UIViewController.getVisibleViewController(nil)
if let controller = currentController {
controller.present(mailComposeViewController, animated: true) {
}
}
} else {
self.showSendMailErrorAlert()
}
}
func configuredMailComposeViewController(recipients: [String], withText text: String, withFile file: Data? = nil) -> MFMailComposeViewController {
if mailComposerVC == nil {
mailComposerVC = MFMailComposeViewController()
}
if let file = file {
mailComposerVC.addAttachmentData(file, mimeType: "text/csv", fileName: "AppData.csv")
}
mailComposerVC.mailComposeDelegate = self
mailComposerVC.setToRecipients(recipients)
mailComposerVC.setMessageBody(text, isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertView(title: NSLocalizedString("Cannot send email", comment: ""),
message: NSLocalizedString("For allowing device to send email please check your mail settings and try again.", comment: ""), delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true, completion: {
self.mailComposerVC = nil
})
}
}
// MARK: MFMessageComposeViewController
extension SSHelperManager: MFMessageComposeViewControllerDelegate {
func showMessageComposerFor(recipients: [String], withText text: String) {
if MFMessageComposeViewController.canSendText() {
let messageComposeViewController = configuredMessageComposeViewController(recipients: recipients, withText: text)
let currentController = UIViewController.getVisibleViewController(nil)
if let controller = currentController {
controller.present(messageComposeViewController, animated: true) {
}
}
} else {
self.showSendMessageErrorAlert()
}
}
func configuredMessageComposeViewController(recipients: [String], withText text: String) -> MFMessageComposeViewController {
if messageComposerVC == nil {
messageComposerVC = MFMessageComposeViewController()
}
messageComposerVC.messageComposeDelegate = self
messageComposerVC.recipients = recipients
messageComposerVC.body = text
return messageComposerVC
}
func showSendMessageErrorAlert() {
let sendMessageErrorAlert = UIAlertView(title: NSLocalizedString("Cannot send message", comment: ""),
message: NSLocalizedString("For allowing device to send message please check your message settings and try again.", comment: ""), delegate: self, cancelButtonTitle: "OK")
sendMessageErrorAlert.show()
}
func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
controller.dismiss(animated: true, completion: {
self.messageComposerVC = nil
})
}
}
| true
|
b7f9bdb280e371410c2f6b1b373c6399520bfd2e
|
Swift
|
nofelmahmood/TvTime
|
/TvTime/Models/Credit.swift
|
UTF-8
| 722
| 2.859375
| 3
|
[] |
no_license
|
//
// Credits.swift
// TvTime
//
// Created by Nofel Mahmood on 12/03/2017.
// Copyright © 2017 Nineish. All rights reserved.
//
import UIKit
import Decodable
struct Credit {
let characterName: String!
let creditID: String!
let id: Int32!
let name: String!
let thumbnailURL: String!
let order: Int32!
}
extension Credit: Decodable {
static func decode(_ json: Any) throws -> Credit {
return try Credit(
characterName: json => "character",
creditID: json => "credit_id",
id: json => "id",
name: json => "name",
thumbnailURL: json => "profile_path",
order: json => "order"
)
}
}
| true
|
d3cefad7d7ec81b9a266feaf39cdbe89dcd3a4bd
|
Swift
|
josephbae96/iOS_13_and_Swift_5
|
/I Am Rich/I Am Rich/ContentView.swift
|
UTF-8
| 976
| 3.125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// I Am Rich
//
// Created by Joseph Bae on 1/8/21.
// Created according to instruction from Angela Yu
// of the iOS & Swift - The Complete iOS App Development Bootcamp
// on Udemy. This project was created entirely using
// SwiftUI.
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
Color(.systemTeal)
.edgesIgnoringSafeArea(.all)
VStack {
Text("I Am Rich")
.font(.system(size: 40))
.fontWeight(.bold)
.foregroundColor(.white)
.padding()
Image("diamond")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 200, height: 200, alignment: .center)
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
71f02a8c7bea8a1013fc798612483bef833ccf8d
|
Swift
|
blue52/foodhomework
|
/AddDataTableview/MovieTableViewController.swift
|
UTF-8
| 5,111
| 2.625
| 3
|
[] |
no_license
|
//
// MovieTableViewController.swift
// AddDataTableview
//
// Created by sky on 2016/8/2.
// Copyright © 2016年 sky. All rights reserved.
//
import UIKit
class MovieTableViewController: UITableViewController {
//var foodArray = [["name":"黯然銷魂飯", "match": "牛雜湯"],["name":"奪命香雞腿", "match": "凍檸茶"]]
var foodArray:Array<Dictionary<String,String>> = [] //如少掉Array就不能新增
override func viewDidLoad() {
super.viewDidLoad()
let notificationName = Notification.Name("AddfoodNoti")
NotificationCenter.default.addObserver(self, selector: #selector(MovieTableViewController.addfoodNoti(noti:)), name: notificationName, object: nil)
self.navigationItem.leftBarButtonItem = self.editButtonItem
let notificationEditName = Notification.Name("editfoodNoti")
NotificationCenter.default.addObserver(self, selector: #selector(MovieTableViewController.editfoodNoti(noti:)), name: notificationEditName, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
// override func numberOfSections(in tableView: UITableView) -> Int {
// // #warning Incomplete implementation, return the number of sections
// return 0
// }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return foodArray.count
}
func addfoodNoti(noti:Notification){
//let foodData = noti.userInfo as! String
let foodDic = noti.userInfo as! [String:String]
//let foodData = noti.userInfo as! String
//self.foodArray.insert(foodDic, at: 0)//這個語法比較不熟,故採用下面append新增
self.foodArray.append(foodDic)
let indexPath = IndexPath(row: 0, section: 0)
self.tableView.insertRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
self.tableView.reloadData()
}
func editfoodNoti(noti:Notification){
let notiDic = noti.userInfo as! [String:String]
let index = Int(notiDic["index"]!)//是為了將字串轉成Int,讓index變成數字
foodArray[index!] = notiDic
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell_id", for: indexPath)
//let dic = self.foodArray[indexPath.row]//也可不用設dic
//設定cell
cell.textLabel?.text = foodArray[indexPath.row]["name"]
cell.detailTextLabel?.text = foodArray[indexPath.row]["match"]
cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
// Configure the cell...
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
//新增刪除功能
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
self.foodArray.remove(at: indexPath.row)//必需先從foodArray移除,否則會crash
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "editview"{
if let indexPath = tableView.indexPathForSelectedRow {
let controller = segue.destination as! ViewController
var dic = foodArray[indexPath.row]
dic["index"] = String(indexPath.row)
controller.editdic = dic
}
}
}
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
5843760391118cb131a1872dabb7b01d3bd92e90
|
Swift
|
t-ae/SeveralPerformanceChecks
|
/Profiling/main.swift
|
UTF-8
| 226
| 2.59375
| 3
|
[] |
no_license
|
import Foundation
import SeveralPerformanceChecks
let count = 1_000_000
let a = MyArray<Float>(repeating: 0, count: count)
_ = a.filter { $0 < 0 }
let b = MyFloatArray(repeating: 0, count: count)
_ = b.filter { $0 < 0 }
| true
|
b044bad51e4c3054d433684309c7d2d59ec8c9ac
|
Swift
|
budingts/BJSB
|
/BJSB/BJSB/UIColorEx.swift
|
UTF-8
| 1,243
| 2.984375
| 3
|
[] |
no_license
|
//
// UIColorEx.swift
// MobileLesson
//
// Created by juanq on 15/10/23.
// Copyright © 2015年 Easytech. All rights reserved.
//
import Foundation
import UIKit
//MARK:----颜色部分
extension UIColor{
class func colorFromRGB (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat)->UIColor
{
return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a);
}
class func colorFromHEX (hexValue: UInt)->UIColor
{
return UIColor ( red: CGFloat((hexValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((hexValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(hexValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0));
}
class func colorWithHex(hex: String, alpha: CGFloat) -> UIColor {
var rgb: CUnsignedInt = 0;
let scanner = NSScanner(string: hex)
if hex.hasPrefix("#") {
// skip '#' character
scanner.scanLocation = 1
}
scanner.scanHexInt(&rgb)
let r = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
let g = CGFloat((rgb & 0xFF00) >> 8) / 255.0
let b = CGFloat(rgb & 0xFF) / 255.0
return UIColor(red: r, green: g, blue: b, alpha: alpha)
}
}
| true
|
24aa3c84f397ee492b07eef001802d6809ebe9b9
|
Swift
|
SDyakov/cl_test1
|
/Cl_test1/ViewController.swift
|
UTF-8
| 3,765
| 3.0625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Cl_test1
//
// Created by Admin on 25.09.17.
// Copyright © 2017 Admin. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
//ViewController - делегат протокола MKMapViewDelegate
mapView.delegate = self
//Установите широту и долготу местоположения
let sourceLocation = CLLocationCoordinate2D(latitude: 40.759011, longitude: -73.984472)
let destinitionLocation = CLLocationCoordinate2D(latitude: 40.748441, longitude: -73.985564)
//Создает объекты - метки, содержащие метки координаты местоположения
let sourcePlacemark = MKPlacemark(coordinate: sourceLocation, addressDictionary: nil)
let destinitionPlacemark = MKPlacemark(coordinate: destinitionLocation, addressDictionary: nil)
//MKMapItems используется для маршрутизации, инкапсулирует информацию о конкретной точке на карте
let sourceMapItem = MKMapItem(placemark: sourcePlacemark)
let destinitionMapItem = MKMapItem(placemark: destinitionPlacemark)
//Добавляются Аннотации, которые отображают название меток
let sourceAnnotation = MKPointAnnotation()
sourceAnnotation.title = "Times Square"
if let location = sourcePlacemark.location {
sourceAnnotation.coordinate = location.coordinate
}
let destinitionAnnotation = MKPointAnnotation()
destinitionAnnotation.title = "Empire State Building"
if let location = destinitionPlacemark.location {
destinitionAnnotation.coordinate = location.coordinate
}
//Аннотации отображаются на карте
self.mapView.showAnnotations([sourceAnnotation,destinitionAnnotation], animated: true)
//Класс MKDitecrionRequest используется для вычисление маршрута
let directionRequest = MKDirectionsRequest()
directionRequest.source = sourceMapItem
directionRequest.destination = destinitionMapItem
directionRequest.transportType = .automobile
let direction = MKDirections(request: directionRequest)
// Маршрут рисутеся с использованием полилиний
direction.calculate {
(response, error) -> Void in
guard let response = response else {
if let error = error {
print("Error: \(error)")
}
return
}
let route = response.routes[0]
self.mapView.add((route.polyline), level: MKOverlayLevel.aboveRoads)
let rect = route.polyline.boundingMapRect
self.mapView.setRegion(MKCoordinateRegionForMapRect(rect), animated: true)
}
}
// Возвращает объект рендера, который будет использоваться для рисования маршрута на карте
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay:overlay)
renderer.strokeColor = UIColor.red
renderer.lineWidth = 4.0
return renderer
}
}
| true
|
e2900adb6af83f86078a33daa69e0f11a325c9af
|
Swift
|
BenXia/WhateverPlayground
|
/testSwiftAlgorithm/TsetS/TsetSDocument.swift
|
UTF-8
| 15,617
| 2.703125
| 3
|
[] |
no_license
|
//
// TsetSDocument.swift
// TsetS
//
// Created by Ben on 2023/4/29.
//
import SwiftUI
import UniformTypeIdentifiers
extension UTType {
static var exampleText: UTType {
UTType(importedAs: "com.example.plain-text")
}
}
//class Solution {
// func dfsRecursive(_ n: Int, _ parent: Int, _ manager: inout [Int], _ informTime: inout [Int], _ currentInformTime: Int, _ maxTime: inout Int) {
// if currentInformTime + informTime[parent] > maxTime {
// maxTime = currentInformTime + informTime[parent]
// }
//
// for i in 0..<n {
// if manager[i] == parent {
// dfsRecursive(n, i, &manager, &informTime, currentInformTime + informTime[parent], &maxTime)
// }
// }
// }
//
// func numOfMinutes(_ n: Int, _ headID: Int, _ manager: [Int], _ informTime: [Int]) -> Int {
// var maxTime = 0
// var managerCopy = manager
// var informTimeCopy = informTime
//
// dfsRecursive(n, headID, &managerCopy, &informTimeCopy, informTime[headID], &maxTime)
//
// return maxTime
// }
//}
class DinnerPlates {
private var stackArray = [[Int]]()
private var notFullStackIndexArray = [Int]()
private var stackSize = 0
private var capacity = 0
init(_ capacity: Int) {
self.capacity = capacity
}
func push(_ val: Int) {
if self.stackSize == 0 {
var newPage = [Int](repeating:-1, count:self.capacity)
newPage[0] = val
self.stackArray.append(newPage)
self.stackSize += 1
if 1 < self.capacity {
self.notFullStackIndexArray.append(0)
}
} else {
if self.notFullStackIndexArray.count != 0 {
var firstNotFullStackIndex = self.notFullStackIndexArray[0]
var resultIndex = -1
for j in 0..<self.capacity {
if self.stackArray[firstNotFullStackIndex][j] == -1 {
resultIndex = j
self.stackArray[firstNotFullStackIndex][j] = val
break
}
}
if resultIndex == self.capacity - 1 {
self.notFullStackIndexArray.remove(at:0)
}
} else {
var newPage = [Int](repeating:-1, count:self.capacity)
newPage[0] = val
self.stackArray.append(newPage)
self.stackSize += 1
if 1 < self.capacity {
self.notFullStackIndexArray.append(self.stackArray.count - 1)
}
}
}
}
func pop() -> Int {
if self.stackSize == 0 {
return -1
} else {
var currentStackSize = self.stackSize
for i in 0..<currentStackSize {
if self.stackArray[currentStackSize - 1 - i][0] != -1 {
var result = -1, resultIndex = -1
for j in 0..<self.capacity {
if self.stackArray[currentStackSize - 1 - i][j] == -1 {
break;
} else {
result = self.stackArray[currentStackSize - 1 - i][j]
resultIndex = j
}
}
if resultIndex == 0 {
self.stackArray.remove(at:currentStackSize - 1 - i)
if self.notFullStackIndexArray.count > 0 && self.notFullStackIndexArray[self.notFullStackIndexArray.count - 1] == currentStackSize - 1 - i {
self.notFullStackIndexArray.remove(at:self.notFullStackIndexArray.count - 1)
}
} else {
self.stackArray[currentStackSize - 1 - i][resultIndex] = -1
if self.notFullStackIndexArray.count == 0 || self.notFullStackIndexArray[self.notFullStackIndexArray.count - 1] != currentStackSize - 1 - i {
self.notFullStackIndexArray.append(currentStackSize - 1 - i)
}
}
self.stackSize = self.stackArray.count
return result
} else {
self.stackArray.remove(at:currentStackSize - 1 - i)
if self.notFullStackIndexArray.count > 0 && self.notFullStackIndexArray[self.notFullStackIndexArray.count - 1] == currentStackSize - 1 - i {
self.notFullStackIndexArray.remove(at:self.notFullStackIndexArray.count - 1)
}
}
}
self.stackSize = self.stackArray.count
return -1
}
}
func popAtStack(_ index: Int) -> Int {
if self.stackSize > index {
var result = -1, resultIndex = -1
if self.stackArray[index][0] != -1 {
for i in 0..<self.capacity {
if self.stackArray[index][i] == -1 {
break;
} else {
resultIndex = i
result = self.stackArray[index][i]
}
}
}
if resultIndex == -1 {
// self.stackArray.remove(at:index)
// self.stackSize -= 1
} else {
self.stackArray[index][resultIndex] = -1
if resultIndex == 0 && index == self.stackArray.count - 1 {
self.stackArray.remove(at:self.stackArray.count - 1)
self.stackSize -= 1
if self.notFullStackIndexArray.count > 0 && self.notFullStackIndexArray[self.notFullStackIndexArray.count - 1] == index {
self.notFullStackIndexArray.remove(at:self.notFullStackIndexArray.count - 1)
}
return result
}
}
var left = 0, right = self.notFullStackIndexArray.count - 1, mid = 0, lastRight = self.notFullStackIndexArray.count
while left <= right {
mid = (left + right) / 2
if self.notFullStackIndexArray[mid] >= index {
lastRight = mid
right = mid - 1
} else {
left = mid + 1
}
}
if lastRight == self.notFullStackIndexArray.count {
self.notFullStackIndexArray.append(index)
} else if self.notFullStackIndexArray[lastRight] != index {
self.notFullStackIndexArray.append(index)
if lastRight <= self.notFullStackIndexArray.count - 2 {
var tmp = self.notFullStackIndexArray.count + lastRight
var end = self.notFullStackIndexArray.count - 1
// var count = self.notFullStackIndexArray.count - 2 - lastRight + 1
// for i in 0..<count {
// self.notFullStackIndexArray[self.notFullStackIndexArray.count - 1 - i] = self.notFullStackIndexArray[self.notFullStackIndexArray.count - 2 - i]
// }
for i in lastRight..<end {
self.notFullStackIndexArray[tmp - i - 1] = self.notFullStackIndexArray[tmp - i - 2]
}
}
self.notFullStackIndexArray[lastRight] = index
}
return result
} else {
return -1
}
}
}
//class Solution {
// func maxTotalFruits(_ fruits: [[Int]], _ startPos: Int, _ k: Int) -> Int {
// if fruits.count == 0 {
// return 0
// }
// if k == 0 {
// for i in 0..<fruits.count {
// if fruits[i][0] == startPos {
// return fruits[i][1]
// }
// }
//
// return 0
// }
//
// var minStart = startPos - k, maxStart = startPos, minEnd = startPos, maxEnd = startPos + k
// var endPosCount = [UInt](repeating:0, count:2 * k + 1)
// var endPrefixSum = [UInt](repeating:0, count:2 * k + 1)
// for i in 0..<fruits.count {
// if fruits[i][0] >= minStart && fruits[i][0] <= minStart + 2 * k {
// endPosCount[fruits[i][0] - minStart] = UInt(fruits[i][1])
// }
// }
// endPrefixSum[0] = endPosCount[0]
// for i in 1...2*k {
// endPrefixSum[i] = endPosCount[i] + endPrefixSum[i-1]
// }
//
// var maxCount: UInt = 0
// var endIndex = 0
// for i in 0...k {
// endIndex = k - (k - i) * 2 + k
// if endIndex < k {
// endIndex = k
// }
//
// if i == 0 {
// if endPrefixSum[endIndex] > maxCount {
// maxCount = endPrefixSum[endIndex]
// }
// } else {
// if endPrefixSum[endIndex] - endPrefixSum[i-1] > maxCount {
// maxCount = endPrefixSum[endIndex] - endPrefixSum[i-1]
// }
// }
// }
//
// return Int(maxCount)
// }
//}
class Solution {
func maxValueAfterReverse(_ nums: [Int]) -> Int {
if nums.count < 2 {
return 0
} else if nums.count == 2 {
return Swift.abs(nums[0] - nums[1])
}
var sumAbs = 0, cMaxAbs = 0, maxAbs = 0, maxI = 0, maxJ = nums.count - 1, absV = 0, absX1 = 0, absY1 = 0, absX2 = 0, absY2 = 0
var absArray = [Int]()
//[63674,-34608,86424,-52056,-3992,93347,2084,-28546,-75702,-28400]
//98282, 121032, 138480, 48064, 97339, 91263, 30630, 47156, 47302 = 719548
//[2,4,9,24,2,1,10]
//2,5,15,22,1,9
for i in 0..<nums.count - 1 {
absV = Swift.abs(nums[i] - nums[i+1])
absArray.append(absV)
maxAbs += absV
}
sumAbs = maxAbs
for i in 0..<nums.count - 1 {
if i == 0 {
absX1 = 0
} else {
absX1 = absArray[i-1]
}
for j in i+1..<nums.count {
if j == nums.count - 1 {
absY1 = 0
} else {
absY1 = absArray[j]
}
if i > 0 {
absX2 = Swift.abs(nums[i-1] - nums[j])
} else {
absX2 = 0
}
if j == nums.count - 1 {
absY2 = 0
} else {
absY2 = Swift.abs(nums[j+1] - nums[i])
}
cMaxAbs = sumAbs + absX2 + absY2 - absX1 - absY1
if cMaxAbs > maxAbs {
maxAbs = cMaxAbs
maxI = i
maxJ = j
}
}
}
return maxAbs
}
}
struct TsetSDocument: FileDocument {
var text: String
init(text: String = "Hello, world!") {
self.text = text
// var solution = Solution()
// solution.maxTotalFruits([[0,7],[7,4],[9,10],[12,6],[14,8],[16,5],[17,8],[19,4],[20,1],[21,3],[24,3],[25,3],[26,1],[28,10],[30,9],[31,6],[32,1],[37,5],[40,9]], 21, 30)
// let obj = DinnerPlates(2)
// obj.push(1)
// obj.push(2)
// obj.push(3)
// obj.push(4)
// obj.push(5)
//
// print("\(obj.popAtStack(0))")
//
// obj.push(20)
// obj.push(21)
//
// print("\(obj.popAtStack(0))")
// print("\(obj.popAtStack(2))")
//
// print("\(obj.pop)")
// print("\(obj.pop)")
// print("\(obj.pop)")
// print("\(obj.pop)")
// print("\(obj.pop)")
// ["DinnerPlates","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","popAtStack","popAtStack","popAtStack","popAtStack","popAtStack","popAtStack","popAtStack","popAtStack","popAtStack","popAtStack","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","push","pop","pop","pop","pop","pop","pop","pop","pop","pop","pop"]
//
//
// [[2],[373],[86],[395],[306],[370],[94],[41],[17],[387],[403],[66],[82],[27],[335],[252],[6],[269],[231],[35],[346],[4],[6],[2],[5],[2],[2],[7],[9],[8],[1],[474],[216],[256],[196],[332],[43],[75],[22],[273],[101],[11],[403],[33],[365],[338],[331],[134],[1],[250],[19],[],[],[],[],[],[],[],[],[],[]]
// let obj = DinnerPlates(2)
// obj.push(373)
// obj.push(86)
// obj.push(395)
// obj.push(306)
// obj.push(370)
//
// obj.push(94)
// obj.push(41)
// obj.push(17)
// obj.push(387)
// obj.push(403)
//
// obj.push(66)
// obj.push(82)
// obj.push(27)
// obj.push(335)
// obj.push(252)
//
// obj.push(6)
// obj.push(269)
// obj.push(231)
// obj.push(35)
// obj.push(346)
//
// print("\(obj.popAtStack(4))")
// print("\(obj.popAtStack(6))")
// print("\(obj.popAtStack(2))")
// print("\(obj.popAtStack(5))")
// print("\(obj.popAtStack(2))")
// print("\(obj.popAtStack(2))")
// print("\(obj.popAtStack(7))")
// print("\(obj.popAtStack(9))")
// print("\(obj.popAtStack(8))")
// print("\(obj.popAtStack(1))")
//
// obj.push(474)
// obj.push(216)
// obj.push(256)
// obj.push(196)
// obj.push(332)
// obj.push(43)
// obj.push(75)
// obj.push(22)
// obj.push(273)
// obj.push(101)
// obj.push(11)
// obj.push(403)
// obj.push(33)
// obj.push(365)
// obj.push(338)
// obj.push(331)
// obj.push(134)
// obj.push(1)
// obj.push(250)
// obj.push(19)
//
// print("\(obj.pop)")
// print("\(obj.pop)")
// print("\(obj.pop)")
// print("\(obj.pop)")
// print("\(obj.pop)")
// print("\(obj.pop)")
// print("\(obj.pop)")
// print("\(obj.pop)")
// print("\(obj.pop)")
// print("\(obj.pop)")
// let obj = DinnerPlates(2)
// obj.push(1)
// obj.push(2)
// obj.push(3)
// obj.push(4)
//
// print("\(obj.pop())")
//
// obj.push(4)
//
// print("\(obj.popAtStack(1))")
var solution = Solution()
// solution.maxValueAfterReverse([63674,-34608,86424,-52056,-3992,93347,2084,-28546,-75702,-28400])
// //98282, 121032, 138480, 48064, 97339, 91263, 30630, 47156, 47302 = 719548
solution.maxValueAfterReverse([2,4,9,24,2,1,10])
//2,5,15,22,1,9
}
static var readableContentTypes: [UTType] { [.exampleText] }
init(configuration: ReadConfiguration) throws {
guard let data = configuration.file.regularFileContents,
let string = String(data: data, encoding: .utf8)
else {
throw CocoaError(.fileReadCorruptFile)
}
text = string
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let data = text.data(using: .utf8)!
return .init(regularFileWithContents: data)
}
}
| true
|
87841f34dd9036a7f066e074146e22e11d5f3687
|
Swift
|
bvk4you/Crewards
|
/Crewards/FireStoreData/HDFCInfinia.swift
|
UTF-8
| 4,301
| 2.515625
| 3
|
[] |
no_license
|
//
// HDFCInfinia.swift
// Crewards
//
// Created by vabhaske on 03/08/20.
//
import Foundation
import Firebase
import FirebaseFirestoreSwift
struct HDFCInfinia {
let db = Firestore.firestore()
func create()->Void {
var newCard = Card(
title: "Infinia",
id: 2,
gracePeriod: "20-50",
bank: "HDFC",
interestPerMonth: 1.99,
creditLimit: 0,
partners: [],
contactLess: true,
eligibility: Eligibility(income: 0, ITR: 0, description: "N/A"),
brand: ["visa","master"],
categories: [CardCategory.grocery,CardCategory.shopping,CardCategory.insurance],
tier: ["premium"],
fees: Fees(joiningFees: 2999, renewalFees: 2999, welcomeRewards: WelcomeRewards(cashback: 0, points: 0, pointsValueinINR: 0, description: ""), waiverCondition: "Joining/Renewal Fee: Rs.2,999+Tax (Renewal Fee Waived on 3 Lakh spend)"),
cashAdvance: CashAdvance(limit: "Upto 80% of the credit limit, with a maximum of Rs. 15,000 per day", freeCreditPeriod: "None", financeCharges: 3.35, financeChargeDetails: "Upto Rs.25 or 3.35% per month (40.2% per annum) whichever is higher, from the date of withdrawal", fees: 2.5, feesDetails: "SBI ATMs or other ATMs: 2.5% of transaction amount, subject to a minimum of Rs. 500",internationATMS: "2.5% of transaction amount, subject to a minimum of Rs. 500"),
foreignTransactions: ForeignTransactions(markupFees: 3.5, rewardRate: 0.5),
insurance: Insurance(creditShield: 100000, airDeath: 5000000, medicalAbroad: 0),
rewards: RewardRate(entertainment:2.5, grocery: 2.5, shopping: 0, food: 2.5, travel: 0, others: 0.5,minRate:1.0,maxRate:6.0,utilityBills:5,expiryTime:0),
benefits: [BenefitsCategory.vouchers],
benefitsDetails: Benefits(
vouchers:[
Voucher(brand: "Welcome Gift",
description: "Welcome e-gift Voucher worth Rs. 3,000 from any of the following brands: Bata/Hush Puppies, Pantaloons, Aditya Birla Fashion, Shoppers Stop and Yatra.com",
value:3000.0,isMilestoneLinked: false),
Voucher(brand: "Yatra/Pantaloons",
description: "E-Gift Voucher worth Rs. 7,000 from Yatra.com/Pantaloons on achieving annual spends of Rs. 5 Lakhs",
value: 7000, isMilestoneLinked: true),
Voucher(brand:"Trident Privilege Membership",
description: "Enjoy complimentary Trident Privilege Red Tier Membership\\nGet exclusive 1,000 Welcome Points on registration",
value: 0,isMilestoneLinked: false),
Voucher(brand:"Club Visatara Membership",
description: "Enjoy Complimentary Club Vistara Silver membership",
value: 0, isMilestoneLinked: false),
Voucher(brand:"Pizza Hut",
description: "Get Pizza Hut e-Voucher worth Rs. 1,000 on achieving spends of Rs. 50,000 in a calendar quarter",
value:1000.0,isMilestoneLinked: true)],
loungeAccess:
LoungeAccess(
domesticAirports:
LoungeDetails(charges: 0, freeVisitsPerQuarter: 2, freeVisitsPerYear: 8, unlimited: false,
supplementaryBenefit: false, condtions: "Offer is valid for Primary Cardholders only",programOffering: "VISA/Mastercard"),
internationalAirports: [
LoungeDetails(charges: 28, freeVisitsPerQuarter: 2, freeVisitsPerYear: 4, unlimited: false,
supplementaryBenefit: false, condtions: "Offer is valid for Primary Cardholders only",programOffering: "Priority Pass")])),
highlightedColor: BrandColor(r: 1, g: 1, b: 1, alpha: 1.0),
shadowColor: BrandColor(r:0.5,g:0.5,b:0.5,alpha: 1.0),
gradientColor:[BrandColor(r: 0.149, g: 0.247, b: 0.623, alpha: 1.0),
BrandColor(r: 0.682, g: 0.301, b: 1, alpha: 1.0)]
)
let newCityRef = db.collection("Cards").document("HDFC Infinia")
try?newCityRef.setData(from:newCard)
}
}
| true
|
9164b7f383bcb06a87be2c6c3816d095a64e0a19
|
Swift
|
MariusLingurariu/MyYouTube
|
/MyYouTubeB02/Model/VideoDetailsModel.swift
|
UTF-8
| 1,056
| 2.609375
| 3
|
[] |
no_license
|
//
// VideoDetailsModel.swift
// MyYouTubeB02
//
// Created by Marius on 23/08/2018.
// Copyright © 2018 Marius. All rights reserved.
//
import Foundation
import SwiftyJSON
class VideoDetailsModel {
// MARK: - Public Properties
// MARK: - Private Properties
private(set) var snippet: Snippet
private(set) var viewCount: String!
private(set) var likeCount: String!
private(set) var dislikeCount: String!
private(set) var commentCount: String!
// MARK: - Public Methods
init() {
snippet = Snippet()
viewCount = ""
likeCount = ""
dislikeCount = ""
commentCount = ""
}
init(json: JSON) {
snippet = Snippet(json: json["snippet"])
viewCount = json["statistics"]["viewCount"].stringValue
likeCount = json["statistics"]["likeCount"].stringValue
dislikeCount = json["statistics"]["dislikeCount"].stringValue
commentCount = json["statistics"]["commentCount"].stringValue
}
// MARK: - Private Methods
}
| true
|
5468e9805077a3325364d6895499f65b27babae0
|
Swift
|
jacobmiller22/CollegeTransit
|
/CollegeTransit/Views/BusView.swift
|
UTF-8
| 1,844
| 2.75
| 3
|
[] |
no_license
|
//
// BusView.swift
// CollegeTransit
//
// Created by Jacob Miller on 2/25/20.
// Copyright © 2020 Jacob Miller. All rights reserved.
//
import SwiftUI
struct BusView: View {
@EnvironmentObject var uPrefs: UPrefDelegate
@State var showDetail = false;
var bus: Bus
var body: some View {
VStack(alignment: .leading){
HStack{
Text(bus.patternName)
.font(.headline)
.foregroundColor(Color.gray)
Spacer()
VStack{
if (uPrefs.starredRoutes.contains(bus.routeId)){
Image(systemName: "star.fill")
.foregroundColor(Color.systemYellow)
}
}
}
if(showDetail){
VStack(alignment: .leading){
HStack{
Text("Route:")
Spacer()
Text("\(bus.routeId)")
}
HStack{
Text("Passengers:")
Spacer()
Text("\(bus.passengers!)")
}
HStack{
Text("Stop ID:")
Spacer()
Text("\(bus.stopId)")
}
HStack{
Text("ID:")
Spacer()
Text("\(bus.id)")
}
}
.font(.caption)
.foregroundColor(Color.gray)
}
}
.onTapGesture{
self.showDetail.toggle()
}
.animation(.spring(response: 0.01, dampingFraction: 1, blendDuration: 1))
}
}
| true
|
3448258fefef5627a64b4e38160c2ea1c98d5006
|
Swift
|
to4iki/VideoPlayer
|
/VideoPlayer/presentation/view/PlayerSeekView.swift
|
UTF-8
| 944
| 2.8125
| 3
|
[] |
no_license
|
import UIKit
import RxSwift
import RxCocoa
final class PlayerSeekView: UIStackView {
@IBOutlet private weak var currentTimeLabel: UILabel!
@IBOutlet private weak var slider: UISlider!
@IBOutlet private weak var durationTimeLabel: UILabel!
private let disposeBag = DisposeBag()
func bind(current time: Driver<Float>, duration: Driver<Float>) {
Driver.combineLatest(time, duration)
.map(progress)
.drive(slider.rx.value)
.disposed(by: disposeBag)
time
.map { $0.format(template: .minutes) }
.drive(currentTimeLabel.rx.text)
.disposed(by: disposeBag)
duration
.map { $0.format(template: .minutes) }
.drive(durationTimeLabel.rx.text)
.disposed(by: disposeBag)
}
private func progress(current time: Float, duration: Float) -> Float {
return min((time / duration), 1)
}
}
| true
|
cc5a1dcf6d10c00bf377a3f9275dc6d13aebc7b1
|
Swift
|
sinakhanjani/nerkh
|
/Sources/App/Models/Message.swift
|
UTF-8
| 2,028
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// Notification.swift
// App
//
// Created by Sina khanjani on 12/19/1398 AP.
//
import Foundation
import Vapor
import FluentPostgreSQL
import Authentication
final class Message: Codable {
var id: UUID?
var title: String
var description: String?
var userID: User.ID
var adminID: Admin.ID
var createdAt: Date?
var updatedAt: Date?
static let createdAtKey: TimestampKey? = \.createdAt
static let updatedAtKey: TimestampKey? = \.updatedAt
init(title: String, description: String?, userID: User.ID, adminID: Admin.ID) {
self.title = title
self.description = description
self.userID = userID
self.adminID = adminID
}
final class Public: Codable {
var id: UUID?
var title: String
var description: String?
var userID: User.ID
var responder: String?
var createdAt: Date?
var updatedAt: Date?
static let createdAtKey: TimestampKey? = \.createdAt
static let updatedAtKey: TimestampKey? = \.updatedAt
init(title: String, description: String?, userID: User.ID, responder: String?) {
self.title = title
self.description = description
self.userID = userID
self.responder = responder
}
}
}
extension Message {
func added() throws -> Message {
return self
}
func update(message: Message) -> Message {
return self
}
func remove() throws -> Message {
return self
}
func edit(_ notification: Message) throws -> Message {
return self
}
}
extension Message {
var user: Parent<Message, User> {
return self.parent(\.userID)
}
var admin: Parent<Message, Admin> {
return self.parent(\.userID)
}
}
extension Message: PostgreSQLUUIDModel {}
extension Message: Migration {}
extension Message: Parameter {}
extension Message: Content {}
extension Message.Public: Content {}
| true
|
f8eabf3233a3e4ca86d49add37f869a5132c75af
|
Swift
|
Luzo/FBQuest
|
/FBQuest/Feature/Slides/Model/TopicSlide.swift
|
UTF-8
| 436
| 2.546875
| 3
|
[] |
no_license
|
//
// TopicSlide.swift
// FBQuest
//
// Created by Lubos Lehota on 28/05/2017.
// Copyright © 2017 LubosLehota. All rights reserved.
//
import ObjectMapper
struct TopicSlide: Mappable {
var title: String?
var description: String?
var image: String?
init?(map: Map) {}
mutating func mapping(map: Map) {
title <- map["title"]
description <- map["description"]
image <- map["image"]
}
}
| true
|
51c2bc4bf471be1953f08dcfa1080291eedebc10
|
Swift
|
imalberto/03Homework
|
/03Homework-beta/HeadlineViewController.swift
|
UTF-8
| 13,669
| 2.515625
| 3
|
[] |
no_license
|
//
// HeadlineViewController.swift
// 03Homework-beta
//
// Created by albertoc on 6/20/14.
// Copyright (c) 2014 AC. All rights reserved.
//
import UIKit
class HeadlineViewController: UIViewController, UIGestureRecognizerDelegate {
var originalTransform: CGAffineTransform!
var images:String[] = ["headline10", "headline11"]
var imageIndex: Int = 0
var timer: NSTimer! = nil
var invView:UIView!
// Once the view is loaded, calculate the increment value that
// the opacity should be changed in order to go from 0->1, or 1->0 based
// on the height of self.view
var opacityIncrement: CGFloat!
// Keep state of the headlineView starting position.
// These two variables should be updated in sync.
var startContainerViewFrame:CGRect! // only top or bottom
var startHeadlineTopPosition: Bool = true
// Keep state of which direction the drag is happening to handle the
// following use cases:
// 1. If start from the top, and last know drag was up, restore
// 2. If start from the bottom, and last known drag was down, restore
var lastKnownVelocity:CGPoint = CGPointMake(0, 0)
// TODO why init with false ?
var draggingDown: Bool!
@IBOutlet var panGestureRecognizer: UIPanGestureRecognizer
@IBOutlet var headlineImageView: UIImageView
@IBOutlet var newsFeedScrollView: UIScrollView
@IBOutlet var containerView: UIView
@IBOutlet var newsFeedImageView: UIImageView
@IBOutlet var newsFeedPanGestureRecognizer: UIPanGestureRecognizer
// Tap recognizer on the HeadlineImageView
@IBAction func onTap(sender: UITapGestureRecognizer) {
// NSLog("onTap")
if self.timer == nil {
timer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "updateHeadlines", userInfo: nil, repeats: true)
NSLog("timer started")
} else {
timer.invalidate()
timer = nil
NSLog("timer stopped")
}
// self.imageIndex = (self.imageIndex + 1) % 2
// self.updateHeadlines()
}
// Pan recognizer on the HeadlineImageView
@IBAction func onPan(sender: UIPanGestureRecognizer) {
var frame:CGRect = self.containerView.frame
var newFrame: CGRect!
// Restore to original position
func restoreWithOptions(options: UIViewAnimationOptions) {
UIView.animateWithDuration(0.35, delay: 0.0, options: options, animations: {
self.containerView.frame = self.startContainerViewFrame
}, completion: { (Bool) -> Void in
if self.startHeadlineTopPosition {
self.invView.layer.opacity = 1.0
} else {
self.invView.layer.opacity = 0.0
}
})
}
let location = sender.locationInView(self.containerView)
let translation = sender.translationInView(self.containerView)
let velocity = sender.velocityInView(self.containerView)
// detect if user is dragging outside of the headlineImageView and ignore
let inView = sender.locationInView(self.containerView)
// NSLog("location = %@", NSStringFromCGPoint(location)) // where the touch is
// NSLog("%@", NSStringFromCGPoint(translation))
// NSLog("inView = %@", NSStringFromCGPoint(inView))
switch (sender.state) {
case .Began:
self.startContainerViewFrame = frame
// NSLog("[begin] translation.y = %f, velocity.y = %f", translation.y, velocity.y)
self.draggingDown = false
if velocity.y > 0.0 {
self.draggingDown = true
}
// self.draggingDown == true ? NSLog("[begin] dragging DOWN") : NSLog("[begin] dragging UP")
// Store current velocity to decide if user changed the panning direction
// in .Changed
self.lastKnownVelocity = velocity
case .Changed:
NSLog("[changed] velocity = %@", NSStringFromCGPoint(velocity))
// Track which direction user is dragging
if self.startHeadlineTopPosition == true && self.lastKnownVelocity.x == 0 && self.lastKnownVelocity.y == 0 {
// keep the current self.draggingDown
} else {
if velocity.x * lastKnownVelocity.x + velocity.y * lastKnownVelocity.y > 0.0 {
// NSLog("Same direction")
} else {
// NSLog("Reverse direction")
self.draggingDown = !self.draggingDown
}
lastKnownVelocity = velocity;
}
// self.draggingDown == true ? NSLog("[begin] dragging DOWN") : NSLog("[begin] dragging UP")
// Increase drag force if necessary
if (frame.origin.y < 0.0) {
newFrame = CGRectMake(frame.origin.x,
(self.startContainerViewFrame.origin.y + translation.y) / 10.0,
frame.size.width,
frame.size.height)
} else {
// Move the headlines with the same distance as the finger is dragging
newFrame = CGRectMake(frame.origin.x,
self.startContainerViewFrame.origin.y + translation.y,
frame.size.width,
frame.size.height)
}
self.containerView.frame = newFrame
// Animate alpha as user is dragging (in points)
let incOpacity: Float = 1.0 / 60.0
// TODO more sophistication is required here
if velocity.y > 0 {
if (self.invView.layer.opacity - incOpacity) > 0.0 {
self.invView.layer.opacity -= incOpacity
}
} else {
if (self.invView.layer.opacity + incOpacity) < 1.0 {
self.invView.layer.opacity += incOpacity
}
}
// NSLog("invView.layer.opacity = %f", self.invView.layer.opacity)
case .Ended:
// Depending on the starting position, and the last known dragging
// direction, decide if headlineView should be restored ?
if self.startHeadlineTopPosition && !self.draggingDown {
// NSLog("restore top position")
restoreWithOptions(UIViewAnimationOptions.CurveEaseOut)
return
}
if !self.startHeadlineTopPosition && self.draggingDown {
// NSLog("restore bottom position")
restoreWithOptions(UIViewAnimationOptions.CurveEaseOut)
return
}
// How much vertical movement before we start animation
let y_offset:CGFloat = 3.0
// How much gap to leave after the animation complete when dragging down
let y_visible:CGFloat = 54.0
var y_delta:CGFloat = velocity.y
var options:UIViewAnimationOptions = UIViewAnimationOptions.CurveEaseOut
if y_delta < 0 {
y_delta *= -1
}
// First, let's determine if we were dragging up or down
if (velocity.y > 0) {
// moving down
if y_delta >= y_offset {
UIView.animateWithDuration(0.35, delay: 0.0, options: options, animations: {
newFrame = CGRectMake(frame.origin.x,
self.view.frame.size.height - y_visible,
frame.size.width,
frame.size.height)
self.containerView.frame = newFrame
self.invView.layer.opacity = 0.0
}, completion: { (Bool) -> Void in
// NSLog("done")
self.startContainerViewFrame = newFrame
self.startHeadlineTopPosition = false
})
} else {
restoreWithOptions(options)
}
} else if velocity.y < 0 {
// moving up
// User would have to move up a bit more to start the animation up
if y_delta >= (y_offset / 2.0) {
UIView.animateWithDuration(0.35, delay: 0.0, options: options, animations: {
newFrame = CGRectMake(frame.origin.x, 0.0, frame.size.width, frame.size.height)
self.containerView.frame = newFrame
self.invView.layer.opacity = 1.0
}, completion: { (Bool) -> Void in
// NSLog("done")
self.startContainerViewFrame = newFrame
self.startHeadlineTopPosition = true
})
} else {
restoreWithOptions(options)
}
} else {
NSLog("NO OP")
}
case .Cancelled:
let xx = 1.0
default:
let xx = 1.0
}
}
// Pan recognizer on the NewsFeedImageView
@IBAction func onPanNewsFeed(sender: UIPanGestureRecognizer) {
let translation = sender.translationInView(self.newsFeedImageView)
let velocity = sender.velocityInView(self.newsFeedImageView)
var baseScale = 1.0
var transform: CGAffineTransform!
var scale:CGFloat = 1.0
var scalex: CGFloat!
var scaley: CGFloat!
if abs(translation.y) > abs(translation.x) {
switch (sender.state) {
// case .Ended:
case .Began:
self.originalTransform = self.newsFeedScrollView.transform
scale = self.originalTransform.tx
NSLog("[begin] scale = %f", scale)
case .Changed:
// NSLog("pan newsfeed")
scalex = self.newsFeedImageView.transform.tx
scaley = self.newsFeedImageView.transform.ty
// NSLog("scalex = %f, scaley = %f", scalex, scaley)
// NSLog("translation = %@", NSStringFromCGPoint(translation))
// NSLog("velocity = %@", NSStringFromCGPoint(velocity))
if velocity.y > 0.0 {
if scale > 1.0 {
// reduce
NSLog("PRE scale = %f", scale)
scale = scale - abs(translation.y) / 160.0
NSLog("POST scale = %f", scale)
}
} else {
if scale >= 1.0 {
// increase
scale = 1.0 + abs(translation.y) / 160.0
// transform = CGAffineTransformMakeScale(1.1, 1.1)
}
}
NSLog("scale = %f", scale)
// transform = CGAffineTransformScale(self.originalTransform, scale, scale)
// self.newsFeedScrollView.transform = transform
default:
NSLog("-")
}
}
}
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.clearColor()
self.containerView.backgroundColor = UIColor.clearColor()
self.headlineImageView.backgroundColor = UIColor.clearColor()
self.headlineImageView.layer.cornerRadius = 5.0
self.headlineImageView.layer.masksToBounds = true
// Add a view behind the container view that changes alpa
self.invView = UIView(frame: self.view.bounds)
self.invView.backgroundColor = UIColor.blackColor()
self.invView.layer.opacity = 1.0
self.view.insertSubview(self.invView, belowSubview: self.containerView)
// Compute the amount that opacity of the background should change
// as the headlineView is dragged
self.opacityIncrement = (1.0 / self.view.frame.height)
// add the newsfeed image view to the scrollview
self.newsFeedScrollView.scrollsToTop = false
self.newsFeedScrollView.backgroundColor = UIColor.clearColor()
self.newsFeedScrollView.directionalLockEnabled = true
self.newsFeedScrollView.alwaysBounceVertical = false
self.newsFeedPanGestureRecognizer.delegate = self
self.newsFeedImageView.image = UIImage(named: "news")
self.newsFeedImageView.sizeThatFits(self.newsFeedImageView.image.size)
self.newsFeedImageView.frame = CGRectMake(0, 0, self.newsFeedImageView.image.size.width, self.newsFeedImageView.image.size.height)
// NSLog("Image size: %@", NSStringFromCGSize(self.newsFeedImageView.image.size))
// NSLog("Image frame: %@", NSStringFromCGRect(self.newsFeedImageView.frame))
self.newsFeedScrollView.addSubview(self.newsFeedImageView)
self.newsFeedScrollView.contentSize = self.newsFeedImageView.image.size
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
func updateHeadlines() {
self.imageIndex = (self.imageIndex + 1) % 2
let toImage = UIImage(named:self.images[self.imageIndex])
UIView.transitionWithView(self.headlineImageView, duration: 0.7, options: .TransitionCrossDissolve, animations: {
self.headlineImageView.image = toImage
}, completion: { (Bool) -> Void in
// NSLog("transition done")
})
}
// @optional func gestureRecognizer(gestureRecognizer: UIGestureRecognizer!, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer!) -> Bool
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer!, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer!) -> Bool {
var result = false
let re: UIPanGestureRecognizer = gestureRecognizer as UIPanGestureRecognizer
let trans = re.translationInView(self.newsFeedImageView)
// Only recoginize both gestures when moving "horizontal"
// Filter for only "vertical" movement in ur gestureRecognizer
if abs(trans.x) > abs(trans.y) {
result = true
}
// result == true ? NSLog("recog") : NSLog("no recog")
return result
}
// @optional func gestureRecognizer(gestureRecognizer: UIGestureRecognizer!, shouldRequireFailureOfGestureRecognizer otherGestureRecognizer: UIGestureRecognizer!) -> Bool
}
| true
|
45a90df8a5bdf09058a7c7a0da33ae13c3670b48
|
Swift
|
mbrandonw/project-euler-swift-playgrounds
|
/5/project-euler-5.playground/section-1.swift
|
UTF-8
| 4,183
| 4.34375
| 4
|
[
"MIT"
] |
permissive
|
import Foundation
/*========================================================
================= Problem #6 ===========================
========================================================
https://projecteuler.net/problem=5
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
========================================================
========================================================
======================================================== */
/**
Naive solution:
The playground has trouble with plugging in 20, so
use at your own risk.
*/
func naiveEuler5 (n: Int) -> Int {
var answer = 0
while true {
answer += n
var allDivisible = true
for d in 2..<n {
if answer % d != 0 {
allDivisible = false
break
}
}
if allDivisible {
return answer
}
}
}
/**
Smarter solution:
The problem is essentially asking for the least common multiple
of 1 through 20. The easy way to do this is probably to factor
each of the numbers (since they are so small) and gather all
of their prime factors. We can also use the observation that
lcm(1, 2, ..., 20) = lcm(10, 11, ..., 20)
since all of the numbers in the first half of the range [1, 20]
appear as factors in the numbers in the second half of the range.
*/
// Truncates a sequence by using a predicate.
func takeWhile <S: SequenceType> (p: S.Generator.Element -> Bool) -> S -> [S.Generator.Element] {
return {sequence in
var taken: [S.Generator.Element] = []
for s in sequence {
if p(s) {
taken.append(s)
} else {
break
}
}
return taken
}
}
// A sequence to generate prime numbers.
struct PrimeSequence : SequenceType {
func generate() -> GeneratorOf<Int> {
var knownPrimes: [Int] = []
return GeneratorOf<Int>() {
if let lastPrime = knownPrimes.last {
var possiblePrime = lastPrime+1
while true {
let sqrtPossiblePrime = Int(sqrtf(Float(possiblePrime)))
var somePrimeDivides = false
for prime in knownPrimes {
// Sieve of Eratosthenes
if prime > sqrtPossiblePrime {
break
}
if possiblePrime % prime == 0 {
somePrimeDivides = true
break
}
}
if somePrimeDivides {
possiblePrime++
} else {
break
}
}
knownPrimes.append(possiblePrime)
return possiblePrime
} else {
knownPrimes.append(2)
return 2
}
}
}
}
// Easy integer exponentiation
infix operator ** {}
func ** (lhs: Int, rhs: Int) -> Int {
return Int(pow(Float(lhs), Float(rhs)))
}
// Returns a dictionary mapping primes to powers in an
// integer's factorization.
func primeFactorization (n: Int) -> [Int:Int] {
let primes = takeWhile { $0 <= n } (PrimeSequence())
let sqrtN = Int(sqrtf(Float(n)))
return primes.reduce([Int:Int]()) { accum, prime in
var r = accum
for power in 1...n {
if n % (prime ** power) != 0 {
if power != 1 {
r[prime] = power-1
}
break
}
}
return r
}
}
func smartEuler5 (n: Int) -> Int {
let a = Int(n/2) + 1
// Prime/power factors of LCM of 11-20
let factors = Array(a...n)
.map { primeFactorization($0) }
.reduce([Int:Int]()) { accum, factorization in
var r = accum
for (prime, power) in factorization {
if let currentPower = accum[prime] {
r[prime] = max(power, currentPower)
} else {
r[prime] = power
}
}
return r
}
return Array(factors.keys).reduce (1) { accum, prime in accum * (prime ** factors[prime]!) }
}
smartEuler5(10)
naiveEuler5(10)
smartEuler5(20)
//naiveEuler5(20) // <-- takes too long, use at your own risk
// Let's go crazy and solve the problem for 42! This
// is the biggest number we can plug into `smartEuler5`
// before we get an integer overflow
smartEuler5(42)
"done"
| true
|
d34404f537f35b5e2119e6136aae601890b6e43b
|
Swift
|
Nirajpaul2/contacts-cleanswiftvip-sqlite-ios
|
/Contacts/Utils/Extensions/UIViewController+StatusBar.swift
|
UTF-8
| 1,009
| 2.765625
| 3
|
[] |
no_license
|
//
// UIViewController+StatusBar.swift
// Contacts
//
// Created by Glenn Posadas on 3/26/21.
// Copyright © 2021 Outliant. All rights reserved.
//
import UIKit
extension UIViewController {
/// A helper function that can be called from any controller.
/// Example: `navigationController?.setStatusBarAppearance()`.
func setStatusBarAppearance(
statusBarShouldBeHidden hidden: Bool,
statusBarAnimationStyle: UIStatusBarAnimation = .slide,
statusBarStyle: UIStatusBarStyle = .lightContent
) {
func set(controller: BaseNavigationController) {
controller.statusBarShouldBeHidden = hidden
controller.statusBarAnimationStyle = statusBarAnimationStyle
controller.statusBarStyle = statusBarStyle
controller.updateStatusBarAppearance()
}
if let controller = self as? BaseNavigationController {
set(controller: controller)
} else if let controller = self.navigationController as? BaseNavigationController {
set(controller: controller)
}
}
}
| true
|
c2b8f408b598a6cc188bcdf56eff2454baf8ede0
|
Swift
|
swiftymf/SwiftLocation
|
/Sources/SwiftLocation/Requests/Auto Complete/AutoComplete+Support.swift
|
UTF-8
| 7,268
| 3.21875
| 3
|
[
"MIT",
"CC-BY-3.0"
] |
permissive
|
//
// SwiftLocation - Efficient Location Tracking for iOS
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: hello@danielemargutti.com
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
import Foundation
import MapKit
import CoreLocation
public extension AutoCompleteRequest {
/// Service to use.
///
/// - apple: apple service.
/// - google: google service.
/// - openStreet: open streep map service.
enum Service: CustomStringConvertible {
case apple(Options?)
case google(GoogleOptions)
public static var all: [Service] {
return [.apple(nil), .google(GoogleOptions(APIKey: ""))]
}
public var description: String {
switch self {
case .apple: return "Apple"
case .google: return "Google"
}
}
}
/// Type of autocomplete operation.
///
/// - partialSearch: it's a partial search operation. Usually it's used when you need to provide a search
/// inside search boxes of the map. Once you have the full query or the address you can
/// use a placeDetail search to retrive more info about the place.
/// - placeDetail: when you have a full search query (from services like apple) or the place id (from service like google)
/// you can use this operation to retrive more info about the place.
enum Operation: CustomStringConvertible {
case partialSearch(String)
case placeDetail(String)
public static var all: [Operation] {
return [.partialSearch(""),.placeDetail("")]
}
public var value: String {
switch self {
case .partialSearch(let v): return v
case .placeDetail(let v): return v
}
}
public var description: String {
switch self {
case .partialSearch: return "Partial Search"
case .placeDetail: return "Place Detail"
}
}
}
class Options {
// MARK: - Public Properties -
/// Type of autocomplete operation
/// By default is `.partialSearch`.
internal var operation: Operation = .partialSearch("")
/// The region that defines the geographic scope of the search.
/// Use this property to limit search results to the specified geographic area.
/// The default value is nil which for `AppleOptions` means a region that spans the entire world.
/// For other services when nil the entire parameter will be ignored.
public var region: MKCoordinateRegion?
// Use this property to determine whether you want completions that represent points-of-interest
// or whether completions might yield additional relevant query strings.
// The default value is set to `.locationAndQueries`:
// Points of interest and query suggestions.
/// Specify this value when you want both map-based points of interest and common
/// query terms used to find locations. For example, the search string “cof” yields a completion for “coffee”.
public var filter: MKLocalSearchCompleter.FilterType = .locationsAndQueries
// MARK: - Private Methods -
/// Return server parameters to compose the url.
///
/// - Returns: URL
internal func serverParams() -> [URLQueryItem] {
return []
}
public init() { }
}
class GoogleOptions: Options {
/// API Key for searvice.
public var APIKey: String?
/// Restrict results from a Place Autocomplete request to be of a certain type.
/// See: https://developers.google.com/places/web-service/autocomplete#place_types
///
/// - geocode: return only geocoding results, rather than business results.
/// - address: return only geocoding results with a precise address.
/// - establishment: return only business results.
/// - regions: return any result matching the following types: `locality, sublocality, postal_code, country, administrative_area_level_1, administrative_area_level_2`
/// - cities: return results that match `locality` or `administrative_area_level_3`.
public enum PlaceTypes: String {
case geocode
case address
case establishment
case regions
case cities
}
/// Restrict results to be of certain type, `nil` to ignore this filter.
public var placeTypes: Set<PlaceTypes>? = nil
/// The distance (in meters) within which to return place results.
/// Note that setting a radius biases results to the indicated area,
/// but may not fully restrict results to the specified area.
/// More info: https://developers.google.com/places/web-service/autocomplete#location_biasing
/// and https://developers.google.com/places/web-service/autocomplete#location_restrict.
public var radius: Float? = nil
/// Returns only those places that are strictly within the region defined by location and radius.
/// This is a restriction, rather than a bias, meaning that results outside this region will
/// not be returned even if they match the user input.
public var strictBounds: Bool = false
/// The language code, indicating in which language the results should be returned, if possible.
public var locale: String?
/// A grouping of places to which you would like to restrict your results up to 5 countries.
/// Countries must be added in ISO3166-1_alpha-2 version you can found:
/// https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2.
public var countries: Set<String>?
public init(APIKey: String?) {
self.APIKey = APIKey
}
// MARK: - Private Functions -
internal override func serverParams() -> [URLQueryItem] {
var list = [URLQueryItem]()
if let placeTypes = self.placeTypes {
list.append(URLQueryItem(name: "types", value: placeTypes.map { $0.rawValue }.joined(separator: ",")))
}
if let radius = self.radius {
list.append(URLQueryItem(name: "radius", value: String(radius)))
}
if self.strictBounds == true {
list.append(URLQueryItem(name: "strictbounds", value: nil))
}
if let locale = self.locale {
list.append(URLQueryItem(name: "language", value: locale.lowercased()))
}
if let countries = self.countries {
list.append(URLQueryItem(name: "components", value: countries.map {
return "country:\($0)"
}.joined(separator: "|")))
}
return list
}
}
}
| true
|
6606180db4839b9f11d02ccd707474522755c968
|
Swift
|
twof/DatasAndAlgos
|
/DatasAndAlgos/TestingHelpers.swift
|
UTF-8
| 1,899
| 2.78125
| 3
|
[] |
no_license
|
//
// TestingHelpers.swift
// DatasAndAlgos
//
// Created by Carter Appleton on 9/11/16.
// Copyright © 2016 Carter Appleton. All rights reserved.
//
func testFunction<E: Equatable>(testCase: String, inputs: [([E]?,[E]?)]) {
print("Starting Testing: \(testCase)")
var failedCases = ""
for (index,input) in inputs.enumerate() {
if let lhs = input.0, let rhs = input.1 {
if lhs != rhs {
failedCases += "\(index), "
}
} else if input.0 != nil || input.1 != nil {
failedCases += "\(index), "
}
}
if failedCases != "" {
print("- FAILED: [\(failedCases.substringToIndex(failedCases.endIndex.predecessor().predecessor()))]")
} else {
print("- SUCCESS")
}
print("")
}
func testFunction<E: Equatable>(testCase: String, inputs: [(E?,E?)]) {
print("Starting Testing: \(testCase)")
var failedCases = ""
for (index,input) in inputs.enumerate() {
if let lhs = input.0, let rhs = input.1 {
if lhs != rhs {
failedCases += "\(index), "
}
} else if input.0 != nil || input.1 != nil {
failedCases += "\(index), "
}
}
if failedCases != "" {
print("- FAILED: [\(failedCases.substringToIndex(failedCases.endIndex.predecessor().predecessor()))]")
} else {
print("- SUCCESS")
}
print("")
}
func testFunction(testCase: String, inputs: [(Bool,Bool)]) {
print("Starting Testing: \(testCase)")
var failedCases = ""
for (index,input) in inputs.enumerate() {
if input.0 != input.1 {
failedCases += "\(index), "
}
}
if failedCases != "" {
print("- FAILED: [\(failedCases.substringToIndex(failedCases.endIndex.predecessor().predecessor()))]")
} else {
print("- SUCCESS")
}
print("")
}
| true
|
b3065f9c81d9fa0b85f2182c27d941c826bf000e
|
Swift
|
digime/digime-sdk-ios
|
/Examples/Genrefy/Genrefy/Activities/Analysis/AccountTableViewCell.swift
|
UTF-8
| 2,079
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// AccountTableViewCell.swift
// Genrefy
//
// Created on 19/07/2018.
// Copyright © 2018 digi.me. All rights reserved.
//
import Kingfisher
import UIKit
class AccountTableViewCell: UITableViewCell {
@IBOutlet weak var logoImageView: RoundedImageView!
@IBOutlet weak var serviceNameLabel: UILabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var switchView: UISwitch!
private var switchChangedCallback: ((String) -> Void)?
private var uid: String = ""
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.selectionStyle = .none
switchView.addTarget(self, action: #selector(switchChanged(_:)), for: .valueChanged)
}
@objc private func switchChanged(_ switchView: UISwitch) {
let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()
switchChangedCallback?(uid)
}
}
extension AccountTableViewCell: AccountCell {
var accountIdentifier: String {
return uid
}
func setSelectionChangedCallback(callback: @escaping ((String) -> Void)) {
self.switchChangedCallback = callback
}
func setAccountIdentifier(_ accountIdentifier: String) {
uid = accountIdentifier
}
func display(serviceName: String?) {
serviceNameLabel.text = serviceName
}
func display(accountName: String?) {
usernameLabel.text = accountName
}
func display(imageUrl: String?) {
guard
let imageUrl = imageUrl,
let url = URL(string: imageUrl) else {
logoImageView.image = nil
return
}
logoImageView.kf.indicatorType = .activity
logoImageView.kf.setImage(with: url)
}
func display(toggleable: Bool, selected: Bool, animated: Bool) {
switchView.isHidden = !toggleable
switchView.setOn(selected, animated: animated)
}
func display(icon: UIImage?) {
logoImageView.image = icon
}
}
| true
|
e0953e5fc7735e0bb9ae2efa6ff64b89810b4f56
|
Swift
|
sopt-ios/GithubSearch-Minyoung
|
/GithubSearch/GithubSearch/Network/SearchService.swift
|
UTF-8
| 2,037
| 2.75
| 3
|
[] |
no_license
|
//
// SearchService.swift
// GithubSearch
//
// Created by 구민영 on 08/02/2019.
// Copyright © 2019 구민영. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
struct SearchService : APIManager {
static let shared = SearchService()
let searchURL = url("/search/users")
let userURL = url("/users")
func getResultList(page: Int? = 1,
limit: Int = 20,
input : String,
completion : @escaping ([Items]) -> Void) {
let header: HTTPHeaders = [
"Authorization": ""
]
let queryURL = searchURL + "?q=\(input)&page=\(page ?? 1)&per_page=\(limit)"
Alamofire.request(queryURL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: header).responseObject { (res: DataResponse<ResponseArray<Items>>) in
switch res.result {
case .success:
guard let data = res.result.value else {return}
guard let itemList = data.items else {return}
completion(itemList)
case .failure(let err):
print(err)
}
}
}
func getNumOfRepos(name : String,
completion : @escaping (Int) -> Void) {
let header: HTTPHeaders = [
"Authorization": ""
]
let queryURL = userURL + "/" + name
Alamofire.request(queryURL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: header).responseObject { (res: DataResponse<ResponseBody>) in
switch res.result {
case .success:
guard let data = res.result.value else {return}
guard let reposNum = data.public_repos else {return}
completion(reposNum)
case .failure(let err):
print(err)
}
}
}
}
| true
|
e27071aeaaf4e74145a27217b4e456f4cbd0f0bd
|
Swift
|
chammchamm/chammApp
|
/chammApp/MapFlow/MapViewController.swift
|
UTF-8
| 3,445
| 2.515625
| 3
|
[] |
no_license
|
//
// MapViewController.swift
// chammApp
//
// Created by Jennifer Lin on 2019/6/24.
// Copyright © 2019 Jennifer Lin. All rights reserved.
//
import UIKit
import MapKit
import CoreLocation
class MapViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
// Location
let locationManager = CLLocationManager()
let regionRadius : CLLocationDistance = 10000
override func viewDidLoad() {
super.viewDidLoad()
//
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
mapView.delegate = self
mapView.showsUserLocation = true
//
let flag = MapFlag(
title: "客製化圖標",
locationName: "長榮大學",
description: "位於台灣台南市歸仁區",
coordinate: CLLocationCoordinate2D(
latitude: 22.910524,
longitude: 120.273730),
url: "https://www.cjcu.edu.tw")
mapView.addAnnotation(flag)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let annotation = annotation as? MapFlag else{
return nil
}
let identifier = "marker"
let annotationView : MKAnnotationView
if let dequeueView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKMarkerAnnotationView {
dequeueView.annotation = annotation
annotationView = dequeueView
}else{
annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
annotationView.canShowCallout = true
annotationView.calloutOffset = CGPoint( x: -5, y: 5)
let button = UIButton(type: .detailDisclosure)
annotationView.rightCalloutAccessoryView = button
button.addTarget(self, action: #selector(self.moveToWebView(sender:)), for: .touchUpInside)
}
return annotationView
}
func centerMapOnLocation( location : CLLocation ) {
let coordinateRegion = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: regionRadius, longitudinalMeters: regionRadius)
mapView.setRegion(coordinateRegion, animated: true)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let locValue : CLLocationCoordinate2D = manager.location?.coordinate else {
return
}
print("latitude:\( locValue.latitude ):longitude:\( locValue.longitude )")
centerMapOnLocation(location: manager.location! )
}
@objc func moveToWebView( sender : UIButton ){
DispatchQueue.main.async {
self.performSegue(withIdentifier: "moveToWebViewSegue", sender: self)
}
}
}
| true
|
3d6c22f7f8caccfa5545ac40f8c08a539f721b94
|
Swift
|
Gomay88/Tweeter
|
/Tweeter/Domain/GetTweetsInteractor.swift
|
UTF-8
| 446
| 2.875
| 3
|
[] |
no_license
|
import Foundation
protocol GetTweetsInteractor {
func execute(completion: @escaping (_ tweets: [Twit]) -> ())
}
class GetTweetsInteractorDefault: GetTweetsInteractor {
private var twitterRepository: TwitterRepository
init() {
twitterRepository = TwitterRepositoryDefault()
}
func execute(completion: @escaping (_ tweets: [Twit]) -> ()) {
twitterRepository.getTwits(completion: completion)
}
}
| true
|
de2988581e3d51624b5a624ba22ac265ce4da4eb
|
Swift
|
JoyceMatos/Albums
|
/PhotoAlbum/Photo.swift
|
UTF-8
| 1,974
| 3.375
| 3
|
[] |
no_license
|
//
// Photo.swift
// PhotoAlbum
//
// Created by Joyce Matos on 4/3/17.
// Copyright © 2017 Joyce Matos. All rights reserved.
//
import Foundation
import UIKit
final class Photo {
let albumID: Int
let id: Int
let title: String
let urlString: String
let thumbnailURLString: String
var image: UIImage?
var isDownloadingImage = false
var hashValue: Int {
return id.hashValue
}
init(JSON: JSON) {
self.albumID = JSON["albumId"] as! Int
self.id = JSON["id"] as! Int
self.title = JSON["title"] as! String
self.urlString = JSON["url"] as! String
self.thumbnailURLString = JSON["thumbnailUrl"] as! String
}
// NOTE: - Model should not handle this information. Extract functionality and perform any downloads in a networking layer
func downloadImage(handler: @escaping (Bool) -> Void) {
isDownloadingImage = true
let session = URLSession.shared
let url = URL(string: thumbnailURLString)!
let request = URLRequest(url: url)
session.dataTask(with: request, completionHandler: { data, response, error in
DispatchQueue.main.async {
guard let data = data,
let newImage = UIImage(data: data) else {
handler(false)
return
}
self.image = newImage
handler(true)
}
}).resume()
}
}
// NOTE: - This extension was created with the intension of making the Photos hashable so that I can create a dictionary of [Photo: Image] in the networking layer. Essentially, this dictionary would be used to populate the data models with the images without having to download the images themselves.
extension Photo: Hashable {
static func == (lhs: Photo, rhs: Photo) -> Bool {
return lhs.id == rhs.id && lhs.albumID == rhs.albumID
}
}
| true
|
ac4ee3707992f05c56e9a205f05e9daa3f2eefab
|
Swift
|
AleGiovanardi/FoodAppUI
|
/FoodAppUI/Views/RecipeOverview/RecipeInteractionView.swift
|
UTF-8
| 2,393
| 2.90625
| 3
|
[] |
no_license
|
//
// RecipeInteractionView.swift
// FoodAppUI
//
// Created by Muhammad Khan on 8/23/21.
//
import SwiftUI
struct RecipeInteractionView: View {
let recipe: RecipeItem
let index: Int
let count: Int
@ObservedObject var manager: RecipeManager
public var viewSpace: Namespace.ID //lets add some matched geometry effect
var body: some View {
ZStack {
Circle()
.stroke(
LinearGradient(
gradient: Gradient(colors: [
manager.currentRecipeIndex%2 == 0 ? Color.lightBackground.opacity(0.1) : Color.darkBackground.opacity(0.1),
Color.green, Color.green
]),
startPoint: .leading,
endPoint: .trailing),
lineWidth: 4
)
.scaleEffect(1.15)
.matchedGeometryEffect(id: "borderId", in: viewSpace, isSource: true)
ArrowShape(reachedTop: index == 0, reachedBottom: index == count - 1)
.stroke(Color.gray,
style: StrokeStyle(lineWidth: 2.5, lineCap: .round, lineJoin: .round))
.frame(width: UIScreen.screenWidth - 32, height: UIScreen.screenWidth - 32)
.scaleEffect(1.15)
.matchedGeometryEffect(id: "arrowId", in: viewSpace, isSource: true)
Image(recipe.imageName)
.resizable()
.scaledToFit()
.matchedGeometryEffect(id: "imageId", in: viewSpace, isSource: true)
// this circle will be used to drag interaction
Circle()
.fill(Color.black.opacity(0.001))
.scaleEffect(1.2)
.gesture(
DragGesture(minimumDistance: 10)
.onChanged({ value in
withAnimation {
manager.chageSwipeValue(value: value.translation.height)
}
})
.onEnded({ value in
withAnimation {
manager.swipeEnded(value: value.translation.height)
}
})
)
}
}
}
| true
|
535dcddb79e75f2cbcdbd8d01f003a77eea0ee68
|
Swift
|
Maggielon/SwiftUIStarter
|
/SwiftUIStarter/SwiftUIStarter/Tab/TabScreenView.swift
|
UTF-8
| 1,858
| 2.921875
| 3
|
[] |
no_license
|
//
// TabScreenView.swift
// SwiftUIStarter
//
// Created by Анастасия on 28.08.2020.
// Copyright © 2020 Анастасия. All rights reserved.
//
import SwiftUI
struct TabScreenView: View {
@State var showModal = false
@State private var selection = 0
//@State private var openRandomRowInList: Bool = false
@State private var randomSelectedIndex: Int?
var body: some View {
TabView(selection: $selection) {
FirstTabView(selection: $selection, randomSelectedIndex: $randomSelectedIndex)
.font(.title)
.tabItem {
VStack {
Image(systemName: "house")
Text("Home")
}
}
.tag(0)
SecondTabView(randomSelectedIndex: $randomSelectedIndex)
.font(.title)
.tabItem {
VStack {
Image(systemName: "list.bullet")
Text("List")
}
}
.tag(1)
VStack {
Text("Info")
Button(action: {
self.showModal = true
}) {
Text("Show Modal")
}.sheet(isPresented: $showModal) {
VStack {
ModalView()
}
}
}
.font(.title)
.tabItem {
VStack {
Image(systemName: "info.circle")
Text("About")
}
}
.tag(2)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
TabScreenView()
}
}
| true
|
6098507629c229ebdba11d5ada5dab23f49dc067
|
Swift
|
AlexeyKrestinin/Lesson2Krestinin
|
/Lesson2Krestinin/MacFonts.swift
|
UTF-8
| 627
| 2.84375
| 3
|
[] |
no_license
|
//
// MacFonts.swift
// Lesson2Krestinin
//
// Created by Алексей Крестинин on 05.03.17.
// Copyright © 2017 Alexey Krestinin. All rights reserved.
//
import Foundation
import UIKit
struct Fonts {
var fontName:[String]
let fontFamilyNames = UIFont.familyNames
func printFonts() -> [String] {
let fontFamilyNames = UIFont.familyNames
var result = [String]()
for familyName in fontFamilyNames {
let names = UIFont.fontNames(forFamilyName: familyName)
for name in names {
result.append (name)
}
}
return result
}
}
| true
|
b779dcc71eac6b0fda338b88b34101b55211bd5c
|
Swift
|
rahimizad/Peek
|
/Pod/Classes/Transformers/NSNumber+Transformer.swift
|
UTF-8
| 935
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// Float+Transformer.swift
// Peek
//
// Created by Shaps Mohsenin on 24/03/2016.
// Copyright © 2016 Snippex. All rights reserved.
//
import UIKit
final class NumberTransformer: NSValueTransformer {
private static var floatFormatter: NSNumberFormatter {
let formatter = NSNumberFormatter()
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 1
formatter.minimumIntegerDigits = 1
return formatter
}
override func transformedValue(value: AnyObject?) -> AnyObject? {
if let value = value as? NSNumber where value.isBool() {
return nil
}
if let value = value as? NSNumber where value.isFloat() {
return NumberTransformer.floatFormatter.stringFromNumber(value)!
}
if let value = value as? NSNumber {
return "\(value)"
}
return nil
}
override class func allowsReverseTransformation() -> Bool {
return false
}
}
| true
|
31859f7af89bee1a151840f627e1cd13d0ac86e5
|
Swift
|
megavolt605/CNLogo
|
/CNLogoCore/CNLCStatementIf.swift
|
UTF-8
| 3,079
| 2.578125
| 3
|
[] |
no_license
|
//
// CNLCStatementIf.swift
// CNLogoCore
//
// Created by Igor Smirnov on 08/04/16.
// Copyright © 2016 Complex Number. All rights reserved.
//
import Foundation
open class CNLCStatementIf: CNLCStatement {
override open var identifier: String {
return "IF"
}
var statementsElse: [CNLCStatement] = []
override open func prepare() -> CNLCBlockPrepareResult {
let result = super.prepare()
if result.isError { return result }
if executableParameters.count != 1 {
return CNLCBlockPrepareResult.error(block: self, error: .statementParameterCountMismatch(statementIdentifier: identifier, excpectedCount: 1, actualCount: executableParameters.count))
}
return result
}
open override func executeStatements() -> CNLCValue {
///
return .unknown
}
override open func execute(_ parameters: [CNLCExpression] = []) -> CNLCValue {
var result = super.execute(parameters)
if result.isError { return result }
CNLCEnviroment.defaultEnviroment.appendExecutionHistory(CNLCExecutionHistoryItemType.step, fromBlock: self)
if let value = executableParameters.first?.variableValue.execute() {
switch value {
case let .bool(condition):
let statementsToExecute = condition ? statements : statementsElse
for statement in statementsToExecute {
result = statement.execute()
if result.isError { return result }
}
default: return .error(block: self, error: .boolValueExpected)
}
}
return result
}
override open func store() -> [String: Any] {
var res = super.store()
res["statement-else"] = statementsElse.map { $0.store() }
return res
}
public init(executableParameters: [CNLCVariable], statements: [CNLCStatement] = [], statementsElse: [CNLCStatement] = []) {
super.init(executableParameters: executableParameters, statements: statements)
self.statementsElse = statementsElse
}
required public init(data: [String : AnyObject]) {
super.init(data: data)
if let info = data["statements-else"] as? [[String: Any]] {
statementsElse = info
.map { item in return CNLCStatement(data: item) }
} else {
statementsElse = []
}
}
public required init(statements: [CNLCStatement]) {
fatalError("init(statements:) has not been implemented")
}
public required init(executableParameters: [CNLCVariable]) {
fatalError("init(executableParameters:) has not been implemented")
}
public required init(executableParameters: [CNLCVariable], statements: [CNLCStatement]) {
super.init(executableParameters: executableParameters, statements: statements)
}
public required init(data: [String : Any]) {
fatalError("init(data:) has not been implemented")
}
}
| true
|
fb4f95b4c10df87f4d14a549dcaec25b5fa6d316
|
Swift
|
ecenurozsy/shopare
|
/Final/Final/ProductTableViewController.swift
|
UTF-8
| 2,342
| 2.546875
| 3
|
[] |
no_license
|
//
// ProductTableViewController.swift
// Final
//
// Created by ECENUR on 31.01.2021.
//
import UIKit
import Alamofire
class ProductTableViewController: UITableViewController{
var arr: [Bilgiler]? = []
override func viewDidLoad() {
super.viewDidLoad()
//http://jsonbulut.com/json/product.php?ref=5380f5dbcc3b1021f93ab24c3a1aac24&start=0
let params = [ "ref" : "5380f5dbcc3b1021f93ab24c3a1aac24", "start" : "0"]
let url = "http://jsonbulut.com/json/product.php"
AF.request(url, method: .get, parameters: params).responseJSON { (res) in
if (res.response?.statusCode == 200) {
let prod_json = try? JSONDecoder().decode(ProductData.self, from: res.data!)
self.arr = prod_json?.products[0].bilgiler
self.tableView.reloadData()
}
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arr!.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ShopCell
let item = arr![indexPath.row]
cell.pTitle.text = item.productName
cell.pPrice.text = item.price + "₺"
cell.pCategory.text = item.categories[0].categoryName
let url = URL(string: item.images[0].normal)
let data = try! Data(contentsOf: url!)
cell.img.image = UIImage(data: data)
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let item = arr![indexPath.row]
performSegue(withIdentifier: "goDetail", sender: item )
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if ( segue.identifier == "goDetail" ) {
let vc = segue.destination as! Detail
vc.item = sender as? Bilgiler
}
}
@IBAction func btnGoMyOrder(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "goMyOrder", sender: nil)
}
}
| true
|
07251e9f2750146c0845fd254e8af248713ae1c4
|
Swift
|
hovven/SaveManager
|
/SaveManager/SaveManager.swift
|
UTF-8
| 2,401
| 2.75
| 3
|
[] |
no_license
|
//
// SaveManager.swift
//
// Created by Hossein Vesali Naseh on 4/15/18.
// Copyright © 2018 Hoven. All rights reserved.
//
import Foundation
import UIKit
class SaveManager {
// MARK: Singleton
private static let instance = SaveManager()
class func sharedInstance () -> SaveManager {
return instance
}
// MARK: Manager
func save<T:Encodable>(object: T, key: SaveManagerKeys) {
do{
let encoder = JSONEncoder()
let encoded = try encoder.encode(object)
standard().set(encoded, forKey: key.rawValue)
}catch{
}
sync()
}
func save<T:Encodable>(array: [T], key: SaveManagerKeys) {
do{
let encoder = JSONEncoder()
let encoded = try encoder.encode(array)
standard().set(encoded, forKey: key.rawValue)
}catch{
}
sync()
}
func save (object: AnyObject, key: SaveManagerKeys) {
standard().set(object, forKey: key.rawValue)
sync()
}
func get (key: SaveManagerKeys) -> AnyObject? {
return standard().object(forKey: key.rawValue) as AnyObject
}
func get <T:Decodable> (key: SaveManagerKeys) -> T? {
do{
let jsonData : Data? = UserDefaults.standard.value(forKey: key.rawValue) as? Data
if let data = jsonData {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} else {
return nil
}
}catch{
}
return T.self as? T
}
func delete (key: SaveManagerKeys) {
standard().removeObject(forKey: key.rawValue)
sync()
}
func unarchive (key: SaveManagerKeys) -> AnyObject? {
if let data = get(key: key) as? NSData {
return NSKeyedUnarchiver.unarchiveObject(with: data as Data) as AnyObject
} else {
return nil
}
}
func archive (object: AnyObject, key: SaveManagerKeys) {
let data = NSKeyedArchiver.archivedData(withRootObject: object)
save (object: data as AnyObject, key: key)
}
// MARK: Helpers
func standard () -> UserDefaults {
return UserDefaults.standard
}
func sync () {
standard().synchronize()
}
}
| true
|
fb1d4317fae21910d61a8b02e7ade3aa73b79d6c
|
Swift
|
mattmega4/InstaCreatureGram
|
/InstaCreatureGram/User.swift
|
UTF-8
| 2,298
| 2.796875
| 3
|
[] |
no_license
|
//
// User.swift
// InstaCreatureGram
//
// Created by Rafael Auriemo on 2/8/16.
// Copyright © 2016 Matthew Howes Singleton. All rights reserved.
//
import UIKit
class User: NSObject {
let myRootRef = Firebase(url: FirebaseUrl)
let userDefaults = NSUserDefaults()
func createNewUser(email:String, password:String) {
myRootRef.createUser(email, password: password,
withValueCompletionBlock: { error, result in
if error != nil {
// There was an error creating the account
} else {
let uid = result["uid"] as? String
print("Successfully created user account with uid: \(uid)")
UID = uid! as String
self.userDefaults.setObject(UID, forKey: "uid")
self.userDefaults.setObject(email, forKey: "useremail")
print("set defaults")
EMAIL = email
self.createUserInDB(email)
}
})
}
func createUserInDB(email:String) {
let user = myRootRef.childByAppendingPath("users").childByAppendingPath(UID)
let imageData:NSData = UIImagePNGRepresentation(UIImage(named: "user_pic")!)!
let imageString = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
let newUser = ["email":email, "profile_pic":imageString]
user.setValue(newUser)
print("created user in Database")
}
func createFollowerRelationship(toFollow:String) {
let userFollows = myRootRef.childByAppendingPath("followers").childByAppendingPath(UID).childByAppendingPath(toFollow)
userFollows.setValue(true)
}
func loginUser(username:String, password:String) {
myRootRef.authUser(username, password: password) { (error, data) -> Void in
if error != nil {
// There was an error creating the account
} else {
//perform segue
UID = String(data)
EMAIL = username
self.userDefaults.setObject(String(data), forKey: "uid")
self.userDefaults.setObject(username, forKey: "useremail")
print("set defaults")
}
}
}
}
| true
|
e273df49dc6aa5e1439857d92af2449af79f655f
|
Swift
|
Organ-xinao/XinaoEnergy
|
/XinaoEnergy/CustomSearchDemo/SearchViewController.swift
|
UTF-8
| 6,379
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
//
// SearchViewController.swift
// XinaoEnergy
//
// Created by jun on 2018/9/10.
// Copyright © 2018年 jun. All rights reserved.
//
import UIKit
class SearchViewController: UIViewController{
var tableView: UITableView!
var dataArray = [String]() //存储文件内容
var filteredArray = [String]() //存储搜索结果数据
var shouldShowSearchResults = false //是否显示搜索结果
var searchController: UISearchController!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
configureSearchController()
// loadListOfCountries()
}
func configureSearchController(){
//通过参数searchResultsController传nil来初始化UISearchController,意思是我们告诉search controller我们会用相同的视图控制器来展示我们的搜索结果,如果我们想要指定一个不同的view controller,那就会被替代为显示搜索结果。
searchController = UISearchController(searchResultsController: nil)
//设置代理,searchResultUpdater是UISearchController的一个属性,它的值必须实现UISearchResultsUpdating协议,这个协议让我们的类在UISearchBar文字改变时被通知到,我们之后会实现这个协议。
searchController.searchResultsUpdater = self
//默认情况下,UISearchController暗化前一个view,这在我们使用另一个view controller来显示结果时非常有用,但当前情况我们并不想暗化当前view,即设置开始搜索时背景是否显示
searchController.dimsBackgroundDuringPresentation = false
searchController.view.backgroundColor = UIColor.red
searchController.definesPresentationContext = true
//设置默认显示内容
searchController.searchBar.placeholder = "Search here..."
//设置searchBar的代理
searchController.searchBar.delegate = self
//设置searchBar自适应大小
searchController.searchBar.sizeToFit()
//设置definesPresentationContext为true,我们保证在UISearchController在激活状态下用户push到下一个view controller之后search bar不会仍留在界面上。
searchController.definesPresentationContext = true
tableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight-49))
self.view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
dataArray = ["1222","233","1234","325","567"]
tableView.reloadData()
//将searchBar设置为tableview的头视图
tableView.tableHeaderView = searchController.searchBar
}
func loadListOfCountries(){
//获取文件的指定路径
let pathToFile = Bundle.main.path(forResource: "countries", ofType: "txt")
//判断路径是否存在
if let path = pathToFile{
do{
//加载文件变成字符串
let countriesString = try String(contentsOfFile: path, encoding: .utf8)
//将字符串变为数组
dataArray = countriesString.components(separatedBy: "\n")
//刷新列表
tableView.reloadData()
}catch{
print(error.localizedDescription)
}
}
}
}
//扩展SearchViewController实现UITableViewDelegate,UITableViewDataSource两个协议,并控制数据的显示
extension SearchViewController:UITableViewDelegate,UITableViewDataSource{
//MARK: UITableView Delegate and Datasource functions
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if shouldShowSearchResults {//是否显示搜索结果
return filteredArray.count
}
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell:UITableViewCell? = UITableViewCell.init()
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "ss")
}
if shouldShowSearchResults{
cell?.textLabel?.text = dataArray[indexPath.row]
}else{
cell?.textLabel?.text = "\(indexPath.row)"
}
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60.0
}
}
//扩展SearchViewController实现UISearchBarDelegate和UISearchResultsUpdating两个协议
extension SearchViewController:UISearchBarDelegate,UISearchResultsUpdating{
//开始进行文本编辑,设置显示搜索结果,刷新列表
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
shouldShowSearchResults = true
tableView.reloadData()
}
//点击Cancel按钮,设置不显示搜索结果并刷新列表
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
shouldShowSearchResults = false
tableView.reloadData()
}
//点击搜索按钮,触发该代理方法,如果已经显示搜索结果,那么直接去除键盘,否则刷新列表
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if !shouldShowSearchResults{
shouldShowSearchResults = true
tableView.reloadData()
}
searchController.searchBar.resignFirstResponder()
}
//这个updateSearchResultsForSearchController(_:)方法是UISearchResultsUpdating中唯一一个我们必须实现的方法。当search bar 成为第一响应者,或者search bar中的内容被改变将触发该方法.不管用户输入还是删除search bar的text,UISearchController都会被通知到并执行上述方法。
func updateSearchResults(for searchController: UISearchController) {
let searchString = searchController.searchBar.text
//过滤数据源,存储匹配的数据
filteredArray = dataArray.filter({ (country) -> Bool in
let countryText: NSString = country as NSString
return (countryText.range(of: searchString!, options: .caseInsensitive).location) != NSNotFound
})
//刷新表格
tableView.reloadData()
}
}
| true
|
d81a6a1f36fb6e816273140cc979e1946d69490d
|
Swift
|
mcdubjr/hehestreamsAppleTV
|
/hehestreams/FireMock/FireMockDataSource.swift
|
UTF-8
| 931
| 2.921875
| 3
|
[] |
no_license
|
//
// FireMockDataSource.swift
// FireMock
//
// Created by Albert Arroyo on 3/3/18.
//
import UIKit
/// Class to prepare Category Section for Collasped / Expanded
class FireMockCategorySection {
var title: String
var mocks: [FireMock.ConfigMock]
var collapsed: Bool
init(title: String, mocks: [FireMock.ConfigMock], collapsed: Bool = true) {
self.title = title
self.mocks = mocks
self.collapsed = collapsed
}
}
/// DataType for FireMock
class FireMockCategoriesDataType {
var configMockSections: [FireMockCategorySection]
init(mockSections: [FireMockCategorySection]) {
self.configMockSections = mockSections
}
}
extension FireMockCategoriesDataType: FireMockDataType {
var numberOfSections: Int {
return configMockSections.count
}
func numberOfItems(section: Int) -> Int {
return configMockSections[section].mocks.count
}
}
| true
|
d9ecb829d889d028c0a3e75959fa3f86a6538af4
|
Swift
|
itsabugnotafeature/Sword-and-Board
|
/Sword And Board/Engine/GameECSManager.swift
|
UTF-8
| 2,400
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
//
// GameECSEngine.swift
// Sword And Board
//
// Created by Max Sonderegger on 11/13/18.
// Copyright © 2018 Max Sonderegger. All rights reserved.
//
typealias ECSEntity = Int
class GameECSManager: ContainsEntities {
var entityCount: Int { return entityManager.entityCount }
weak var engine: GameEngine?
private let entityManager: ECSEntityManager = ECSEntityManager()
var systems: [ECSSystemPriorities: [ECSSystem]] = [:]
init(withEngine engine: GameEngine) {
self.engine = engine
}
@discardableResult func addSystem(_ system: ECSSystem, withPriority priority: ECSSystemPriorities) -> Bool {
if system.start() {
system.entityManager = self.entityManager
if systems[priority] != nil {
systems[priority]!.append(system)
} else {
systems[priority] = [system]
}
return true
} else {
return false
}
}
@discardableResult func removeSystem(_ systemToBeRemoved: ECSSystem) -> Bool {
for (_, var systemList) in systems {
for index in 0..<systemList.count {
if systemList[index] === systemToBeRemoved {
systemList.remove(at: index)
return true
}
}
}
return false
}
func update(afterTime dt: TimeInterval) {
entityManager.update()
for (_, systemList) in systems {
for system in systemList {
system.update(afterTime: dt)
}
}
}
func appendComponent(_ component: ECSComponent, toEntity entity: ECSEntity) {
entityManager.appendComponent(component, toEntity: entity)
}
func removeComponent(ofType type: ECSComponentType, from entity: ECSEntity) {
entityManager.removeComponent(ofType: type, from: entity)
}
func addEntity() -> ECSEntity {
return entityManager.addEntity()
}
func addEntityWithComponents(_ components: [ECSComponent]) -> ECSEntity {
return entityManager.addEntityWithComponents(components)
}
func removeEntity(_ entity: ECSEntity) {
entityManager.removeEntity(entity)
}
func typeOfEntity(_ entity: ECSEntity) -> ECSEntityType {
return entityManager.typeOfEntity(entity)
}
}
| true
|
6986daa154e945f0c2e28649d06d6d2c47db1121
|
Swift
|
sjrankin/DeskBlockCam
|
/DeskBlockCam/BlockView/OptionalParameters/CharactersOptionalParameters.swift
|
UTF-8
| 1,645
| 3
| 3
|
[] |
no_license
|
//
// CharactersOptionalParameters.swift
// DeskBlockCam
//
// Created by Stuart Rankin on 2/6/20.
// Copyright © 2020 Stuart Rankin. All rights reserved.
//
import Foundation
import AppKit
class CharactersOptionalParameters: OptionalParameters
{
init()
{
super.init(WithShape: .Characters)
self.Read()
}
init(WithCharacters: String, FontName: String)
{
super.init(WithShape: .Characters)
_CharacterList = WithCharacters
self.FontName = FontName
}
init(WithSet: CharacterSets)
{
super.init(WithShape: .Characters)
_CharSet = WithSet
}
private var _CharSet: CharacterSets = .Latin
public var CharSet: CharacterSets
{
get
{
return _CharSet
}
set
{
_CharSet = newValue
}
}
private var _CharacterList: String = "abcdefghijklmnopqrstuvwxyz"
public var CharacterList: String
{
get
{
return _CharacterList
}
set
{
_CharacterList = newValue
}
}
private var _FontName: String = "Avenir"
public var FontName: String
{
get
{
return _FontName
}
set
{
_FontName = newValue
}
}
override public func Read()
{
_CharSet = Settings.GetEnum(ForKey: .CharacterSet, EnumType: CharacterSets.self, Default: CharacterSets.Latin)
}
override public func Write()
{
Settings.SetEnum(CharSet, EnumType: CharacterSets.self, ForKey: .CharacterSet)
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.