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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b81ce19172d3028a651f6de3f9beee35daee93b1
|
Swift
|
yaojiqian/Swift-Programming-Learning
|
/Files and Folder Management/Saving Objects to Files/Saving Objects to Files/ViewController.swift
|
UTF-8
| 2,015
| 2.90625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Saving Objects to Files
//
// Created by Yao Jiqian on 10/01/2018.
// Copyright © 2018 BigBit Corp. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var writeButton : UIButton?
var readButton : UIButton?
var firstPerson : Person?
override func viewDidLoad() {
super.viewDidLoad()
firstPerson = Person(firstName: "Yao", lastName : "JQ")
writeButton = UIButton(type: .system)
if let wbtn = writeButton {
wbtn.frame = CGRect(x: 0, y: 0, width: 170, height: 70)
wbtn.setTitle("write person", for: .normal)
wbtn.addTarget(self, action: #selector(writePersonToFile), for: .touchUpInside)
view.addSubview(wbtn)
}
readButton = UIButton(type: .system)
if let rbtn = readButton {
rbtn.frame = CGRect(x: 0, y: 80, width: 170, height: 70)
rbtn.setTitle("read person", for: .normal)
rbtn.addTarget(self, action: #selector(readPersonFromFile), for: .touchUpInside)
view.addSubview(rbtn)
}
}
func writePersonToFile(){
let fileManager = FileManager()
let path = fileManager.temporaryDirectory.appendingPathComponent("person")
NSKeyedArchiver.archiveRootObject(firstPerson!, toFile: path.path)
}
func readPersonFromFile(){
let fileManager = FileManager()
let path = fileManager.temporaryDirectory.appendingPathComponent("person")
let secondPerson = NSKeyedUnarchiver.unarchiveObject(withFile: path.path) as! Person
if firstPerson! == secondPerson{
debugPrint("firstPerson == secondPerson")
}else{
debugPrint("firstPerson != secondPerson")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
f9e573fd9cd1a6e765576d9c8fec1e4ec725b157
|
Swift
|
Takarkiz/drinkParty_iOS
|
/nomitter/ListViewController.swift
|
UTF-8
| 2,524
| 2.59375
| 3
|
[] |
no_license
|
//
// ListViewController.swift
// nomitter
//
// Created by 澤田昂明 on 2017/03/08.
// Copyright © 2017年 takarki. All rights reserved.
//
import UIKit
import Firebase
class ListViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet var table:UITableView!
@IBOutlet var navigationBar:UINavigationController!
// MARK: Properties
var items: [database] = []
var user: User!
let ref = FIRDatabase.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
print("ViewDidload")
self.getUserData()
let newRef = ref.child(user.uid).child("event")
// 1
newRef.observe(.value, with: { snapshot in
// 2
var newItems: [database] = []
// 3
for item in snapshot.children {
// 4
let eventItem = database(snapshot: item as! FIRDataSnapshot)
newItems.append(eventItem)
}
// 5
self.items = newItems
self.table.reloadData()
})
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath as IndexPath)
return cell
}
@IBAction func add(){
self.performSegue(withIdentifier: "add", sender: nil)
}
func getUserData(){
//ログインしているユーザー情婦を取得
FIRAuth.auth()!.addStateDidChangeListener { auth, user in
//ログインが完了していなかったら、ログイン画面へとぶ
if user != nil{
guard let user = user else { return }
self.user = User(authData: user)
print("ユーザー認証完了")
}else{
print("ユーザー登録し直してください")
self.performSegue(withIdentifier: "login", sender: nil)
}
}
}
}
| true
|
00aced132aac4ace31d42556e3af21501f221b80
|
Swift
|
filosofisto/FirebaseAuthPasswordIOS
|
/FirebaseAuthPasswordIOS/MainViewController.swift
|
UTF-8
| 1,712
| 2.796875
| 3
|
[] |
no_license
|
//
// MainViewController.swift
// FirebaseAuthPasswordIOS
//
// Created by Eduardo Ribeiro da Silva on 08/07/19.
// Copyright © 2019 Eduardo Ribeiro da Silva. All rights reserved.
//
import UIKit
import Firebase
class MainViewController: UIViewController {
var logoutSuccess = false
@IBOutlet weak var labelWelcome: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
navigationConfig()
}
private func navigationConfig() {
Auth.auth().addStateDidChangeListener() { auth, user in
if user == nil {
self.navigateToLogin()
} else {
self.updateUIWithUser(user)
}
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == "mainToLogin" {
do {
try Auth.auth().signOut()
logoutSuccess = true
} catch let signOutError as NSError {
logoutSuccess = false
print ("SignOut error: \(signOutError)")
}
}
return logoutSuccess
}
private func navigateToLogin() {
}
private func updateUIWithUser(_ user: User?) {
guard let email = user?.email else { return }
labelWelcome.text = "Bem vindo \(email)"
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
965c65b373c45baef2407e60293f2a5495bed9dd
|
Swift
|
crosskyle/Swift-Playgrounds
|
/extensions.playground/Contents.swift
|
UTF-8
| 809
| 3.65625
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
extension UIColor {
static var favoriteColor: UIColor {
return UIColor(red: 0.5, green: 0.1, blue: 0.5, alpha: 1.0)
}
}
extension String {
mutating func pluralized() {
// Complex code that takes the current value (self) and converts it to the plural version
}
}
var apple = "Apple"
print(apple.pluralized())
struct Employee {
var firstName: String
var lastName: String
var jobTitle: String
var phoneNumber: String
}
extension Employee: Equatable {
static func ==(lhs: Employee, rhs: Employee) -> Bool {
return lhs.firstName == rhs.firstName && lhs.lastName ==
rhs.lastName && lhs.jobTitle == rhs.jobTitle &&
lhs.phoneNumber == rhs.phoneNumber
}
}
| true
|
55c04edaaaf657823c20e4353f92eeeb0565498f
|
Swift
|
Wisors/OBD2Connect
|
/Sources/OBDConnectionProtocol.swift
|
UTF-8
| 2,767
| 2.78125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Copyright (c) 2015-2017 Nikishin Alexander https://twitter.com/wisdors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
/// Protocol covers properties and methods of the connection to an OBD adapter.
public protocol OBDConnectionProtocol: AnyObject {
var configuration: OBDConnectionConfiguration { get }
// MARK: State
var state: OBDConnectionState { get }
var onStateChanged: OBDConnectionStateCallback? { get set }
// MARK: Data transmitting
func send(data: Data, completion: OBDResultCallback?)
// MARK: Connection hadling methods
func open()
func close()
}
public enum OBDConnectionState: CustomStringConvertible {
case closed
case connecting
case open
case transmitting
case error(OBDConnectionError)
public var description: String {
switch self {
case .closed: return "Connection closed"
case .connecting: return "Trying to connect to OBD adapter"
case .open: return "Connection ready to send data"
case .transmitting: return "Transmitting data between host and adapter"
case .error(let error): return "Error: \(String(describing: error))"
}
}
}
extension OBDConnectionState: Equatable {}
public func == (lhs: OBDConnectionState, rhs: OBDConnectionState) -> Bool {
switch (lhs, rhs) {
case (.closed, .closed): return true
case (.connecting, .connecting): return true
case (.open, .open): return true
case (.transmitting, .transmitting): return true
case (.error(_), .error(_)): return true
default: return false
}
}
| true
|
f0515c68dfe6eb0878db7f73ab5add40ea0ee986
|
Swift
|
KrispyKeK/Juan_CSP
|
/Juan_CSP/Controller/AlgorithmsController.swift
|
UTF-8
| 2,070
| 2.96875
| 3
|
[] |
no_license
|
//
// AlgorithmsController.swift
// Juan_CSP
//
// Created by Dela Cruz, Juan on 10/26/17.
// Copyright © 2017 Dela Cruz, Juan. All rights reserved.
//
import UIKit
public class AlgorithmsController: UIViewController{
@IBOutlet weak var algorithmsText: UILabel!
private func setupAlgorithms() -> Void{
var algorithmSteps : [String] = []
let algorithm: String = "These are the insturcture to create a project within Java using Eclipse and Github \n"
let stepOne: String = "First, "
let stepTwo: String = "Second, "
let stepThree: String = "Third, "
algorithmSteps = [stepOne, stepTwo, stepThree]
let attributesDictionary = [NSAttributedStringKey.font : algorithmsText.font]
let fullAttributedString = NSMutableAttributedString(string: algorithm, attributes: attributesDictionary)
for step in algorithmSteps{
let bullet: String = "Heart"
let formattedStep: String = "\n\(bullet) \(step)"
let attributedStringStep: NSMutableAttributedString = NSMutableAttributedString(string: formattedStep)
let paragraphStyle = createParagraphStyle()
attributedStringStep.addAttributes([NSAttributedStringKey.paragraphStyle : paragraphStyle], range: NSMakeRange(0, attributedStringStep.length))
fullAttributedString.append(attributedStringStep)
}
algorithmsText.attributedText = fullAttributedString
}
private func createParagraphStyle() -> NSParagraphStyle{
let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .left
paragraphStyle.defaultTabInterval = 15
paragraphStyle.firstLineHeadIndent = 20
paragraphStyle.headIndent = 35
return paragraphStyle
}
override public func viewDidLoad(){
super.viewDidLoad()
setupAlgorithms()
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| true
|
bb289d379f42f4f88c39b0d9f32456fd7db9455a
|
Swift
|
Benny-iPhone/hackeru_ios_eve_december_2016
|
/ImageFromWebProject/ImageFromWebProject/ViewController.swift
|
UTF-8
| 2,774
| 2.984375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ImageFromWebProject
//
// Created by Benny Davidovitz on 13/02/2017.
// Copyright © 2017 xcoder.solutions. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var indicator : UIActivityIndicatorView!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var imageView: UIImageView!
@IBAction func downloadAction2(_ sender : UIButton){
let urlString = "https://i.ytimg.com/vi/cNycdfFEgBc/maxresdefault.jpg"
//validate url
guard let url = URL(string: urlString) else {
print("url no good")
return
}
//before download
indicator.startAnimating()
progressView.progress = 0
progressView.isHidden = false
//using SDWebImage's method to download the image with, url, placeholder-image, progress block, completion block
imageView.sd_setImage(with: url, placeholderImage: #imageLiteral(resourceName: "template"), options: .progressiveDownload, progress: { (received, expected, _) in
//calculate progress
let p = Float(received) / Float(expected)
self.progressView.progress = p
}) { (_, _, _, _) in
//donwload finished
//self.progressView.progress = 1
self.progressView.isHidden = true
self.indicator.stopAnimating()
}
//imageView.sd_setImage(with: url)
/*
let before = Date().timeIntervalSince1970
imageView.sd_setImage(with: url) { (_, _, _, _) in
let after = Date().timeIntervalSince1970
print(after - before)
}*/
}
@IBAction func downloadAction(_ sender: UIButton) {
let urlString = "https://i.ytimg.com/vi/cNycdfFEgBc/maxresdefault.jpg"
//validate url
guard let url = URL(string: urlString) else {
print("url no good")
return
}
//go to background thread
DispatchQueue.global().async {
//download
guard let data = try? Data(contentsOf: url) else {
print("no data")
return
}
print("done downloading image")
//convert data to image
guard let image = UIImage(data: data) else{
print("data no good")
return
}
//back to main thread
DispatchQueue.main.async {
self.imageView.image = image
}
}
}
}
| true
|
e1d72271c34d5772d642478e31cff9233fa90a4c
|
Swift
|
currency-converter/ios
|
/CurrencyConverter/Iconfont.swift
|
UTF-8
| 1,033
| 2.71875
| 3
|
[] |
no_license
|
//
// Iconfont.swift
// CurrencyConverter
//
// Created by zhi.zhong on 2019/3/2.
// Copyright © 2019 zhi.zhong. All rights reserved.
//
import UIKit
extension UIImage {
public static func iconFont(fontSize: CGFloat, unicode: String, color: UIColor? = nil) -> UIImage {
var attributes = [NSAttributedString.Key: Any]()
attributes[NSAttributedString.Key.font] = UIFont(name: "CurrencyConverter", size: fontSize)
if let color = color {
attributes[NSAttributedString.Key.foregroundColor] = color
}
let attributedString = NSAttributedString(string: unicode, attributes: attributes)
let rect = attributedString.boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: fontSize), options: .usesLineFragmentOrigin, context: nil)
let imageSize: CGSize = rect.size
UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale)
attributedString.draw(in: rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
}
| true
|
f1df76338de766d066a7ba5f250968b19d6cd52e
|
Swift
|
DeVitoC/LoadingUI
|
/LoadingUIFramework/LoadingViewController.swift
|
UTF-8
| 2,473
| 3
| 3
|
[] |
no_license
|
//
// LoadingViewController.swift
// LoadingUIFramework
//
// Created by Christopher Devito on 4/22/20.
// Copyright © 2020 Christopher Devito. All rights reserved.
//
import UIKit
/// The ViewController that presents a loading screen GIF.
public class LoadingViewController: UIViewController {
/// A loading view GIF object.
var loadingGIF: IndeterminateLoadingView!
var successLabel: UILabel!
public override func viewDidLoad() {
presentLoadingGIF()
super.viewDidLoad()
}
func updateViews() {
guard successLabel != nil else { return }
successLabel.text = "Success"
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
/// This method sets up the loading screen GIF.
public func presentLoadingGIF() {
//loadingGIF = (UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) as! IndeterminateLoadingView)
loadingGIF = IndeterminateLoadingView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.addSubview(loadingGIF)
loadingGIF.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
loadingGIF.centerYAnchor.constraint(equalTo: view.centerYAnchor),
loadingGIF.centerXAnchor.constraint(equalTo: view.centerXAnchor),
loadingGIF.heightAnchor.constraint(equalToConstant: 100),
loadingGIF.widthAnchor.constraint(equalToConstant: 100)
])
loadingGIF.startAnimating()
}
/// This method displays an optional message briefly before disappearing.
public func loadingGIFWillDisappear() {
loadingGIF.isHidden = true
successLabel = UILabel()
successLabel.isHidden = false
view.addSubview(successLabel)
successLabel.translatesAutoresizingMaskIntoConstraints = false
successLabel.text = "Success!"
NSLayoutConstraint.activate([
successLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
successLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
successLabel.heightAnchor.constraint(equalToConstant: 100),
successLabel.widthAnchor.constraint(equalToConstant: 100)
])
//viewDidAppear(true)
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
self.dismiss(animated: true)
}
}
}
| true
|
dd79850b24272781e5fab8af2ad4b36e1a2db152
|
Swift
|
HalitGumus/TheMovieDbApp
|
/TheMovieDbApp/MovieDetail/MovieDetailPresenter.swift
|
UTF-8
| 708
| 2.53125
| 3
|
[] |
no_license
|
//
// MovieDetailPresenter.swift
// TheMovieDbApp
//
// Created by HalitG on 7.03.2021.
// Copyright (c) 2021 HalitG. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so
// you can apply clean architecture to your iOS and Mac projects,
// see http://clean-swift.com
//
import UIKit
protocol MovieDetailPresentationLogic
{
func presentMovie(movie: Movie, selectedMovieIndex: Int)
}
class MovieDetailPresenter: MovieDetailPresentationLogic
{
weak var viewController: MovieDetailDisplayLogic?
func presentMovie(movie: Movie, selectedMovieIndex: Int)
{
viewController?.load(movie: movie, selectedMovieIndex: selectedMovieIndex)
}
}
| true
|
1ed52ed37ac753da55a043cf3ea80cb56800f2ab
|
Swift
|
aatanac/TaskManager
|
/TaskManager/Shared/Extensions/UIColor+Extenstions.swift
|
UTF-8
| 345
| 2.859375
| 3
|
[] |
no_license
|
//
// UIColor+Extenstions.swift
// TaskManager
//
// Created by Aleksandar Atanackovic on 12/15/17.
// Copyright © 2017 Aleksandar Atanackovic. All rights reserved.
//
import Foundation
extension UIColor {
convenience init(r: CGFloat, g: CGFloat, b: CGFloat, alpha: CGFloat = 1) {
self.init(red: r/255, green: g/255, blue: b/255, alpha: alpha)
}
}
| true
|
042429947c0afc5806a33ae581a7e551c2e902fc
|
Swift
|
ThickFive/Playground
|
/Base/indices.swift
|
UTF-8
| 1,030
| 3.53125
| 4
|
[] |
no_license
|
/* FILEPATH = "./Base/indices.swift"
* Indices Of Collection
*/
/*
* TEST
*/
import Foundation
class Test {
class func run(_ code:() -> ()) {
let start = Date()
print("\(start): Test start")
code()
let end = Date()
print("\(end): Test end in \(Int((end.timeIntervalSince1970 - start.timeIntervalSince1970)*1000))ms")
}
}
Test.run {
let string: String = "abc123"
print(string.indices)
for indice in string.indices {
print(indice, string[indice])
}
}
Test.run {
let array: [Int] = [1, 2, 3]
print(array.indices)
for indice in array.indices {
print(indice, array[indice])
}
}
Test.run {
let dict: [String: Int] = [
"a": 100,
"b": 200,
"c": 300,
]
print(dict.indices)
for indice in dict.indices {
print(indice, dict[indice])
}
}
Test.run {
let set: Set<Int> = [1, 2, 3, 4]
print(set.indices)
for indice in set.indices {
print(indice, set[indice])
}
}
| true
|
36274c6867fce141abcf07692f75f009ba042820
|
Swift
|
raphaeljaoui/Swift-PA
|
/LinkSAppIOS/Model/Message.swift
|
UTF-8
| 611
| 2.671875
| 3
|
[] |
no_license
|
//
// Message.swift
// LinkSAppIOS
//
// Created by Sandrine Patin on 18/07/2020.
// Copyright © 2020 imane. All rights reserved.
//
import Foundation
class Message: CustomStringConvertible {
var id: Int
var content: String
var date: String
var id_sender: Int
var id_dest: Int
init(id: Int, content: String, date: String, id_sender: Int, id_dest: Int){
self.id = id
self.content = content
self.date = date
self.id_sender = id_sender
self.id_dest = id_dest
}
var description: String {
return "\(self.content)"
}
}
| true
|
110ffce93392e09210a3b461e63d61423b201219
|
Swift
|
justinhavas/iOS_Device_UI_Builder
|
/UIBuilderProject/UIBuilderProject/AddProjectViewController.swift
|
UTF-8
| 2,097
| 2.8125
| 3
|
[] |
no_license
|
//
// AddProjectViewController.swift
// UIBuilderProject
//
// Created by Justin Havas on 4/16/20.
// Copyright © 2020 DeviceUIBuilder. All rights reserved.
//
// This class is used to represent the Add Project View that appears when the user wishes to create a new project on the iPad.
import UIKit
class AddProjectViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
nameTextField.placeholder = "eg. myProject"
}
// 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.
guard let projectMenu = segue.destination as? ProjectMenuTableViewController else { return }
if (sender as? UIBarButtonItem)?.description == saveButton.description {
let newProj = build(nameTextField.text ?? "", [[:]])
projects.update(newProj)
projectMenu.tableView.reloadData()
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
let name = nameTextField.text ?? ""
let value = (sender as? UIBarButtonItem)?.description != saveButton.description || (!testWithRegex(testString: name, pattern: "^[a-zA-z0-9_-]{1,10}$") && !projects.getAllProjectNames().contains(name))
if !value {
let alert = UIAlertController(title: "Error", message: "Project Name must be unique, have no more than 10 characters, and only contain letter, number, underscore, or dash characters.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}
return value
}
}
| true
|
15da990c6ef39668223c5ea1c77dbd8021965000
|
Swift
|
7se7olod/Students-Llst
|
/Students Llst/Message.swift
|
UTF-8
| 436
| 2.78125
| 3
|
[] |
no_license
|
import UIKit
var messageOne = "Пожалуйста, введите средний балл от 1 до 5"
var messageTwo = "Допустимы только русские или английскте буквы"
var imageSt: UIImage? = UIImage(systemName: "person.circle")
let ruCharacters = "йцукенгшщзхъфывапролджэёячсмитьбю"
let engCharacters = "qwertyuiopasdfghjklzxcvbnm"
let numbers = "12345"
| true
|
49647cb2b0773b6d28fab528f1f1e4dcf0edfb6d
|
Swift
|
nf17/clicker-ios
|
/Clicker/Extensions/Utils.swift
|
UTF-8
| 879
| 2.859375
| 3
|
[] |
no_license
|
//
// Utils.swift
// Clicker
//
// Created by Kevin Chan on 4/28/18.
// Copyright © 2018 CornellAppDev. All rights reserved.
//
import Foundation
// CONVERT INT TO MC OPTIONS
func intToMCOption(_ intOption: Int) -> String {
return String(Character(UnicodeScalar(intOption + Int(("A" as UnicodeScalar).value))!))
}
// GET MM/DD/YYYY OF TODAY
func getTodaysDate() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
return formatter.string(from: Date())
}
// USER DEFAULTS
func encodeObjForKey(obj: Any, key: String) {
let encodedData = NSKeyedArchiver.archivedData(withRootObject: obj)
UserDefaults.standard.set(encodedData, forKey: key)
}
func decodeObjForKey(key: String) -> Any {
let decodedData = UserDefaults.standard.value(forKey: key) as! Data
return NSKeyedUnarchiver.unarchiveObject(with: decodedData)!
}
| true
|
3303da8cbf4cea62c07e02315d77df6e4d673eb4
|
Swift
|
Agarrovi1/Example
|
/Projects/FoursquaresMap/FoursquaresMapTests/FoursquaresMapTests.swift
|
UTF-8
| 2,385
| 2.703125
| 3
|
[] |
no_license
|
//
// FoursquaresMapTests.swift
// FoursquaresMapTests
//
// Created by Angela Garrovillas on 11/4/19.
// Copyright © 2019 Angela Garrovillas. All rights reserved.
//
import XCTest
@testable import FoursquaresMap
class FoursquaresMapTests: 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 testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
func testVenueStruct() {
let testVenue = FourSquareVenues(response: ResponseWrapper(venues: [Venues(id: "58cc9644739d8523a63d716a", name: "Allegro Coffee Company", location: Location(address: "1095 Avenue Of The Americas", lat: 40.75453645610046, lng: -73.98430530273227, crossStreet: "41st"))]))
XCTAssertTrue(testVenue.response.venues[0].id == "58cc9644739d8523a63d716a")
XCTAssertTrue(testVenue.response.venues[0].name == "Allegro Coffee Company")
XCTAssertTrue(testVenue.response.venues[0].location.address == "1095 Avenue Of The Americas")
XCTAssertTrue(testVenue.response.venues[0].location.lat == 40.75453645610046)
XCTAssertTrue(testVenue.response.venues[0].location.lng == -73.98430530273227)
XCTAssertTrue(testVenue.response.venues[0].location.crossStreet == "41st")
}
func testCollectionsStruct() {
let testCollections = Collections(title: "TestOne", tip: nil, venues: [])
XCTAssertTrue(testCollections.title == "TestOne")
XCTAssertNil(testCollections.tip)
XCTAssertTrue(testCollections.venues.count == 0)
}
func testTipInCollections() {
let testCollections = Collections(title: "TestOne", tip: "TipOne", venues: [])
XCTAssertTrue(testCollections.title == "TestOne")
XCTAssertNotNil(testCollections.tip)
XCTAssertTrue(testCollections.tip == "TipOne")
XCTAssertTrue(testCollections.venues.count == 0)
}
}
| true
|
51d23fa5a226c2bee59191cd7f67f359d5c075fc
|
Swift
|
iStudyiOS/SimpleDiary_B
|
/Schedule_B/DetailMemoViewController.swift
|
UTF-8
| 2,757
| 2.828125
| 3
|
[] |
no_license
|
//
// DetailMemoViewController.swift
// Schedule_B
//
// Created by KEEN on 2021/02/15.
//
import UIKit
class DetailMemoViewController: UIViewController {
enum ViewType {
case add
case update
}
var memoType: Memo?
var viewType: ViewType = .add
var savedMemos: [Memo] = []
// TODO: 데이터 주입해주기
// TODO: 메모 수정 / 메모 추가 시, navigationBar title 바뀌도록 할 것.
// TODO: 메모의 내용을 입력하지 않을 시 저장이 되지 않고 alert문을 띄우도록 할 것.
@IBOutlet weak var titleLabel: UITextField!
@IBOutlet weak var contentsTextView: UITextView!
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var cancelButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
titleLabel.delegate = self
if let memo = memoType {
navigationItem.title = "메모 수정"
titleLabel.text = memo.mainText
contentsTextView.text = memo.contentText
}
navigationItem.leftBarButtonItem = cancelButton
updateSaveButtonState()
}
// MARK: 메모 추가 시, tableView에 띄워주는 코드.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let button = sender as? UIBarButtonItem, button == saveButton else { return }
let title = titleLabel.text ?? ""
let contents = contentsTextView.text ?? ""
// TODO: Refactoring
memoType = Memo(mainText: title, contentText: contents)
let newMemo = Memo(mainText: title, contentText: contents)
savedMemos.append(memoType ?? newMemo)
}
@IBAction func saveAction(_ sender: Any) {
}
// MARK: 취소 버튼 action
@IBAction func cancelAction(_ sender: Any) {
let addMode = presentingViewController is UINavigationController
if addMode {
dismiss(animated: true, completion: nil)
} else if let ownedNVC = navigationController {
ownedNVC.popViewController(animated: true)
} else {
fatalError("detailMemoVC가 navigation controller 안에 없습니다.")
}
}
}
// MARK: textFieldDelegate
extension DetailMemoViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
saveButton.isEnabled = false
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
contentsTextView.resignFirstResponder()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
updateSaveButtonState()
navigationItem.title = textField.text
}
private func updateSaveButtonState() {
let text = titleLabel.text ?? ""
saveButton.isEnabled = !text.isEmpty
}
}
| true
|
c2f9bc0384c90c84125ef465e8a88960762cb5d8
|
Swift
|
littleyerri/BoutTime
|
/BoutTime/EventFoundation.swift
|
UTF-8
| 3,492
| 3.3125
| 3
|
[] |
no_license
|
//
// EventFoundation.swift
// BoutTime
//
// Created by Jerry Zayas on 7/5/17.
// Copyright © 2017 Little Yerri. All rights reserved.
//
import Foundation
import GameKit
// MARK: Protocols
// Insures correct data is included in each event.
protocol Content {
var event: String { get }
var year: Int { get }
var url: String { get }
}
// Insures game functionality.
protocol Game {
var collectionOfEvents: [Content] { get set }
var rounds: Int { get set }
var numberOfRounds: Int { get }
var points: Int { get set }
var timer: Int { get }
init(collectionOfEvents: [Content])
func randomEvents(_ amount: Int) -> [Content]
func checkOrder(of event: [Content]) -> Bool
}
// Delegate to conform View Controller.
protocol GameOverDelegate {
func playAgainPressed(_ playAgain: Bool)
}
// MARK: Structs
// Stores event conten.
struct Event: Content {
let event: String
let year: Int
let url: String
}
// MARK: Enums
// Errors
enum ContentError: Error {
case invalidResource
case conversionFailure
case invalidData
}
// MARK: Classes
// Converts data from plist file.
class PlistImporter {
static func dictionary(fromFile name: String, ofType type: String) throws -> [[String: AnyObject]] {
guard let path = Bundle.main.path(forResource: name, ofType: type) else {
throw ContentError.invalidResource
}
guard let dictionaryArray = NSArray.init(contentsOfFile: path) as? [[String: AnyObject]] else {
throw ContentError.conversionFailure
}
return dictionaryArray
}
}
// Unarchives data from plist file.
class CollectionUnarchiver {
static func collection(from array: [[String: AnyObject]]) throws -> [Content] {
var collection: [Content] = []
for dictionary in array {
if let event = dictionary["movie"] as? String, let year = dictionary["year"] as? Int, let url = dictionary["url"] as? String {
let event = Event(event: event, year: year, url: url)
collection.append(event)
} else {
print("It didn't work!")
}
}
return collection
}
}
// Models game events.
class GameEvents: Game {
var collectionOfEvents: [Content]
var points: Int = 0
var rounds: Int = 0
var numberOfRounds: Int = 6
var timer: Int = 60
required init(collectionOfEvents: [Content]) {
self.collectionOfEvents = collectionOfEvents
}
func randomEvents(_ amount: Int) -> [Content] {
var pickedEvents: [Content] = []
var usedNumbers: [Int] = []
while pickedEvents.count < amount {
let randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: collectionOfEvents.count)
if usedNumbers.contains(randomNumber) == false {
pickedEvents.append(collectionOfEvents[randomNumber])
usedNumbers.append(randomNumber)
}
}
return pickedEvents
}
func checkOrder(of event: [Content]) -> Bool {
if event[0].year > event[1].year,
event[1].year > event[2].year,
event[2].year > event[3].year {
points += 1
return true
} else {
return false
}
}
}
| true
|
b7986da1a1e870f13a3525af8d44f7ba3c2b2f10
|
Swift
|
Denisaleshin/Pictures
|
/Pictures/Screens/CollectionViewScreen/CollectionViewModel.swift
|
UTF-8
| 1,356
| 2.828125
| 3
|
[] |
no_license
|
//
// CollectionViewModel.swift
// Pictures
//
// Created by Dzianis Alioshyn on 2/21/19.
// Copyright © 2019 myOwn. All rights reserved.
//
import Foundation
import UIKit
protocol Contentable {
func setupContetn(title: String)
func setupContetnt(price: Int)
func setupContetnt(image: UIImage)
}
protocol SectionViewModelProtocol {
var items: [CellItemProtocol] { get }
func model(for elementOfKind: String) -> CellItemProtocol?
}
protocol CellItemProtocol {
var reuseIndetifier: String { get }
func setup(_ cell: UICollectionReusableView, in collectionView: UICollectionView, at indexPath: IndexPath)
func cancelDownloadingFor(_ cell: UICollectionReusableView, in collectionView: UICollectionView, at indexPath: IndexPath)
}
struct Label {
static func makeStandartLabel() -> UILabel {
let label = UILabel(frame: .zero)
label.translatesAutoresizingMaskIntoConstraints = false
label.font = label.font.withSize(15)
label.textColor = UIColor.black // just to test
return label
}
}
protocol CollectionViewModelProtocol {
var sections: [SectionViewModelProtocol] { get set }
}
final class CollectionViewModel: CollectionViewModelProtocol {
var sections: [SectionViewModelProtocol]
init(sections:[SectionViewModelProtocol] ) {
self.sections = sections
}
}
| true
|
167833500ab4cfa9ee71c1544fb1d06d01fcae1c
|
Swift
|
mcritz/FateballMobile
|
/Fateball Mobile/Controllers/PredictionClientController.swift
|
UTF-8
| 3,325
| 2.671875
| 3
|
[] |
no_license
|
//
// PredictionClientController.swift
// Fateball Mobile
//
// Created by Michael Critz on 6/23/18.
// Copyright © 2018 Map of the Unexplored. All rights reserved.
//
import Foundation
protocol PredictionControllerDelegate {
func handle(predictions: [Prediction])
}
class PredictionController {
init(delegate: PredictionControllerDelegate) {
self.delegate = delegate
}
var delegate: PredictionControllerDelegate
var predictions: [Prediction]?
func handleError(error: Error) {
print(error)
}
func uploadPrediction(data: Data, completionHandler: @escaping () -> Void) throws {
let maybeUrl = URL(string: "http://localhost:8080/predictions")
guard let url: URL = maybeUrl else { return }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.uploadTask(with: urlRequest, from: data) { data, response, error in
if let error = error {
print ("error: \(error)")
return
}
guard let response = response as? HTTPURLResponse,
(200...299).contains(response.statusCode) else {
print ("server error")
completionHandler()
return
}
if let mimeType = response.mimeType,
mimeType == "application/json",
let data = data,
let dataString = String(data: data, encoding: .utf8) {
completionHandler()
print ("got data: \(dataString)")
return
}
}
task.resume()
}
func startLoad() throws {
let maybeUrl = URL(string: "http://localhost:8080/predictions")
guard let url: URL = maybeUrl else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print(error)
self.handleError(error: error)
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
// self.handleError(error: response, isServer: true)
print(response.debugDescription)
return
}
if let mimeType = httpResponse.mimeType,
mimeType == "application/json",
let data = data
// , let string = String(data: data, encoding: .utf8)
{
// print(string)
let decoder = JSONDecoder()
do {
self.predictions = try decoder.decode([Prediction].self, from: data)
if let realPredix: [Prediction] = self.predictions {
self.delegate.handle(predictions: realPredix)
}
} catch {
return
}
// DispatchQueue.main.async {
// self.webView.loadHTMLString(string, baseURL: url)
// }
}
}
task.resume()
}
}
| true
|
d30a94f145faf7fa910b81a255cb3857c6dc86ca
|
Swift
|
gangelo/Thinkful-iOS
|
/Unit 02/Lesson 03/FibonacciSequence.playground/section-1.swift
|
UTF-8
| 2,270
| 4.4375
| 4
|
[] |
no_license
|
// Thinkful Playground
// Thinkful.com
// Fibonacci Sequence
// By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two.
import UIKit
class FibonacciSequence {
let includesZero:Bool
var values:[Int] = []
init(maxNumber: Int, includesZero: Bool) {
self.includesZero = includesZero
//TODO: Create an array which contains the numbers in the Fibonacci sequence, but don't add any numbers to the array which exceed the maxNumber. For example, if the maxNumber is 10 then the array should contain [0,1,1,2,3,5,8] because the next number is 13 which is higher than the maxNumber. If includesZero is false then you should not include the number 0 in the sequence.
initializeValuesArray()
while true {
let sequence = values[values.count - 1] + values[values.count - 2]
if (sequence > maxNumber) { break }
values.append(sequence)
print(values)
}
print("Max sequence: \(values.last!)")
}
init(numberOfItemsInSequence: Int, includesZero: Bool) {
self.includesZero = includesZero
//TODO: Create an array which contains the numbers in the Fibonacci sequence, and the array should contain this many items: numberOfItemsInSequence. For example, if numberOfItemsInSequence is 10 then the array should contain [0,1,1,2,3,5,8,13,21,34] if inlcudesZero is true, or [1,1,2,3,5,8,13,21,34,55] if includesZero is false.
initializeValuesArray()
for _ in values.count..<numberOfItemsInSequence {
let sequence = values[values.count - 1] + values[values.count - 2]
values.append(sequence)
print(values)
}
print("Total sequences: \(values.count)")
}
func initializeValuesArray() {
includesZero ? values.append(0) : values.append(1)
values.append(1)
}
}
let fibanocciSequence = FibonacciSequence(maxNumber:12345, includesZero: true)
let anotherSequence = FibonacciSequence(numberOfItemsInSequence: 25, includesZero: false)
| true
|
a5edb72df0d446cf5d2d140e60f792d4c8dd390e
|
Swift
|
rpramirez87/Filhoops
|
/Filhoops/TeamGameDataCell.swift
|
UTF-8
| 746
| 2.78125
| 3
|
[] |
no_license
|
//
// TeamGameDataCell.swift
// Filhoops
//
// Created by Ron Ramirez on 12/2/16.
// Copyright © 2016 Mochi Apps. All rights reserved.
//
import UIKit
class TeamGameDataCell: UICollectionViewCell {
@IBOutlet weak var gameTimeLabel: UILabel!
@IBOutlet weak var gameDateLabel: UILabel!
@IBOutlet weak var gameTitleLabel: UILabel!
@IBOutlet weak var team1ScoreLabel: UILabel!
@IBOutlet weak var team2ScoreLabel: UILabel!
func configureCell(game : Game) {
self.gameTitleLabel.text = game.gameTitle
self.gameTimeLabel.text = game.gameTime
self.gameDateLabel.text = game.gameDate
self.team1ScoreLabel.text = game.team1Score
self.team2ScoreLabel.text = game.team2Score
}
}
| true
|
91da30a87e436c0e855057e284d0759f38956294
|
Swift
|
mpangburn/RayTracer
|
/RayTracer/Models/Vector.swift
|
UTF-8
| 5,033
| 3.890625
| 4
|
[
"MIT"
] |
permissive
|
//
// Vector.swift
// RayTracer
//
// Created by Michael Pangburn on 6/25/17.
// Copyright © 2017 Michael Pangburn. All rights reserved.
//
import Foundation
/// Represents a vector in 3D space.
struct Vector {
/// The x-component of the vector.
var x: Double
/// The y-component of the vector.
var y: Double
/// The z-component of the vector.
var z: Double
/**
Creates a vector from the given components.
- Parameters:
- x: The x-component of the vector.
- y: The y-component of the vector.
- z: The z-component of the vector.
*/
init(x: Double, y: Double, z: Double) {
self.x = x
self.y = y
self.z = z
}
/**
Creates a vector from the initial point to the terminal point.
- Parameters:
- initial: The point from which the vector begins.
- terminal: The point at which the vector ends.
*/
init(from initial: Point, to terminal: Point) {
self.init(x: terminal.x - initial.x, y: terminal.y - initial.y, z: terminal.z - initial.z)
}
}
// MARK: - Vector properties
extension Vector {
/// The length of the vector, equivalent to its magnitude.
var length: Double {
return sqrt((x * x) + (y * y) + (z * z))
}
/// The magnitude of the vector, equivalent to its length.
var magnitude: Double {
return self.length
}
}
// MARK: - Vector math
extension Vector {
/// Normalizes the vector.
mutating func normalize() {
self = self.normalized()
}
/**
Returns the normalized vector.
- Returns: The vector with the same direction and magnitude 1.
*/
func normalized() -> Vector {
return self / self.magnitude
}
/**
Scales the vector by the scalar.
- Parameter scalar: The scalar to scale by.
*/
mutating func scale(by scalar: Double) {
self = self.scaled(by: scalar)
}
/**
Returns the vector scaled by the scalar.
- Parameter scalar: The scalar to scale by.
- Returns: The vector scaled by the scalar.
*/
func scaled(by scalar: Double) -> Vector {
return Vector(x: self.x * scalar, y: self.y * scalar, z: self.z * scalar)
}
/**
Returns the dot product with the given vector.
- Parameter other: The vector to dot with.
- Returns: The dot product of the vectors.
*/
func dot(with other: Vector) -> Double {
return (self.x * other.x) + (self.y * other.y) + (self.z * other.z)
}
/**
Returns the cross product with the given vector.
- Parameter other: The vector to cross with.
- Returns: The cross product of the vectors.
*/
func cross(with other: Vector) -> Vector {
let x = self.y * other.z - self.z * other.y
let y = -(self.x * other.z - self.z * other.x)
let z = self.x * other.y - self.y * other.x
return Vector(x: x, y: y, z: z)
}
}
// MARK: - Vector operators
extension Vector {
/// Negates each component of the vector.
static prefix func - (vector: Vector) -> Vector {
return Vector(x: -vector.x, y: -vector.y, z: -vector.z)
}
/// Adds the components of the two vectors.
static func + (lhs: Vector, rhs: Vector) -> Vector {
return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y, z: lhs.z + rhs.z)
}
/// Subtracts the components of the second vector from the first.
static func - (lhs: Vector, rhs: Vector) -> Vector {
return lhs + (-rhs)
}
/// Multiplies each component of the the vector by the scalar.
static func * (lhs: Vector, rhs: Double) -> Vector {
return lhs.scaled(by: rhs)
}
/// Multiplies each component of the the vector by the scalar.
static func * (lhs: Double, rhs: Vector) -> Vector {
return rhs.scaled(by: lhs)
}
/// Divides each component of the vector by the scalar.
static func / (lhs: Vector, rhs: Double) -> Vector {
return lhs * (1 / rhs)
}
}
// MARK: - Custom vector operators
infix operator •: MultiplicationPrecedence
infix operator ×: MultiplicationPrecedence
extension Vector {
/// Returns the dot product of the two vectors.
static func • (lhs: Vector, rhs: Vector) -> Double {
return lhs.dot(with: rhs)
}
/// Returns the cross product of the two vectors.
static func × (lhs: Vector, rhs: Vector) -> Vector {
return lhs.cross(with: rhs)
}
}
// MARK: - Vector constants
extension Vector {
/// The zero vector.
static var zero: Vector {
return Vector(x: 0, y: 0, z: 0)
}
}
extension Vector: Equatable { }
func == (lhs: Vector, rhs: Vector) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z
}
extension Vector: CustomStringConvertible, CustomDebugStringConvertible {
var description: String {
return "<\(self.x), \(self.y), \(self.z)>"
}
var debugDescription: String {
return "Vector(x: \(self.x), y: \(self.y), z: \(self.z))"
}
}
| true
|
9f2706d39abdea7ce546edd9b09983dfead5b7a1
|
Swift
|
nE4TC0De/100-Days-Of-SwiftUI
|
/PeopleIdentifierChallenge/PeopleIdentifierChallenge/View/ContentView.swift
|
UTF-8
| 2,964
| 2.890625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// PeopleIdentifierChallenge
//
// Created by Ryan Park on 3/2/21.
//
import SwiftUI
import CoreData
struct ContentView: View {
@Environment(\.managedObjectContext) var moc
@FetchRequest(entity: Person.entity(), sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)]) var people: FetchedResults<Person>
@State private var showingAddScreen = false
var body: some View {
NavigationView {
List {
ForEach(people, id: \.self) { person in
NavigationLink(destination: DetailView(person: person)) {
if loadImageFromDocumentDirectory(nameOfImage: person.id!.uuidString) != nil {
Image(uiImage: loadImageFromDocumentDirectory(nameOfImage: person.id!.uuidString)!)
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 60, height: 60)
.clipped()
.cornerRadius(10)
} else {
Image(systemName: "person.crop.square")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 60, height: 60)
.clipped()
.cornerRadius(10)
}
Text(person.name ?? "Unknown Person")
.font(.headline)
}
}
.onDelete(perform: deletePeople)
}
.navigationBarTitle("PeopleIdentifier")
.navigationBarItems(leading: EditButton(), trailing: Button(action: {
self.showingAddScreen.toggle()
}) {
Image(systemName: "plus")
})
.sheet(isPresented: $showingAddScreen) {
AddView().environment(\.managedObjectContext, self.moc)
}
}
}
func deletePeople(at offsets: IndexSet) {
for offset in offsets {
let person = people[offset]
moc.delete(person)
}
try? moc.save()
}
func loadImageFromDocumentDirectory(nameOfImage : String) -> UIImage? {
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
if let dirPath = paths.first{
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent(nameOfImage)
let image = UIImage(contentsOfFile: imageURL.path)
return image
}
return UIImage.init(named: "default.png")!
}
}
| true
|
dde398d2edc66f0ca140be9c04b4a5462ec4e3cb
|
Swift
|
jerryArsuaga/SocialNetwork
|
/SocialNetwork/SignInVC.swift
|
UTF-8
| 4,675
| 2.515625
| 3
|
[] |
no_license
|
//
// SignInVC.swift
// SocialNetwork
//
// Created by José Ramón Arsuaga Sotres on 08/09/16.
// Copyright © 2016 Whappif. All rights reserved.
//
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
import Firebase
import SwiftKeychainWrapper
class SignInVC: UIViewController,UITextFieldDelegate {
@IBOutlet weak var passwordField: FancyField!
@IBOutlet weak var emailField: FancyField!
override func viewDidLoad() {
super.viewDidLoad()
passwordField.delegate = self;
emailField.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let _ = KeychainWrapper.defaultKeychainWrapper.stringForKey(keyUID)
{
performSegue(withIdentifier: "FeedVC", sender: nil)
}
}
@IBAction func fbButtonTapped(_ sender: AnyObject) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
if error != nil
{
}else if result?.isCancelled == true{
}else
{
//Generamos las credenciales para fire base
let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
self.fireBaseAuthenticate(credential)
}
}
}
func fireBaseAuthenticate(_ credential: FIRAuthCredential)
{
FIRAuth.auth()?.signIn(with: credential, completion: { (user, error) in
if error != nil
{
print("Jerry: Unable to authenticate with fireBase")
}else
{
print("Jerry: Succesfully authenticated with fireBase")
if let user = user
{
let userData = ["provider":credential.provider]
self.completeSignIn(id: user.uid,userData: userData);
}
}
})
}
@IBAction func signInTapped(_ sender: AnyObject) {
guard let email = emailField.text, !email.isEmpty else{
print("The email field needs to be populated")
return
}
guard let pwd = passwordField.text , !pwd.isEmpty else{
print("The password field needs to be populated")
return
}
FIRAuth.auth()?.signIn(withEmail: email, password: pwd, completion: { (user, error) in
if error == nil
{
print("Jerry: Able to authenticate with fireBase by mail")
if let user = user{
let userData = ["provider":user.providerID]
self.completeSignIn(id: user.uid,userData:userData)
}
}else
{
print("Jerry: Unable to authenticate with fireBase by mail")
print("Jerry:" + error.debugDescription)
FIRAuth.auth()?.createUser(withEmail: email, password: pwd, completion: { (user, error) in
if(error != nil)
{
print("Jerry: Unable to save user")
}else
{
if let user = user{
let userData = ["provider":user.providerID]
self.completeSignIn(id: user.uid,userData: userData)
}
}
})
}
})
}
func completeSignIn(id: String,userData: Dictionary<String,String>)
{
// Esto es para tener un control de sesiones y a parte así poder hacer que el usuario inicie sesión automaticamente
let keyChainResult = KeychainWrapper.defaultKeychainWrapper.setString(id, forKey: keyUID)
DataService.ds.createFirebaseDBUser(uid: id, userData: userData)
performSegue(withIdentifier: "FeedVC", sender: nil)
print("Jerry: Datos guardados correctamente \(keyChainResult)");
}
}
| true
|
3aa7607693a13f3c090b7ea8f642ad089a7919dd
|
Swift
|
algolia/instantsearch-ios
|
/Tests/InstantSearchCoreTests/Unit/Helpers.swift
|
UTF-8
| 1,110
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
import AlgoliaSearchClient
import Foundation
func safeIndexName(_ name: String) -> IndexName {
var targetName = Bundle.main.object(forInfoDictionaryKey: "BUILD_TARGET_NAME") as? String ?? ""
targetName = targetName.replacingOccurrences(of: " ", with: "-")
let rawName: String
if let travisBuild = ProcessInfo.processInfo.environment["TRAVIS_JOB_NUMBER"] {
rawName = "\(name)_travis_\(travisBuild)"
} else if let bitriseBuild = Bundle.main.object(forInfoDictionaryKey: "BITRISE_BUILD_NUMBER") as? String {
rawName = "\(name)_bitrise_\(bitriseBuild)_\(targetName)"
} else {
rawName = name
}
return IndexName(rawValue: rawName)
}
func average(values: [Double]) -> Double {
return values.reduce(0, +) / Double(values.count)
}
/// Generate a new host name in the `algolia.biz` domain.
/// The DNS lookup for any host in the `algolia.biz` domain will time-out.
/// Generating a new host name every time avoids any system-level or network-level caching side effect.
///
func uniqueAlgoliaBizHost() -> String {
return "swift-\(UInt32(NSDate().timeIntervalSince1970)).algolia.biz"
}
| true
|
7467a994469723785053c6f97d5baf3d8d07577b
|
Swift
|
JonoCX/comic-hub-ios
|
/comic-hub-ios/Comic.swift
|
UTF-8
| 746
| 2.78125
| 3
|
[] |
no_license
|
//
// Comic.swift
// comic-hub-ios
//
// Created by Jonathan Carlton on 26/05/2016.
// Copyright © 2016 Jonathan Carlton. All rights reserved.
//
import Foundation
class Comic {
var id:Int
var name:String
var volume:String
var issue:Int
var publisher:String
var publishedDate:String
var imageRef:String
var inLibrary:Bool
init(id:Int, name:String, volume:String, issue:Int, publisher:String,
publishedDate:String, imageRef:String, inLibrary:Bool) {
self.id = id
self.name = name
self.volume = volume
self.issue = issue
self.publisher = publisher
self.publishedDate = publishedDate
self.imageRef = imageRef
self.inLibrary = inLibrary
}
}
| true
|
18a02581e1de0716965da0a1bd38c6b9629cb473
|
Swift
|
JordiGamez/Marvel_Heroes
|
/Marvel Heroes/Presentation/Presenter/Abstraction/HeroesCollectionPresenterProtocol.swift
|
UTF-8
| 542
| 2.75
| 3
|
[] |
no_license
|
import Foundation
/// Abstraction for HeroesCollectionPresenter
protocol HeroesCollectionPresenterProtocol {
/// Bind the presenter and the view
///
/// - Parameter view: A HeroesCollectionViewProtocol conformance object
func bind(view: HeroesCollectionViewProtocol)
/// Load heroes
func loadHeroes()
/// Detect when the search button is clicked
func searchButtonClicked()
/// Search hero by name
///
/// - Parameter name: The hero name
func searchHeroName(name: String)
}
| true
|
39cad1840fb59a6dbbccc709ecf4c08984c037e1
|
Swift
|
jraggio/match-test
|
/Matchtime/ViewController.swift
|
UTF-8
| 10,671
| 2.78125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Matchtime
//
// Created by Raggios on 5/12/16.
// Copyright © 2016 Raggios. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, MatchingCardGameDelegate {
private let cardReuseIdentifier = "CardCell"
private let numberOfItemsPerRow = 4
private var numberOfCards = 0 // until user selects difficulty
private let removedAlpha = 0.20 // used to dim the matched cards
private var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
private var gameModel:MatchingCardGame?
@IBOutlet weak var cardsCollectionView: UICollectionView!
@IBOutlet weak var scoreLabel: UILabel!
// MARK: Lifetime
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
pickGameLevel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func startNewGame(level:Int){
cardsCollectionView.hidden = true
numberOfCards = level
startActivityIndicator()
scoreLabel.text = "Building new deck..."
gameModel = MatchingCardGame(withDeckSize: numberOfCards, andDelegate: self)
}
// MARK: UICollectionView
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfCards
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
gameModel?.itemSelected(atIndex: indexPath.row)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
// print("cv.cellForItemAtIndexPath caled for \(indexPath.row)")
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cardReuseIdentifier, forIndexPath: indexPath) as!CardCollectionViewCell
if let card = gameModel?.getCard(atIndex: indexPath.row){
if card.isRemoved{
cell.alpha = CGFloat(removedAlpha)
}
else{
cell.alpha = 1
}
cell.cardImage.image = card.image
cell.cardLabel.text = String(indexPath.row + 1)
}
return cell
}
/*
Allows the cells to be sized perfectly to fit the specified number across each row. The constant below is set to 4 for this sample app.
Sizing the cells in IB would not work since even if the correct size was determined it would only work on certain device types and not others.
*/
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
let totalSpace = flowLayout.sectionInset.left
+ flowLayout.sectionInset.right
+ (flowLayout.minimumInteritemSpacing * CGFloat(numberOfItemsPerRow - 1))
let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(numberOfItemsPerRow))
return CGSize(width: size, height: size)
}
// MARK: Utility
func startActivityIndicator() {
let screenSize: CGRect = UIScreen.mainScreen().bounds
activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
activityIndicator.frame = CGRectMake(0, 0, screenSize.width, screenSize.height)
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
// Change background color and alpha channel here
activityIndicator.backgroundColor = UIColor.blackColor()
activityIndicator.clipsToBounds = true
activityIndicator.alpha = 0.5
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
}
func stopActivityIndicator() {
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
/*
Executes the given block on the main thread after a specified delay in seconds.
This is used to flip cards over afer a specified delay if they match and also if
they do not match. Each uses a different delay.
*/
func delayClosure(delay: Double, closure: () -> Void) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
// MARK: UI Events
@IBAction func dealClicked(sender: AnyObject) {
numberOfCards = 4
pickGameLevel()
}
enum Difficulty:Int{
case Easy = 8
case Medium = 16
case Extreme = 32
}
func pickGameLevel() {
let optionMenu = UIAlertController(title: nil, message: "Choose Difficulty", preferredStyle: .ActionSheet)
let easyAction = UIAlertAction(title: "Easy (\(Difficulty.Easy.rawValue))", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
self.startNewGame(Difficulty.Easy.rawValue)
})
let mediumAction = UIAlertAction(title: "Medium (\(Difficulty.Medium.rawValue))", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
self.startNewGame(Difficulty.Medium.rawValue)
})
let extremeAction = UIAlertAction(title: "Extreme (\(Difficulty.Extreme.rawValue))", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in
self.startNewGame(Difficulty.Extreme.rawValue)
})
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
optionMenu.addAction(easyAction)
optionMenu.addAction(mediumAction)
optionMenu.addAction(extremeAction)
optionMenu.addAction(cancelAction)
self.presentViewController(optionMenu, animated: true, completion: nil)
}
// MARK:-
// MARK:MatchingCardGameDelegate
func removeCardsAtIndices(indices: [Int]){
delayClosure(1.0){
for index in indices{
if let cell = self.cardsCollectionView.cellForItemAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as?CardCollectionViewCell{
UIView.animateWithDuration(1,
animations: {
cell.alpha = CGFloat(self.removedAlpha) },
completion: nil)
}
self.gameModel?.clearSelected()
}
}
}
func showCardFrontAtIndex(index: Int){
if let cell = cardsCollectionView.cellForItemAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as?CardCollectionViewCell{
let card = gameModel?.getCard(atIndex: index)
UIView.transitionWithView(cell.contentView,
duration: 0.75,
options: .TransitionFlipFromRight,
animations: { cell.cardImage.image = card?.image },
completion: nil)
}
}
func showCardBacksAtIndices(indices: [Int]){
delayClosure(1.5){
for index in indices{
if let cell = self.cardsCollectionView.cellForItemAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as?CardCollectionViewCell{
let card = self.gameModel?.getCard(atIndex: index)
UIView.transitionWithView(cell.contentView,
duration: 1,
options: .TransitionFlipFromLeft,
animations: { cell.cardImage.image = card?.image },
completion: nil)
}
}
self.scoreLabel.text = "Mismatches: \(self.gameModel?.missCount)"
self.gameModel?.clearSelected()
}
}
func gameReady(){
scoreLabel.text = "Mismatches: 0"
cardsCollectionView.hidden = false
// need to reload the data source since the new game may have a different number of cards
cardsCollectionView.reloadData()
stopActivityIndicator()
}
func gameOver(){
let score = gameModel?.missCount
let alert = UIAlertController(title: "All matches found",
message: "You finished with \(score!) mismatch\(score == 1 ? "":"es")",
preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
self.dismissViewControllerAnimated(true, completion: nil)
self.pickGameLevel()
return
}))
// delay this slightly to give the final two cards a little bit of time to fade away
delayClosure(2.0){
self.presentViewController(alert, animated: true, completion: nil)
}
}
func gameInitFailure(){
let alert = UIAlertController(title: "Error",
message: "Unable to load the card deck from Flickr",
preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
self.dismissViewControllerAnimated(true, completion: nil)
self.pickGameLevel()
return
}))
stopActivityIndicator()
self.presentViewController(alert, animated: true, completion: nil)
}
}
| true
|
d657e630588fa1075d3428703328c424b8eda003
|
Swift
|
silverstar194/KeyboardKit
|
/Sources/KeyboardKit/Views/System/SystemKeyboardSpaceButton.swift
|
UTF-8
| 3,544
| 3.234375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// SystemKeyboardSpaceButton.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2021-01-10.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import SwiftUI
/**
This view mimics a system space button, with custom content,
that takes up as much horizontal space as needed.
This view will adapt its content to conform to the provided
`appearance` and applies keyboard gestures for the provided
`actionHandler` and `context`.
To mimic a native space button, that starts with displaying
a locale text, then fades to the localized name for "space",
use `SystemKeyboardSpaceButtonContent` as content.
*/
public struct SystemKeyboardSpaceButton<Content: View>: View {
/**
Create a system keyboard space button.
- Parameters:
- actionHandler: The name of the current locale, if any.
- appearance: The keyboard appearance to use.
- context: The keyboard context to which the button should apply.
- content: The content to display inside the button.
*/
public init(
actionHandler: KeyboardActionHandler,
appearance: KeyboardAppearance,
context: KeyboardContext,
@ViewBuilder content: @escaping ContentBuilder) {
self.actionHandler = actionHandler
self.appearance = appearance
self.context = context
self.content = content()
}
private let actionHandler: KeyboardActionHandler
private let appearance: KeyboardAppearance
private let context: KeyboardContext
private let content: Content
private var action: KeyboardAction { .space }
@State private var isPressed = false
/**
This typealias represents the configuration action that
is used to customize the content of the button.
*/
public typealias ContentBuilder = () -> Content
public var body: some View {
button
.keyboardGestures(
for: action,
context: context,
actionHandler: actionHandler,
isPressed: $isPressed)
}
}
private extension SystemKeyboardSpaceButton {
var button: some View {
SystemKeyboardButton(
content: content.frame(maxWidth: .infinity),
style: buttonStyle)
}
var buttonStyle: SystemKeyboardButtonStyle {
appearance.systemKeyboardButtonStyle(
for: action,
isPressed: isPressed)
}
}
struct SystemKeyboardSpaceButton_Previews: PreviewProvider {
static var spaceText: some View {
SystemKeyboardSpaceButtonContent(
localeText: KeyboardLocale.english.localizedName,
spaceText: KKL10n.space.text(for: .english))
}
static var spaceView: some View {
SystemKeyboardSpaceButtonContent(
localeText: KeyboardLocale.spanish.localizedName,
spaceView: Text("🇪🇸"))
}
static func button<Content: View>(for content: Content) -> some View {
SystemKeyboardSpaceButton(
actionHandler: PreviewKeyboardActionHandler(),
appearance: .crazy,
context: .preview) {
content.frame(height: 50)
}
}
static var previews: some View {
VStack {
Group {
button(for: spaceText)
button(for: spaceView)
button(for: Image.keyboardGlobe)
}
.padding()
.background(Color.red)
.cornerRadius(10)
}
}
}
| true
|
2e03b44d93a7a3c8755e95fbb59dd90926f62b17
|
Swift
|
stzn/CombineStudy
|
/Sampleapp/ComplexUserRegistrationSwiftUI/ComplexUserRegistrationSwiftUI/Models/AddressCandidate.swift
|
UTF-8
| 2,651
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
//
// AddressCandidate.swift
// ComplexUserRegistration
//
//
import Foundation
import Combine
struct AddressCandidate {
var zipcode: String
var prefecture: String
var city: String
var other: String
}
extension AddressCandidate: Hashable, Identifiable {
var id: Self {
self
}
init(apiResponse: ZipAPIResponse.Address) {
self.zipcode = apiResponse.zipcode
self.prefecture = apiResponse.address1
self.city = apiResponse.address2 + apiResponse.address3
self.other = ""
}
}
struct ZipAPIResponse: Codable {
var message: String?
var status: Int
var results: [Address]
struct Address: Codable {
var address1: String
var address2: String
var address3: String
var zipcode: String
}
}
// MARK: - Zip Client
struct ZipClient {
var get:(Int) -> AnyPublisher<[AddressCandidate], Error>
static let live = ZipClient { zipcode in
let baseURL = URL(string: "https://zipcloud.ibsnet.co.jp/api/search?zipcode=\(zipcode)")!
return URLSession.shared
.dataTaskPublisher(for: baseURL)
.map(\.data)
.decode(type: ZipAPIResponse.self, decoder: JSONDecoder())
.map { result in
result.results.compactMap(AddressCandidate.init(apiResponse:))
}
.eraseToAnyPublisher()
}
static let mock = ZipClient { zipcode in
Just(
[
AddressCandidate(zipcode: "\(zipcode)", prefecture: "Tokyo", city: "Tokyo", other: ""),
AddressCandidate(zipcode: "\(zipcode)", prefecture: "Osaka", city: "Osaka", other: ""),
AddressCandidate(zipcode: "\(zipcode)", prefecture: "Fukuoka", city: "Fukuoka", other: ""),
])
.setFailureType(to: Error.self)
.eraseToAnyPublisher()
}
}
// MARK: - AddressCandidateModel
final class AddressCandidateModel: ObservableObject {
@Published private(set) var addressCandidates: [AddressCandidate] = []
private var cancellables = Set<AnyCancellable>()
func getAddressCandidates(zipcode: Int, using client: ZipClient) {
client.get(zipcode)
.receive(on: DispatchQueue.main)
.sink(receiveCompletion: { finished in
if case .failure(let error) = finished {
print(error.localizedDescription)
}
}, receiveValue: { [weak self] value in
self?.addressCandidates = value
}).store(in: &cancellables)
}
func clearAddressCandidates() {
addressCandidates = []
}
}
| true
|
63f94c762ff003bc1c8b45b1a66883796e6c0d32
|
Swift
|
vdkhiem/ANZTaxCalc
|
/ANZTaxCalc/Models/TaxBucketBase.swift
|
UTF-8
| 815
| 2.921875
| 3
|
[] |
no_license
|
//
// TaxBucketBase.swift
// ANZTaxCalc
//
// Created by Vo Duy Khiem on 6/06/18.
// Copyright © 2018 Vo Duy Khiem. All rights reserved.
//
import Foundation
class TaxBucketBase {
var TaxBucket: [Tax] = []
func TaxRate(bySalary: Double) -> Double {
var incomeTax: Double = 0.0
var maxLimit: Double = 0.0
var exit = false
for i in 0..<TaxBucket.count {
if bySalary < Double(TaxBucket[i].MaxLimit) {
maxLimit = bySalary
exit = true
} else {
maxLimit = Double(TaxBucket[i].MaxLimit)
}
incomeTax += TaxBucket[i].Rate * (maxLimit - Double(TaxBucket[i].MinLimit))
if exit {
return incomeTax
}
}
return incomeTax
}
}
| true
|
ed90adbf0d2943455546a0b5590530756ce4a49c
|
Swift
|
vapor/vapor
|
/Sources/Vapor/Server/Application+Servers.swift
|
UTF-8
| 2,220
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
import NIOConcurrencyHelpers
extension Application {
public var servers: Servers {
.init(application: self)
}
public var server: Server {
guard let makeServer = self.servers.storage.makeServer.withLockedValue({ $0.factory }) else {
fatalError("No server configured. Configure with app.servers.use(...)")
}
return makeServer(self)
}
public struct Servers: Sendable {
public struct Provider {
let run: @Sendable (Application) -> ()
public init(_ run: @Sendable @escaping (Application) -> ()) {
self.run = run
}
}
struct CommandKey: StorageKey {
typealias Value = ServeCommand
}
final class Storage: Sendable {
struct ServerFactory {
let factory: (@Sendable (Application) -> Server)?
}
let makeServer: NIOLockedValueBox<ServerFactory>
init() {
self.makeServer = .init(.init(factory: nil))
}
}
struct Key: StorageKey {
typealias Value = Storage
}
func initialize() {
self.application.storage[Key.self] = .init()
}
public func use(_ provider: Provider) {
provider.run(self.application)
}
public func use(_ makeServer: @Sendable @escaping (Application) -> (Server)) {
self.storage.makeServer.withLockedValue { $0 = .init(factory: makeServer) }
}
public var command: ServeCommand {
if let existing = self.application.storage.get(CommandKey.self) {
return existing
} else {
let new = ServeCommand()
self.application.storage.set(CommandKey.self, to: new) {
$0.shutdown()
}
return new
}
}
let application: Application
var storage: Storage {
guard let storage = self.application.storage[Key.self] else {
fatalError("Servers not initialized. Configure with app.servers.initialize()")
}
return storage
}
}
}
| true
|
1460de955be480de9e89011a400facaeb7340581
|
Swift
|
gongjiehong/LeetcodeDemos
|
/Binary Tree Pruning.playground/Contents.swift
|
UTF-8
| 1,767
| 3.828125
| 4
|
[
"MIT"
] |
permissive
|
import UIKit
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
class Solution {
func pruneTree(_ root: TreeNode?) -> TreeNode? {
// 骚写法,执行完左所有右子树剪枝后如果头结点还是0,则自身也被剪掉
if !nodeContainsOne(root), root?.left == nil, root?.right == nil {
return nil
}
return root
}
/// 判断子树是否有1,如果有,则保留继续向下递归,如果没有,则剪枝
/// - Parameter root: 节点
/// - Returns: 有1 true,没有1false
func nodeContainsOne(_ root: TreeNode?) -> Bool {
guard let root = root else {
return false
}
let leftContainsOne = nodeContainsOne(root.left)
let rightContainsOne = nodeContainsOne(root.right)
if !leftContainsOne {
root.left = nil
}
if !rightContainsOne {
root.right = nil
}
// 这里只要任意一个条件成立,证明当前节点有1
return root.val == 1 || leftContainsOne || rightContainsOne
}
}
let tree = TreeNode(1,
TreeNode(0,
TreeNode(0),
TreeNode(0)),
TreeNode(1,
TreeNode(0),
TreeNode(1)))
Solution().pruneTree(tree)
| true
|
788bbc94ff276e392d0c3deb2b426102de65ba7b
|
Swift
|
MacMark/IAP_Demo_Offical
|
/Swift/macOS/MainViewController.swift
|
UTF-8
| 9,643
| 2.734375
| 3
|
[] |
no_license
|
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
Manages the child view controllers: AvailableProducts, InvalidProductIdentifiers, PurchasesDetails, and MessagesViewController. Requests product
information about a list of product identifiers using StoreManager. Calls StoreObserver to implement the restoration of purchases. Displays a pop-up
menu that allows users to toggle between available products and invalid product identifiers; also between purchased transactions and restored
transactions.
*/
import Cocoa
import StoreKit
class MainViewController: NSViewController {
// MARK: - Properties
@IBOutlet weak fileprivate var popUpMenu: NSPopUpButton!
@IBOutlet weak fileprivate var stackView: NSStackView!
@IBOutlet weak fileprivate var containerView: NSView!
fileprivate var utility = Utilities()
fileprivate var purchaseType: SectionType = .purchased
fileprivate var storeResponse = [Section]()
fileprivate var contentType: ViewControllerNames = .products {
didSet {
purchaseType = ((contentType == .purchases) && utility.restoreWasCalled) ? .restored : .purchased
}
}
// MARK: - Instantiate View Controllers
fileprivate lazy var availableProducts: AvailableProducts = {
let identifier: NSStoryboard.SceneIdentifier = ViewControllerIdentifiers.availableProducts
guard let controller = storyboard?.instantiateController(withIdentifier: identifier) as? AvailableProducts
else { fatalError("\(Messages.unableToInstantiateAvailableProducts)") }
return controller
}()
fileprivate lazy var invalidIdentifiers: InvalidProductIdentifiers = {
let identifier: NSStoryboard.SceneIdentifier = ViewControllerIdentifiers.invalidProductdentifiers
guard let controller = storyboard?.instantiateController(withIdentifier: identifier) as? InvalidProductIdentifiers
else { fatalError("\(Messages.unableToInstantiateInvalidProductIds)") }
return controller
}()
fileprivate lazy var messagesViewController: MessagesViewController = {
let identifier: NSStoryboard.SceneIdentifier = ViewControllerIdentifiers.messages
guard let controller = storyboard?.instantiateController(withIdentifier: identifier) as? MessagesViewController
else { fatalError("\(Messages.unableToInstantiateMessages)") }
return controller
}()
fileprivate lazy var purchasesDetails: PurchasesDetails = {
let identifier: NSStoryboard.SceneIdentifier = ViewControllerIdentifiers.purchases
guard let controller = storyboard?.instantiateController(withIdentifier: identifier) as? PurchasesDetails
else { fatalError("\(Messages.unableToInstantiateMessages)") }
return controller
}()
// MARK: - View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
disableUI()
StoreManager.shared.delegate = self
StoreObserver.shared.delegate = self
}
// MARK: - Populate Pop Up Menu
/// Used to update the UI with available products, invalid identifiers, purchases, or restored purchases.
@IBAction fileprivate func popUpMenuDidChangeValue(_ sender: NSPopUpButton) {
guard let title = sender.titleOfSelectedItem, let type = SectionType(rawValue: title) else { return }
switch type {
case .availableProducts:
if let section = Section.parse(storeResponse, for: .availableProducts), let items = section.elements as? [SKProduct], !items.isEmpty {
switchToViewController(availableProducts)
availableProducts.reload(with: items)
}
case .invalidProductIdentifiers:
if let section = Section.parse(storeResponse, for: .invalidProductIdentifiers), let items = section.elements as? [String], !items.isEmpty {
switchToViewController(invalidIdentifiers)
invalidIdentifiers.reload(with: items)
}
case .purchased: utility.restoreWasCalled = false
case .restored: utility.restoreWasCalled = true
default: break
}
if contentType == .purchases {
let data = utility.dataSourceForPurchasesUI
purchaseType = type
if let transactions = Section.parse(data, for: type)?.elements as? [SKPaymentTransaction] {
purchasesDetails.reload(with: transactions)
}
}
}
/// Updates the pop-up menu with the given items and selects the item with the specified title.
fileprivate func reloadPopUpMenu(with items: [String], andSelectItemWithTitle title: String) {
popUpMenu.removeAllItems()
if !items.isEmpty {
popUpMenu.addItems(withTitles: items)
popUpMenu.selectItem(withTitle: title)
}
}
// MARK: - Handle Restored Transactions
/// Handles succesful restored transactions. Switches to the Purchases view.
fileprivate func handleRestoredSucceededTransaction() {
utility.restoreWasCalled = true
contentType = .purchases
reloadViewController(.purchases)
}
// MARK: - Switching Between View Controllers
/// Adds a child view controller to the container.
fileprivate func addPrimaryViewController(_ viewController: NSViewController) {
addChild(viewController)
var newViewControllerFrame = viewController.view.frame
newViewControllerFrame.size.height = containerView.frame.height
newViewControllerFrame.size.width = containerView.frame.width
viewController.view.frame = newViewControllerFrame
containerView.addSubview(viewController.view)
NSLayoutConstraint.activate([viewController.view.topAnchor.constraint(equalTo: containerView.topAnchor),
viewController.view.bottomAnchor.constraint(equalTo: containerView.bottomAnchor),
viewController.view.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
viewController.view.trailingAnchor.constraint(equalTo: containerView.trailingAnchor)])
}
/// Removes a child view controller from the container.
fileprivate func removePrimaryViewController(_ viewController: NSViewController) {
viewController.view.removeFromSuperview()
viewController.removeFromParent()
}
/// Removes all child view controllers from the container.
fileprivate func removeAllPrimaryChildViewControllers() {
for child in children {
removePrimaryViewController(child)
}
}
// MARK: - Configure UI
/// Hides the pop-up button and the status message.
fileprivate func disableUI() {
if self.isViewLoaded {
popUpMenu.hide()
self.view.layoutSubtreeIfNeeded()
}
}
/// Displays the specified view controller.
func switchToViewController(_ viewController: NSViewController) {
removeAllPrimaryChildViewControllers()
addPrimaryViewController(viewController)
}
/// Reloads the UI of the specified view controller.
func reloadViewController(_ viewController: ViewControllerNames, with message: String = String()) {
disableUI()
contentType = viewController
var menu = [String]()
var selectedItem = String()
let resourceFile = ProductIdentifiers()
if viewController == .messages {
switchToViewController(messagesViewController)
messagesViewController.message = message
} else if viewController == .products {
guard let identifiers = resourceFile.identifiers else { return }
popUpMenu.show()
self.view.layoutSubtreeIfNeeded()
selectedItem = SectionType.invalidProductIdentifiers.description
menu.append(selectedItem)
switchToViewController(invalidIdentifiers)
invalidIdentifiers.reload(with: identifiers)
storeResponse = [Section(type: .invalidProductIdentifiers, elements: identifiers)]
// Fetch product information.
StoreManager.shared.startProductRequest(with: identifiers)
} else if viewController == .purchases {
let data = utility.dataSourceForPurchasesUI
if !data.isEmpty {
popUpMenu.show()
selectedItem = purchaseType.description
menu = data.compactMap { (item: Section) in item.type.description }
guard let transactions = Section.parse(data, for: purchaseType)!.elements as? [SKPaymentTransaction] else { return }
switchToViewController(purchasesDetails)
purchasesDetails.reload(with: transactions)
} else {
switchToViewController(messagesViewController)
messagesViewController.message = "\(Messages.noPurchasesAvailable)\n\(Messages.useStoreRestore)"
}
}
if !menu.isEmpty && !selectedItem.isEmpty {
reloadPopUpMenu(with: menu, andSelectItemWithTitle: selectedItem)
}
}
}
// MARK: - StoreManagerDelegate
/// Extends MainViewController to conform to StoreManagerDelegate.
extension MainViewController: StoreManagerDelegate {
func storeManagerDidReceiveResponse(_ response: [Section]) {
if !response.isEmpty {
var selectedItem = String()
contentType = .products
storeResponse = response
let menu: [String] = response.compactMap { (item: Section) in item.type.description }
if let section = Section.parse(response, for: .invalidProductIdentifiers),
let items = section.elements as? [String] {
selectedItem = SectionType.invalidProductIdentifiers.description
switchToViewController(invalidIdentifiers)
invalidIdentifiers.reload(with: items)
}
if let section = Section.parse(response, for: .availableProducts),
let items = section.elements as? [SKProduct] {
selectedItem = SectionType.availableProducts.description
switchToViewController(availableProducts)
availableProducts.reload(with: items)
}
reloadPopUpMenu(with: menu, andSelectItemWithTitle: selectedItem)
}
}
func storeManagerDidReceiveMessage(_ message: String) {
reloadViewController(.messages, with: message)
}
}
// MARK: - StoreObserverDelegate
/// Extends MainViewController to conform to StoreObserverDelegate.
extension MainViewController: StoreObserverDelegate {
func storeObserverDidReceiveMessage(_ message: String) {
reloadViewController(.messages, with: message)
}
func storeObserverRestoreDidSucceed() {
handleRestoredSucceededTransaction()
}
}
| true
|
0d87e2a6b0309ecc043350e629c706a684fd7bf6
|
Swift
|
kbw2204/algorismSwift
|
/문자열/공백왕빈칸/공백왕빈칸/main.swift
|
UTF-8
| 2,002
| 3.3125
| 3
|
[] |
no_license
|
//
// main.swift
// 공백왕빈칸
//
// Created by 강병우 on 2020/05/23.
// Copyright © 2020 강병우. All rights reserved.
//
import Foundation
func solution(input: String) {
var arr: [String] = input.components(separatedBy: "\n")
var doubleArr: [[String]] = []
var countArr: [Int] = []
for i in 0 ..< arr.count {
while arr[i].contains(" ") {
arr[i] = arr[i].replacingOccurrences(of: " ", with: " ")
}
// 뒤 빈칸 삭제
while arr[i].last == Character(" ") {
arr[i].removeLast()
}
//앞 빈칸
arr[i] = String(arr[i].reversed())
while arr[i].last == Character(" ") {
arr[i].removeLast()
}
arr[i] = String(arr[i].reversed())
let line: [String] = arr[i].components(separatedBy: " ")
doubleArr.append(line)
for c in 0 ..< line.count {
if countArr.count < c + 1 {
countArr.append(line[c].count)
} else {
let count = line[c].count
if count > countArr[c] {
countArr[c] = count
}
}
}
}
for i in 0 ..< doubleArr.count {
var line: String = ""
for j in 0 ..< doubleArr[i].count {
line += adjust(str: doubleArr[i][j], size: countArr[j])
if j != doubleArr[i].count - 1 {
line += " "
}
}
while line.last == Character(" ") {
line.removeLast()
}
print(line)
}
}
func adjust(str: String, size: Int) -> String {
let count = size - str.count
var vStr = str
for _ in 0 ..< count {
vStr = vStr + " "
}
return vStr
}
let input = " start: integer; // begins here\nstop: integer; // ends here\n s: string;\nc: char; // temp "
//let input = "a bc z\nde f zz"
//let input: String = readLine()!
solution(input: input)
| true
|
d8052a47f90b25fa429377e3e29099e13fe2dd05
|
Swift
|
chinaysun/LandmarkRemark
|
/LandmarkRemark/Screens/MarkDetail/MarkDetailViewController.swift
|
UTF-8
| 2,650
| 2.859375
| 3
|
[] |
no_license
|
//
// MarkDetailViewController.swift
// LandmarkRemark
//
// Created by Yu Sun on 31/8/19.
// Copyright © 2019 Yu Sun. All rights reserved.
//
import UIKit
struct MarkDetailViewControllerModel {
let heading: String
let title: String
let note: String
}
final class MarkDetailViewController: UIViewController {
private let model: MarkDetailViewControllerModel
private let horizontalPadding: CGFloat = 16
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = .systemFont(ofSize: 13, weight: .medium)
label.textAlignment = .center
return label
}()
private lazy var noteTextView: UITextView = {
let view = UITextView()
view.translatesAutoresizingMaskIntoConstraints = false
view.font = .systemFont(ofSize: 12, weight: .regular)
view.textAlignment = .justified
view.textColor = .gray
view.layer.cornerRadius = 2
view.layer.borderColor = UIColor.black.withAlphaComponent(0.5).cgColor
view.layer.borderWidth = 1
view.isEditable = false
return view
}()
init(model: MarkDetailViewControllerModel) {
self.model = model
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(titleLabel)
view.addSubview(noteTextView)
layout()
prepareViewModel()
}
private func layout() {
NSLayoutConstraint.activate([
titleLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 20),
titleLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: horizontalPadding),
titleLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -horizontalPadding),
noteTextView.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 12),
noteTextView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: horizontalPadding),
noteTextView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -horizontalPadding),
noteTextView.bottomAnchor.constraint(equalTo: viewSafeBottomAnchor)
])
}
private func prepareViewModel() {
title = model.heading
titleLabel.text = model.title
noteTextView.text = model.note
}
}
| true
|
04339d99950ecc5cebf5d7793cd7bc758ee16dc9
|
Swift
|
LiberAC/CV
|
/CVMVVMTests/ListControllerTest.swift
|
UTF-8
| 2,607
| 2.625
| 3
|
[] |
no_license
|
//
// ListControllerTest.swift
// CVMVVMTests
//
// Created by Liber Alfonso on 5/13/19.
// Copyright © 2019 LAC. All rights reserved.
//
import XCTest
class ListControllerTest: XCTestCase {
let listController : CVListController = CVListController()
var data: CVData? = nil
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
let anURL = URL(string: "https://as2.ftcdn.net/jpg/01/47/82/43/500_F_147824394_y6VTXKqUOjWarhztDqx0UmqOo45ARn5F.jpg")
let job = Jobs(company: "company",
role: "role",
description: "description",
companyLogo:anURL!)
let skill = Skills(skillName: "name", experienceYears: "1", skillLogo: anURL!)
self.data = CVData(summary: "summary", jobs: [job], skills: [skill])
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
self.data = nil
}
func testHarCodedModelGeneration() {
listController.createViewModels(cv: data!)
XCTAssertEqual(listController.viewModel.sectionViewModels.value.count, 3, "Expected 3 models")
let summary = listController.viewModel.sectionViewModels.value.first
XCTAssertEqual(summary?.rowViewModels.count, 1, "Expected 1 model")
guard let _ = summary?.rowViewModels.first as? SummaryCellViewModel else {
XCTAssert(false, "Expected SummaryCellViewModel class")
return
}
}
func testModelGenerationfromWS(){
let expectation = self.expectation(description: "consulting")
var aCVData: CVData?
var anError : Error?
let apiClient = APIClient()
apiClient.getCVData( completion: { result in
expectation.fulfill()
switch result {
case .success(let cvData):
aCVData = cvData
case .failure(let error):
anError = error
}
})
waitForExpectations(timeout: 5, handler: nil)
XCTAssertNil(anError)
XCTAssertNotNil(aCVData)
listController.createViewModels(cv: aCVData!)
XCTAssertEqual(listController.viewModel.sectionViewModels.value.count, 3, "Expected 3 models")
let jobs = listController.viewModel.sectionViewModels.value[1]
XCTAssertEqual(jobs.rowViewModels.count, 2, "Expected 2 model")
}
}
| true
|
6a1a6211f32f0e15ec1a2a4cdd7df19ecbb4dbfb
|
Swift
|
adamhorner/AdventOfCode2019
|
/2022/AoC 2022 Day08/AoC 2022 Day08/main.swift
|
UTF-8
| 4,818
| 3.5
| 4
|
[] |
no_license
|
//
// main.swift
// AoC 2022 Day08
//
// Created by Adam Horner on 08/12/2022.
//
import Foundation
let datafile = "/Users/adam/Development/Personal/AdventOfCode/2022/day08-data.txt"
var inputText: String
do {
inputText = try String(contentsOfFile: datafile)
} catch {
print("Couldn't read text file \(datafile), exiting")
exit(1)
}
//MARK: - Data Structures
struct TreeMap {
var treeMap: [[Int]] = []
var currentRow: Int = -1
mutating func addRow() {
let newRow: [Int] = []
treeMap.append(newRow)
currentRow += 1
}
mutating func addTree(height: Int) {
treeMap[currentRow].append(height)
}
func getHeight(row: Int, column: Int) -> Int {
return treeMap[row][column]
}
func columnLength() -> Int {
return treeMap.count
}
func rowLength(_ row: Int? = nil) -> Int {
// use currentRow if row is not specified
let myRow = row ?? currentRow
assert(myRow >= 0)
return treeMap[myRow].count
}
func getColumn(_ column: Int) -> [Int] {
var columnHeights: [Int] = []
for row in 0..<columnLength() {
columnHeights.append(treeMap[row][column])
}
return columnHeights
}
func isVisible(row: Int, column: Int) -> Bool {
let rowLength = rowLength(row)
let columnLength = columnLength()
assert(row >= 0 || row < rowLength || column >= 0 || column < columnLength, "given row or column are outside bounds of treemap, row: \(row), column: \(column)")
if row == 0 || column == 0 || row == rowLength-1 || column == columnLength-1 {
return true
}
let myHeight = getHeight(row: row, column: column)
let maxLeft = treeMap[row][0..<column].reduce(Int.min, max)
if maxLeft < myHeight {
return true
}
let maxRight = treeMap[row][column+1..<rowLength].reduce(Int.min, max)
if maxRight < myHeight {
return true
}
let treeColumn = getColumn(column)
let maxTop = treeColumn[0..<row].reduce(Int.min, max)
if maxTop < myHeight {
return true
}
let maxBottom = treeColumn[row+1..<columnLength].reduce(Int.min, max)
if maxBottom < myHeight {
return true
}
//else
return false
}
func scenicScore(row: Int, column: Int) -> Int {
let rowLength = rowLength(row)
let columnLength = columnLength()
assert(row >= 0 || row < rowLength || column >= 0 || column < columnLength, "given row or column are outside bounds of treemap, row: \(row), column: \(column)")
if row == 0 || column == 0 || row == rowLength-1 || column == columnLength-1 {
return 0
}
let myHeight = getHeight(row: row, column: column)
var northCount = 0
var southCount = 0
var eastCount = 0
var westCount = 0
for north in stride(from: row-1, through: 0, by: -1) {
northCount += 1
if getHeight(row: north, column: column) >= myHeight {
break
}
}
for west in stride(from: column-1, through: 0, by: -1) {
westCount += 1
if getHeight(row: row, column: west) >= myHeight {
break
}
}
for south in row+1..<rowLength {
southCount += 1
if getHeight(row: south, column: column) >= myHeight {
break
}
}
for east in column+1..<columnLength {
eastCount += 1
if getHeight(row: row, column: east) >= myHeight {
break
}
}
return northCount * southCount * eastCount * westCount
}
}
//MARK: - Main Loop
var rows = inputText.split(separator: "\n")
var treeMap = TreeMap()
for row in rows {
treeMap.addRow()
let treeHeights = row.split(separator: "")
for treeHeight in treeHeights {
treeMap.addTree(height: Int(treeHeight)!)
}
}
// map built, let's check it has the expected number of rows and columns
print("TreeMap built, rows: \(treeMap.columnLength()), columns: \(treeMap.rowLength())")
var visibleTreeCount = 0
for row in 0..<treeMap.rowLength() {
for column in 0..<treeMap.columnLength() {
if treeMap.isVisible(row: row, column: column) {
visibleTreeCount += 1
}
}
}
print("Visible tree count in treeMap: \(visibleTreeCount)")
var maxScenicScore = 0
for row in 0..<treeMap.rowLength() {
for column in 0..<treeMap.columnLength() {
maxScenicScore = max(maxScenicScore, treeMap.scenicScore(row: row, column: column))
}
}
print("Maximum scenic score in treeMap: \(maxScenicScore)")
| true
|
0ec8cc5abaea623fb4c220eaae78b1bc0cf11851
|
Swift
|
johndpope/swift-ast-explorer
|
/Sources/swift-ast-explorer/main.swift
|
UTF-8
| 3,264
| 2.796875
| 3
|
[
"Apache-2.0"
] |
permissive
|
import Foundation
import Basic
import SwiftSyntax
class TokenVisitor : SyntaxVisitor {
var list = [String]()
var types = [ImportDeclSyntax.self, StructDeclSyntax.self, ClassDeclSyntax.self, UnknownDeclSyntax.self, FunctionDeclSyntax.self, VariableDeclSyntax.self,
IfStmtSyntax.self, SwitchStmtSyntax.self, ForInStmtSyntax.self, WhileStmtSyntax.self, RepeatWhileStmtSyntax.self,
DoStmtSyntax.self, CatchClauseSyntax.self, FunctionCallExprSyntax.self] as [Any.Type]
override func visitPre(_ node: Syntax) {
for t in types {
if type(of: node) == t {
list.append("<div class=\"box \(type(of: node))\" data-tooltip=\"\(type(of: node))\">")
}
}
}
override func visit(_ token: TokenSyntax) {
token.leadingTrivia.forEach { (piece) in
processTriviaPiece(piece)
}
processToken(token)
token.trailingTrivia.forEach { (piece) in
processTriviaPiece(piece)
}
}
override func visitPost(_ node: Syntax) {
for t in types {
if type(of: node) == t {
list.append("</div>")
}
}
}
private func processToken(_ token: TokenSyntax) {
var kind = "\(token.tokenKind)"
if let index = kind.index(of: "(") {
kind = String(kind.prefix(upTo: index))
}
if kind.hasSuffix("Keyword") {
kind = "keyword"
}
list.append(withSpanTag(class: kind, text: token.text))
}
private func processTriviaPiece(_ piece: TriviaPiece) {
switch piece {
case .spaces(let count):
list.append(String(repeating: " ", count: count))
case .newlines(let count), .carriageReturns(let count), .carriageReturnLineFeeds(let count):
var count = count
if let last = list.last, last.hasPrefix("<div") {
count -= 1
}
for _ in 0..<count {
list.append("<br>\n")
}
case .backticks(let count):
list.append(String(repeating: "`", count: count))
case .lineComment(let text), .blockComment(let text), .docLineComment(let text), .docBlockComment(let text):
list.append(withSpanTag(class: "comment", text: text))
default:
break
}
}
private func withSpanTag(class c: String, text: String) -> String {
return "<span class='\(c)'>" + text + "</span>"
}
}
let arguments = Array(CommandLine.arguments.dropFirst())
let filePath = URL(fileURLWithPath: arguments[0])
let sourceFile = try! SourceFileSyntax.parse(filePath)
let visitor = TokenVisitor()
visitor.visit(sourceFile)
let html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
Swift AST Explorer
</title>
<link rel="stylesheet" href="css/default.css" type="text/css" />
</head>
<body>
\(visitor.list.joined())
</body>
</html>
"""
let htmlPath = filePath.deletingPathExtension().appendingPathExtension("html")
let fileSystem = Basic.localFileSystem
try! fileSystem.writeFileContents(AbsolutePath(htmlPath.path), bytes: ByteString(encodingAsUTF8: html))
| true
|
a5b1b01310fdc3ce2f32aece43888e619a6df23e
|
Swift
|
rheehot/This-is-Swift
|
/CollectionType.playground/Pages/Set.xcplaygroundpage/Contents.swift
|
UTF-8
| 1,876
| 4.8125
| 5
|
[] |
no_license
|
//: [Previous](@previous)
import Foundation
/*:
# Set
Set 형태로 저장되기 위해서는 반드시 타입이 hashable
Array와 마찬가지로 같은 타입만 넣을수 있다.
*/
var letters = Set<Character>()
print(letters.count)
letters.insert("a")
print(letters)
letters = []
print(letters)
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip Hop"]
print(favoriteGenres)
var favoriteGenres2: Set = ["Rock", "Classical", "Hip Hop"]
favoriteGenres2.update(with: "Ballad")
favoriteGenres2.remove("Classical")
// favoriteGenres2에서 Hip Hop을 가지는 인덱스 삭제
favoriteGenres2.remove(at: favoriteGenres2.firstIndex(of: "Hip Hop")!)
// Set은 중복된 값을 허용하지 않기 때문에 같은 값을 넣어도 변화가 없다.
favoriteGenres2.insert("Rock")
print(favoriteGenres2)
// Set의 특별한 메서드
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
// 합집합
print(oddDigits.union(evenDigits).sorted(by: <))
// 교집합 (중복된 값 출력)
print(oddDigits.intersection(evenDigits))
// A.subtracting(B) A에만 포함되어있는 집합
print(oddDigits.subtracting(singleDigitPrimeNumbers).sorted(by: <))
// 합집합 - 교집합
print(oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted(by: <))
// Set 동등 비교
let houseAnimals: Set = ["Dog", "Cat"]
let farmAnimals: Set = ["Cow", "Chicken", "Sheep", "Dog", "Cat"]
let cityAnimals: Set = ["Pigeon", "Mouse"]
// A.isSubset(of: B) A가 B에 포함이 되는지 true/false
houseAnimals.isSubset(of: farmAnimals)
// A.isSuperset(of: B) A가 B의 상위집합인지 true/false
farmAnimals.isSuperset(of: houseAnimals)
// A.isDisjoint(with: B) A와 B의 교집합이 없을때 true 교집합이 있을 경우 false
farmAnimals.isDisjoint(with: cityAnimals)
//: [Next](@next)
| true
|
eee125b52baa64b7c84e35f5c10e533c2eb14d99
|
Swift
|
chenjm0617/map
|
/aWeMap/aWeMap/ViewController.swift
|
UTF-8
| 4,272
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// aWeMap
//
// Created by qianfeng on 16/9/8.
// Copyright © 2016年 SOLO. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let mapView = MAMapView.init(frame: UIScreen.mainScreen().bounds)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.addSubview(mapView)
//地图类型:普通和卫星,默认是普通
mapView.mapType = .Standard
//路况信息
mapView.showTraffic = false
//logo中心点坐标,logo必须完整的展示在mapView里
mapView.logoCenter = CGPointMake(0, 0)
//指南针/罗盘
//mapView.showsCompass = false
mapView.compassOrigin = CGPointMake(350, 30)
//比例尺
//mapView.showsScale = false
mapView.scaleOrigin = CGPointMake(10, 30)
//用代码缩放地图,缩放级别3到19
mapView.setZoomLevel(11, animated: true)
//设置允许缩放的范围
mapView.minZoomLevel = 3
mapView.maxZoomLevel = 19
//成为代理
mapView.delegate = self
//添加地图标记
let annotation = MAPointAnnotation()
//标记的经纬度 先纬度 后经度
annotation.coordinate = CLLocationCoordinate2DMake(39.989631, 116.481018)
annotation.title = "方恒国际"
annotation.subtitle = "阜通东大街6号"
mapView.addAnnotation(annotation)
//定位
mapView.showsUserLocation = true
mapView.setUserTrackingMode(.Follow, animated: true)
}
override func viewDidAppear(animated: Bool) {
/*
let iconView = UIImageView.init(frame: CGRectMake(0, 0, 200, 200))
self.view.addSubview(iconView)
//地图截屏:从mapView里截出一张图片
iconView.image = mapView.takeSnapshotInRect(iconView.frame)
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: MAMapViewDelegate {
func mapView(mapView: MAMapView!, viewForAnnotation annotation: MAAnnotation!) -> MAAnnotationView! {
//如果annotation不是MAPointAnnotation这个类就直接return
if !annotation.isKindOfClass(MAPointAnnotation) {
return nil
}
/*
#if false
//默认的大头针样式
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("qqq") as? MAPinAnnotationView
if annotationView == nil {
annotationView = MAPinAnnotationView.init(annotation: annotation, reuseIdentifier: "qqq")
}
//是否显示气泡
annotationView?.canShowCallout = true
//以动画形式
annotationView?.animatesDrop = true
//设置标注可以拖动
annotationView?.draggable = true
//设置大头针的颜色
annotationView?.pinColor = .Purple
#else
//自定制大头针的图片
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("qqq")
if annotationView == nil {
annotationView = MAAnnotationView.init(annotation: annotation, reuseIdentifier: "qqq")
}
annotationView.image = UIImage.init(named: "111")
annotationView.canShowCallout = true
annotationView?.draggable = true
//设置中心点的便宜
annotationView.centerOffset = CGPointMake(0, 0)
#endif
*/
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier("qqq") as? MyAnnotationView
if annotationView == nil {
annotationView = MyAnnotationView(annotation: annotation, reuseIdentifier: "qqq")
}
annotationView?.image = UIImage.init(named: "111")
annotationView?.canShowCallout = false
annotationView?.draggable = true
return annotationView!
}
}
| true
|
a6434745b3e0c58b122f72d84b9313c979500d14
|
Swift
|
sophie-traynor/MyFilms
|
/MyFilms/MovieViewController.swift
|
UTF-8
| 9,017
| 2.6875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// MyFilms
//
// Created by Sophie Traynor on 02/11/2017.
// Copyright © 2017 Sophie Traynor. All rights reserved.
//
import UIKit
import os.log
class MovieViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPickerViewDataSource, UIPickerViewDelegate, UITextViewDelegate {
//MARK: Properties
@IBOutlet weak var avoidingView: UIView!
@IBOutlet weak var movieNameTextField: UITextField!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var ratingControl: RatingControl!
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var genreTextField: UITextField!
@IBOutlet weak var yearTextField: UITextField!
@IBOutlet weak var ageSegmentedControl: UISegmentedControl!
@IBOutlet weak var reviewTextView: UITextView!
var movie: Movie?
var pickGenre = ["Action", "Adventure", "Comedy", "Crime", "Drama", "Historical", "Horror","Kids", "Musical", "Sci-Fi", "War", "Western", "Not Listed"]
var maxLength = 4
override func viewDidLoad() {
super.viewDidLoad()
//Set up views if editing an existing movie
if let movie = movie {
navigationItem.title = movie.name
movieNameTextField.text = movie.name
photoImageView.image = movie.photo
ratingControl.rating = movie.rating
yearTextField.text = movie.year
genreTextField.text = movie.genre
ageSegmentedControl.selectedSegmentIndex = movie.age
reviewTextView.text = movie.review
}
//Set up genre picker view
let genrePickerView = UIPickerView()
genrePickerView.delegate = self
genreTextField.inputView = genrePickerView
yearTextField.keyboardType = UIKeyboardType.numberPad
movieNameTextField.returnKeyType = .done
reviewTextView.layer.borderWidth = 1
//Move view up when fields in view are clicked
KeyboardAvoiding.avoidingView = self.avoidingView
//Handle the text fields user input through delegate callbacks
movieNameTextField.delegate = self
yearTextField.delegate = self
setUpToolbar()
updateSaveButtonState()
}
//MARK: Done Button
func setUpToolbar()
{
let toolbar = UIToolbar()
toolbar.sizeToFit()
let doneButton = UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem
.done, target: self, action: #selector(self.doneClicked))
toolbar.setItems([doneButton], animated: false)
yearTextField.inputAccessoryView = toolbar
genreTextField.inputAccessoryView = toolbar
reviewTextView.inputAccessoryView = toolbar
}
@objc func doneClicked()
{
view.endEditing(true)
updateSaveButtonState()
}
//MARK: PickerView
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickGenre.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickGenre[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
genreTextField.text = pickGenre[row]
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
movieNameTextField.resignFirstResponder()
yearTextField.resignFirstResponder()
updateSaveButtonState()
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
updateSaveButtonState()
if textField == movieNameTextField {
navigationItem.title = textField.text
}
}
func textFieldDidBeginEditing(_ textField: UITextField) {
// Disable the Save button while editing.
saveButton.isEnabled = false
}
//Allow numbers only to be entered into Year text field else allow any
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == yearTextField {
let allowedCharacters = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: string)
return allowedCharacters.isSuperset(of: characterSet)
}
else{
return true
}
}
// These delegate methods can be used so that test fields that are
// hidden by the keyboard are shown when they are focused
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField == self.reviewTextView {
KeyboardAvoiding.padding = 20
KeyboardAvoiding.avoidingView = self.avoidingView
KeyboardAvoiding.padding = 0
}
return true
}
//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
//Dismiss the picker if the user cancelled
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//The info dictionary may contain multiple representations of the image
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
//Set photoImageView to display the selected image
photoImageView.image = selectedImage
//Dismiss the picker
dismiss(animated:true, completion: nil)
}
//MARK: Navigation
@IBAction func cancel(_ sender: UIBarButtonItem) {
//Depending on style of presentation (modal or push presentation), this vie controller needs to be dismissed in two different ways
let isPresentingInAddMovieMode = presentingViewController is UINavigationController
if isPresentingInAddMovieMode {
dismiss(animated: true, completion: nil)
}
else if let owningNavigationController = navigationController {
owningNavigationController.popViewController(animated: true)
}
else {
fatalError("The MovieViewController is not inside a navigation controller")
}
}
//This method lets you configure a view controller before it's presented.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
// Configure the destination view controller only when the save button is pressed.
guard let button = sender as? UIBarButtonItem, button === saveButton else {
os_log("The save button was not pressed, cancelling", log: OSLog.default, type: .debug)
return
}
let name = movieNameTextField.text ?? ""
let photo = photoImageView.image
let rating = ratingControl.rating
let year = yearTextField.text ?? ""
let genre = genreTextField.text ?? ""
let age = ageSegmentedControl.selectedSegmentIndex
let review = reviewTextView.text
// Set the movie to be passed to MovieTableViewController after the unwind segue.
movie = Movie(name: name, photo: photo, rating: rating, year: year, genre: genre, age: age, review: review)
}
//MARK: Actions
@IBAction func limitWhileEditing(_ sender: Any) {
if yearTextField.text!.count > maxLength {
yearTextField.text?.removeLast()
}
}
@IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
//UIImagePickerController is a view controller that lets a user pick media from their photo library
let imagePickerController = UIImagePickerController()
//Only allow photos to be picked, not taken
imagePickerController.sourceType = .photoLibrary
//Make sure ViewController is notified when the user picks an image
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
//MARK: Private Methods
private func updateSaveButtonState() {
//Disable the Save button if the text field is empty.
let nameText = movieNameTextField.text ?? ""
let yearText = yearTextField.text ?? ""
let genreText = genreTextField.text ?? ""
saveButton.isEnabled = !nameText.isEmpty && !yearText.isEmpty && !genreText.isEmpty
}
}
| true
|
e2346ece7685b19472e784fed073f43e015271b2
|
Swift
|
ololx/simple-ram-disk
|
/commons/process/Action.swift
|
UTF-8
| 584
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
//
// Action.swift
// simple ram disk
//
// Created by Alexander A. Kropotin on 24.03.2021.
//
import Foundation
public struct Action {
public enum Method: Int {
case LAUNCH = 0
case LAUNCH_AND_WAIT = 1
}
private var process: Process!
private var type: Method!
public init(some process: Process!, type: Method!) {
self.process = process;
self.type = type;
}
public func getProcess() -> Process! {
return self.process;
}
public func getType() -> Method {
return self.type;
}
}
| true
|
7d179e77862b96d9dc8f71fc0cbdd3bcd5a3578e
|
Swift
|
sajjadsarkoobi/filmFestTDD
|
/filmFest/Models/Movie.swift
|
UTF-8
| 366
| 2.640625
| 3
|
[] |
no_license
|
//
// Movie.swift
// filmFest
//
// Created by Sajjad Sarkoobi on 8/19/20.
// Copyright © 2020 sajjad. All rights reserved.
//
import Foundation
struct Movie: Equatable{
let title:String
let releaseDate:String?
init(title:String, releaseDate:String? = nil) {
self.title = title
self.releaseDate = releaseDate
}
}
| true
|
64c9356fd8b31f95f44da719099093a293146f2c
|
Swift
|
sttbtt/ios-journal-REST
|
/Journal/Journal/View Controllers/EntriesTableViewController.swift
|
UTF-8
| 2,885
| 2.765625
| 3
|
[] |
no_license
|
//
// EntriesTableViewController.swift
// Journal
//
// Created by Scott Bennett on 9/20/18.
// Copyright © 2018 Scott Bennett. All rights reserved.
//
import UIKit
class EntriesTableViewController: UITableViewController {
let entryController = EntryController()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
entryController.fetchEntries { (error) in
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return entryController.entries.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "JournalCell", for: indexPath) as? EntryTableViewCell else { return UITableViewCell() }
let entry = entryController.entries[indexPath.row]
cell.titleLabel.text = entry.title
let dateFormatter = DateFormatter()
cell.timeStampLabel.text = dateFormatter.string(from: entry.timestamp)
cell.bodyTextLabel.text = entry.bodyText
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 to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
entryController.entries.remove(at: indexPath.row)
}
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ViewEntry" {
guard let destinationVC = segue.destination as? EntryDetailViewController,
let indexPath = tableView.indexPathForSelectedRow else { return }
let entry = entryController.entries[indexPath.row]
destinationVC.entryController = entryController
destinationVC.entry = entry
}
if segue.identifier == "NewEntry" {
guard let destinationVC = segue.destination as? EntryDetailViewController else { return }
destinationVC.entryController = entryController
}
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
}
| true
|
03f8e5b59391923bd8febfc9a8494b4d8295f350
|
Swift
|
mavlink/MAVSDK-Swift-Example
|
/Mavsdk-Swift-Example/App/Menu/Camera/CameraView.swift
|
UTF-8
| 1,336
| 2.5625
| 3
|
[] |
no_license
|
//
// CameraView.swift
// Mavsdk-Swift-Example
//
// Created by Douglas on 20/05/21.
//
import SwiftUI
struct CameraView: View {
@ObservedObject var camera = CameraViewModel()
let cameraSettingsView = CameraSettingsView()
var body: some View {
List() {
Section(header: Text("Subscriptions")) {
InfoRowView(title: "Mode", value: camera.mode)
InfoRowView(title: "Capture Info", value: camera.captureInfo)
InfoRowView(title: "Camera specs", value: camera.information)
InfoRowView(title: "Camera status", value: camera.status)
}
Section(header: Text("Camera Setttings")) {
NavigationLink("Camera Setttings",
destination: cameraSettingsView)
.isDetailLink(false)
}
Section(header: Text("Camera Actions")) {
ForEach(camera.actions, id: \.text) { action in
ButtonContent(text: action.text, action: action.action)
}
}
}
.font(.system(size: 14, weight: .medium, design: .default))
.listStyle(PlainListStyle())
}
}
struct CameraView_Previews: PreviewProvider {
static var previews: some View {
CameraView()
}
}
| true
|
7c680a7e8724d04ca7b83cd1bd7e2099747629df
|
Swift
|
mohsinalimat/XCoordinator
|
/XCoordinator/Classes/StaticTransitionAnimation.swift
|
UTF-8
| 1,229
| 2.546875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// StaticTransitionAnimation.swift
// XCoordinator
//
// Created by Stefan Kofler on 03.05.18.
// Copyright © 2018 QuickBird Studios. All rights reserved.
//
open class StaticTransitionAnimation: NSObject, TransitionAnimation {
// MARK: - Stored properties
internal let duration: TimeInterval
public let performAnimation: (_ transitionContext: UIViewControllerContextTransitioning) -> Void
// MARK: - Computed properties
public var interactionController: PercentDrivenInteractionController? {
return self as? PercentDrivenInteractionController
}
// MARK: - Init
public init(duration: TimeInterval, performAnimation: @escaping (UIViewControllerContextTransitioning) -> Void) {
self.duration = duration
self.performAnimation = performAnimation
}
// MARK: - Methods
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return duration
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
performAnimation(transitionContext)
}
// MARK: - TransitionAnimation
public func start() {}
public func cleanup() {}
}
| true
|
d9428fb5067f24d0ece592c68930ea53ac9e65da
|
Swift
|
NiltiakSivad/ListDetailExercise
|
/ListDetailCodingExercise/UI/ProCompany/Detail/ProCompanyDetailViewController.swift
|
UTF-8
| 1,925
| 2.53125
| 3
|
[] |
no_license
|
import Foundation
import UIKit
class ProCompanyDetailViewController: UIViewController {
var company: ProCompanyViewModel?
@IBOutlet weak var companyNameLabel: UILabel?
@IBOutlet weak var specialtyLabel: UILabel?
@IBOutlet weak var ratingLabel: UILabel?
@IBOutlet weak var locationLabel: UILabel?
@IBOutlet weak var servicesLabel: UILabel?
@IBOutlet weak var overviewTextView: UITextView?
@IBOutlet weak var stackView: UIStackView?
private lazy var emailButton: CallToActionButton = {
let emailButton = CallToActionButton()
emailButton.setTitle("EMAIL", for: .normal)
emailButton.delegate = self
return emailButton
}()
private lazy var callButton: CallToActionButton = {
let callButton = CallToActionButton()
callButton.setTitle("CALL", for: .normal)
callButton.delegate = self
return callButton
}()
override func viewDidLoad() {
self.title = "Details"
companyNameLabel?.text = company?.companyName
specialtyLabel?.text = company?.specialty
ratingLabel?.text = company?.formattedRating
locationLabel?.text = company?.primaryLocation
servicesLabel?.text = company?.servicesOffered
overviewTextView?.text = company?.companyOverview
stackView?.addArrangedSubview(callButton)
stackView?.addArrangedSubview(emailButton)
}
override func viewDidLayoutSubviews() {
overviewTextView?.setContentOffset(.zero, animated: false)
}
}
extension ProCompanyDetailViewController: CallToActionButtonDelegate {
func callToActionButtonClicked(_ button: CallToActionButton) {
guard let company = company else { return }
if button == callButton {
print("phone = <\(company.phoneNumber)>")
} else if button == emailButton {
print("email = <\(company.email)>")
}
}
}
| true
|
d8bbb254ca44ea5b3a5ebc86a689fed8daa9b33e
|
Swift
|
ncarmine/NathanCarmineAMAD
|
/project3/Linked List/Linked List/SubTableViewController.swift
|
UTF-8
| 4,398
| 2.65625
| 3
|
[] |
no_license
|
//
// SubTableViewController.swift
// Linked List
//
// Created by Nathan Carmine
// Copyright © 2017 ncarmine. All rights reserved.
//
import UIKit
import Firebase
class SubTableViewController: UITableViewController {
var ref: FIRDatabaseReference!
var currCat = String()
var links = [String: String]()
var linkNames = [String]()
override func viewDidLoad() {
super.viewDidLoad()
//Set up Firebase observer
ref.child(currCat).observe(.value, with: {snapshot in
self.links = [String: String]()
for link in snapshot.children.allObjects as! [FIRDataSnapshot]{
self.links[link.key] = link.value as? String
}
self.linkNames = Array(self.links.keys.sorted())
self.tableView.reloadData()
})
}
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 {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return links.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell", for: indexPath)
// Configure the cell...
cell.textLabel?.text = linkNames[indexPath.row]
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 to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let deleteLink = linkNames[indexPath.row]
let linkRef = ref.child(currCat).child(deleteLink)
linkRef.ref.removeValue()
}
}
// MARK: - Navigation
@IBAction func unwindSegue(segue: UIStoryboardSegue) {
if segue.identifier == "savegue" {
let source = segue.source as! AddItemViewController
let newName = source.addedName
let newURL = source.addedURL
if !newName.isEmpty && !newURL.isEmpty {
links[newName] = newURL
ref.child(currCat).child(newName).setValue(newURL)
}
} else if segue.identifier == "editsave" {
let source = segue.source as! EditItemViewController
let oldName = source.oldName
let newName = source.newName
let editURL = source.editURL
let catRef = ref.child(currCat)
if newName != nil && !(newName?.isEmpty)! && editURL != nil && !(editURL?.isEmpty)! && oldName != nil {
if newName != oldName {
catRef.child(oldName!).ref.removeValue()
}
catRef.child(newName!).setValue(editURL)
}
}
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if segue.identifier == "showeb" {
let detailVC = segue.destination as! WebViewController
let indexPath = tableView.indexPath(for: sender as! UITableViewCell)!
let segueLinkName = linkNames[indexPath.row]
//sets the data for the destination controller
detailVC.title = segueLinkName
detailVC.webPage = links[segueLinkName]
} else if segue.identifier == "editSegue" {
let editVC = segue.destination as! EditItemViewController
let indexPath = tableView.indexPath(for: sender as! UITableViewCell)!
let segueLinkName = linkNames[indexPath.row]
editVC.oldName = segueLinkName
editVC.editURL = links[segueLinkName]!
}
}
}
| true
|
00c4195863ccf29a7fa43d1e77acef23bce013e8
|
Swift
|
yangmengjiao/CiderHouseRestaurantWaiter
|
/CiderHouseRestaurantWaiter/CiderHouseRestaurantWaiter/home/OrderViewController.swift
|
UTF-8
| 3,732
| 2.8125
| 3
|
[] |
no_license
|
//
// OrderViewController.swift
// CiderHouseRestaurantWaiter
//
// Created by mengjiao on 5/16/18.
// Copyright © 2018 mengjiao. All rights reserved.
//
import Foundation
import MIOButtonFramework
class OrderViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var table: UITableView!
// Tableで使用する配列を設定する
private let myItems: NSArray = ["TEST1", "TEST2", "TEST3","TEST1", "TEST2", "TEST3","TEST1", "TEST2", "TEST3","TEST1", "TEST2", "TEST3","TEST1", "TEST2", "TEST3"]
private var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.hidesBottomBarWhenPushed = true
// Status Barの高さを取得する.
let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height
// Viewの高さと幅を取得する.
let displayWidth: CGFloat = self.view.frame.width
let displayHeight: CGFloat = self.view.frame.height
// TableViewの生成(Status barの高さをずらして表示).
// myTableView = UITableView(frame: CGRect(x: 0, y: barHeight, width: displayWidth, height: displayHeight))
// Cell名の登録をおこなう.
// myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "MyCell")
// DataSourceを自身に設定する.
table.dataSource = self
// Delegateを自身に設定する.
table.delegate = self
// Viewに追加する.
// self.view.addSubview(myTableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
Cellが選択された際に呼び出される
*/
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Num: \(indexPath.row)")
print("Value: \(myItems[indexPath.row])")
}
/*
Cellの総数を返す.
*/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myItems.count
}
/*
Cellに値を設定する
*/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// 再利用するCellを取得する.
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath) as! CustomOrderMealTabelViewCell
// cell.bringSubview(toFront: cell.orderNumberButton)
// Cellに値を設定する.
// cell.textLabel!.text = "\(myItems[indexPath.row])"
cell.selectionStyle = .none
return cell
}
// func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// return 44
// }
}
//
//class OrderViewController: ViewController {
//
//
// @IBOutlet weak var numberButton: MIOButton!
// override func viewDidLoad() {
// numberButton.shakeAnimation = true
// numberButton.borderColor(#colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1))
// numberButton.maxValue = 10
// numberButton.minValue = 0
// numberButton.numberResult { (number) in
//
// print(number)
// }
// }
//}
| true
|
e15042cdbcd58174ce7783eb679653c0db249711
|
Swift
|
gffny/laaatte-ios
|
/laaatte/models/PlaceModel.swift
|
UTF-8
| 1,595
| 3
| 3
|
[
"MIT"
] |
permissive
|
//
// LaaatteRestService.swift
// laaatte
//
// Created by John D. Gaffney on 3/22/18.
// Copyright © 2018 gffny.com. All rights reserved.
//
import Foundation
import CoreLocation
/// Backling class for every place in the Laaatte
final class PlaceModel {
// MARK: Properties
/// Unique identifier for the place
var identifier: String = ""
/// Human readable place title
var title: String = ""
/// GoogleMaps API ID for this Place
var googlePlaceId: String = ""
/// Defines where the place is located
var location: CLLocation = CLLocation()
/// Array of coordinates which defines the path up to the placemark
var coordinates = [CLLocation]()
/// Human readable description of the place
var placeDescription = ""
/**
Convenience initializer. Sets all the properties for the `Placemark` class.
- parameter identifier: the identifier for the `Placemark`.
- parameter name: the name for the `Placemark`.
- parameter location: the location for the `Placemark`.
- parameter coordinates: the coordinates associated with the `Placemark`.
- parameter placemarkDescription: the description for the `Placemark`.
- parameter lookAt: `LookAt` associated with the `Placemark`.
*/
init(identifier: String, title: String, location: CLLocation, coordinates: [CLLocation], placeDescription: String?) {
self.identifier = identifier
self.title = title
self.location = location
self.coordinates = coordinates
self.placeDescription = placeDescription!
}
}
| true
|
27aab64e977a1e8f48d890c99f618203401c341f
|
Swift
|
achkars/rileylink_ios
|
/OmniKit/MessageTransport/MessageBlocks/GetStatusCommand.swift
|
UTF-8
| 1,554
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// GetStatusCommand.swift
// OmniKit
//
// Created by Pete Schwamb on 10/14/17.
// Copyright © 2017 Pete Schwamb. All rights reserved.
//
import Foundation
public struct GetStatusCommand : MessageBlock {
public enum StatusType: UInt8 {
case normal = 0x00
case configuredAlerts = 0x01
case faultEvents = 0x02
case dataLog = 0x03
case faultDataInitializationTime = 0x04
case hardcodedValues = 0x06
case resetStatus = 0x46 // including state, initialization time, any faults
case dumpRecentFlashLog = 0x50
case dumpOlderFlashlog = 0x51 // but dumps entries before the last 50
// https://github.com/openaps/openomni/wiki/Command-0E-Status-Request
}
public let blockType: MessageBlockType = .getStatus
public let length: UInt8 = 1
public let requestType: StatusType
public init(requestType: StatusType = .normal) {
self.requestType = requestType
}
public init(encodedData: Data) throws {
if encodedData.count < 3 {
throw MessageBlockError.notEnoughData
}
guard let requestType = StatusType(rawValue: encodedData[2]) else {
throw MessageError.unknownValue(value: encodedData[2], typeDescription: "StatusType")
}
self.requestType = requestType
}
public var data: Data {
var data = Data(bytes: [
blockType.rawValue,
length
])
data.append(requestType.rawValue)
return data
}
}
| true
|
095033fab5a0e2c50da856724590de2e30813281
|
Swift
|
processout/processout-ios
|
/Sources/ProcessOut/Sources/UI/Modules/NativeAlternativePaymentMethod/Models/Style/PONativeAlternativePaymentMethodStyle.swift
|
UTF-8
| 3,943
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// PONativeAlternativePaymentMethodStyle.swift
// ProcessOut
//
// Created by Andrii Vysotskyi on 22.11.2022.
//
import UIKit
/// Defines style for native alternative payment method module.
public struct PONativeAlternativePaymentMethodStyle {
/// Title style.
public let title: POTextStyle
/// Section title text style.
public let sectionTitle: POTextStyle
/// Input style.
public let input: POInputStyle
/// Input style.
public let codeInput: POInputStyle
/// Radio button style.
public let radioButton: PORadioButtonStyle
/// Error description text style.
public let errorDescription: POTextStyle
/// Actions style.
public let actions: POActionsContainerStyle
/// Activity indicator style. Please note that maximum height of activity indicator
/// is limited to 256.
public let activityIndicator: POActivityIndicatorStyle
/// Message style.
///
/// - NOTE: This style may be used to render rich attributed text so please make sure that your font's
/// typeface supports different variations. Currently framework may use bold, italic and mono space traits.
public let message: POTextStyle
/// Success message style.
public let successMessage: POTextStyle
/// Background style.
public let background: PONativeAlternativePaymentMethodBackgroundStyle
/// Separator color.
public let separatorColor: UIColor
public init(
title: POTextStyle? = nil,
sectionTitle: POTextStyle? = nil,
input: POInputStyle? = nil,
codeInput: POInputStyle? = nil,
radioButton: PORadioButtonStyle? = nil,
errorDescription: POTextStyle? = nil,
actions: POActionsContainerStyle? = nil,
activityIndicator: POActivityIndicatorStyle? = nil,
message: POTextStyle? = nil,
successMessage: POTextStyle? = nil,
background: PONativeAlternativePaymentMethodBackgroundStyle? = nil,
separatorColor: UIColor? = nil
) {
self.title = title ?? Constants.title
self.sectionTitle = sectionTitle ?? Constants.sectionTitle
self.input = input ?? Constants.input
self.codeInput = codeInput ?? Constants.codeInput
self.radioButton = radioButton ?? Constants.radioButton
self.errorDescription = errorDescription ?? Constants.errorDescription
self.actions = actions ?? Constants.actions
self.activityIndicator = activityIndicator ?? Constants.activityIndicator
self.message = message ?? Constants.message
self.successMessage = successMessage ?? Constants.successMessage
self.background = background ?? Constants.background
self.separatorColor = separatorColor ?? Constants.separatorColor
}
// MARK: - Private Nested Types
private enum Constants {
static let title = POTextStyle(color: Asset.Colors.Text.primary.color, typography: .Medium.title)
static let sectionTitle = POTextStyle(color: Asset.Colors.Text.secondary.color, typography: .Fixed.labelHeading)
static let input = POInputStyle.default()
static let codeInput = POInputStyle.default(typography: .Medium.title)
static let radioButton = PORadioButtonStyle.default
static let errorDescription = POTextStyle(color: Asset.Colors.Text.error.color, typography: .Fixed.label)
static let actions = POActionsContainerStyle()
static let activityIndicator = POActivityIndicatorStyle.system(
.whiteLarge, color: Asset.Colors.Text.secondary.color
)
static let message = POTextStyle(color: Asset.Colors.Text.primary.color, typography: .Fixed.body)
static let successMessage = POTextStyle(color: Asset.Colors.Text.success.color, typography: .Fixed.body)
static let background = PONativeAlternativePaymentMethodBackgroundStyle()
static let separatorColor = Asset.Colors.Border.subtle.color
}
}
| true
|
c2f82b3a4a31f5e22d55d3040d36a6f5ff8d6cfc
|
Swift
|
LiliStorm/TicTacToe
|
/TicTacToe/ViewController.swift
|
UTF-8
| 2,590
| 3.09375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TicTacToe
//
// Created by Lili Storm on 01102021--.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var showPlayerTurn: UILabel!
var board : TicTacToeBoard = TicTacToeBoard()
var playerTurn : Int = 1
@IBAction func boardButtonPressed(_ sender: UIButton) {
if (sender.currentTitle != nil) {
return
}
let x_s : String = "" + sender.accessibilityLabel!.suffix(1)
let y_s : String = "" + sender.accessibilityLabel!.prefix(1)
let x = Int(x_s)
let y = Int(y_s)
if(playerTurn == 1) {
sender.setTitle("X", for: .normal)
} else {
sender.setTitle("O", for: .normal)
}
processPressedButton(xPosition: x!, yPosition: y!)
}
override func viewDidLoad() {
super.viewDidLoad()
resetBoard()
showPlayerTurn.text = "Player 1's turn."
}
func processPressedButton(xPosition : Int, yPosition : Int) {
board.setOwner(x: xPosition, y: yPosition, newOwner: playerTurn)
if board.checkForWinner() != 0 {
showAlert(message: "Player \(playerTurn) won!")
} else {
if(playerTurn == 1) {
playerTurn = 2
} else {
playerTurn = 1
}
showPlayerTurn.text = "Player \(playerTurn)'s turn."
if board.checkIfBoardIsFull() {
showAlert(message: "It was a draw!")
}
}
}
func resetBoard() {
for subview in self.view.subviews {
if subview is UIButton {
let button = subview as! UIButton
button.setTitle(nil, for: .normal)
button.layer.borderWidth = 2
button.layer.borderColor = UIColor.black.cgColor
button.layer.backgroundColor = UIColor.white.cgColor
}
}
playerTurn = 1
board = TicTacToeBoard()
}
func showAlert(message: String) {
let playAgainAlert = UIAlertController(title: "Game over!", message: message, preferredStyle: UIAlertController.Style.alert)
playAgainAlert.addAction(UIAlertAction(title: "Play again", style: .default, handler: { (action: UIAlertAction!) in
self.resetBoard()
}))
self.present(playAgainAlert, animated: true, completion: nil)
}
}
| true
|
77c9a8efa448feeab9596b7ae23461a24cfb97ef
|
Swift
|
ChangJoo-Park/feedsmashapp
|
/DubsFeed/FeedController.swift
|
UTF-8
| 1,866
| 2.546875
| 3
|
[] |
no_license
|
//
// FeedController.swift
// Feedsmash
//
// Created by ChangJoo Park on 2016. 4. 7..
// Copyright © 2016년 ChangJoo Park. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireImage
import SwiftyJSON
class FeedController: NSObject {
private let apiKey = ""
let query: String = "dubsmash"
let maxResults: Int = 20
var feedItems: [FeedItem]?
var nextToken: String?
func parseRowToItem(item: JSON) -> FeedItem {
return FeedItem(data: item)
}
func requestDubsmashes(updateType: FeedUpdateType, completionHandler: (NSError?) -> Void) {
let baseUrl = "https://www.googleapis.com/youtube/v3/search?part=snippet&"
let searchOption = "order=date&"
let queryString = "q=\(query)&type=video&maxResults=\(maxResults)&key=\(apiKey)"
let nextTokenString = updateType == FeedUpdateType.INITIALIZE ?
"" : "&pageToken=\(nextToken as String!)"
let urlString = "\(baseUrl)\(searchOption)\(queryString)\(nextTokenString)"
let url = NSURL(string: urlString)
Alamofire.request(.GET, url!).validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
self.feedItems = []
let items = JSON(value)["items"]
if let token: String = JSON(value)["nextPageToken"].rawString()! as String {
self.nextToken = token
} else {
self.nextToken = ""
}
log.debug(self.nextToken)
for item in items.arrayValue {
let newItem = self.parseRowToItem(item)
self.feedItems?.append(newItem)
}
completionHandler(nil)
}
break
case .Failure(let error):
log.error("Not connected")
completionHandler(error)
break
}
}
}
}
| true
|
6363b452bced7d4d55ae7a3822ae8596b2cdc135
|
Swift
|
Mr-fanglin/GPS_demo
|
/SmartTile_Gps/Tools/SDKHelper/NIMHeper/LXFWeChatTools/XCXinChatTools+Session.swift
|
UTF-8
| 3,301
| 2.546875
| 3
|
[] |
no_license
|
//
// XCXinChatTools+Session.swift
//
//
// Created by FangLin on 2019/1/16.
// Copyright © 2019年 FangLin. All rights reserved.
//
import Foundation
import NIMSDK
// MARK:- 获取最近会话
extension XCXinChatTools {
// MARK: 获取最近会话
func getAllRecentSession() -> [NIMRecentSession]? {
return NIMSDK.shared().conversationManager.allRecentSessions()
}
}
// MARK:- 消息/会话的删除
extension XCXinChatTools {
// MARK: 单条消息的删除
func deleteMessage(with message: NIMMessage) {
NIMSDK.shared().conversationManager.delete(message)
}
// MARK: 单个会话批量消息删除
// removeRecentSession 标记了最近会话是否会被保留,会话内消息将会标记为已删除
// 调用此方法会触发最近消息修改的回调,如果选择保留最近会话, lastMessage 属性将会被置成一条空消息。
func deleteAllMessagesInSession(_ session: NIMSession) {
let delOption = NIMDeleteMessagesOption.init()
delOption.removeSession = false
NIMSDK.shared().conversationManager.deleteAllmessages(in: session, option: delOption)
}
// MARK: 最近会话的删除
func deleteRecentSession(_ recentSession: NIMRecentSession) {
NIMSDK.shared().conversationManager.delete(recentSession)
}
// MARK: 清空所有会话的消息
// removeRecentSession 标记了最近会话是否会被保留。
// 调用这个接口只会触发 - (void)allMessagesDeleted 回调,其他针对单个 recentSession 的回调都不会被调用。
func deleteAllmessagesInSession(_ session: NIMSession) {
let delOption = NIMDeleteMessagesOption.init()
delOption.removeSession = false
NIMSDK.shared().conversationManager.deleteAllmessages(in: session, option: delOption)
}
}
// MARK:- 其它
extension XCXinChatTools {
// MARK: 总未读数获取
func getAllUnreadCount() -> Int {
return NIMSDK.shared().conversationManager.allUnreadCount()
}
// MARK: 标记某个会话为已读
// 调用这个方法时,会将所有属于这个会话的消息都置为已读状态。
// 相应的最近会话(如果有的话)未读数会自动置 0 并且触发最近消息修改的回调
func markAllMessagesReadInSession(userId: String?) {
guard let userId = userId else { return }
let session = NIMSession.init(userId, type: .P2P)
NIMSDK.shared().conversationManager.markAllMessagesRead(in: session)
}
// MARK: 标记所有会话为已读
func markAllMessagesRead() {
NIMSDK.shared().conversationManager.markAllMessagesRead()
}
}
// MARK:- NIMConversationManagerDelegate
extension XCXinChatTools : NIMConversationManagerDelegate {
// MARK: 增加最近会话 回调
func didAdd(_ recentSession: NIMRecentSession, totalUnreadCount: Int) {
Dprint("增加最近会话 回调")
}
// MARK: 修改最近会话 回调
func didUpdate(_ recentSession: NIMRecentSession, totalUnreadCount: Int) {
Dprint("修改最近会话 回调")
}
// MARK: 删除最近会话 回调
func didRemove(_ recentSession: NIMRecentSession, totalUnreadCount: Int) {
Dprint("删除最近会话 回调")
}
}
| true
|
c60d18d7bf881d928260e053d77ff36e81cbfebe
|
Swift
|
jeremygurr/TimeGuardian
|
/Time Budget/DayViewAction.swift
|
UTF-8
| 848
| 3.03125
| 3
|
[] |
no_license
|
//
// DayViewAction.swift
// Time Budget
//
// Created by Jeremy Gurr on 8/2/20.
// Copyright © 2020 Pure Logic Enterprises. All rights reserved.
//
import Foundation
import SwiftUI
enum DayViewAction: Int, CaseIterable, Buttonable {
case add = 0
case remove
case toggle
var asInt: Int {
return self.rawValue
}
var asString: String {
switch self {
case .add: return "Add"
case .remove: return "Remove"
case .toggle: return "Toggle"
}
}
var longDescription: String {
switch self {
case .add: return "add [***] to time slot"
case .remove: return "remove fund from time slot"
case .toggle: return "removes or adds [***]"
}
}
var longPressVersion: DayViewAction? {
switch self {
default: return nil
}
}
static var allCasesInRows: [[DayViewAction]] {
[
[.add, .remove, .toggle],
]
}
}
| true
|
4df7403fde656dc90c6c2419cdab06eb58b1bde9
|
Swift
|
faacar/LocallyFood
|
/LocallyFood/View/CollectionViewCell/CountryFilterCollectionViewCell.swift
|
UTF-8
| 1,042
| 2.59375
| 3
|
[] |
no_license
|
//
// CountryFilterCollectionViewCell.swift
// LocallyFood
//
// Created by Ahmet Acar on 7.04.2021.
//
import UIKit
import SnapKit
class CountryFilterCollectionViewCell: UICollectionViewCell {
static let reuseIdentifier: String = "CountryFilterCollectionViewCell"
private lazy var countryLabel = LFLabel(fontSize: 15)
override init(frame: CGRect) {
super.init(frame: .zero)
configure()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func set(buttonTitle: String) {
//countryButton.setTitle(buttonTitle, for: .normal)
countryLabel.text = buttonTitle
}
func configure() {
contentView.addSubview(countryLabel)
backgroundColor = LFColors.smallCellColor
layer.masksToBounds = true
layer.cornerRadius = 15.0
countryLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(self)
make.centerY.equalTo(self)
}
}
}
| true
|
a6646f86e6c013749e62a3eee86633c63fe9855f
|
Swift
|
Ricky2494/Bootcamp
|
/iOS/Exercise 16 Notification/Exercise 16 Question 3/Exercise 16 Question 3/ViewController.swift
|
UTF-8
| 3,719
| 2.859375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Exercise 16 Question 3
//
// Created by Anindya Guha on 27/03/19.
// Copyright © 2019 Anindya Guha. All rights reserved.
//
import UIKit
import UserNotifications
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
@IBOutlet weak var messageTextfield: UITextField!
@IBOutlet weak var resetButton: UIButton!
@IBOutlet weak var notifyButton: UIButton!
let center = UNUserNotificationCenter.current()
override func viewDidLoad() {
super.viewDidLoad()
registerLocal()
}
//MARK: - Register for local notification -
@objc func registerLocal() {
// let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("It is running")
} else {
print("It is not running")
}
}
}
//MARK: - Button Action -
@IBAction func buttonScheduleNotificationTapped(_ sender: Any) {
let time = Date()
center.removeAllPendingNotificationRequests()
registerCategories()
let content = UNMutableNotificationContent()
content.title = "Hi Sir!"
content.subtitle = "\(time)"
content.body = "This is the messgae \(messageTextfield.text!) "
content.categoryIdentifier = "alert"
content.userInfo = ["set by": "Ani"]
content.sound = UNNotificationSound(named: UNNotificationSoundName(rawValue: "quite-impressed.m4r"))
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 02, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request)
}
@IBAction func buttonClearAllNotificationTapped(_ sender: Any) {
center.removeAllPendingNotificationRequests()
}
func registerCategories() {
center.delegate = self
let show = UNNotificationAction(identifier: "show", title: "Tell me more…", options: .foreground)
let category = UNNotificationCategory(identifier: "alert", actions: [show], intentIdentifiers: [])
center.setNotificationCategories([category])
}
//MARK: - UNUserNotification Delegate Method -
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// pull out the buried userInfo dictionary
let userInfo = response.notification.request.content.userInfo
if let customData = userInfo["customData"] as? String {
print("Custom data received: \(customData)")
switch response.actionIdentifier {
case UNNotificationDefaultActionIdentifier:
// the user swiped to unlock
print("Default identifier")
case "show":
// the user tapped our "show more info…" button
print("Show more information…")
default:
break
}
}
// you must call the completion handler when you're done
completionHandler()
}
}
| true
|
ec93e1a756b382a95aaaa4ab1036470c24cad0fe
|
Swift
|
andanamulya/usecase2b-ncs-ios
|
/SP_Usecase/Modules/Base/BaseTableView.swift
|
UTF-8
| 719
| 2.515625
| 3
|
[] |
no_license
|
//
// BaseTableView.swift
// SP_Usecase
//
// Created by Lester Cabalona on 28/6/21.
//
import UIKit
class BaseTableView: UITableView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
var hasSeparator:Bool = true {
didSet{
if hasSeparator {
self.separatorStyle = .singleLine
}else{
self.separatorStyle = .none
}
}
}
/// Set the table footer view to empty view
func clearTableFooterView(){
self.tableFooterView = UIView()
}
}
| true
|
3f36014301b0193f174661ffd780c13bf5d82189
|
Swift
|
kichikuchi/swift_nlp_100
|
/chapter2/18.swift
|
UTF-8
| 445
| 2.75
| 3
|
[] |
no_license
|
import Foundation
let path = Bundle.main.path(forResource: "hightemp", ofType: "txt")!
let content = try! String(contentsOfFile: path)
let array = content.components(separatedBy: ["\n"])
var row: [[String]] = []
for content in array {
if content.count > 0 {
row.append(content.components(separatedBy: "\t"))
}
}
let sorted = row.sorted { $0[2] < $1[2] }.map { $0.joined(separator: "\t")}
print(sorted.joined(separator: "\n"))
| true
|
925d0c5c9545ce6ae1927f293c18d1a1cfe021d5
|
Swift
|
harwoodspike/arcusios
|
/i2app/i2app/UI/ViewControllers/AlarmMoreTableViewSectionHeader.swift
|
UTF-8
| 2,161
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// AlarmMoreTableViewSectionHeader.swift
// i2app
//
// Created by Arcus Team on 1/6/17.
/*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
import Foundation
import Cornea
/// A custom tableview Section Header for the Alarm More View Controller
class AlarmMoreTableViewSectionHeader: ArcusTwoLabelTableViewSectionHeader, ReuseableCell {
/// Displays one line of text
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var iconImageView1: UIImageView!
@IBOutlet weak var iconImageView2: UIImageView!
@IBOutlet weak var iconImageView3: UIImageView!
@IBOutlet weak var iconImageView4: UIImageView!
@IBOutlet weak var iconImageView5: UIImageView!
/**
Takes in a list of images and sets them in order **right to left** on the right hand side of the view
* maximum of 4 images
* extra UIImageViews are hidden
* resets images if reused
This is a cocoa caveman's cheap stack view
*/
func setImages(_ images: [UIImage]) {
let imageViews = [iconImageView1, iconImageView2, iconImageView3, iconImageView4, iconImageView5]
imageViews.forEach { v in
v?.isHidden = true
}
// Note to future programmer, Swift 2.3 doesn't have iterators yet when I wrote this
var i = images.startIndex
images.reversed().forEach { image in
let imageView = imageViews[i]
imageView?.image = image
imageView?.isHidden = false
i += 1
}
}
class var reuseIdentifier: String {
return "AlarmMoreTableViewSectionHeader"
}
class var nib: UINib {
return UINib(nibName: "AlarmMoreTableViewSectionHeader", bundle: Bundle.main)
}
}
| true
|
93ae98cec47dfa1f74291a43247a3d22c7a36e82
|
Swift
|
MonadicConsulting/BencodeKit
|
/Sources/Bencode.swift
|
UTF-8
| 4,479
| 2.765625
| 3
|
[] |
no_license
|
//
// Bencode.swift
// BencodeKit
//
// Created by Charlotte Tortorella on 25/1/17.
// Copyright © 2017 Monadic Consulting. All rights reserved.
//
import CryptoSwift
public enum BencodingError: Error {
case emptyString
case nonExistentFile(String)
case unexpectedCharacter(Character, Data.Index)
case negativeZeroEncountered(Data.Index)
case invalidStringLength(Data.Index)
case invalidInteger(Data.Index)
case contaminatedInteger(Data.Index)
case unterminatedInteger(Data.Index)
case invalidList(Data.Index)
case unterminatedList(Data.Index)
case invalidDictionary(Data.Index)
case nonStringDictionaryKey(Data.Index)
case unterminatedDictionary(Data.Index)
case nonAsciiString
}
public indirect enum Bencode: Equatable {
case integer(Int)
case bytes(Data)
case list([Bencode])
case dictionary(OrderedDictionary<String, Bencode>)
init(_ integer: Int) {
self = .integer(integer)
}
init(_ string: String) throws {
guard let value = string.data(using: .ascii) else { throw BencodingError.nonAsciiString }
self = .bytes(value)
}
init(_ bytes: Data) {
self = .bytes(bytes)
}
init(_ list: [Bencode]) {
self = .list(list)
}
init(_ dictionary: [(String, Bencode)]) {
self.init(OrderedDictionary<String, Bencode>(dictionary))
}
init(_ dictionary: OrderedDictionary<String, Bencode>) {
self = .dictionary(dictionary)
}
public func encodedString() -> String {
switch self {
case .integer(let integer):
return "i\(String(integer))e"
case .bytes(let bytes):
let string = bytes.asciiString
return "\(string.count):\(string)"
case .list(let list):
return "l\(list.map { $0.encodedString() }.joined())e"
case .dictionary(let dictionary):
return "d\(dictionary.map { "\($0.count):\($0)\($1.encodedString())" }.joined())e"
}
}
public func toString() -> String {
switch self {
case .integer(let integer):
return String(integer)
case .bytes(let bytes):
return bytes.asciiString
case .list(let list):
return "[" + list.map { $0.toString() }.joined(separator: ", ") + "]"
case .dictionary(let dictionary):
return "[" + dictionary.map { "\"\($0)\": \($1.toString())" }.joined(separator: ", ") + "]"
}
}
public subscript(index: String) -> Bencode? {
get {
guard case .dictionary(let dictionary) = self else {
return nil
}
return dictionary[index]
}
}
}
public extension Bencode {
public static func decode(_ data: Data) throws -> Bencode {
return try bdecode(data, data.startIndex).match
}
}
public extension Bencode {
public static func decodeFile(atPath path: String) throws -> Bencode {
guard let data = FileManager.default.contents(atPath: path) else {
throw BencodingError.nonExistentFile(path)
}
return try decode(data)
}
}
public extension Bencode {
public func encoded() -> Data {
switch self {
case .integer(let integer):
return "i\(String(integer))e".asciiData
case .bytes(let bytes):
return "\(bytes.count):".asciiData + bytes
case .list(let list):
return "l".asciiData + list.map { $0.encoded() }.joined() + "e".asciiData
case .dictionary(let dictionary):
return "d".asciiData + dictionary.map { "\($0.count):\($0)".asciiData + $1.encoded() }.joined() + "e".asciiData
}
}
}
public extension Bencode {
public func sha1Hash() -> String {
return SHA1().calculate(for: encoded().bytes).reduce("") { $0.appendingFormat("%02x", $1) }
}
}
public extension Bencode {
public static func ==(lhs: Bencode, rhs: Bencode) -> Bool {
switch (lhs, rhs) {
case (.integer(let a), .integer(let b)):
return a == b
case (.bytes(let a), .bytes(let b)):
return a == b
case (.list(let a), .list(let b)) where a.count == b.count:
return zip(a, b).all(where: ==)
case (.dictionary(let a), .dictionary(let b)) where a.count == b.count:
return zip(a, b).all(where: ==)
default:
return false
}
}
}
| true
|
dfb6c61504b15bfe31675052717b146a1152de53
|
Swift
|
marbleinteractivespain/fundamentosiOS
|
/PracticaFundamentosiOS/Features/Photo/Controllers/PhotoViewController.swift
|
UTF-8
| 997
| 2.65625
| 3
|
[] |
no_license
|
//
// PhotoViewController.swift
// PracticaFundamentosiOS
//
// Created by DAVID DE LA PUENTE on 8/7/21.
//
import UIKit
class PhotoViewController: UIViewController {
//MARK: - IBOutlets
@IBOutlet weak var imgPhotoView: UIImageView!
@IBOutlet weak var closeButton: UIButton!
//MARK: - IBACtions
@IBAction func closeScreen(_ sender: Any) {
navigationController?.popViewController(animated: true)
}
//MARK: - Public properties
var character: Character?
var photoID: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
closeButton.layer.cornerRadius = 15
closeButton.clipsToBounds = true
if let photoSelected = character?.gallery[photoID]{
imgPhotoView.image = UIImage(named: photoSelected)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.isNavigationBarHidden = false
}
}
| true
|
e59536ddc1520494bcc9299797ee99766331d1f2
|
Swift
|
eunmo/tango
|
/Watch Extension/TestInterfaceController.swift
|
UTF-8
| 2,973
| 2.875
| 3
|
[] |
no_license
|
//
// TestInterfaceController.swift
// Watch Extension
//
// Created by Eunmo Yang on 5/29/18.
// Copyright © 2018 Eunmo Yang. All rights reserved.
//
import WatchKit
import Foundation
class TestInterfaceController: WKInterfaceController {
@IBOutlet var wordLabel: WKInterfaceLabel!
@IBOutlet var yomiganaLabel: WKInterfaceLabel!
@IBOutlet var meaningLabel: WKInterfaceLabel!
@IBOutlet var trueButton: WKInterfaceButton!
@IBOutlet var falseButton: WKInterfaceButton!
var showMeaning = false {
didSet {
trueButton.setBackgroundColor(UIColor.darkGray)
falseButton.setBackgroundColor(UIColor.darkGray)
if word!.result == true {
trueButton.setBackgroundColor(UIColor(red: 4/255, green: 222/255, blue: 113/255, alpha: 1))
} else if word!.result == false {
falseButton.setBackgroundColor(UIColor(red: 255/255, green: 59/255, blue: 48/255, alpha: 1))
}
if showMeaning {
yomiganaLabel.setAlpha(1.0)
meaningLabel.setAlpha(1.0)
} else {
yomiganaLabel.setAlpha(0.0)
meaningLabel.setAlpha(0.0)
}
}
}
func formatYomiganaString(yomigana: String) -> String {
return yomigana == "" ? " " : yomigana
}
func formatMeaningString(meaning: String) -> NSAttributedString {
var string = meaning
for i in 2...5 {
string = string.replacingOccurrences(of: " \(i))", with: "\n\(i))")
}
let tok = string.components(separatedBy: "\n")
let fontSize = tok.count >= 3 ? 14 : 16
return NSAttributedString(string: string, attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: CGFloat(fontSize))])
}
var word: TestWord? {
didSet {
wordLabel.setText(word!.word)
yomiganaLabel.setText(formatYomiganaString(yomigana: word!.yomigana))
meaningLabel.setAttributedText(formatMeaningString(meaning: word!.meaning))
}
}
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
word = context as? TestWord
showMeaning = false
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
showMeaning = false
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
showMeaning = false
}
@IBAction func checkTruePressed() {
word!.result = true
showMeaning = !showMeaning
}
@IBAction func checkFalsePressed() {
word!.result = false
showMeaning = !showMeaning
}
}
| true
|
506d1d22bab00902be72aad0359a9c6b40a2365a
|
Swift
|
dmaulikr/C4Fitness
|
/C4Fitness/TrainerModel.swift
|
UTF-8
| 1,303
| 2.921875
| 3
|
[] |
no_license
|
//
// TrainerModel.swift
// C4Fitness
//
// Created by Owner on 11/17/16.
// Copyright © 2016 Mike Vork. All rights reserved.
//
import UIKit
class TrainerModel: NSObject {
var name: String = ""
var title: String = ""
var imageName: String = ""
var details: String = ""
var sequenceNumber: Int = 0
init(name: String = "", title: String = "", imageName: String = "", details: String = "", sequenceNumber: Int = 0) {
self.name = name
self.title = title
self.details = details
self.imageName = imageName
self.sequenceNumber = sequenceNumber
}
}
extension TrainerModel: DownloadableDataModel {
convenience init(jsonData: JSONDictionary) {
self.init()
if let itemFields: AnyObject = jsonData["fields"] {
self.name = (itemFields["name"] as? String) ?? ""
self.title = (itemFields["title"] as? String) ?? ""
self.imageName = (itemFields["imageName"] as? String) ?? ""
self.details = (itemFields["details"] as? String) ?? ""
self.sequenceNumber = (itemFields["sequenceNumber"] as? Int) ?? 0
}
}
static func createInstance(jsonData: JSONDictionary) -> DownloadableDataModel {
return TrainerModel(jsonData: jsonData)
}
}
| true
|
7b695150e970d8a89a656cedf18ce88d8db4eafa
|
Swift
|
jorge-mr/TicTacToe
|
/TicTacToe/Gato.swift
|
UTF-8
| 5,492
| 2.796875
| 3
|
[] |
no_license
|
//
// Gato.swift
// TicTacToe
//
// Created by Jorge MR on 22/06/17.
// Copyright © 2017 Jorge MR. All rights reserved.
//
import UIKit
class Gato: UIViewController {
@IBOutlet weak var ganadorLabel: UILabel!
@IBOutlet weak var nuevoJuegoBoton: UIBarButtonItem!
@IBOutlet weak var pausaBoton: UIBarButtonItem!
@IBOutlet weak var nombreJugador1Label: UILabel!
@IBOutlet weak var nombreJugador2Label: UILabel!
@IBOutlet weak var avatarJugador1: UIButton!
@IBOutlet weak var avatarJugador2: UIButton!
var jugadorActivo : Int = 1
//jugadorActivo : 1 circulos, 2 taches
var estadoJuego = [0,0,0,0,0,0,0,0,0]
// 0 (no hay imagen), 1(circulo), 2(taches)
let combinacionesGanadoras = [
//horizontales
[0,1,2], [3,4,5], [6,7,8],
//verticales
[0,3,6], [1,4,7], [2,5,8],
//ddiagonales
[0,4,8], [2,4,6]
]
var partidaActiva : Bool = true
var contador : Int = 0
//Informacion pasada desde el primer ViewController
var nombreJugador1 = "Jugador 1"
var nombreJugador2 = "Jugador 2"
var iconoJugador1 : Int = 3
var iconoJugador2 : Int = 1
override func viewDidLoad() {
super.viewDidLoad()
ganadorLabel.isHidden = true
if nombreJugador1 != ""{
nombreJugador1Label.text = nombreJugador1
}
if nombreJugador2 != "" {
nombreJugador2Label.text = nombreJugador2
}
ganadorLabel.center = CGPoint(x: ganadorLabel.center.x - 500, y: ganadorLabel.center.y)
avatarJugador1.center = CGPoint(x: avatarJugador1.center.x - 500, y: avatarJugador1.center.y)
avatarJugador2.center = CGPoint(x: avatarJugador2.center.x + 500, y: avatarJugador2.center.y)
avatarJugador1.setImage(UIImage(named: "user\(iconoJugador1)"),for: [])
avatarJugador2.setImage(UIImage(named: "user\(iconoJugador2)"),for: [])
UIView.animate(withDuration: 3){
self.avatarJugador1.center = CGPoint(x: self.avatarJugador1.center.x + 500, y: self.avatarJugador1.center.y)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func botonPrecionado(_ sender: UIButton) {
let posActiva = sender.tag - 1
if estadoJuego[posActiva] == 0 && partidaActiva {
sender.alpha=0
if jugadorActivo == 1{
UIView.animate(withDuration: 0.5){
sender.alpha = 1
sender.setImage(UIImage(named: "circulo.png"),for: [])
//for: [] es para el estado por defecto del boton
self.contador += 1
}
jugadorActivo = 2
}else{
UIView.animate(withDuration: 0.5){
sender.alpha = 1
sender.setImage(UIImage(named: "tache.png"),for: [])
//for: [] es para el estado por defecto del boton
self.contador += 1
}
jugadorActivo = 1
}
estadoJuego[posActiva] = jugadorActivo
for combinacion in combinacionesGanadoras{
if estadoJuego[combinacion[0]] != 0 && estadoJuego[combinacion[0]] == estadoJuego[combinacion[1]] && estadoJuego[combinacion[1]] == estadoJuego[combinacion[2]] && estadoJuego[combinacion[0]] == estadoJuego[combinacion[2]] {
partidaActiva = false
ganadorLabel.isHidden = false
//1 si ganan los circulos
if estadoJuego[combinacion[0]] == 1 {
ganadorLabel.text = "Ganó \(nombreJugador2Label.text!)"
}else{ //0 si ganan los taches
ganadorLabel.text = "Ganó \(nombreJugador1Label.text!)"
}
UIView.animate(withDuration: 1){
self.ganadorLabel.center = CGPoint(x: self.ganadorLabel.center.x + 500, y: self.ganadorLabel.center.y)
}
}else{
if contador >= 9{
ganadorLabel.isHidden = false
ganadorLabel.text = "Gato encerrado"
UIView.animate(withDuration: 1){
self.ganadorLabel.center = CGPoint(x: self.ganadorLabel.center.x + 500, y: self.ganadorLabel.center.y)
}
}
}
}
}else{
print("partida inactiva")
}
print("Contador : \(contador)")
}
@IBAction func nuevoJuego(_ sender: UIBarButtonItem) {
estadoJuego = [0,0,0,0,0,0,0,0,0]
jugadorActivo = 1
contador = 0
partidaActiva = true
for i in 1...9{
if let button = view.viewWithTag(i) as? UIButton{
button.setImage(nil, for: [])
}
}
ganadorLabel.isHidden = true
ganadorLabel.center = CGPoint(x: ganadorLabel.center.x - 500, y: ganadorLabel.center.y)
}
@IBAction func pausa(_ sender: UIBarButtonItem) {
partidaActiva = !partidaActiva
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| true
|
0971860ace4aa5ba416b48823deeef06791eab10
|
Swift
|
namalu/Swift-FHIR
|
/fhir-parser-resources/FHIRDecimal.swift
|
UTF-8
| 4,192
| 2.921875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// FHIRNumbers.swift
// SwiftFHIR
//
// Created by Pascal Pfiffner on 08.12.16.
// 2016, SMART Health IT.
//
import Foundation
/**
Struct to hold on to a decimal value.
By design, FHIRDecimal does not conform to `ExpressibleByFloatLiteral` in order to avoid precision issues.
*/
public struct FHIRDecimal: FHIRPrimitive, LosslessStringConvertible, ExpressibleByStringLiteral, ExpressibleByIntegerLiteral {
/// The actual decimal value.
public var decimal: Decimal
/// An optional id of the element.
public var id: String?
/// The parent/owner of the receiver, if any. Used to dereference resources.
public weak var _owner: FHIRAbstractBase?
/// Optional extensions of the element.
public var extension_fhir: [Extension]?
/**
Designated initializer.
- parameter dcm: The decimal to represent.
*/
public init(_ dcm: Decimal) {
decimal = dcm
}
// MARK: - FHIRJSONType
#if os(Linux)
public typealias JSONType = Double
#else
public typealias JSONType = NSNumber
#endif
/**
Initializer from the value the JSON parser returns.
We're using a string format approach using "%.15g" since NSJSONFormatting returns NSNumber objects instantiated
with Double() or Int(). In the former case this causes precision issues (e.g. try 8.7). Unfortunately, some
doubles with 16 and 17 significant digits will be truncated (e.g. a longitude of "4.844614000123024").
TODO: replace JSONSerialization with a different parser?
*/
public init(json: JSONType, owner: FHIRAbstractBase?, context: inout FHIRInstantiationContext) {
#if os(Linux)
self.init(Decimal(json))
#else
if let _ = json.stringValue.firstIndex(of: ".") {
self.init(stringLiteral: String(format: "%.15g", json.doubleValue))
}
else {
self.init(json.decimalValue)
}
#endif
_owner = owner
}
public func asJSON(errors: inout [FHIRValidationError]) -> JSONType {
#if os(Linux)
return Double("\(decimal)") ?? 0.0
#else
return decimal as NSNumber
#endif
}
// MARK: - LosslessStringConvertible & CustomStringConvertible
public init?(_ description: String) {
guard let dcm = Decimal(string: description) else {
return nil
}
self.init(dcm)
}
public var description: String {
return decimal.description
}
// MARK: - ExpressibleBy
public init(stringLiteral string: StringLiteralType) {
let dcm = Decimal(string: string)
self.init(dcm ?? Decimal())
}
public init(unicodeScalarLiteral value: Character) {
self.init(stringLiteral: "\(value)")
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(stringLiteral: value)
}
public init(booleanLiteral bool: Bool) {
self.init(bool ? Decimal(1) : Decimal(0))
}
public init(integerLiteral integer: Int) {
self.init(Decimal(integer))
}
}
extension FHIRDecimal: Equatable, Comparable {
public static func ==(l: FHIRDecimal, r: FHIRDecimal) -> Bool {
return l.decimal == r.decimal
}
public static func ==(l: Decimal, r: FHIRDecimal) -> Bool {
return l == r.decimal
}
public static func ==(l: FHIRDecimal, r: Decimal) -> Bool {
return l.decimal == r
}
public static func ==(l: Double, r: FHIRDecimal) -> Bool {
return Decimal(l) == r.decimal
}
public static func ==(l: FHIRDecimal, r: Double) -> Bool {
return l.decimal == Decimal(r)
}
public static func ==(l: Int, r: FHIRDecimal) -> Bool {
return Decimal(l) == r.decimal
}
public static func ==(l: FHIRDecimal, r: Int) -> Bool {
return l.decimal == Decimal(r)
}
public static func <(lh: FHIRDecimal, rh: FHIRDecimal) -> Bool {
return lh.decimal < rh.decimal
}
public static func <(lh: Decimal, rh: FHIRDecimal) -> Bool {
return lh < rh.decimal
}
public static func <(lh: FHIRDecimal, rh: Decimal) -> Bool {
return lh.decimal < rh
}
public static func <(lh: Double, rh: FHIRDecimal) -> Bool {
return Decimal(lh) < rh.decimal
}
public static func <(lh: FHIRDecimal, rh: Double) -> Bool {
return lh.decimal < Decimal(rh)
}
public static func <(lh: Int, rh: FHIRDecimal) -> Bool {
return Decimal(lh) < rh.decimal
}
public static func <(lh: FHIRDecimal, rh: Int) -> Bool {
return lh.decimal < Decimal(rh)
}
}
| true
|
3ff27c6f91664d9cd40b228d74627067244b14a2
|
Swift
|
wangjianquan/CustomWidget_SwiftUIApp
|
/CustomWidget_SwiftUIApp/AppSettingsView.swift
|
UTF-8
| 1,537
| 3.03125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// AppSettingsView.swift
// CustomWidget_SwiftUIApp
//
// Created by MacBook Pro on 2021/4/12.
//
import SwiftUI
public class Features: ObservableObject {
public static let shared = Features()
private init() {
}
@Published public var isDebugMenuEnabled = false
}
@propertyWrapper
public struct Feature<T>: DynamicProperty {
@ObservedObject private var features: Features
private let keyPath: KeyPath<Features, T>
public init(_ keyPath: KeyPath<Features, T>, features: Features = .shared) {
self.keyPath = keyPath
self.features = features
}
public var wrappedValue: T {
return features[keyPath: keyPath]
}
}
public class AppSettings: ObservableObject {
@AppStorage("appSetting1") public var appSetting1: Int = 42
@AppStorage("appSetting2") public var appSetting2: String = "Hello"
}
public class SceneSettings: ObservableObject {
@SceneStorage("sceneValue1") public var sceneSetting1: Int = 54
@SceneStorage("sceneValue2") public var sceneSetting2: String = "World"
}
struct AppSettingsView: View {
@Feature(\.isDebugMenuEnabled) var showDebugMenu
// @SceneSetting(\.shouldShowThatOneInfoSection) var showInfo
var body: some View {
Form {
if showDebugMenu {
NavigationLink(destination: BannerTest()) { Text("Debug Settings") }
}
}
}
}
struct AppSettingsView_Previews: PreviewProvider {
static var previews: some View {
AppSettingsView()
}
}
| true
|
7e55487401006d69361601a003c727fcb8bde648
|
Swift
|
vault12/TrueEntropy
|
/TrueEntropy/Constants.swift
|
UTF-8
| 1,411
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
// Copyright (c) 2017 Vault12, Inc.
// MIT License https://opensource.org/licenses/MIT
import UIKit
import AVFoundation
struct Constants {
// Block preferences
// =========================
static let blockSizes = [100, 250, 512, 1024, 1536, 2048]
static let blockSizeLabels = ["100 KB", "250 KB", "512 KB", "1 MB", "1.5 MB", "2 MB"]
// Camera
// =========================
// Capture setting preset
// Change to `AVCaptureSession.Preset.medium` or `AVCaptureSession.Preset.low` for faster entropy generation.
// See all available values on:
// https://developer.apple.com/documentation/avfoundation/avcapturesession.preset#topics
static let cameraPreset = AVCaptureSession.Preset.hd1920x1080
// Extractor/collector preferences
// =========================
static let extractorCapacity = 4*1024*1024
static let skipFrames = 10
static let meanRange = -0.1..<0.1
static let sampleDelta = 8
// Network preferences
// =========================
static let waitForResponse = 5
static let sessionRefresh = 300.0
// View preferences
// =========================
static let spinnerAnimationDuration = 80.0
// Colors
// =========================
static let mainColor = UIColor(red:0.32, green:0.81, blue:0.98, alpha:1.00) // Light blue
static let warningColor = UIColor(red:0.93, green:0.39, blue:0.43, alpha:1.00) // Light red
}
| true
|
5964f773373d3357668ec6ac6998d89f8276bd64
|
Swift
|
zbz-lvlv/GPS-Log
|
/GPS Log/TabBarViewController.swift
|
UTF-8
| 3,917
| 2.828125
| 3
|
[] |
no_license
|
//
// TabBarViewController.swift
// GPS Log
//
// Created by Zhang Bozheng on 15/11/17.
// Copyright © 2017 Zhang Bozheng. All rights reserved.
//
import UIKit
import CoreLocation
//This is the main class
class TabBarViewController: UITabBarController, CLLocationManagerDelegate {
var dateTimeProvider: DateTimeProvider!
var locationProvider: LocationProvider!
var altitudeProvider: AltitudeProvider!
var sunProvider: SunProvider!
var locationManager = CLLocationManager()
var location = Location()
override func viewDidLoad() {
super.viewDidLoad()
UITabBar.appearance().tintColor = Constants.BACKGROUND_COLOR
dateTimeProvider = DateTimeProvider(tabBarViewControllerIn: self)
locationProvider = LocationProvider(tabBarViewControllerIn: self)
altitudeProvider = AltitudeProvider(tabBarViewControllerIn: self)
sunProvider = SunProvider(tabBarViewControllerIn: self)
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()
self.locationManager.startUpdatingHeading()
}
func addViewController(title: String, viewController: UIViewController){
let icon = UITabBarItem(title: title, image: UIImage(named: "first.png"), selectedImage: UIImage(named: "first.png"))
viewController.tabBarItem = icon
self.addChildViewController(viewController)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location.latitude = (locations.last?.coordinate.latitude)!
location.longitude = (locations.last?.coordinate.longitude)!
location.altitude = (locations.last?.altitude)! - Geoid.getOffset(lat: location.latitude, longi: location.longitude)
location.altitudeNoGeoid = (locations.last?.altitude)!
location.speed = (locations.last?.speed)! * 3.6 //in km/h
CLGeocoder().reverseGeocodeLocation((locations.last)!, completionHandler:
{(placemarks, error) in
if (error != nil)
{
print("reverse geodcode fail: \(error!.localizedDescription)")
}
else{
let pm = placemarks! as [CLPlacemark]
if pm.count > 0 {
let pm = placemarks![0]
if pm.locality != nil {
self.location.locality = pm.locality!
}
}
}
})
locationProvider.locationCallback(location: location)
altitudeProvider.locationCallback(location: location)
sunProvider.locationCallback(location: location)
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
location.heading = newHeading.trueHeading;
locationProvider.locationCallback(location: location)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
struct Location{
var latitude = 0.0
var longitude = 0.0
var altitude = 0.0
var altitudeNoGeoid = 0.0
var heading = 0.0
var speed = 0.0
var locality = ""
}
| true
|
ed5a5f78e0b94f941b367e488e762d842307ccad
|
Swift
|
imodeveloperlab/ImoTableView
|
/Examples/ImoTableViewExample/ImoTableViewExample/AddDeleteIfExistExample.swift
|
UTF-8
| 2,982
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
//
// AutomaticScrollAdjustExampleVC.swift
// ImoTableViewExample
//
// Created by Borinschi Ivan on 5/10/17.
// Copyright © 2017 Imodeveloperlab. All rights reserved.
//
import Foundation
import UIKit
import ImoTableView
import Fakery
class AddDeleteIfExistExample: BaseViewController {
let faker = Faker.init()
let mainSection = ImoTableViewSection()
let firstSection = ImoTableViewSection()
let secondSection = ImoTableViewSection()
var table: ImoTableView!
override func exploreTitle() -> String {
return "Add / Delete if exist"
}
override func viewDidLoad() {
super.viewDidLoad()
//HIDE THE KAYBOARD WHEN TAPPED ARROUND
self.hideKeyboardWhenTappedAround()
//TABLE
self.table = ImoTableView(on: self.view)
let addSourceInFirst = ActionCellSource(title: "Add First Comparable")
mainSection.add(addSourceInFirst, target: self, #selector(addFirstSource))
let deleteSourceInFirst = ActionCellSource(title: "Delete First Comparable")
mainSection.add(deleteSourceInFirst, target: self, #selector(deleteFirstSource))
let addSourceInSecond = ActionCellSource(title: "Add Second Comparable")
mainSection.add(addSourceInSecond, target: self, #selector(addSecondSource))
let deleteSourceInSecond = ActionCellSource(title: "Delete Second Comparable")
mainSection.add(deleteSourceInSecond, target: self, #selector(deleteSecondSource))
//ADD SECTIONS TO TABLE
table.add(section: mainSection)
table.add(section: firstSection)
table.add(section: secondSection)
let firstName = TextCellSource(text: "First Name: \(faker.name.firstName())")
firstSection.add(firstName)
let lastName = TextCellSource(text: "Last Name: \(faker.name.lastName())")
firstSection.add(lastName)
let company = TextCellSource(text: "Company: \(faker.company.name())")
secondSection.add(company)
}
@objc func addFirstSource() {
let source = ComparableCellSource(message: "First Comparable")
firstSection.addIfNotExist(source: source)
table.updateChangedSections()
}
@objc func deleteFirstSource() {
let source = ComparableCellSource(message: "First Comparable")
firstSection.deleteIfExist(source: source)
table.updateChangedSections()
}
@objc func addSecondSource() {
let source = ComparableCellSource(message: "Second Comparable")
secondSection.addIfNotExist(source: source)
table.updateChangedSections()
}
@objc func deleteSecondSource() {
let source = ComparableCellSource(message: "Second Comparable")
secondSection.deleteIfExist(source: source)
table.updateChangedSections()
}
}
| true
|
ce32ed59a150a616c4e29d0c0c0b59b95a71c76e
|
Swift
|
FTChinese/iPhoneApp
|
/FT Academy/NowPlayingCenter.swift
|
UTF-8
| 1,776
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// NowPlayingCenter.swift
// FT中文网
//
// Created by Oliver Zhang on 2017/4/10.
// Copyright © 2017年 Financial Times Ltd. All rights reserved.
//
import Foundation
import AVKit
import AVFoundation
import MediaPlayer
import WebKit
struct NowPlayingCenter {
func updateInfo(title: String, artist: String, albumArt: UIImage?, currentTime: NSNumber, mediaLength: NSNumber, PlaybackRate: Double){
if let artwork = albumArt {
let mediaInfo: Dictionary <String, Any> = [
MPMediaItemPropertyTitle: title,
MPMediaItemPropertyArtist: artist,
MPMediaItemPropertyArtwork: MPMediaItemArtwork(image: artwork),
// MARK: - Useful for displaying Background Play Time under wifi
MPNowPlayingInfoPropertyElapsedPlaybackTime: currentTime,
MPMediaItemPropertyPlaybackDuration: mediaLength,
MPNowPlayingInfoPropertyPlaybackRate: PlaybackRate
]
MPNowPlayingInfoCenter.default().nowPlayingInfo = mediaInfo
}
}
func updateTimeForPlayerItem(_ player: AVPlayer?) {
if let player = player {
if let playerItem = player.currentItem, var nowPlayingInfo = MPNowPlayingInfoCenter.default().nowPlayingInfo {
let duration = CMTimeGetSeconds(playerItem.duration)
let currentTime = CMTimeGetSeconds(playerItem.currentTime())
let rate = player.rate
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = duration
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = currentTime
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = rate
print ("Update: \(currentTime)/\(duration)/\(rate)")
}
}
}
}
| true
|
2f62c1f7ef0d1a0dc58f0f8dee2a483704e7ca1f
|
Swift
|
rborquezdiaz/RappiFlix
|
/RappiFlix/Helpers/Network/NetworkManager.swift
|
UTF-8
| 6,790
| 2.96875
| 3
|
[] |
no_license
|
//
// NetworkManager.swift
// RappiFlix
//
// Created by Rodrigo Borquez Diaz on 01/06/21.
//
import Foundation
public enum URLType {
case endpoint
case images
}
public enum HTTPMethod: String {
case post = "POST"
case put = "PUT"
case get = "GET"
case delete = "DELETE"
case patch = "PATCH"
}
public enum RequestParams {
case body(_ : [String: Any]?)
case url(_ : [String: Any]?)
}
public protocol Request {
var path : String { get }
var method : HTTPMethod { get }
var parameters : RequestParams? { get }
var headers : [String: Any]? { get }
var urlType : URLType { get }
}
public enum ServerRequest: Request {
case movieGenres
case popularMovies(Int)
case topRatedMovies(Int)
case upcomingMovies(Int)
case movieDetail(Int)
case poster(String)
case backdrop(String)
case movieVideos(Int)
public var path: String {
switch self {
case .movieGenres:
return "/genre/movie/list"
case .popularMovies(_):
return "/movie/popular"
case .topRatedMovies(_):
return "/movie/top_rated"
case .upcomingMovies(_):
return "/movie/upcoming"
case .movieDetail(let id):
return "/movie/\(id)"
case .poster(let poster):
return "\(poster)"
case .backdrop(let backdrop):
return "\(backdrop)"
case .movieVideos(let id):
return "/movie/\(id)/videos"
}
}
public var method: HTTPMethod {
switch self {
case .movieGenres:
return .get
case .popularMovies(_):
return .get
case .topRatedMovies(_):
return .get
case .upcomingMovies(_):
return .get
case .movieDetail(_):
return .get
case .poster(_):
return .get
case .backdrop(_):
return .get
case .movieVideos(_):
return .get
}
}
public var parameters: RequestParams? {
switch self {
case .movieGenres:
return nil
case .popularMovies(let page):
return .url(["page" : page])
case .topRatedMovies(let page):
return .url(["page" : page])
case .upcomingMovies(let page):
return .url(["page" : page])
case .movieDetail(_):
return nil
case .poster(_):
return nil
case .backdrop(_):
return nil
case .movieVideos(_):
return nil
}
}
public var headers: [String : Any]? {
switch self {
default:
return nil
}
}
public var urlType : URLType {
switch self {
case .movieGenres:
return .endpoint
case .popularMovies(_):
return .endpoint
case .topRatedMovies(_):
return .endpoint
case .upcomingMovies(_):
return .endpoint
case .movieDetail(_):
return .endpoint
case .poster(_):
return .images
case .backdrop(_):
return .images
case .movieVideos(_):
return .endpoint
}
}
}
public class NetworkManager {
private static var sharedInstance: NetworkManager = {
let networkManager = NetworkManager()
return networkManager
}()
private let baseURL = "https://api.themoviedb.org/"
private let imagesURL = "https://image.tmdb.org/t/p/original/"
private let apiVersion = 3
private var baseRequestURL : String {
return baseURL + "\(apiVersion)"
}
public var session = URLSession.shared
private init() { }
// MARK: - Accessors
public class func shared() -> NetworkManager {
return sharedInstance
}
private func getAPIKey() -> String {
return "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhNTcwMmQ2MjdjMjEzMWRlODE5NWVmZmMyYzNjOGEwOCIsInN1YiI6IjYwYjNmMzVlM2UwOWYzMDAyYWNkODY4YyIsInNjb3BlcyI6WyJhcGlfcmVhZCJdLCJ2ZXJzaW9uIjoxfQ.Qt3KizvEdRaCKtCklgiYYFvP4YRf0KTB8iIRgGCs27c"
}
private func prepareURLRequest(for request: Request) throws -> URLRequest {
let requestURL = request.urlType == .endpoint ? baseRequestURL + request.path : imagesURL
guard let url = URL(string: requestURL) else {
throw NetworkError.badInput
}
var urlRequest = URLRequest(url: url)
switch request.parameters {
case .body(let params):
// Parameters are part of the body
guard let params = params else { throw NetworkError.badInput}
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: params, options: .init(rawValue: 0))
case .url(let params):
// Parameters are part of the url
guard let params = params else { throw NetworkError.badInput }
let queryParams = params.map({ (element) -> URLQueryItem in
return URLQueryItem(name: element.key, value: "\(element.value)")
})
guard var components = URLComponents(string: requestURL) else {
throw NetworkError.badInput
}
components.queryItems = queryParams
urlRequest.url = components.url
case .none:
break
}
// Headers for request
urlRequest.addValue("Bearer \(getAPIKey())", forHTTPHeaderField: "Authorization")
urlRequest.addValue("application/json;charset=utf-8", forHTTPHeaderField: "Content-Type")
// HTTP method for request
urlRequest.httpMethod = request.method.rawValue
return urlRequest
}
public func urlRequest(for request: ServerRequest) -> URLRequest? {
return try? prepareURLRequest(for: request)
}
public func responseResult(statusCode : Int) -> (Result<Bool, NetworkError>) {
switch statusCode {
case 200...299:
return .success(true)
default:
return .failure(ErrorHandler.requestErrorFrom(statusCode: statusCode))
}
}
}
extension URLResponse {
func getStatusCode() -> Int? {
if let httpResponse = self as? HTTPURLResponse {
return httpResponse.statusCode
}
return nil
}
}
extension Data {
func getDecodedObject<T>(from object : T.Type)->T? where T : Decodable {
do {
return try JSONDecoder().decode(object, from: self)
} catch let error {
print("Manually parsed ", (try? JSONSerialization.jsonObject(with: self, options: .allowFragments)) ?? "nil")
print("Error in Decoding OBject ", error)
return nil
}
}
}
| true
|
0bc68c3d54cc53c6ffd8dd17b509f59186762399
|
Swift
|
ivzeus/swiftui-learning
|
/01_Basic/01_Basic/01_Basic/PokemonStatsView.swift
|
UTF-8
| 2,883
| 3.578125
| 4
|
[] |
no_license
|
//
// PokemonStats.swift
// 01_Basic
//
// Created by Hoang Ngoc Toan on 1/6/20.
// Copyright © 2020 Hoang Ngoc Toan. All rights reserved.
//
import SwiftUI
struct PokemonStats {
var hp: Int
var speed: Int
var defense: Int
var attack: Int
var specialDefense: Int
var specialAttack: Int
init() {
self.hp = 0
self.speed = 0
self.defense = 0
self.attack = 0
self.specialDefense = 0
self.specialAttack = 0
}
mutating func setHP(hp: Int) {
self.hp = hp
}
mutating func setSpeed(speed: Int) {
self.speed = speed
}
mutating func setAtk(atk: Int) {
self.attack = atk
}
mutating func setSpecialAtk(specialAtk: Int) {
self.specialAttack = specialAtk
}
mutating func setDef(def: Int) {
self.defense = def
}
mutating func setSpecialDef(specialDef: Int) {
self.specialDefense = specialDef
}
}
struct PokemonStatsView: View {
var pokemonStats: PokemonStats;
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading) {
Text("Abilities:")
Text("Moves:")
Text("Stats:")
HStack {
Text("- HP: ")
Text(String(pokemonStats.hp))
Spacer()
}
HStack {
Text("- Speed: ")
Text(String(pokemonStats.speed))
Spacer()
}
HStack {
Text("- Attack: ")
Text(String(pokemonStats.attack))
Spacer()
}
HStack {
Text("- Special Attack: ")
Text(String(pokemonStats.specialAttack))
Spacer()
}
HStack {
Text("- Defense: ")
Text(String(pokemonStats.defense))
Spacer()
}
HStack {
Text("- Special Defense: ")
Text(String(pokemonStats.specialDefense))
Spacer()
}
Text("Types:")
}.padding(32)
}
}
}
struct PokemonStats_Previews: PreviewProvider {
static var previews: some View {
var pokemonStats = PokemonStats()
pokemonStats.setHP(hp: 1000)
pokemonStats.setSpeed(speed: 200)
pokemonStats.setAtk(atk: 250)
pokemonStats.setDef(def: 240)
pokemonStats.setSpecialAtk(specialAtk: 450)
pokemonStats.setSpecialDef(specialDef: 350)
return PokemonStatsView(pokemonStats: pokemonStats)
}
}
| true
|
bea644a5797177ae43184ff894dbbdc934bff567
|
Swift
|
princebharti/xcode-TwitterClone
|
/TwitterClone/Models/TweetImage.swift
|
UTF-8
| 386
| 2.765625
| 3
|
[] |
no_license
|
//
// TweetImage.swift
// TwitterClone
//
// Created by Prince Bharti on 14/09/18.
// Copyright © 2018 Prince Bharti. All rights reserved.
//
import Foundation
struct TweetImage: Decodable {
var width: Double?
var height: Double?
var imageURL: String?
enum codingKeys: String, CodingKey {
case width
case height
case imageURL = "imageUrl"
}
}
| true
|
534081e238b7e67d224cdaf55bc603c78f7259f2
|
Swift
|
davidWilliams96080/ios-reading-list
|
/Reading List/Reading List/BookDetailViewController.swift
|
UTF-8
| 2,739
| 2.734375
| 3
|
[] |
no_license
|
//
// BookDetailViewController.swift
// Reading List
//
// Created by David Williams on 2/14/20.
// Copyright © 2020 Lambda School. All rights reserved.
//
import UIKit
import Photos
class BookDetailViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var bookTitleLabel: UITextField!
@IBOutlet weak var reasonToReadTextField: UITextView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var editBookCoverLabel: UIButton!
@IBOutlet weak var editBookLabel: UILabel!
var bookcontroller: BookController?
var book: Book?
override func viewDidLoad() {
super.viewDidLoad()
title = "Add the book:"
updateViews()
imagePicker.delegate = self
}
var imagePicker = UIImagePickerController()
func updateViews() {
loadViewIfNeeded()
guard let book = book else { return }
bookTitleLabel.text = book.title
reasonToReadTextField.text = book.reasonToRead
editBookCoverLabel.setTitle("Update Cover Image", for: [])
editBookLabel.text = "Edit a Book"
title = book.title
}
@IBAction func saveBookTapped(_ sender: Any) {
guard let title = bookTitleLabel.text,
let reason = reasonToReadTextField.text,
!title.isEmpty,
!reason.isEmpty else { return }
if let book = book {
bookcontroller?.editBook(book: book, title, reason: reason)
} else {
bookcontroller?.createBook(named: title, reasonToRead: reason, hasBeenRead: false)
}
navigationController?.popViewController(animated: true)
}
@IBAction func addCoverImageTapped(_ sender: Any) {
imagePicker.sourceType = .photoLibrary
present(imagePicker, animated: true)
}
}
#warning("Why does this not work?")
extension BookDetailViewController {
// private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//
// let image = info[.originalImage] as? UIImage
//
// picker.dismiss(animated: true, completion: nil)
// }
}
extension BookDetailViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let text = textField.text,
!text.isEmpty else { return false }
print("\(String(describing: textField.text))")
switch textField {
case bookTitleLabel:
reasonToReadTextField.textInputView.resignFirstResponder()
default:
textField.resignFirstResponder()
}
return true
}
}
| true
|
1e0f83d7abbe970b16b136be3818f006f8c1c9f5
|
Swift
|
laocat2004/CS-193P
|
/Calculator/Calculator/CalculatorBrain.swift
|
UTF-8
| 11,806
| 3.9375
| 4
|
[
"MIT"
] |
permissive
|
//
// CalculatorBrain.swift
// Calculator
//
// Created by abdelrahman mohamed on 1/18/16.
// Copyright © 2016 Abdulrhman dev. All rights reserved.
//
import Foundation
/// #### Calcaulator class
/// - simply doing all the work
/// - class uses recursive method to get operands from a stack
class CalculatorBrain {
/// custom type of enum to save the operation.
/// this type is decribable.
private enum Op: CustomStringConvertible{
case operand(Double)
case variable(String)
case constantValue(String, Double)
case unaryOperation(String, (Double) ->Double, (Double -> String?)?)
case binaryOperation(String, (Double, Double) ->Double, ((Double) -> String?)?)
var description: String {
get{
switch self {
case .operand(let operand):
return "\(operand)"
case .variable(let symbol):
return "\(symbol)"
case .constantValue(let symbol, _):
return "\(symbol)"
case .unaryOperation(let symbol, _, _):
return "\(symbol)"
case .binaryOperation(let symbol, _, _):
return "\(symbol)"
}
}
}
var precedence: Int {
get{
switch self{
case .binaryOperation(let symbol, _, _):
switch symbol{
case "×", "%", "÷":
return 2
case "+", "-":
return 1
default: return Int.max
}
default:
return Int.max
}
}
}
}
// contains all the operation entered through the user to calcluator.
private var opStack = [Op]()
// knownOps contains all known operations to the calculator.
private var knownOps = Dictionary<String, Op>()
// saving variables into the stack
var variableValues = [String: Double]()
/// String to save error if there's one.
private var error: String?
/// A properity gets the program to public.
/// caller won't have any idea what's it.
/// this's good if we want to save the information as cookie or something alike.
/// it's a ProperityList.
var program: AnyObject {
set{
if let opSymbols = newValue as? Array<String> {
var newOpStack = [Op]()
for opSymbol in opSymbols {
if let op = knownOps[opSymbol]{
newOpStack.append(op)
}else if let operand = Double(opSymbol){
newOpStack.append(.operand(operand))
}else{
newOpStack.append(.variable(opSymbol))
}
}
opStack = newOpStack
}
}
get{
return opStack.map { $0.description }
}
}
init(){
/// this function is just there to not type the string of the function twice.
/// - Parameter op: takes the operation type declarition in order to iniate the ops Stack.
func learnOps(op: Op){
knownOps[op.description] = op
}
learnOps(Op.constantValue("π", M_PI))
learnOps(Op.binaryOperation("+", +, nil))
learnOps(Op.binaryOperation("−", { $1 - $0}, nil))
learnOps(Op.binaryOperation("×", *, nil))
learnOps(Op.binaryOperation("%", { $1 % $0},
{ $0 == 0.0 ? "Division by zero" : nil }))
learnOps(Op.binaryOperation("÷", { $1 / $0},
{ $0 == 0.0 ? "Division by zero" : nil }))
learnOps(Op.unaryOperation("√", sqrt, {$0 < 0 ? "square root zero": nil}))
learnOps(Op.unaryOperation("sin", sin, nil))
learnOps(Op.unaryOperation("cos", cos, nil))
learnOps(Op.unaryOperation("tan", tan, nil))
learnOps(Op.unaryOperation("+/-", { -$0 }, nil))
learnOps(Op.unaryOperation("x²", { $0 * $0 }, nil))
learnOps(Op.variable("M"))
}
/// Evaluation function. It works recursivly through the array.
/// - Parameter ops: Array of Op enum special type defined earlier.
/// - Returns: a list contains result and the rest of the input array.
/// Error test handling has been added to the function as a closure.
///
private func evaluate(ops: [Op]) -> (result: Double?, remainingOps: [Op]){
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .operand(let operand):
return (operand, remainingOps)
case .variable(let symbol):
if let value = variableValues[symbol]{
return (value, remainingOps)
}
error = "Variable Not Set"
return (nil, remainingOps)
case .constantValue(_, let operand):
return (operand, remainingOps)
case .unaryOperation(_, let operation, let errorTest):
let operandEvaluation = evaluate(remainingOps)
if let operand = operandEvaluation.result {
// checking error test closure
if let errorMessage = errorTest?(operand) {
error = errorMessage
return (nil, operandEvaluation.remainingOps)
}
return (operation(operand), operandEvaluation.remainingOps)
}
case .binaryOperation(_, let operation, let errorTest):
let op1Evaluation = evaluate(remainingOps)
if let operand1 = op1Evaluation.result {
// checking error test closure
if let errorMessage = errorTest?(operand1) {
error = errorMessage
return (nil, op1Evaluation.remainingOps)
}
let op2Evaluation = evaluate(op1Evaluation.remainingOps)
if let operand2 = op2Evaluation.result {
return (operation(operand1, operand2), op2Evaluation.remainingOps)
}
}
}
if error == nil {
error = "Not Enough Operands"
}
}
return (nil, ops)
}
/// Evalute second function, calls insider function with same name in order to get the results.
/// - Returns: nil or Double, depends if there's error in calculating what's inside the Op stack.
func evaluate() -> Double? {
error = nil
let (result, _) = evaluate(opStack)
// print("\(opStack) = \(result) with \(remainder) leftover")
return result
}
// evaluateAndReportErrors()
func evaluateAndReportErrors() -> AnyObject? {
let (result, _) = evaluate(opStack)
return result != nil ? result : error
}
/// description of what's inside the stack without evaluation, works recursively as evaluate function.
/// - Parameter ops : operation stack
/// - returns: results as a string, plus remaining operations and presedence of the rest.
private func description (ops: [Op]) -> (result: String?, remainingOps: [Op], precedence: Int?){
if !ops.isEmpty{
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case.operand(let operand):
return (String(format: "%g", operand), remainingOps, op.precedence)
case .variable(let symbol):
return ("\(symbol)", remainingOps, op.precedence)
case .constantValue(let symbol, _):
return ("\(symbol)", remainingOps, op.precedence)
case .unaryOperation(let symbol, _, _):
let operandEvaluation = description(remainingOps)
if var operand = operandEvaluation.result {
if op.precedence > operandEvaluation.precedence {
operand = "(\(operand))"
}
return ("\(symbol)\(operand)", operandEvaluation.remainingOps, op.precedence)
}
case .binaryOperation(let symbol, _, _):
let op1Evaluation = description(remainingOps)
if var operand1 = op1Evaluation.result {
if op.precedence > op1Evaluation.precedence {
operand1 = "(\(operand1))"
}
let op2Evaluation = description(op1Evaluation.remainingOps)
if var operand2 = op2Evaluation.result {
if op.precedence > op2Evaluation.precedence {
operand2 = "(\(operand2))"
}
return ("\(operand2) \(symbol) \(operand1)",
op2Evaluation.remainingOps, op.precedence)
}
}
}
}
return("?", ops, Int.max)
}
/// calling description function through this var.
var discription: String {
get{
var (result, ops) = ("", opStack)
repeat {
var current: String?
(current, ops, _) = description(ops)
// result adds up if no operations added to the stack and sepreated by comma ,.
result = result == "" ? current! : "\(current!), \(result)"
} while ops.count > 0
return result
}
}
/// private method to get the last operand in the stack into vars dic
/// i guess there's simple ways, but this one looks appealing now
private func addVarValue(ops: [Op]){
if !ops.isEmpty{
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case.operand(let operand):
variableValues["M"] = operand
default:
break
}
}
}
/// public version of previous func.
func addOperandValueM() -> Bool{
addVarValue(opStack)
return popOperand()
}
/// Pushing operand inside the OpStack and then calls evaluate function.
/// - Parameter operand: takes an operand into the stack.
/// - Returns: The result from the evaluation.
func pushOperand(operand: Double) -> Double? {
opStack.append(Op.operand(operand))
return evaluate()
}
/// Pushing operation into the OpStack
/// - Parameter symbol: takes variable such as X, Y, check if it's known to our variableValues Dic.
/// - Returns: evaluate, as usual optional!
func pushOperand(symbol: String) -> Double? {
opStack.append(Op.variable(symbol))
return evaluate()
}
/// Pushing operation into the OpStack
/// - Parameter symbol: takes any operation that to be applied, check if it's known to our knownOps Stack.
/// - Returns: evaluate, as usual optional!
func performOperation(symbol: String) -> Double? {
if let operation = knownOps[symbol] {
opStack.append(operation)
}
return evaluate()
}
func popOperand() -> Bool{
if !opStack.isEmpty{
opStack.popLast()
return true
}
return false
}
}
| true
|
07a6ba89dba5a7f712ae7b27eb6d829a8d2c5eec
|
Swift
|
hubertka/scuba-app
|
/Scuba/DiveViewController.swift
|
UTF-8
| 7,274
| 2.640625
| 3
|
[] |
no_license
|
//
// DiveViewController.swift
// Scuba
//
// Created by Hubert Ka on 2018-01-06.
// Copyright © 2018 Hubert Ka. All rights reserved.
//
import UIKit
import os.log
class DiveViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
//MARK: Properties
@IBOutlet weak var activityLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var diveNumberTextField: UITextField!
@IBOutlet weak var activityTextField: UITextField!
@IBOutlet weak var dateTextField: UITextField!
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
private var textFields = [UITextField]()
/*
This value is either passed by 'DiveTableViewController' in 'prepare(for:sender:)' or constructed as part of adding a new dive.
*/
var dive: Dive?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
textFields += [
diveNumberTextField,
activityTextField,
dateTextField,
locationTextField
]
// Handle the text field's user input through delegate callbacks.
for index in 0..<textFields.count {
textFields[index].delegate = self
textFields[index].tag = index
}
// Set up views if editing an existing Dive
if let dive = dive {
navigationItem.title = "Dive \(dive.diveNumber)"
diveNumberTextField.text = dive.diveNumber
activityTextField.text = dive.activity
dateTextField.text = dive.date
locationTextField.text = dive.location
photoImageView.image = dive.photo
}
// Enable the Save button only if the text fields have valid entries.
updateSaveButtonState()
}
//MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard.
if textField == textFields.last {
textField.resignFirstResponder()
}
else {
let nextField = textField.tag + 1
textFields[nextField].becomeFirstResponder()
}
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
switch (textField) {
case diveNumberTextField:
navigationItem.title = "Dive \(textField.text ?? "")"
case activityTextField:
activityLabel.text = textField.text
case dateTextField:
dateLabel.text = textField.text
case locationTextField:
locationLabel.text = textField.text
default:
fatalError("The text field, \(textField), is not in the textFields array: \(textFields)")
}
updateSaveButtonState()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
// Disable the Save button while editing.
saveButton.isEnabled = false
}
//MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
// Dismiss the picker if the user cancelled.
dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// The info dictionary may contain multiple representations of the image. You want to use the original.
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
//MARK: Navigation
@IBAction func cancel(_ sender: UIBarButtonItem) {
// Depending on the style of presentation (model or push presentation), this view controller needs to be dismissed in two different ways. Segue identifiers are not necessary here because dismissal type of the view controller is only based on the presentation (or animation in) of a view controller (i.e. modal -> dimiss, show -> pop)
let isPresentingInAddDiveMode = presentingViewController is UINavigationController
if isPresentingInAddDiveMode {
dismiss(animated: true, completion: nil)
}
else if let owningNavigationController = navigationController {
owningNavigationController.popViewController(animated: true)
}
else {
fatalError("The DiveViewController is not inside a navigation controller.")
}
}
// This method lets you configure a view controller before it's presented.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
// Configure the destination view controller only when the save button is pressed.
guard let button = sender as? UIBarButtonItem, button === saveButton else {
os_log("The save button was not pressed, cancelling.", log: OSLog.default, type: .debug)
return
}
let diveNumber = diveNumberTextField.text ?? ""
let activity = activityTextField.text ?? ""
let date = dateTextField.text ?? ""
let location = locationTextField.text ?? ""
let photo = photoImageView.image
// Set the dive to be passed to DiveTableViewController after the unwind segue.
dive = Dive(diveNumber: diveNumber, activity: activity, date: date, location: location, photo: photo)
}
//MARK: Actions
@IBAction func selectImageFromPhotoLibrary(_ sender: UITapGestureRecognizer) {
// Hide the keyboard.
for index in 0..<textFields.count {
textFields[index].resignFirstResponder()
}
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .photoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
//MARK: Private Methods
private func updateSaveButtonState() {
// Disable the Save button if the text fields are empty
let diveNumberText = diveNumberTextField.text ?? ""
let activityText = activityTextField.text ?? ""
let dateText = dateTextField.text ?? ""
let locationText = locationTextField.text ?? ""
saveButton.isEnabled = !diveNumberText.isEmpty || !activityText.isEmpty || !dateText.isEmpty || !locationText.isEmpty
}
}
| true
|
9102d0275e23ac3a38c6dd08123b2735a8a8de08
|
Swift
|
tsaieugene/ios-decal-proj4
|
/SCloudNine/SCloudNine/Constants.swift
|
UTF-8
| 1,998
| 2.59375
| 3
|
[] |
no_license
|
//
// Constants.swift
// SCloudNine
//
// Created by Eddy Kim on 4/24/16.
// Copyright © 2016 iOSDecal. All rights reserved.
//
import Foundation
import UIKit
struct Constants {
// General width and height for any screen size.
static let screenWidth : CGFloat = UIScreen.mainScreen().bounds.size.width
static let screenHeight : CGFloat = UIScreen.mainScreen().bounds.size.height
static var loggedIn : Bool = false
static var inGroup : Bool = false
// Constants for ViewController instances.
static let logoWidth : CGFloat = 300.0
static let logoHeight : CGFloat = 300.0
static let labelWidth : CGFloat = 0.8 * screenWidth
static let labelHeight : CGFloat = 100.0
static let loginButtonWidth : CGFloat = 250.0
static let loginButtonHeight : CGFloat = 30.0
// Constants for MainViewController instances.
static let tabBarWidth : CGFloat = screenWidth
static let tabBarHeight : CGFloat = 0.1 * screenHeight
static let tabItemWidth : CGFloat = 30.0
static let tabItemHeight : CGFloat = 30.0
static var onGroupPage : Bool = true
static var onSearchPage : Bool = false
static var onPlaylistPage : Bool = false
static var songsInPlaylist = []
// NavBar Items
static let navBarWidth: CGFloat = screenWidth
static let navBarHeight = 0.1 * screenHeight
static let navItemWidth = 30.0
static let navItemHeight = 30.0
//TextField
// static let textFieldWidth = 31.0
static let textFieldHeight: CGFloat = 31.0
static func setTextFieldAttributes(someTextField : UITextField) {
someTextField.textAlignment = .Center
someTextField.autocorrectionType = .No
someTextField.textColor = UIColor.orangeColor()
someTextField.backgroundColor = UIColor.whiteColor()
}
// Centers object horizontally
static func centerHorizontally(objectSize: CGFloat) -> CGFloat {
return screenWidth/2 - objectSize/2
}
}
| true
|
56e525530315963eadbc4ddf80cf54353d2edaaa
|
Swift
|
bartjacobs/CoreDataFundamentals-ReadingAndUpdatingManagedObjects
|
/Core Data/AppDelegate.swift
|
UTF-8
| 5,549
| 2.84375
| 3
|
[] |
no_license
|
//
// AppDelegate.swift
// Core Data
//
// Created by Bart Jacobs on 03/01/16.
// Copyright © 2016 Bart Jacobs. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var coreDataManager = CoreDataManager()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let managedObjectContext = coreDataManager.managedObjectContext
// Helpers
var list: NSManagedObject? = nil
// Fetch List Records
let lists = fetchRecordsForEntity("List", inManagedObjectContext: managedObjectContext)
if let listRecord = lists.first {
list = listRecord
} else if let listRecord = createRecordForEntity("List", inManagedObjectContext: managedObjectContext) {
list = listRecord
}
// print("number of lists: \(lists.count)")
// print("--")
if let list = list {
// print(list.valueForKey("name"))
// print(list.valueForKey("createdAt"))
if list.valueForKey("name") == nil {
list.setValue("Shopping List", forKey: "name")
}
if list.valueForKey("createdAt") == nil {
list.setValue(NSDate(), forKey: "createdAt")
}
let items = list.mutableSetValueForKey("items")
// Create Item Record
if let item = createRecordForEntity("Item", inManagedObjectContext: managedObjectContext) {
// Set Attributes
item.setValue("Item \(items.count + 1)", forKey: "name")
item.setValue(NSDate(), forKey: "createdAt")
// Set Relationship
item.setValue(list, forKey: "list")
// Add Item to Items
items.addObject(item)
}
print("number of items: \(items.count)")
print("---")
for itemRecord in items {
print(itemRecord.valueForKey("name"))
}
}
do {
// Save Managed Object Context
try managedObjectContext.save()
} catch {
print("Unable to save managed object context.")
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
coreDataManager.saveContext()
}
// MARK: -
// MARK: Helper Methods
func createRecordForEntity(entity: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> NSManagedObject? {
// Helpers
var result: NSManagedObject? = nil
// Create Entity Description
let entityDescription = NSEntityDescription.entityForName(entity, inManagedObjectContext: managedObjectContext)
if let entityDescription = entityDescription {
// Create Managed Object
result = NSManagedObject(entity: entityDescription, insertIntoManagedObjectContext: managedObjectContext)
}
return result
}
func fetchRecordsForEntity(entity: String, inManagedObjectContext managedObjectContext: NSManagedObjectContext) -> [NSManagedObject] {
// Create Fetch Request
let fetchRequest = NSFetchRequest(entityName: entity)
// Helpers
var result = [NSManagedObject]()
do {
// Execute Fetch Request
let records = try managedObjectContext.executeFetchRequest(fetchRequest)
if let records = records as? [NSManagedObject] {
result = records
}
} catch {
print("Unable to fetch managed objects for entity \(entity).")
}
return result
}
}
| true
|
24d1a7f3a39fb61fbd971121bdc235c67286448a
|
Swift
|
buicuong/QuocCuongProject
|
/QuocCuongProject/QuocCuongProject/WebService/RequestAPI.swift
|
UTF-8
| 2,291
| 2.640625
| 3
|
[] |
no_license
|
//
// RequestAPI.swift
// QuocCuongProject
//
// Created by Mojave on 8/1/20.
// Copyright © 2020 Mojave. All rights reserved.
//
import Foundation
import Alamofire
let servicesRequestAPI = ServicesRequestAPI.shared
class ServicesRequestAPI: NSObject {
static var shared = ServicesRequestAPI()
func requestAPI(requestParameters: MI, success :@escaping ((Login_DTO)->Void)) {
let tempHeaders: HTTPHeaders = [
"Content-Type": "application/json",
"Accept": "application/json;charset=utf-8",
"Accept-Encoding": "gzip"
]
let requestAPI = "http://yelp-test.kennjdemo.com/api/v1/user/login"
let parameters = processParameter.repareRequest(requestParameters.dictionary() as Dictionary<String, AnyObject>)
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: [])
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print("===\nAPI: \(requestAPI) \nJSON : \(json)\n=== end === \n\n")
}
} catch {
print("===\nLỗi API \(requestAPI) :\(error)\n===")
}
Alamofire.request(requestAPI, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: tempHeaders).responseJSON(completionHandler: {(response) in
let apiResponse = processParameter.processReponse(response: response)
switch (response.result) {
case .success (_):
success(apiResponse)
break
case .failure(let error):
print("\n\nAuth request failed with error:\n \(error)")
break
}
})
}
}
extension ServicesRequestAPI {
class func login (request : Login_Request, success : @escaping ((LoginData, Bool)->Void)) {
servicesRequestAPI.requestAPI(requestParameters: request, success: { (response) in
let dto = LoginData.init(dictionary: response.data as! NSDictionary)
success(dto, response.result)
})
}
}
| true
|
2a1166f6f39979f400d86912d7db6eb76bc098a4
|
Swift
|
nhunghuynhthihong/RxAstroChannels
|
/RxAstroChannels/Models/Entities/Event.swift
|
UTF-8
| 2,302
| 3.078125
| 3
|
[] |
no_license
|
//
// Event.swift
// RxAstroChannels
//
// Created by Candice H on 10/24/17.
// Copyright © 2017 Candice H. All rights reserved.
//
import Foundation
struct Event {
var eventID: Double?
var channelId: Int?
var channelStbNumber: String?
var channelTitle: String?
var displayDateTimeUtc: String?
var displayDateTime: String?
var displayDuration: String?
var programmeTitle: String?
var displayHour: String?
var displayLocalDateTime: Date?
var section: String?
}
extension Event {
private enum Keys: String, SerializationKey {
case eventID = "eventID"
case channelId = "channelId"
case channelStbNumber = "channelStbNumber"
case channelTitle = "channelTitle"
case displayDateTimeUtc = "displayDateTimeUtc"
case displayDateTime = "displayDateTime"
case displayDuration = "displayDuration"
case programmeTitle
}
init(serialization: Serialization) {
eventID = serialization.value(forKey: Keys.eventID)
channelId = serialization.value(forKey: Keys.channelId)
channelStbNumber = serialization.value(forKey: Keys.channelStbNumber)
channelTitle = serialization.value(forKey: Keys.channelTitle)
displayDateTimeUtc = serialization.value(forKey: Keys.displayDateTimeUtc)
displayDateTime = serialization.value(forKey: Keys.displayDateTime)
displayDuration = serialization.value(forKey: Keys.displayDuration)
programmeTitle = serialization.value(forKey: Keys.programmeTitle)
if let dateStringFromServer = displayDateTimeUtc {
let dateFormatter = DateFormatter()
displayLocalDateTime = dateFormatter.date(fromSwapiString: dateStringFromServer)
let secondDateFormatter = DateFormatter()
secondDateFormatter.dateFormat = "h:mm a"
displayHour = secondDateFormatter.string(from: displayLocalDateTime!)
let calendar = Calendar.current
let hour = calendar.component(.hour, from: displayLocalDateTime!)
let minutes = calendar.component(.minute, from: displayLocalDateTime!)
section = minutes < 30 ? HOURS[hour] : HALF_HOURS[hour]
}
}
}
| true
|
33e4b456c3c77dfafd9927512dfb92b41248b0f1
|
Swift
|
st-small/VIPER-template
|
/VIPER-Template/FirstModule/ModuleProtocols.swift
|
UTF-8
| 835
| 2.65625
| 3
|
[] |
no_license
|
//
// ModuleProtocols.swift
// VIPER-Template
//
// Created by Stanly Shiyanovskiy on 19.07.2018.
// Copyright © 2018 Stanly Shiyanovskiy. All rights reserved.
//
import Foundation
import UIKit
protocol ModuleViewProtocol: class {
func setLabelTitle(with title: String)
func setBackground(with color: UIColor)
}
protocol ModulePresenterProtocol: class {
var router: ModuleRouterProtocol! { get set }
func configureView()
func closeButtonClicked()
func changeColorButtonClicked()
func updateBackgroundColor(with color: UIColor)
}
protocol ModuleInteractorProtocol: class {
var labelTitle: String { get }
func getRandomColor()
}
protocol ModuleRouterProtocol: class {
func closeCurrentViewController()
}
protocol ModuleCofiguratorProtocol: class {
func configure(with viewController: ModuleViewController)
}
| true
|
add092419e6fd67c8f181cc075e1b6f0e34a326f
|
Swift
|
imvm/OpenTextTools
|
/OpenTextTools/FleschKincaidReadingLevel.swift
|
UTF-8
| 1,315
| 3.328125
| 3
|
[] |
no_license
|
//
// FleschKincaidReadingLevel.swift
// OpenTextTools
//
// Created by Ian Manor on 06/02/21.
//
enum FleschKincaidReadingLevel: CustomStringConvertible {
case veryEasy
case easy
case fairlyEasy
case medium
case fairlyHard
case hard
case veryHard
case extremelyHard
init(fles: Double) {
switch fles {
case 90...:
self = .veryEasy
case 80..<90:
self = .easy
case 70..<80:
self = .fairlyEasy
case 60..<70:
self = .medium
case 50..<60:
self = .fairlyHard
case 30..<50:
self = .hard
case 10..<30:
self = .veryHard
case ...10:
self = .extremelyHard
default:
fatalError()
}
}
var description: String {
switch self {
case .veryEasy:
return "Very Easy"
case .easy:
return "Easy"
case .fairlyEasy:
return "Fairly Easy"
case .medium:
return "Medium"
case .fairlyHard:
return "Fairly Hard"
case .hard:
return "Hard"
case .veryHard:
return "Very Hard"
case .extremelyHard:
return "Extremely Hard"
}
}
}
| true
|
accbf607785d41d17f7778a9cd1eaf6d5ff86483
|
Swift
|
simon9211/swift_server
|
/Sources/swift_service/userModel.swift
|
UTF-8
| 931
| 2.796875
| 3
|
[] |
no_license
|
////
//// File.swift
////
////
//// Created by xiwang wang on 2019/11/15.
////
//
//import MySQLStORM
//import StORM
//
//
//class User: MySQLStORM {
// var id : Int = 0
// var firstname : String = ""
// var lastname : String = ""
// var email : String = ""
//
// override func table() -> String {
// return usertable
// }
//
// override func to(_ this: StORMRow) {
// id = this.data["id"] as! Int
// firstname = this.data["firstname"] as! String
// lastname = this.data["lastname"] as! String
// email = this.data["email"] as! String
// }
//
// func rows() -> [User] {
// var rows = [User]()
// for i in 0..<self.results.rows.count {
// let row = User()
// row.to(self.results.rows[i])
// rows.append(row)
// }
// return rows
// }
//}
| true
|
72eaf9e00f0d59459f7b40056d826ec06093785c
|
Swift
|
huangxinping/CoreImageKit
|
/CoreImageKit/CoreImage+CICategoryDistortionEffect.swift
|
UTF-8
| 10,672
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
import CoreImage
import CoreGraphics
public extension CIImage {
func bumpDistortion(closure: ((inout center: CIVector, inout radius: NSNumber, inout scale: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CIBumpDistortion")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _center: CIVector = CIVector()
var _radius: NSNumber = 0
var _scale: NSNumber = 0
closure!(center: &_center, radius: &_radius, scale: &_scale)
filter?.setValue(_center, forKey: "inputCenter")
filter?.setValue(_radius, forKey: "inputRadius")
filter?.setValue(_scale, forKey: "inputScale")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func bumpDistortionLinear(closure: ((inout center: CIVector, inout radius: NSNumber, inout angle: NSNumber, inout scale: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CIBumpDistortionLinear")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _center: CIVector = CIVector()
var _radius: NSNumber = 0
var _angle: NSNumber = 0
var _scale: NSNumber = 0
closure!(center: &_center, radius: &_radius, angle: &_angle, scale: &_scale)
filter?.setValue(_center, forKey: "inputCenter")
filter?.setValue(_radius, forKey: "inputRadius")
filter?.setValue(_angle, forKey: "inputAngle")
filter?.setValue(_scale, forKey: "inputScale")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func circleSplashDistortion(closure: ((inout center: CIVector, inout radius: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CICircleSplashDistortion")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _center: CIVector = CIVector()
var _radius: NSNumber = 0
closure!(center: &_center, radius: &_radius)
filter?.setValue(_center, forKey: "inputCenter")
filter?.setValue(_radius, forKey: "inputRadius")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func circularWrap(closure: ((inout center: CIVector, inout radius: NSNumber, inout angle: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CICircularWrap")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _center: CIVector = CIVector()
var _radius: NSNumber = 0
var _angle: NSNumber = 0
closure!(center: &_center, radius: &_radius, angle: &_angle)
filter?.setValue(_center, forKey: "inputCenter")
filter?.setValue(_radius, forKey: "inputRadius")
filter?.setValue(_angle, forKey: "inputAngle")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func displacementDistortion(closure: ((inout displacementImage: CIImage, inout scale: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CIDisplacementDistortion")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _displacementImage: CIImage = CIImage()
var _scale: NSNumber = 0
closure!(displacementImage: &_displacementImage, scale: &_scale)
filter?.setValue(_displacementImage, forKey: "inputDisplacementImage")
filter?.setValue(_scale, forKey: "inputScale")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func droste(closure: ((inout insetPoint0: CIVector, inout insetPoint1: CIVector, inout strands: NSNumber, inout periodicity: NSNumber, inout rotation: NSNumber, inout zoom: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CIDroste")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _insetPoint0: CIVector = CIVector()
var _insetPoint1: CIVector = CIVector()
var _strands: NSNumber = 0
var _periodicity: NSNumber = 0
var _rotation: NSNumber = 0
var _zoom: NSNumber = 0
closure!(insetPoint0: &_insetPoint0, insetPoint1: &_insetPoint1, strands: &_strands, periodicity: &_periodicity, rotation: &_rotation, zoom: &_zoom)
filter?.setValue(_insetPoint0, forKey: "inputInsetPoint0")
filter?.setValue(_insetPoint1, forKey: "inputInsetPoint1")
filter?.setValue(_strands, forKey: "inputStrands")
filter?.setValue(_periodicity, forKey: "inputPeriodicity")
filter?.setValue(_rotation, forKey: "inputRotation")
filter?.setValue(_zoom, forKey: "inputZoom")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func glassDistortion(closure: ((inout texture: CIImage, inout center: CIVector, inout scale: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CIGlassDistortion")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _texture: CIImage = CIImage()
var _center: CIVector = CIVector()
var _scale: NSNumber = 0
closure!(texture: &_texture, center: &_center, scale: &_scale)
filter?.setValue(_texture, forKey: "inputTexture")
filter?.setValue(_center, forKey: "inputCenter")
filter?.setValue(_scale, forKey: "inputScale")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func glassLozenge(closure: ((inout point0: CIVector, inout point1: CIVector, inout radius: NSNumber, inout refraction: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CIGlassLozenge")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _point0: CIVector = CIVector()
var _point1: CIVector = CIVector()
var _radius: NSNumber = 0
var _refraction: NSNumber = 0
closure!(point0: &_point0, point1: &_point1, radius: &_radius, refraction: &_refraction)
filter?.setValue(_point0, forKey: "inputPoint0")
filter?.setValue(_point1, forKey: "inputPoint1")
filter?.setValue(_radius, forKey: "inputRadius")
filter?.setValue(_refraction, forKey: "inputRefraction")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func holeDistortion(closure: ((inout center: CIVector, inout radius: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CIHoleDistortion")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _center: CIVector = CIVector()
var _radius: NSNumber = 0
closure!(center: &_center, radius: &_radius)
filter?.setValue(_center, forKey: "inputCenter")
filter?.setValue(_radius, forKey: "inputRadius")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func lightTunnel(closure: ((inout center: CIVector, inout rotation: NSNumber, inout radius: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CILightTunnel")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _center: CIVector = CIVector()
var _rotation: NSNumber = 0
var _radius: NSNumber = 0
closure!(center: &_center, rotation: &_rotation, radius: &_radius)
filter?.setValue(_center, forKey: "inputCenter")
filter?.setValue(_rotation, forKey: "inputRotation")
filter?.setValue(_radius, forKey: "inputRadius")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func pinchDistortion(closure: ((inout center: CIVector, inout radius: NSNumber, inout scale: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CIPinchDistortion")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _center: CIVector = CIVector()
var _radius: NSNumber = 0
var _scale: NSNumber = 0
closure!(center: &_center, radius: &_radius, scale: &_scale)
filter?.setValue(_center, forKey: "inputCenter")
filter?.setValue(_radius, forKey: "inputRadius")
filter?.setValue(_scale, forKey: "inputScale")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func stretchCrop(closure: ((inout size: CIVector, inout cropAmount: NSNumber, inout centerStretchAmount: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CIStretchCrop")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _size: CIVector = CIVector()
var _cropAmount: NSNumber = 0
var _centerStretchAmount: NSNumber = 0
closure!(size: &_size, cropAmount: &_cropAmount, centerStretchAmount: &_centerStretchAmount)
filter?.setValue(_size, forKey: "inputSize")
filter?.setValue(_cropAmount, forKey: "inputCropAmount")
filter?.setValue(_centerStretchAmount, forKey: "inputCenterStretchAmount")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func torusLensDistortion(closure: ((inout center: CIVector, inout radius: NSNumber, inout width: NSNumber, inout refraction: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CITorusLensDistortion")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _center: CIVector = CIVector()
var _radius: NSNumber = 0
var _width: NSNumber = 0
var _refraction: NSNumber = 0
closure!(center: &_center, radius: &_radius, width: &_width, refraction: &_refraction)
filter?.setValue(_center, forKey: "inputCenter")
filter?.setValue(_radius, forKey: "inputRadius")
filter?.setValue(_width, forKey: "inputWidth")
filter?.setValue(_refraction, forKey: "inputRefraction")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func twirlDistortion(closure: ((inout center: CIVector, inout radius: NSNumber, inout angle: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CITwirlDistortion")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _center: CIVector = CIVector()
var _radius: NSNumber = 0
var _angle: NSNumber = 0
closure!(center: &_center, radius: &_radius, angle: &_angle)
filter?.setValue(_center, forKey: "inputCenter")
filter?.setValue(_radius, forKey: "inputRadius")
filter?.setValue(_angle, forKey: "inputAngle")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
func vortexDistortion(closure: ((inout center: CIVector, inout radius: NSNumber, inout angle: NSNumber) -> Void)?) -> CIImage? {
let filter = CIFilter(name: "CIVortexDistortion")
// print(filter?.attributes)
filter?.setDefaults()
if closure != nil {
var _center: CIVector = CIVector()
var _radius: NSNumber = 0
var _angle: NSNumber = 0
closure!(center: &_center, radius: &_radius, angle: &_angle)
filter?.setValue(_center, forKey: "inputCenter")
filter?.setValue(_radius, forKey: "inputRadius")
filter?.setValue(_angle, forKey: "inputAngle")
}
filter?.setValue(self, forKey: kCIInputImageKey)
return filter?.outputImage
}
}
| true
|
a0fde19bb3a00523ed427f351bf9c13be27ac884
|
Swift
|
maverick0220/SpiderCards
|
/SpiderCards-2/SpiderCards-2/GameView.swift
|
UTF-8
| 4,943
| 3.078125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// SpiderCards-2
//
// Created by Maverick on 2020/11/11.
//
import SwiftUI
struct GameView: View {
@ObservedObject var game: Game
var body: some View {
HStack{
//main view
VStack(){
HStack(){
ForEach(game.cardsStack){ stack in
StackView(game: game, stack: stack)
.onTapGesture(perform: {
game.getSubStack(fromStack: stack.id, subStackHead: 1)
})
}
}
.padding()
}
//.frame(width: 600, height: 400, alignment: .topLeading)
//Side info
VStack(){
ControlCenter(game: game).frame(alignment: .top)
Text("Card Pack left:\n \(game.getLeftCardsPacks())")
.frame(alignment: .center)
Text("Card Pack solved:\n \(game.solvedPack)")
.frame(alignment: .center)
Text("Current Stack:\n")
.frame(alignment: .center)
//current card stack preview:
ForEach(game.currentSubStack){ card in
ZStack{
RoundedRectangle(cornerRadius: 6.0)
.fill(card.color)
Text(String(card.number))
.font(Font.largeTitle)
.foregroundColor(.black)
}
.frame(width: 120, height: 100, alignment: .center)
.onTapGesture(count: 1, perform: {
game.gameOperate(type: 2, info: (game.currentStack, card.id))
})
}
}
}
}
}
struct StackView: View {
var game: Game
var stack: CardStack
var body: some View {
VStack{
ForEach(stack.cards){ card in
CardView(game: game, stack: stack, card: card).onTapGesture(count:1, perform: {
})
Spacer()
}
}
.onTapGesture(count:1, perform: {
game.gameOperate(type: 1, info: (stack.id, -1))
})
}
}
struct CardView: View {
var game: Game
var stack: CardStack
var card: Card
var body: some View{
ZStack{
RoundedRectangle(cornerRadius: 6.0)
.fill(card.color)
if card.number != -1{
Text(String(card.number))
.font(Font.largeTitle)
.foregroundColor(.black)
}else{
Text("HERE")
.font(.largeTitle)
}
}
.onTapGesture(count: 1, perform: {
game.gameOperate(type: 1, info: (stack.id, card.id))
})
}
}
struct CurrentStackPreview: View {
var game: Game
var stack: [Card]
var body: some View{
VStack{
ForEach(stack){ card in
RoundedRectangle(cornerRadius: 6.0)
.fill(card.color)
if card.number != -1{
Text(String(card.number))
.font(Font.largeTitle)
.foregroundColor(.black)
}else{
Text(" ")
.font(Font.largeTitle)
.foregroundColor(.black)
}
}
}
.onTapGesture(count: 1, perform: {
game.gameOperate(type: 2, info: (-1, -1))
})
.frame(width: 120, height: 300, alignment: .center)
}
}
struct ControlCenter: View {
var game: Game
var body: some View{
VStack(){
MenuButton("Type"){
Button("1 type", action: { game.cardTypes=1; game.createGames() })
Button("2 type", action: { game.cardTypes=2; game.createGames() })
Button("4 type", action: { game.cardTypes=4; game.createGames() })
}
.frame(width: 80, height: 20, alignment: .center)
Button("print info", action: {
game.printGameInfo("manually")
})
Button("SendCard", action: {
print("send card")
game.sendCards(isStartGame: false)
})
Button("restart", action: {
game.createGames()
}).frame(alignment: .bottomTrailing)
}
.padding()
}
}
struct GameView_Previews: PreviewProvider {
static var previews: some View {
/*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/
}
}
| true
|
26c88bd717f663fcc228f564b7b481452f227019
|
Swift
|
HuaboTang/extensions-swift
|
/extensions-swift/extensions/UIAlertExtension.swift
|
UTF-8
| 533
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// UIAlertExtension.swift
// UWifi
//
// Created by 唐华嶓 on 12/27/14.
// Copyright (c) 2014 piKey. All rights reserved.
//
import UIKit
extension UIAlertView {
class func alert(message: String, delegate: UIAlertViewDelegate?, tag: Int) {
let alert = UIAlertView(title: "提示", message: message, delegate: delegate,
cancelButtonTitle: "确定")
alert.tag = tag
alert.show()
}
class func alert(message: String) {
self.alert(message, delegate: nil, tag:1)
}
}
| true
|
f77af70e3753e1fe3e1935e1b5b10466feebed53
|
Swift
|
vijay-clone/NewTableView
|
/SampleTableView/SampleTableView/Custom Cell/CustomTableViewCell.swift
|
UTF-8
| 1,247
| 2.65625
| 3
|
[] |
no_license
|
//
// CustomTableViewCell.swift
// SampleTableView
//
// Created by Vijay Vikram Singh on 04/10/20.
// Copyright © 2020 Vijay Vikram Singh. All rights reserved.
//
import UIKit
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var userImage: UIImageView!
@IBOutlet weak var userName: UILabel!
@IBOutlet weak var userId: UILabel!
@IBOutlet weak var userTime: UILabel!
@IBOutlet weak var userCommentView: UIView!
@IBOutlet weak var userCommentLabel: UILabel!
var imageName = ["1","2","3","4"]
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func updateUserInfo() {
userImage.image = UIImage(named: imageName.randomElement()!)
// nameLabel.text = (userData.firstName ?? "") + " " + (userData.lastName ?? "")
// commentLabel.text = userData.message
//
// userNameLabel.text = "@" + (userData.firstName ?? "").lowercased() + "_" + (userData.lastName ?? "").lowercased()
// timeLabel.text = imageName.randomElement()! + "m"
}
}
| true
|
1afb0154a087dd9df50c2c25281be7401fc19044
|
Swift
|
diegolopezbugna/board-games-timer
|
/BoardGamesTimer/Views/PlaySectionHeaderView.swift
|
UTF-8
| 1,293
| 2.609375
| 3
|
[
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// PlaySectionHeaderView.swift
// BoardGamesTimer
//
// Created by Diego Lopez bugna on 18/3/19.
// Copyright © 2019 Diego. All rights reserved.
//
import UIKit
class PlaySectionHeaderView: UITableViewHeaderFooterView {
var containerView: UIView!
var monthLabel: UILabel!
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.containerView = UIView(forAutoLayout: ())
self.addSubview(self.containerView)
self.containerView.autoPinEdgesToSuperviewEdges()
self.containerView.backgroundColor = UIColor.orange
self.monthLabel = UILabel(forAutoLayout: ())
self.containerView.addSubview(self.monthLabel)
self.monthLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16))
self.monthLabel.font = UIFont.boldSystemFont(ofSize: 20)
self.monthLabel.textColor = UIColor.white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func config(text: String, textColor: UIColor, backgroundColor: UIColor) {
self.monthLabel.text = text
self.monthLabel.textColor = textColor
self.containerView.backgroundColor = backgroundColor
}
}
| true
|
7ae7965f8f967289b4f5d44de4892b9976b3b0f7
|
Swift
|
danligas/Neebla
|
/Neebla/Database/FileInfo+Extras.swift
|
UTF-8
| 475
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import SQLite
import iOSBasics
extension Array where Element == IndexObject {
func upsert(db: Connection) throws {
guard count > 0 else {
return
}
for object in self {
try ServerObjectModel.upsert(db: db, indexObject: object)
for file in object.downloads {
try ServerFileModel.upsert(db: db, file: file, object: object)
}
}
}
}
| true
|
67b9e06d329a50738e18f46966851cfa287c4481
|
Swift
|
raytso/Facer
|
/FacialRecognition/FacialRecognition/ViewController.swift
|
UTF-8
| 2,127
| 2.625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// FacialRecognition
//
// Created by Ray Tso on 10/1/15.
// Copyright © 2015 Ray Tso. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var openCVImageView: UIImageView!
var passedImage: UIImage?
// test only
var testImg: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
if passedImage != nil {
// openCVImageView.image = OpenCVWrapper.processImageWithOpenCV(img)
openCVImageView.image = passedImage
testImg = UIImage(named: "1/2.bmp")
} else {
print("No photo ERROR")
// openCVImageView.frame.width = openCVImageView.frame.height
testImg = UIImage(named: "1/2.bmp")
openCVImageView.image = testImg
}
// Do any additional setup after loading the view, typically from a nib.
// testImg = UIImage(named: "3/10.bmp")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// if segue.identifier == "backToCamera" {
// if let navController = splitViewController?.viewControllers[1] as? UINavigationController {
// navController.popToViewController(, animated: true)
// }
// }
// }
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// if segue.identifier == "processImage" {
//
// // pass values to AnalyzeViewController
// // Sends popup alert message if face has not been detected yet
//
// if let controller = segue.destinationViewController as? AnalyzerViewController {
//// faceDetection.takePicture()
//// let image = faceDetection.userWantedFace
// controller.imageToBeAnalyzed = testImg
// print("preparing segue")
// }
// }
// }
}
| true
|
061232e2775ee763133d672febb815a15cdc71a7
|
Swift
|
Shitaolol/EhPanda
|
/EhPanda/View/Home/QuickSearchView.swift
|
UTF-8
| 4,309
| 2.984375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// QuickSearchView.swift
// EhPanda
//
// Created by 荒木辰造 on R 3/09/25.
//
import SwiftUI
struct QuickSearchView: View, StoreAccessor {
@EnvironmentObject var store: Store
@State private var isEditting = false
@State private var refreshID = UUID().uuidString
private let searchAction: (String) -> Void
init(searchAction: @escaping (String) -> Void) {
self.searchAction = searchAction
}
// MARK: QuickSearchView
var body: some View {
NavigationView {
ZStack {
List {
ForEach(words) { word in
QuickSearchWordRow(
word: word, isEditting: $isEditting,
submitID: $refreshID, searchAction: searchAction,
submitAction: { store.dispatch(.modifyQuickSearchWord(newWord: $0)) }
)
}
.onDelete { store.dispatch(.deleteQuickSearchWord(offsets: $0)) }
.onMove(perform: move)
}
.id(refreshID)
ErrorView(error: .notFound, retryAction: nil).opacity(words.isEmpty ? 1 : 0)
}
.environment(\.editMode, .constant(isEditting ? .active : .inactive))
.toolbar(content: toolbar).navigationTitle("Quick search")
}
}
// MARK: Toolbar
private func toolbar() -> some ToolbarContent {
ToolbarItem(placement: .navigationBarTrailing) {
HStack {
Button {
store.dispatch(.appendQuickSearchWord)
} label: {
Image(systemName: "plus")
}
.opacity(isEditting ? 1 : 0)
Button {
isEditting.toggle()
} label: {
Image(systemName: "pencil.circle")
.symbolVariant(isEditting ? .fill : .none)
}
}
}
}
}
private extension QuickSearchView {
var words: [QuickSearchWord] {
homeInfo.quickSearchWords
}
func move(from source: IndexSet, to destination: Int) {
refreshID = UUID().uuidString
store.dispatch(.moveQuickSearchWord(source: source, destination: destination))
}
}
// MARK: QuickSearchWordRow
private struct QuickSearchWordRow: View {
@FocusState private var isFocused
@State private var editableContent: String
private var plainWord: QuickSearchWord
@Binding private var isEditting: Bool
@Binding private var submitID: String
private var searchAction: (String) -> Void
private var submitAction: (QuickSearchWord) -> Void
init(
word: QuickSearchWord,
isEditting: Binding<Bool>,
submitID: Binding<String>,
searchAction: @escaping (String) -> Void,
submitAction: @escaping (QuickSearchWord) -> Void
) {
_editableContent = State(initialValue: word.content)
plainWord = word
_isEditting = isEditting
_submitID = submitID
self.searchAction = searchAction
self.submitAction = submitAction
}
var body: some View {
ZStack {
Button(plainWord.content) {
searchAction(plainWord.content)
}
.withArrow().foregroundColor(.primary)
.opacity(isEditting ? 0 : 1)
TextEditor(text: $editableContent)
.textInputAutocapitalization(.none)
.disableAutocorrection(true)
.opacity(isEditting ? 1 : 0)
.focused($isFocused)
}
.onChange(of: isFocused, perform: trySubmit)
.onChange(of: submitID, perform: trySubmit)
.onChange(of: isEditting) { _ in
trySubmit()
isFocused = false
}
}
private func trySubmit(_: Any? = nil) {
guard editableContent != plainWord.content else { return }
submitAction(QuickSearchWord(id: plainWord.id, content: editableContent))
}
}
struct QuickSearchView_Previews: PreviewProvider {
static var previews: some View {
QuickSearchView(searchAction: { _ in })
.preferredColorScheme(.dark)
.environmentObject(Store.preview)
}
}
| true
|
79db09958bb40d5d24380ed036345cfd07a357e3
|
Swift
|
wuuhaokun/WSOSTemplate
|
/WSOSTemplate/Classes/Tools/WSTimeUtility.swift
|
UTF-8
| 2,893
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//
// WSTimeUtility.swift
// shareba_business
//
// Created by 吳招坤 on 2018/9/20.
// Copyright © 2018年 WU CHAO KUN. All rights reserved.
//
import Foundation
public class WSTimeUtility {
public init(){
}
public static func stringFromTimeInterval(interval: TimeInterval) -> NSString {
let timeStamp:Int = Int(interval)
let timeInterval:TimeInterval = TimeInterval(timeStamp)
let date:Date = Date(timeIntervalSince1970: timeInterval)
let dateFormat:DateFormatter = DateFormatter()
dateFormat.dateFormat = "HH:mm"
let timeString = (dateFormat.string(from: date) as NSString)
return timeString
}
public static func stringFromDateInterval(interval: TimeInterval) -> NSString {
let timeStamp:Int = Int(interval)
let timeInterval:TimeInterval = TimeInterval(timeStamp)
let date:Date = Date(timeIntervalSince1970: timeInterval)
let dateFormat:DateFormatter = DateFormatter()
dateFormat.dateFormat = "YYYY/MM/dd"
let timeString = (dateFormat.string(from: date) as NSString)
return timeString
}
public static func stringFromDateAndTimeInterval(interval: TimeInterval) -> NSString {
let timeStamp:Int = Int(interval)
let timeInterval:TimeInterval = TimeInterval(timeStamp)
let date:Date = Date(timeIntervalSince1970: timeInterval)
let dateFormat:DateFormatter = DateFormatter()
dateFormat.dateFormat = "YYYY/MM/dd HH:mm"
let timeString = (dateFormat.string(from: date) as NSString)
return timeString
}
open func getNowTime() -> String {
let now = Date()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm"
let dateString = formatter.string(from: now)
return dateString
}
open func getNowDate() -> String {
let now = Date()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd"
let dateString = formatter.string(from: now)
return dateString
}
open func getNowDateAndTime() -> String {
let now = Date()
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateString = formatter.string(from: now)
return dateString
}
public static func compareDate(_ date1: Date, date date2: Date) -> Bool {
let result = date1.compare(date2)
switch result {
case .orderedDescending:// date1 小于 date2
return true
case .orderedSame:// 相等
return false
case .orderedAscending:// date1 大于 date2
return false
}
}
}
| true
|
a38a103d0e5944fe43bb3683ac956277c9ac2477
|
Swift
|
iOS-11/Swift-Playgrounds
|
/Loops.playground/Contents.swift
|
UTF-8
| 562
| 3.9375
| 4
|
[] |
no_license
|
//: Loops
import UIKit
// In Stock: phones, games, tablets, laptops, headphones
var inStockItems = [750.00, 60.00, 250.00, 1200.00, 300.00]
// Sale, 10% off all items today
// Repeat
var index = 0
repeat {
inStockItems[index] = inStockItems[index] - (inStockItems[index] * 0.10)
index += 1
} while index < inStockItems.count
print(inStockItems)
// For Loop
for index in 0..<inStockItems.count {
inStockItems[index] = inStockItems[index] - (inStockItems[index] * 0.10)
}
print(inStockItems)
for item in inStockItems {
print("Item Price: $\(item)")
}
| true
|
e1e58be2e94b034742fa12922c20c811acc35ef3
|
Swift
|
dpostigo/qolla
|
/Qolla/Protocols/Autorepresentable-Decodable.swift
|
UTF-8
| 2,033
| 3.453125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Created by Daniela Postigo on 3/9/18.
//
import Foundation
extension Autorepresentable where Self: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
self = try container.decode()
}
}
fileprivate enum ValueType {
case int(Int)
case string(String)
init(container: SingleValueDecodingContainer) throws {
let values = try ValueType.valueTypes(from: container)
switch values.first {
case .none: throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Andea.Autorepresentable decoding failed. Implement a custom init(from:)"
)
case .some(let first): self = first
}
}
init(rawValueType: RawValueType, container: SingleValueDecodingContainer) throws {
switch rawValueType {
case .int: self = try .int(container.decode(Int.self))
case .string: self = try .string(container.decode(String.self))
}
}
static func valueTypes(from: SingleValueDecodingContainer) throws -> [ValueType] {
return RawValueType.all.flatMap { try? ValueType(rawValueType: $0, container: from) }
}
}
extension Autorepresentable {
fileprivate init?(rawValueType: ValueType) {
switch rawValueType {
case .int(let intValue): self.init(rawValue: intValue)
case .string(let stringValue): self.init(stringValue: stringValue)
}
}
}
enum RawValueType: Int, Autorepresentable {
case int
case string
}
extension SingleValueDecodingContainer {
fileprivate func decode<T: Autorepresentable>(_ type: T.Type = T.self) throws -> T {
let rawValueType = try ValueType(container: self)
let value = T.init(rawValueType: rawValueType)
switch value {
case .none: throw DecodingError.dataCorruptedError(in: self, debugDescription: "")
case .some(let value): return value
}
}
}
| true
|
ad4e11936bd5699a9c2adb6292b7716a64041992
|
Swift
|
Askomaro/todo-list
|
/TodoList/TodoList/Supporting Files/APIClient.swift
|
UTF-8
| 7,256
| 2.71875
| 3
|
[] |
no_license
|
//
// APIRetriever.swift
// TodoList
//
// Created by Anton Skomarovskyi on 10/6/19.
// Copyright © 2019 Anton Skomarovskyi. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
class APIClient {
private let testApiUrl : String = "https://testapi.doitserver.in.ua/api"
private var token : String = ""
func authorizeUser(email : String, password : String, completionHandler: @escaping (ErrorModel?) -> Void) -> Void {
let parameters = [
"email": email,
"password": password
]
request("\(testApiUrl)/auth", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: ["Content-Type" : "application/json"])
.responseJSON{ response in
switch response.result {
case .success:
let error = self.validate(response: response)
let json_resp = self.mapToJson(data: response.data!)
self.token = json_resp?["token"].string ?? ""
completionHandler(error)
case .failure(let error):
print(error)
}
}
}
func createUser(email : String, password : String, completionHandler: @escaping (ErrorModel?) -> Void) -> Void {
let parameters = [
"email": email,
"password": password
]
request("\(testApiUrl)/users", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: ["Content-Type" : "application/json"])
.responseJSON{ response in
switch response.result {
case .success:
let error = self.validate(response: response)
let json_resp = self.mapToJson(data: response.data!)
self.token = json_resp?["token"].string ?? ""
completionHandler(error)
case .failure(let error):
print(error)
}
}
}
func getTasks(page : Int = 0, sortOption : String = "priority", completionHandler: @escaping ([TaskModel], ErrorModel?) -> Void) -> Void {
var tasks : [TaskModel] = []
request("\(testApiUrl)/tasks",
method: .get,
parameters: ["sort" : sortOption, "page" : page],
headers: [
"Content-Type" : "application/json",
"Authorization" : "Bearer \(self.token)"
])
.responseJSON{ response in
switch response.result {
case .success:
let error = self.validate(response: response)
tasks = self.mapToTaskModels(data: response.data!)
completionHandler(tasks, error)
case .failure(let error):
print(error)
}
}
}
func createTask(title : String, dueBy : Int, priority : String, completionHandler: @escaping (ErrorModel?) -> Void) -> Void {
request("\(testApiUrl)/tasks",
method: .post,
parameters: ["title" : title, "dueBy" : dueBy, "priority" : priority],
encoding: JSONEncoding.default,
headers: [
"Content-Type" : "application/json",
"Authorization" : "Bearer \(self.token)"
])
.debugLog()
.responseJSON{ response in
switch response.result {
case .success:
let error = self.validate(response: response)
completionHandler(error)
case .failure(let error):
print(error)
}
}
}
func getTask(task : TaskModel, completionHandler: @escaping (TaskModel, ErrorModel?) -> Void) -> Void {
request("\(testApiUrl)/tasks/\(task.id)",
method: .get,
headers: [
"Content-Type" : "application/json",
"Authorization" : "Bearer \(self.token)"
])
.responseJSON{ response in
switch response.result {
case .success:
let error = self.validate(response: response)
let task = self.mapToTaskModel(data: response.data!)
completionHandler(task, error)
case .failure(let error):
print(error)
}
}
}
func updateTask(task : TaskModel, completionHandler: @escaping (ErrorModel?) -> Void) -> Void {
request("\(testApiUrl)/tasks/\(task.id)",
method: .put,
parameters: ["title" : task.title, "dueBy" : task.dueBy, "priority" : task.priority],
headers: [
"Content-Type" : "application/json",
"Authorization" : "Bearer \(self.token)"
])
.responseJSON{ response in
switch response.result {
case .success:
let error = self.validate(response: response)
completionHandler(error)
case .failure(let error):
print(error)
}
}
}
func deleteTask(task : TaskModel, completionHandler: @escaping (ErrorModel?) -> Void) -> Void {
request("\(testApiUrl)/tasks/\(task.id)",
method: .delete,
headers: [
"Content-Type" : "application/json",
"Authorization" : "Bearer \(self.token)"
])
.responseJSON{ response in
switch response.result {
case .success:
let error = self.validate(response: response)
completionHandler(error)
case .failure(let error):
print(error)
}
}
}
private func validate(response : DataResponse<Any>) -> ErrorModel? {
var error : ErrorModel? = nil
if(200..<300 ~= response.response!.statusCode){
} else {
error = ErrorModel(statusCode: response.response!.statusCode, message: JSON(response.data!)["message"].string)
}
return error
}
private func mapToJson(data : Data) -> JSON? {
var json : JSON? = nil
do{
json = try JSON(data: data)
}
catch{
print("JSON Error")
}
return json
}
private func mapToTaskModels(data : Data) -> [TaskModel] {
var tasks : [TaskModel] = []
let json_resp = self.mapToJson(data: data)!
for (_, task) in json_resp["tasks"]{
tasks.append(TaskModel(json_resp: task))
}
return tasks
}
private func mapToTaskModel(data : Data) -> TaskModel {
let json_resp = self.mapToJson(data: data)!
let task = TaskModel(json_resp:json_resp["task"])
return task
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.