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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
28ee60241016f7d19a4146de44a0fd8792666ada
|
Swift
|
chefnobody/DeallocSample
|
/DeallocSample/ViewController.swift
|
UTF-8
| 456
| 2.78125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// DeallocSample
//
// Created by Aaron Connolly on 5/27/21.
//
import UIKit
class ViewController: UIViewController {
init(
_ title: String = "White",
_ color: UIColor = .white
) {
super.init(nibName: nil, bundle: nil)
self.title = title
view.backgroundColor = color
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
6cf6125233729a9c14b65965eab44c1bfeee4179
|
Swift
|
inwoodev/ios-stream-chat-app
|
/StreamChat/StreamChat/Model/Protocols/URLSessionStreamTaskProtocol.swift
|
UTF-8
| 539
| 2.546875
| 3
|
[] |
no_license
|
//
// URLSessionStreamTaskProtocol.swift
// StreamChat
//
// Created by James on 2021/08/19.
//
import Foundation
protocol URLSessionStreamTaskProtocol {
func readData(ofMinLength minBytes: Int, maxLength maxBytes: Int, timeout: TimeInterval, completionHandler: @escaping (Data?, Bool, Error?) -> Void)
func write(_ data: Data, timeout: TimeInterval, completionHandler: @escaping (Error?) -> Void)
func resume()
func closeWrite()
func closeRead()
}
extension URLSessionStreamTask: URLSessionStreamTaskProtocol { }
| true
|
847f074d9a965d3b7accd846fafa3b4301469ba4
|
Swift
|
babudineshas/fooddelivery
|
/FoodDelivery/FoodDelivery/Common/Extensions.swift
|
UTF-8
| 1,581
| 2.984375
| 3
|
[] |
no_license
|
//
// Extensions.swift
// FoodDelivery
//
// Created by Dinesh Babu on 1/11/20.
// Copyright © 2020 DinDinn. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
func toast(_ message: String) {
let alert = UIAlertController(title: "Info", message: message, preferredStyle: (UIDevice.current.userInterfaceIdiom == .pad) ? .alert : .actionSheet)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in
print("toast ok")
alert.dismiss(animated: true)
}))
self.present(alert, animated: true)
// duration in seconds
let duration: Double = 2
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration) {
alert.dismiss(animated: true)
}
}
}
extension UIView {
func zoomInOut() {
let animation = CAKeyframeAnimation(keyPath: "transform.scale")
animation.values = [1.0, 1.6, 1.0]
animation.keyTimes = [0, 0.5, 1]
animation.duration = 1.5
animation.repeatCount = 1.0
self.layer.add(animation, forKey: nil)
}
}
extension UIPageControl {
func updateDots() {
for n in 0..<self.subviews.count {
let dotView = self.subviews[n]
dotView.backgroundColor = (n == self.currentPage) ? self.currentPageIndicatorTintColor : self.pageIndicatorTintColor
if n == self.currentPage {
dotView.zoomInOut()
}
}
}
}
| true
|
a5ead863be2700c7fc4ee8c52c0aff3728afb1a8
|
Swift
|
fatihkaganemre/kuziSport
|
/Karate/News/NewsTableViewController.swift
|
UTF-8
| 2,188
| 2.65625
| 3
|
[] |
no_license
|
//
// NewsViewController.swift
// Karate
//
// Created by Little Frog on 6/2/19.
// Copyright © 2019 Fatih Kagan Emre. All rights reserved.
//
import Foundation
import UIKit
struct NewsViewModel {
let items: [NewsItemCellViewModel]
let calendarAction: (() -> Void)
let didSelect: ((Int) -> Void)
}
class NewsTableViewController: UITableViewController {
private let interactor: NewsInteractor!
private let viewModel: NewsViewModel!
@available (*, unavailable) required init(coder: NSCoder) { fatalError("") }
init(interactor: NewsInteractor) {
self.interactor = interactor
self.viewModel = interactor.viewModel()
super.init(nibName: nil, bundle: nil)
self.title = "KUZI SPORT KARATE"
buildCalenderButton()
setupTableView()
}
private func setupTableView() {
tableView.register(NewsItemCell.self)
tableView.tableFooterView = UIView()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.translatesAutoresizingMaskIntoConstraints = false
}
private func buildCalenderButton() {
let calendarBarButton = UIBarButtonItem(
image: UIImage(named: "calendar"),
style: .plain,
target: self,
action: #selector(calendarAction)
)
calendarBarButton.tintColor = .white
self.navigationItem.rightBarButtonItem = calendarBarButton
}
@objc func calendarAction() {
viewModel.calendarAction()
}
}
extension NewsTableViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.items.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: NewsItemCell = tableView.dequeueReusableCell(forIndexPath: indexPath)
cell.bind(with: viewModel.items[indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
viewModel.didSelect(indexPath.row)
}
}
| true
|
c779a03cfdbedd3aa03ccc645b23a86c68295f37
|
Swift
|
Joneze/learnSwift
|
/swiftProjectTest/customCell/ZHCustomCell.swift
|
UTF-8
| 1,019
| 2.515625
| 3
|
[] |
no_license
|
//
// ZHCustomCell.swift
// swiftProjectTest
//
// Created by jay on 2017/9/22.
// Copyright © 2017年 曾辉. All rights reserved.
//
import UIKit
class ZHCustomCell: UITableViewCell {
var titleLabel:UILabel?
var contentImageView: UIImageView?
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super .init(style: style, reuseIdentifier: reuseIdentifier)
self.setUpUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setUpUI() {
self.titleLabel = UILabel.init()
self.titleLabel?.backgroundColor = UIColor.clear
self.titleLabel?.frame = CGRect(x:20, y:0, width:100, height:30)
self.titleLabel?.text = "自定义cell"
self.titleLabel?.font = UIFont.systemFont(ofSize: 18)
self.titleLabel?.numberOfLines = 0
self.titleLabel?.textAlignment = NSTextAlignment.center
self.addSubview(self.titleLabel!)
}
}
| true
|
221f0487814a25e23e92b1132a6f7ebd8a31203b
|
Swift
|
devxoul/AlertReactor
|
/Examples/UserListApp/UserListApp/UserAlertReactor.swift
|
UTF-8
| 1,338
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// UserAlertReactor.swift
// UserListApp
//
// Created by Suyeol Jeon on 29/07/2017.
// Copyright © 2017 Suyeol Jeon. All rights reserved.
//
import AlertReactor
import ReactorKit
import RxSwift
final class UserAlertReactor: AlertReactor<UserAlertAction> {
fileprivate let userID: String
init(userID: String) {
self.userID = userID
}
override func mutate(action: Action) -> Observable<Mutation> {
switch action {
case .prepare:
return Observable.concat([
Observable.just(.setActions([.copy, .loading, .block, .cancel])),
UserService.isFollowing(userID: self.userID)
.map { isFollowing -> [UserAlertAction] in
let followOrUnfollow: UserAlertAction = !isFollowing ? .follow : .unfollow
return [.copy, followOrUnfollow, .block, .cancel]
}
.map(Mutation.setActions),
])
case let .selectAction(alertAction):
switch alertAction {
case .loading:
return .empty()
case .copy:
return .empty()
case .follow:
return UserService.follow(userID: self.userID).flatMap(Observable.empty)
case .unfollow:
return UserService.unfollow(userID: self.userID).flatMap(Observable.empty)
case .block:
return .empty()
case .cancel:
return .empty()
}
}
}
}
| true
|
ed1082321c37718f7676e5f6e4f94cdaf19f7520
|
Swift
|
markusseidler/FalcoSet
|
/FalcoSet/ViewModel/SetCardShading.swift
|
UTF-8
| 871
| 3.078125
| 3
|
[] |
no_license
|
//
// SetCardShading.swift
// FalcoSet
//
// Created by Markus Seidler on 17/8/20.
// Copyright © 2020 Mata. All rights reserved.
//
import SwiftUI
enum SetCardShading {
case transparent
case semiTransparent
case solid
}
extension SetCardShading: RawRepresentable {
typealias RawValue = Double
init?(rawValue: Double) {
switch rawValue {
case 0: self = .transparent
case 0.3: self = .semiTransparent
case 1: self = .solid
default: return nil
}
}
var rawValue: Double {
switch self {
case .transparent: return 0
case .semiTransparent: return 0.3
case .solid: return 1
}
}
}
struct SetCardShading_Previews: PreviewProvider {
static var previews: some View {
/*@START_MENU_TOKEN@*/Text("Hello, World!")/*@END_MENU_TOKEN@*/
}
}
| true
|
e109e75adad4a6a203008b51cffee03153abdc70
|
Swift
|
enzomaruffa/RealityKit-MemoryGame
|
/Pagliacci/Views/MenuCollectionViewCell.swift
|
UTF-8
| 648
| 2.703125
| 3
|
[] |
no_license
|
//
// MenuCollectionViewCell.swift
// Pagliacci
//
// Created by Enzo Maruffa Moreira on 30/01/20.
// Copyright © 2020 Enzo Maruffa Moreira. All rights reserved.
//
import UIKit
class MenuCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
func setupCell(with card: Card) {
imageView.layer.cornerRadius = 40
if card.revealed {
print("Using correct asset...")
imageView.image = UIImage(named: card.assetName)
} else {
print("Using default asset...")
imageView.image = UIImage(named: Card.defaultCardAssetName)
}
}
}
| true
|
ba0d427050eaf047008708f5690a2e132ec9533c
|
Swift
|
neonio/datastructure101
|
/Swift/Algorithm/Algorithm/Datastructure/Heap.swift
|
UTF-8
| 3,652
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
//
// Heap.swift
// Algorithm
//
// Created by amoyio on 2018/9/12.
// Copyright © 2018年 amoyio. All rights reserved.
//
import Foundation
class Heap<T: ComparableElement>: CustomDebugStringConvertible {
var debugDescription: String {
return data.debugDescription
}
private(set) var data: [T] = []
var size: Int {
return data.count
}
func isEmpty() -> Bool {
return size == 0
}
init() {}
func situSort() {
// 由于我们是存储在数组里面的,这时候想要对数组排序的话
for i in stride(from: size - 1, through: 1, by: -1) {
data.swapAt(0, i)
// 到当前处理的 heap max index 截止
shiftDown(index: 0, until: i)
}
}
func isValid(heapArray:[T]) -> Bool {
for i in 0..<parentIndex(nodeIndex: (size - 1)) {
let result = heapArray[i] < heapArray[leftChildIndex(nodeIndex: i)] || heapArray[i] < heapArray[rightChildindex(nodeIndex: i)]
assert(!result, "error")
}
return true
}
convenience init(list: [T]) {
self.init()
self.data = list
let lastNotLeafElementIndex = parentIndex(nodeIndex: list.count - 1)
for i in 0...lastNotLeafElementIndex {
shiftDown(index: lastNotLeafElementIndex - i, until: data.count)
}
}
func parentIndex(nodeIndex: Int) -> Int {
assert(nodeIndex > 0, "节点的值应该大于0")
return (nodeIndex - 1) / 2
}
func leftChildIndex(nodeIndex: Int) -> Int {
return nodeIndex * 2 + 1
}
func rightChildindex(nodeIndex: Int) -> Int {
return nodeIndex * 2 + 2
}
func add(element: T) {
data.append(element)
shiftUp(index: data.count - 1)
}
func shiftUp(index: Int) {
var currentIndex = index
while currentIndex > 0 && data[parentIndex(nodeIndex: currentIndex)] < data[currentIndex] {
data.swapAt(parentIndex(nodeIndex: currentIndex), currentIndex)
currentIndex = parentIndex(nodeIndex: currentIndex)
}
}
func findMax() -> T? {
if data.isEmpty {
return nil
}
return data[0]
}
func extractMax() -> T? {
if let maxElement = findMax() {
data.swapAt(0, data.count - 1)
data.removeLast()
shiftDown(index: 0, until: data.count)
return maxElement
} else {
return nil
}
}
func shiftDown(index: Int, until:Int) {
var selectedIndex = index
// 这个判断条件是当前 index 不是叶子节点
while leftChildIndex(nodeIndex: selectedIndex) < until {
let leftElementIndex = leftChildIndex(nodeIndex: selectedIndex)
let rightElementIndex = leftElementIndex + 1
var maxChildElementIndex = leftElementIndex
// 这个判断条件是当前有右节点
if rightElementIndex < until && data[rightElementIndex] > data[leftElementIndex] {
maxChildElementIndex = rightElementIndex
}
if data[selectedIndex] >= data[maxChildElementIndex] {
break
}
data.swapAt(maxChildElementIndex, selectedIndex)
selectedIndex = maxChildElementIndex
}
}
func replace(elem: T) -> T? {
guard let maxElem = findMax() else {
return nil
}
data[0] = elem
shiftDown(index: 0, until: data.count)
return maxElem
}
}
| true
|
542451211f4ac802b576a3bb0c422445888fc0b6
|
Swift
|
Ivlad003/PecodeIOSDevelopertask
|
/PecodeIOSDevelopertask/home/ViewControllerApiFuncExtentions.swift
|
UTF-8
| 2,687
| 2.640625
| 3
|
[] |
no_license
|
//
// ViewControllerApiFuncExtentions.swift
// ViewControllerApiFuncExtentions
//
// Created by kosmodev on 06.08.2021.
//
import Foundation
extension ViewController{
func getNews(q: String = "apple") {
sendRequest("https://newsapi.org/v2/everything", parameters: [
"q": "apple",
"from": "2021-08-05",
"sortBy":"publishedAt",
"pageSize": "10",
"page": String(nextPage),
"apiKey": "cd844480954845d59ae6db768267d719"]) { responseObject, error in
guard let responseObject = responseObject, error == nil else {
print(error ?? "Unknown error")
return
}
DispatchQueue.main.async {
if self.newsModel != nil, let articles = responseObject.articles {
self.newsModel?.articles?.append(contentsOf: articles)
} else {
self.newsModel = responseObject
}
self.currentCount = self.newsModel?.articles?.count ?? 0
self.table.reloadData()
self.nextPage += 1
self.spinner?.isHidden = true
}
}
}
func sendRequest(_ url: String, parameters: [String: String], completion: @escaping (NewsModel?, Error?) -> Void) {
var components = URLComponents(string: url)!
components.queryItems = parameters.map { (key, value) in
URLQueryItem(name: key, value: value)
}
components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let request = URLRequest(url: components.url!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard
let data = data, // is there data
let response = response as? HTTPURLResponse, // is there HTTP response
200 ..< 300 ~= response.statusCode, // is statusCode 2XX
error == nil // was there no error
else {
completion(nil, error)
return
}
let json: Any?
json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let result = try! decoder.decode(NewsModel.self, from: data)
completion(result, nil)
}
task.resume()
}
}
| true
|
b34da45057f47c0ad88fe56708736d1ae0075dad
|
Swift
|
Gkolunia/TestQuandooTask
|
/TestQuandooTask/UsersAndPostsModule/Manager/UsersAndPostsServiceManager.swift
|
UTF-8
| 878
| 2.515625
| 3
|
[] |
no_license
|
//
// UsersAndPostsServiceManager.swift
// TestQuandooTask
//
// Created by Hrybeniuk Mykola on 10/30/17.
// Copyright © 2017 Gkol. All rights reserved.
//
import Foundation
/// Path urls for UsersAndPosts Module
fileprivate struct ApiUrls {
static let users = "/users"
static let posts = "/posts"
}
// MARK: - Extends Service Manager for getting users list
extension ServiceManager : UsersLoaderManager {
func loadUsersList(_ handler: @escaping (Bool, [UserModel]?, ErrorMessage?) -> ()) {
doRequest(ApiUrls.users, nil, .get, handler: handler)
}
}
// MARK: - Extends Service Manager for getting post list
extension ServiceManager : PostsLoaderManager {
func loadPostsList(with userId: Int, _ handler: @escaping (Bool, [PostModel]?, ErrorMessage?) -> ()) {
doRequest(ApiUrls.posts, ["userId" : String(userId)], .get, handler: handler)
}
}
| true
|
9acd1bad2016331e9f67f23593693383721b9611
|
Swift
|
unoonesrl/rubacava-spm
|
/Sources/Rubacava/Subclasses/RCImageView.swift
|
UTF-8
| 775
| 2.890625
| 3
|
[] |
no_license
|
//
// RCImageView.swift
//
//
// Created by Tiziano Cialfi on 19/01/21.
//
import UIKit
public final class RCImageView: UIImageView {
public init(image: UIImage? = nil, contentMode: UIView.ContentMode = .scaleAspectFill, cornerRadius: CGFloat = 0) {
super.init(frame: .zero)
self.image = image
set(contentMode: contentMode)
set(cornerRadius: cornerRadius)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func set(contentMode: UIView.ContentMode) {
self.contentMode = contentMode
layer.masksToBounds = true
clipsToBounds = true
}
private func set(cornerRadius: CGFloat) {
layer.cornerRadius = cornerRadius
}
}
| true
|
2ffb0bbf544628c337dfbf7b1579b237a4fca3a0
|
Swift
|
TrendingTechnology/swift-css
|
/Sources/SwiftCss/Properties/Orphans.swift
|
UTF-8
| 390
| 2.859375
| 3
|
[
"WTFPL"
] |
permissive
|
//
// Orphans.swift
// SwiftCss
//
// Created by Tibor Bodecs on 2021. 07. 10..
//
// @TODO: add orphans support
// https://developer.mozilla.org/en-US/docs/Web/CSS/orphans
/// Sets the minimum number of lines that must be left at the bottom of a page when a page break occurs inside an element
public func Orphans(_ value: String) -> Property {
Property(name: "orphans", value: value)
}
| true
|
595e24451eba6887318182bddeee4f6f0d821eba
|
Swift
|
GMRemie/GeoChat-iOS
|
/GeoChat/GeoChat/Objects/MessageContainer.swift
|
UTF-8
| 1,164
| 2.765625
| 3
|
[] |
no_license
|
//
// MessageContainer.swift
// GeoChat
//
// Created by Joseph Storer on 8/29/19.
// Copyright © 2019 Joseph Storer. All rights reserved.
//
import Foundation
import UIKit
struct MessageContainer{
var msg:GeoMessage!
var handle: String!
func getCaption() -> String{
return msg.caption!
}
func getImageUrl() -> String{
return msg.url!
}
func getImage(image: UIImageView){
let url = URL(string: msg.url!)
let config = URLSessionConfiguration.default
let session = URLSession.init(configuration: config)
let task = session.dataTask(with: url!) { (Data, Response, Error) in
if (Error != nil) {
print(Error.debugDescription)
return
}
guard let response = Response as? HTTPURLResponse, response.statusCode == 200 else {
print("Error negative response")
return
}
let loaded = UIImage(data: Data!)
DispatchQueue.main.async {
image.image = loaded
}
}
task.resume()
}
}
| true
|
39809afd1770ca062319b845e91bda745c9f1a41
|
Swift
|
bryoco/iQuiz
|
/iQuiz/iQuiz/DataModel/Metadata.swift
|
UTF-8
| 704
| 2.890625
| 3
|
[] |
no_license
|
//
// Metadata.swift
// iQuiz
//
// Created by Rico Wang on 11/12/18.
// Copyright © 2018 Rico Wang. All rights reserved.
//
import Foundation
class Metadata {
var useCustomizedData: Bool
func getUseCustomizedData() -> Bool {
print("getUseCustomizedData():")
print("Metadata.useCustomizedData = \(self.useCustomizedData)")
return self.useCustomizedData
}
func setUseCustomizedData(_ useCustomizedData: Bool) -> Void {
self.useCustomizedData = useCustomizedData
print("setUseCustomizedData():")
print("Metadata.useCustomizedData = \(self.useCustomizedData)")
}
init() {
self.useCustomizedData = false
}
}
| true
|
4fda6c32ee8f87e43ef5d7e7753b086754bb28f6
|
Swift
|
wilks7/speeding
|
/speeding/FileController.swift
|
UTF-8
| 2,324
| 2.875
| 3
|
[] |
no_license
|
//
// FileController.swift
// speeding
//
// Created by hackintosh on 4/7/19.
// Copyright © 2019 wilksmac. All rights reserved.
//
import Foundation
class FileController {
static var speedLogs: [String] = []
static func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
static func getAllDocuments()-> [URL]{
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
do {
let fileURLs = try FileManager.default.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
print(fileURLs)
return fileURLs
} catch {
print("Error while enumerating files \(documentsURL.path): \(error.localizedDescription)")
return []
}
}
static func getFileURL(_ file: String) -> URL {
return getDocumentsDirectory().appendingPathComponent(file)
}
static func checkFile(_ filename: String){
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: path)
let filePath = url.appendingPathComponent(filename).path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
print("log available")
} else {
print("no log file")
createLog()
}
}
static func createLog(){
let file = "log.txt"
let text = "Speed LOG"
let path = getFileURL(file)
do {
try text.write(to: path, atomically: false, encoding: String.Encoding.utf8)
} catch {
print("ERROR: creating log")
}
}
static func logSpeed(_ logString: String){
do {
let url = FileController.getFileURL("log.txt")
let stringSpace = logString + "\n"
//let data = stringSpace.data(using: String.Encoding.utf8)!
speedLogs.append(stringSpace)
try stringSpace.appendToURL(url)
} catch {
print("ERROR: could not write to log file")
}
}
}
| true
|
3b00ee27b49448429af3f3a1aa5e0765e315db83
|
Swift
|
brunofpinheiro/ufg-ios
|
/beginnertableview/VideoListScreen.swift
|
UTF-8
| 1,444
| 2.84375
| 3
|
[] |
no_license
|
import UIKit
class VideoListScreen: UIViewController {
@IBOutlet weak var tableView: UITableView!
var videos: [Video] = []
override func viewDidLoad() {
super.viewDidLoad()
createArray()
}
func createArray() -> Void {
let url = "https://api.myjson.com/bins/ad054"
let urlObj = URL(string: url)
let task = URLSession.shared.dataTask(with: urlObj!, completionHandler: {
(data, response, error) in do {
let produtos: [Video] = try JSONDecoder().decode([Video].self, from: data!)
self.videos = produtos
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch {
print("Erro ao pegar os produtos. Favor, verificar se a url está correta.")
}
})
task.resume()
}
}
extension VideoListScreen: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return videos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let video = videos[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "VideoCell") as! VideoCell
cell.setVideo(video: video)
return cell
}
}
| true
|
e51275fb1e3519ede4124884ca44788cca0add12
|
Swift
|
maxchuquimia/SwiftFluentValidation
|
/FluentValidation/Extensions/Sequence+Extension.swift
|
UTF-8
| 492
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// Sequence+Extension.swift
// FluentValidation
//
// Created by Max Chuquimia on 29/5/19.
// Copyright © 2019 Chuquimian Productions. All rights reserved.
//
import Foundation
internal extension Sequence {
var isEmpty: Bool {
var isEmpty = true
for _ in self {
isEmpty = false
break
}
return isEmpty
}
var count: Int {
var _count = 0
for _ in self {
_count += 1
}
return _count
}
}
| true
|
754c0880ba1ece56ffe167f775681eea1f010d5b
|
Swift
|
OneCodeMan/mount
|
/mount/Controller/RegisterViewController.swift
|
UTF-8
| 1,531
| 2.5625
| 3
|
[] |
no_license
|
//
// RegisterViewController.swift
// mount
//
// Created by Dave Gumba on 2017-12-28.
// Copyright © 2017 Dave's Organization. All rights reserved.
//
import UIKit
import FirebaseAuth
class RegisterViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var registerButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let keyboardDownGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
self.view.addGestureRecognizer(keyboardDownGestureRecognizer)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
@IBAction func registerPressed(_ sender: Any) {
registerButton.isEnabled = false
let username = usernameTextField.text ?? ""
let password = passwordTextField.text ?? ""
Auth.auth().createUser(withEmail: username, password: password) {
(user, error) in
if error != nil {
print(error!)
} else {
print("Registration complete")
if let vc = self.storyboard?.instantiateViewController(withIdentifier: "FeedView") as? FeedViewController {
vc.username = username
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
}
}
| true
|
2d20409f54f386e99788d1daa7d67084ed9c4dbd
|
Swift
|
codegrande/SwiftLint
|
/Source/SwiftLintFramework/Rules/MultilineArgumentsRule.swift
|
UTF-8
| 3,079
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import SourceKittenFramework
public struct MultilineArgumentsRule: ASTRule, OptInRule, ConfigurationProviderRule {
public var configuration = MultilineArgumentsConfiguration()
public init() {}
public static let description = RuleDescription(
identifier: "multiline_arguments",
name: "Multiline Arguments",
description: "Arguments should be either on the same line, or one per line.",
kind: .style,
nonTriggeringExamples: MultilineArgumentsRuleExamples.nonTriggeringExamples,
triggeringExamples: MultilineArgumentsRuleExamples.triggeringExamples
)
public func validate(file: File,
kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard
kind == .call,
case let arguments = dictionary.enclosedArguments,
arguments.count > 1,
case let contents = file.contents.bridge(),
let nameOffset = dictionary.nameOffset,
let (nameLine, _) = contents.lineAndCharacter(forByteOffset: nameOffset) else {
return []
}
var visitedLines = Set<Int>()
if configuration.firstArgumentLocation == .sameLine {
visitedLines.insert(nameLine)
}
let lastIndex = arguments.count - 1
let violatingOffsets: [Int] = arguments.enumerated().compactMap { idx, argument in
guard
let offset = argument.offset,
let (line, _) = contents.lineAndCharacter(forByteOffset: offset) else {
return nil
}
let (firstVisit, _) = visitedLines.insert(line)
if idx == lastIndex && isTrailingClosure(dictionary: dictionary, file: file) {
return nil
} else if idx == 0 {
switch configuration.firstArgumentLocation {
case .anyLine: return nil
case .nextLine: return line > nameLine ? nil : offset
case .sameLine: return line > nameLine ? offset : nil
}
} else {
return firstVisit ? nil : offset
}
}
// only report violations if multiline
guard visitedLines.count > 1 else { return [] }
return violatingOffsets.map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severityConfiguration.severity,
location: Location(file: file, byteOffset: $0))
}
}
private func isTrailingClosure(dictionary: [String: SourceKitRepresentable], file: File) -> Bool {
guard let offset = dictionary.offset,
let length = dictionary.length,
case let start = min(offset, offset + length - 1),
let text = file.contents.bridge().substringWithByteRange(start: start, length: length) else {
return false
}
return !text.hasSuffix(")")
}
}
| true
|
18a276fe1225954e06367c2fef5adde565cd6223
|
Swift
|
mrdepth/CloudData
|
/CloudData/CloudData/Reachability.swift
|
UTF-8
| 2,777
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// Reachability.swift
// CloudData
//
// Created by Artem Shimanski on 10.03.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import Foundation
import SystemConfiguration
import Darwin
enum NetworkStatus {
case notReachable
case reachableViaWiFi
case reachableViaWWAN
}
extension Notification.Name {
static let ReachabilityChanged = Notification.Name(rawValue: "ReachabilityChanged")
}
class Reachability {
private let reachability: SCNetworkReachability
convenience init?() {
var addr = sockaddr_in()
addr.sin_len = __uint8_t(MemoryLayout<sockaddr_in>.size)
addr.sin_family = sa_family_t(AF_INET)
let ptr = withUnsafePointer(to: &addr) {$0.withMemoryRebound(to: sockaddr.self, capacity: 1){$0}}
self.init(address: ptr)
}
init?(hostName: String) {
if let reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, hostName) {
self.reachability = reachability
}
else {
return nil
}
}
init?(address: UnsafePointer<sockaddr>) {
if let reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, address) {
self.reachability = reachability
}
else {
return nil
}
}
deinit {
stopNotifier()
}
func startNotifier() -> Bool {
var context = SCNetworkReachabilityContext(version: 0, info: Unmanaged.passUnretained(self).toOpaque(), retain: nil, release: nil, copyDescription: nil)
if (SCNetworkReachabilitySetCallback(reachability, {(reachability, flags, info) in
guard let info = info else {return}
let myself = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
NotificationCenter.default.post(name: .ReachabilityChanged, object: myself)
}, &context)) {
return SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
}
return false
}
func stopNotifier() {
SCNetworkReachabilityUnscheduleFromRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
}
var reachabilityStatus: NetworkStatus {
var flags: SCNetworkReachabilityFlags = []
SCNetworkReachabilityGetFlags(reachability, &flags)
if !flags.contains(.reachable) {
return .notReachable
}
else {
var status: NetworkStatus = .notReachable
if !flags.contains(.connectionRequired) {
status = .reachableViaWiFi
}
if flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) {
if !flags.contains(.interventionRequired) {
status = .reachableViaWiFi
}
}
if flags.contains(.isWWAN) {
status = .reachableViaWWAN
}
return status
}
}
var connectionRequired: Bool {
var flags: SCNetworkReachabilityFlags = []
SCNetworkReachabilityGetFlags(reachability, &flags)
return flags.contains(.connectionRequired)
}
}
| true
|
cb0cdd008fe417fe53b438c6bbc0fd6fb92ee8bc
|
Swift
|
DSM-DMS/DMS-iOS
|
/DSMapp/Network/API/InfoAPI.swift
|
UTF-8
| 694
| 2.53125
| 3
|
[] |
no_license
|
//
// InfoAPI.swift
// DSMapp
//
// Created by 이병찬 on 2018. 6. 8..
// Copyright © 2018년 이병찬. All rights reserved.
//
import Foundation
public enum InfoAPI: API{
case getApplyInfo
case getMypageInfo
case getPointInfo
case getVersionInfo
case getMealInfo(date: String)
func getPath() -> String {
switch self {
case .getVersionInfo: return "metadata/version/3"
case .getMealInfo(let date): return "meal/\(date)"
case .getApplyInfo: return "student/info/apply"
case .getPointInfo: return "student/info/point-history"
case .getMypageInfo: return "student/info/mypage"
}
}
}
| true
|
370c7dd7e1ec9336388df26bf69be848b45fb125
|
Swift
|
ICQ9/AdmixerSDKUITestPod
|
/AdmixerSDKUITestPod/Settings.swift
|
UTF-8
| 3,182
| 2.515625
| 3
|
[] |
no_license
|
//
// Settings.swift
// IOSSampleApp
//
// Created by Dima on 10.02.2021.
//
import Foundation
import UIKit
class Settings: UIViewController {
var autorefresh: Bool = true
var resize100set: Bool = false
var delay: Bool = false
@IBOutlet var gotoxml: UIButton!
@IBOutlet var gotolist: UIView!
var expandtofit: Bool = false
var reload: Bool = false
@IBOutlet weak var Reload: UISwitch!
@IBOutlet weak var ExpandToFit: UISwitch!
@IBOutlet weak var Resize: UISwitch!
@IBOutlet weak var Autorefresh: UISwitch!
@IBOutlet weak var Delay: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func ExpandToFit(_ sender: UISwitch){
if ExpandToFit.isOn{
expandtofit = true
} else{expandtofit = false}
}
@IBAction func Reload(_ sender: UISwitch){
if Reload.isOn{
reload = true
Autorefresh.isOn = false
Autorefresh.isEnabled = false
autorefresh = false
} else {
reload = false
Autorefresh.isEnabled = true
}
}
@IBAction func Autorefresh(_ sender: UISwitch){
if Autorefresh.isOn{
autorefresh = true
}
else{ autorefresh = false}
}
@IBAction func Delay5sek(_ sender: UISwitch) {
if sender.isOn{
delay=true
}
else{delay = false}
}
@IBAction func resizeDidChange(_ sender: UISwitch){
if sender.isOn{
resize100set = true
}
else{ resize100set = false
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "gotoxml"{
let destenationXML: BannerXML = segue.destination as! BannerXML
destenationXML.resize100 = resize100set
destenationXML.delayresult = delay
destenationXML.expandtofitresult = expandtofit
destenationXML.reloadresult = reload
destenationXML.autorefreshresult = autorefresh
}
if segue.identifier == "gotolist"{
let destenationList:BannerInLine = segue.destination as! BannerInLine
destenationList.resize100local = resize100set
destenationList.expantToFitLocal = expandtofit
destenationList.reloadlocalresult = reload
destenationList.autorefreshlocalresult = autorefresh
destenationList.delaylocalresult = delay
}
if segue.identifier == "gotocode"{
let destenationCode:BannerInCode = segue.destination as! BannerInCode
destenationCode.resize100code = resize100set
destenationCode.expandtofitresultcode = expandtofit
destenationCode.reloadresultcode = reload
destenationCode.autorefreshresultcode = autorefresh
destenationCode.delayresultcode = delay
}
}
}
| true
|
9946ef2f620f2ed41a3afe37ed092e329030e737
|
Swift
|
tschmidt64/Shuttle
|
/Shuttle/Route.swift
|
UTF-8
| 16,749
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// Route.swift
// Shuttle
//
// Created by Taylor Schmidt on 3/27/16.
// Copyright © 2016 Taylor Schmidt. All rights reserved.
//
import Foundation
import CoreLocation
import SwiftyJSON
class Route {
var routeNum: Int
var routeCoords: [CLLocationCoordinate2D] = []
var stops: [Stop] = []
var busesOnRoute: [String:Bus] = [:]
var nameLong: String
var nameShort: String
init(routeNum rNum: Int, nameShort: String, nameLong: String) {
self.routeNum = rNum
self.nameLong = nameLong
self.nameShort = nameShort
self.generateRouteCoords(1)
self.generateStopCoords(1)
}
/*
This refreshes the array self.busesOnRoute with the most recent data available
*/
func refreshBuses(callback: @escaping () -> ()) {
let urlStr = "https://lnykjry6ze.execute-api.us-west-2.amazonaws.com/prod/gtfsrt-debug?url=https://data.texas.gov/download/eiei-9rpf/application/octet-stream"
let url = URL(string: urlStr)
let newSession = URLSession.shared
UIApplication.shared.isNetworkActivityIndicatorVisible = true
let newTask = newSession.dataTask(with: url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
print("ERROR FOUND")
} else {
let json = JSON(data: data!)
let entityJson = json["entity"].arrayValue
// print("ENTITY ARR LENGTH: ", entityJson.count)
for entity in entityJson {
let vehicle = entity["vehicle"]
let routeNum = vehicle["trip", "route_id"].intValue
if routeNum == self.routeNum {
// print("ENTITY:")
let busId = vehicle["vehicle", "id"].stringValue
// print("BusId: ", busId)
let busOrient = vehicle["position", "bearing"].intValue
// print("BusOrient: ", busOrient)
let lastUpdate = vehicle["timestamp"].intValue
// print("lastUpdate: ", lastUpdate)
let nextStopId = vehicle["stop_id"].stringValue
// print("nextStopId: ", nextStopId)
let busLoc = vehicle["position"]
guard let lat = busLoc["latitude"].double, let lon = busLoc["longitude"].double else {
print("ERROR: NO BUS LOCATION.")
break
}
// print("lat: ", lat, ", Lon: ", lon)
let newBus = Bus(longitude: lon, latitude: lat, orientation: Double(busOrient), updateTime: Double(lastUpdate), nextStopId: nextStopId, busId: busId)
self.busesOnRoute[busId] = newBus
}
UIApplication.shared.isNetworkActivityIndicatorVisible = false
callback()
}
}
})
newTask.resume()
}
/*
/* same function as refresh buses, uses capmetro data instead */
/* https://github.com/tschmidt64/Shuttle/blob/c78794dbf0c3c9fd34c5ee7a99bfbbaa82e1adaf/Shuttle/ViewController.swift */
/* should be similar to getData method */
func refreshBusesCapMetro() {
let urlPath = "https://data.texas.gov/download/cuc7-ywmd/text/plain"
let url:URL? = URL(string: urlPath)
let session = URLSession.shared
let task = session.dataTask(with: url!, completionHandler: { (data, response, error) -> Void in
if error != nil {
print("error found")
} else {
do {
let jsonResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
if jsonResult != nil {
if let allEntities = jsonResult!["entity"] as? NSArray {
if(allEntities.count > 0) {
// Populate busDict
for bus in allEntities {
var temp = [String:AnyObject]()
temp["array_index"] = bus["id"]
temp["alert"] = bus["alert"]
temp["is_deleted"] = bus["is_deleted"]
let vehicleSub:NSDictionary = bus["vehicle"] as! NSDictionary
temp["congestion_level"] = vehicleSub["congestion_level"]
temp["current_status"] = vehicleSub["current_status"]
temp["current_stop_sequence"] = vehicleSub["current_stop_sequence"]
let positionSub:NSDictionary = vehicleSub["position"] as! NSDictionary
temp["bearing"] = positionSub["bearing"]
temp["latitude"] = positionSub["latitude"]
temp["longitude"] = positionSub["longitude"]
temp["odometer"] = positionSub["odometer"]
temp["speed"] = positionSub["speed"]
temp["stop_id"] = vehicleSub["stop_id"]
temp["timestamp"] = vehicleSub["timestamp"]
let tripSub:NSDictionary = vehicleSub["trip"] as! NSDictionary
temp["route_id"] = tripSub["route_id"]
temp["trip_schedule_relationship"] = tripSub["schedule_relationship"]
temp["trip_start_date"] = tripSub["start_date"]
temp["trip_start_time"] = tripSub["start_time"]
temp["trip_id"] = tripSub["speed"]
let subVehicleSub:NSDictionary = vehicleSub["vehicle"] as! NSDictionary
temp["vehicle_id"] = subVehicleSub["id"]
temp["vehicle_label"] = subVehicleSub["label"]
temp["license_plate"] = subVehicleSub["license_plate"]
if (Int(temp["route_id"] as! String) == self.routeNum) {
let lat = temp["latitude"] as! Double
let long = temp["longitude"] as! Double
let orientation = temp["bearing"] as! Double
let updateTime = temp["timestamp"] as! Double
// either next stop or last stop, not actually sure
let nextStopId = temp["stop_id"] as! String
let busId = temp["vehicle_id"] as! String
let tempBus = Bus(longitude: long, latitude: lat, orientation: orientation, updateTime: updateTime, nextStopId: nextStopId, busId: busId)
print(tempBus.toString())
print()
self.busesOnRoute[busId] = tempBus
}
}
} else {
print("ERROR - Something wrong w/ JSON")
}
}
}
} catch {
print("Exception found")
}
}
})
task.resume() // start the request
}
*/
/*
This refreshes the array self.routeCoords with the most recent data available
This method needs to be updated to take in an integer that represents whether the route is inbound or outbound
*/
func generateRouteCoords(_ direction: Int) {
// This is where Micah's code to fetch routes goes
var coords = [CLLocationCoordinate2D]()
if let path = Bundle.main.path(forResource: "routes/shapes_\(self.routeNum)_\(direction)", ofType: "json") {
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let json = JSON(data: data, options: JSONSerialization.ReadingOptions.allowFragments, error: nil)
for (_, point) in json {
let lat = Double(point["shape_pt_lat"].stringValue)!
let long = Double(point["shape_pt_lon"].stringValue)!
coords.append(CLLocationCoordinate2D(latitude: lat, longitude: long))
}
}
}
self.routeCoords = coords;
}
/*
This refreshes the array self.stopCoords with the most recent data available
*/
func generateStopCoords(_ direction: Int) {
let filePath:String = "stops/stops_\(self.routeNum)_\(direction)"
if let path = Bundle.main.path(forResource: filePath, ofType: "json") {
if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) {
let json = JSON(data: data, options: JSONSerialization.ReadingOptions.allowFragments, error: nil)
self.stops = []
for (_, stop) in json {
let lat = Double(stop["stop_lat"].stringValue)!
let long = Double(stop["stop_lon"].stringValue)!
let name = stop["stop_desc"].stringValue
let stopID = stop["stop_id"].stringValue
let stopSeq = stop["stop_sequence"].intValue
let tempStop:Stop = Stop(location: CLLocationCoordinate2D(latitude: lat, longitude: long), name: name, stopID: stopID, index: stopSeq)
self.stops.append(tempStop)
}
}
}
}
func busDistancesFromStop(_ stopId: Stop) -> [String:Double] {
var distances: [String:Double] = [:]
for (_, bus) in self.busesOnRoute {
let busLoc = CLLocation(latitude: bus.location.latitude, longitude: bus.location.longitude)
let stopLoc = CLLocation(latitude: stopId.location.latitude, longitude: stopId.location.longitude)
let closestCoordToBus = self.routeCoords.min(by: { (first, second) -> Bool in
let firstLoc = CLLocation(latitude: first.latitude, longitude: first.longitude)
let secondLoc = CLLocation(latitude: second.latitude, longitude: second.longitude)
return firstLoc.distance(from: busLoc) < secondLoc.distance(from: busLoc)
})
let closestCoordToStop = self.routeCoords.min(by: { (first, second) -> Bool in
let firstLoc = CLLocation(latitude: first.latitude, longitude: first.longitude)
let secondLoc = CLLocation(latitude: second.latitude, longitude: second.longitude)
return firstLoc.distance(from: stopLoc) < secondLoc.distance(from: stopLoc)
})
// TODO: Excuse this disgusting if-let here, will fix later
if var iCur = self.routeCoords.index(where: { (coord) -> Bool in // use bus for curLoc
return closestCoordToBus?.latitude == coord.latitude
&& closestCoordToBus?.longitude == coord.longitude
}), let iStop = self.routeCoords.index(where: { (coord) -> Bool in // use stop for stopLoc
return closestCoordToStop?.latitude == coord.latitude
&& closestCoordToStop?.longitude == coord.longitude
}) {
var iNext = (iCur == self.routeCoords.count - 1) ? 0 : iCur + 1
var distance = 0.0
// current and next CLLocationCoordinate2D
var curCoord = self.routeCoords[iCur]
var nextCoord = self.routeCoords[iNext]
// current and next CLlocation
var curLoc = CLLocation(latitude: curCoord.latitude, longitude: curCoord.longitude)
var nextLoc = CLLocation(latitude: nextCoord.latitude, longitude: nextCoord.longitude)
while iCur != iStop{
let curLen = nextLoc.distance(from: curLoc)
distance += curLen
// Loop the indices
iCur = (iCur == self.routeCoords.count - 1) ? 0 : iCur + 1
iNext = (iNext == self.routeCoords.count - 1) ? 0 : iNext + 1
// print("CURRENT: \(iCur)")
// update CLLocationCoordinate2Ds
curCoord = self.routeCoords[iCur]
nextCoord = self.routeCoords[iNext]
// Update CLLocations
curLoc = CLLocation(latitude: curCoord.latitude, longitude: curCoord.longitude)
nextLoc = CLLocation(latitude: nextCoord.latitude, longitude: nextCoord.longitude)
}
distance += nextLoc.distance(from: curLoc)
distances[bus.busId] = distance
}
}
return distances
}
/*
This function is like the one above, except takes a startStopId as
a string and it uses the stops for measuring distances instead of the actual routes themselves
In other words, this one is worse in every way
*/
// func busDistancesFromStop(stopId startStopId: String) -> [String:Double] {
// var distances: [String:Double] = [:]
// let stops = self.stops.sort { $0.index < $1.index }
// for bus in self.busesOnRoute {
// // get to the current bus stop first
// if var currentIndex = (stops.map {$0.stopId }).indexOf(startStopId) {
// var currentStop: String = stops[currentIndex].stopId
// // travel along stops summing the distances
// var distance = 0.0
// var prevIndex = (currentIndex == 0) ? stops.count-1 : currentIndex-1
// let goalStopId = bus.nextStopId
// if (stops.map{$0.stopId}).contains({ (s) -> Bool in s == goalStopId }) {
// while(currentStop != goalStopId) { // stop once we've reached the bus's next stop
// print("CURRENT: \(currentStop) | GOAL \(goalStopId)")
// // Create CLLocation objs for use by distanceFromLocation
// let curStopCoord = stops[currentIndex].location
// let prevStopCoord = stops[prevIndex].location
// let curStopLoc = CLLocation(latitude: curStopCoord.latitude, longitude: curStopCoord.longitude)
// let prevStopLoc = CLLocation(latitude: prevStopCoord.latitude, longitude: prevStopCoord.longitude)
// // Calculate distance and add to total
// distance += curStopLoc.distanceFromLocation(prevStopLoc)
// // Get new indices and stops
// currentIndex = (currentIndex == 0) ? stops.count-1 : currentIndex-1
// prevIndex = (prevIndex == 0) ? stops.count-1 : prevIndex-1
// currentStop = stops[currentIndex].stopId
// }
// // Calculate distance from the last stop we looked at to the bus itself
// let curStopCoord = stops[currentIndex].location
// let curStopLoc = CLLocation(latitude: curStopCoord.latitude, longitude: curStopCoord.longitude)
// let busLoc = CLLocation(latitude: bus.location.latitude, longitude: bus.location.longitude)
// distance += curStopLoc.distanceFromLocation(busLoc)
// // Append to the return value
// distances[bus.busId] = distance
// }
//
// }
// }
// return distances
// }
}
| true
|
e18f4e854868c9ca9fa18c03d0f8d7eb908e2c66
|
Swift
|
EgorSobko/Products
|
/ProductsApp/ProductsApp/Modules/Main/Logic/MainViewPreheater.swift
|
UTF-8
| 945
| 2.6875
| 3
|
[] |
no_license
|
//
// MainViewPreheater.swift
// ProductsApp
//
// Created by Egor Sobko on 13.10.17.
// Copyright © 2017 Egor Sobko. All rights reserved.
//
import UIKit
import Nuke
protocol MainViewPrefetcherDataProvider {
subscript(index: Int) -> ProductCollectionCellModelInterface { get }
}
class MainViewPrefetcher: NSObject, UICollectionViewDataSourcePrefetching {
// MARK: - Private properties
private let dataProvider: MainViewPrefetcherDataProvider
private let preheater: Preheater
// MARK: - Init
init(dataProvider: MainViewPrefetcherDataProvider, preheater: Preheater) {
self.dataProvider = dataProvider
self.preheater = preheater
}
// MARK: - Methods
func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {
let requests = indexPaths.flatMap { dataProvider[$0.row].productImageURL.flatMap { Request(url: $0) } }
preheater.startPreheating(with: requests)
}
}
| true
|
17fa84b9664eea2f8d83d0f93ade56ef202f7218
|
Swift
|
GiorgioNatili/CryptoMessages
|
/CryptoMessages/authentication/routing/AuthenticationRouting.swift
|
UTF-8
| 937
| 2.53125
| 3
|
[
"Unlicense"
] |
permissive
|
//
// AuthenticationRouting.swift
// CryptoMessages
//
// Created by Giorgio Natili on 5/7/17.
// Copyright © 2017 Giorgio Natili. All rights reserved.
//
import Foundation
import UIKit
class AuthenticationRouter: AuthenticationRouting {
var window: UIWindow?
enum SegueIdentifiers: String {
case MesseagesList = "MesseagesList"
}
init() {
self.window = UIApplication.shared.delegate!.window!
}
func presentMessages() {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let navigationController = UINavigationController()
let view = mainStoryboard.instantiateViewController(withIdentifier: SegueIdentifiers.MesseagesList.rawValue) as! MessagesViewController
navigationController.pushViewController(view, animated: false)
window?.rootViewController = navigationController
}
}
| true
|
bf0b60ce8db5e098a4ded9d0231b4f9fccf0e166
|
Swift
|
MiguelDelgado22/miCV
|
/Globant5CV/Controller/Experience/cell/ExperienceTableViewCell.swift
|
UTF-8
| 939
| 2.734375
| 3
|
[] |
no_license
|
import UIKit
final class ExperienceTableViewCell: UITableViewCell {
@IBOutlet weak var lbName: UILabel?
@IBOutlet weak var lbDate: UILabel?
@IBOutlet weak var lbRole: UILabel?
@IBOutlet weak var lbDescription: UILabel?
@IBOutlet weak var img: UIImageView?
func updateUI(infoExperience: Experience) {
self.lbName?.text = infoExperience.name
self.lbDate?.text = infoExperience.date
self.lbRole?.text = infoExperience.role
self.lbDescription?.text = infoExperience.descripcion
InfoHelper().getDownloadImg(urlImage: infoExperience.image) { [weak self] (response) in
switch response{
case .success(let data):
DispatchQueue.main.async() { [weak self] in
self?.img?.image = UIImage(data: data)
}
break
default:
break
}
}
}
}
| true
|
c353d665ddb32b37e396838c92208955218d837d
|
Swift
|
benjamincarney/Accev
|
/Accev/Helpers/Utilities/BackendCaller.swift
|
UTF-8
| 8,589
| 3
| 3
|
[] |
no_license
|
//
// BackendCaller.swift
// Accev
//
// Created by Benjamin Carney on 3/5/20.
// Copyright © 2020 Accev. All rights reserved.
//
// A good place to throw any functions that will communicate with the backend
// ie creating pin, rating a pin, deleting a pin, etc
// swiftlint:disable all
import Firebase
import Foundation
import GoogleMaps
class BackendCaller {
let database = Firestore.firestore()
func addPinBackend(_ mapView: GMSMapView, _ coordinate: CLLocationCoordinate2D,
_ pinData: Dictionary<String, Any>) -> String {
var ref: DocumentReference? = nil
print(pinData)
ref = database.collection("pins").addDocument(data: [
"longitude": coordinate.longitude,
"latitude": coordinate.latitude,
"upvotes": pinData["upvotes"] ?? 0,
"downvotes": pinData["downvotes"] ?? 0,
"accessibleWheelchair": pinData["accessibleWheelchair"] ?? false,
"accessibleBraille": pinData["accessibleBraille"] ?? false,
"accessibleHearing": pinData["accessibleHearing"] ?? false,
"name": pinData["name"] ?? "",
"description": pinData["description"] ?? ""
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
return ref!.documentID
}
// Any other edits that might need to be made?
func editPinBackend() {
}
// Use this when a user casts an upvote in the pin details view
func upvotePin(_ documentID: String) {
let sfReference = database.collection("pins").document(documentID)
database.runTransaction({ (transaction, errorPointer) -> Any? in
let sfDocument: DocumentSnapshot
do {
try sfDocument = transaction.getDocument(sfReference)
} catch let fetchError as NSError {
errorPointer?.pointee = fetchError
return nil
}
guard let oldUpvote = sfDocument.data()?["upvotes"] as? Int else {
let error = NSError(
domain: "AppErrorDomain",
code: -1,
userInfo: [
NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)"
]
)
errorPointer?.pointee = error
return nil
}
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
transaction.updateData(["upvotes": oldUpvote + 1], forDocument: sfReference)
return nil
}) { (object, error) in
if let error = error {
print("Transaction failed: \(error)")
} else {
print("Transaction successfully committed!")
}
}
}
// Use this when a user casts a downvote in the pin details view
func downvotePin(_ documentID: String) {
let sfReference = database.collection("pins").document(documentID)
database.runTransaction({ (transaction, errorPointer) -> Any? in
let sfDocument: DocumentSnapshot
do {
try sfDocument = transaction.getDocument(sfReference)
} catch let fetchError as NSError {
errorPointer?.pointee = fetchError
return nil
}
guard let oldDownvote = sfDocument.data()?["downvotes"] as? Int else {
let error = NSError(
domain: "AppErrorDomain",
code: -1,
userInfo: [
NSLocalizedDescriptionKey: "Unable to retrieve population from snapshot \(sfDocument)"
]
)
errorPointer?.pointee = error
return nil
}
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
transaction.updateData(["downvotes": oldDownvote + 1], forDocument: sfReference)
return nil
}) { (object, error) in
if let error = error {
print("Transaction failed: \(error)")
} else {
print("Transaction successfully committed!")
}
}
}
// This is what our dictionary for pins looks like
// {
// id432343: {locationName: Krusty Krab, upvotes: 423, downvotes: 21, wheelchairRamp: true}
// id134854: {locationName: Chum Bucket, upvotes: 0, downvotes: 53, wheelchairRamp: false}
// }
func pullPinsBackend(completion: @escaping (Dictionary<String, Dictionary<String, Any>>) -> Void) {
var returnObject = Dictionary<String, Dictionary<String, Any>>()
database.collection("pins").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
returnObject[document.documentID] = document.data()
}
}
completion(returnObject)
}
}
func addFeedbackBackend(_ feedback: String) {
var ref: DocumentReference? = nil
ref = database.collection("feedback").addDocument(data: [
"feedback": feedback
]) { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with ID: \(ref!.documentID)")
}
}
}
/// Store initial profile information (i.e. # pins made, # upvotes/downvotes they've done
/// - Parameter email: The user's email
func addProfileInfo(email: String) {
database.collection("users").document(email).setData([
"numPinsAdded": 0,
"numUpvotesGiven": 0,
"numDownvotesGiven": 0
], completion: { err in
if let err = err {
print("Error adding document: \(err)")
} else {
print("Document added with key: \(email)")
}
})
}
/// Increment the current user's upvote count
/// - Parameter email: The user's email
func addUpvoteForUser(email: String) {
database.collection("users").document(email).updateData([
"numUpvotesGiven": Firebase.FieldValue.increment(Int64(1))
]) { err in
if let err = err {
print("Error incrementing upvote: \(err)")
} else {
print("Upvote incremented with key: \(email)")
}
}
}
/// Increment the current user's downvote count
/// - Parameter email: The user's email
func addDownvoteForUser(email: String) {
database.collection("users").document(email).updateData([
"numDownvotesGiven": Firebase.FieldValue.increment(Int64(1))
]) { err in
if let err = err {
print("Error incrementing downvote: \(err)")
} else {
print("Downvote incremented with key: \(email)")
}
}
}
/// Increment's the current user's pin added count
/// - Parameter email: The user's email
func addPinForUser(email: String) {
database.collection("users").document(email).updateData([
"numPinsAdded": Firebase.FieldValue.increment(Int64(1))
]) { err in
if let err = err {
print("Error incrementing # pins added: \(err)")
} else {
print("# pins incremented with key: \(email)")
}
}
}
/// Fetch the user's profile information (# pins made, # times they've upvoted/downvoted) from Firestore
/// - Parameter email: The user's email
func fetchProfileInfo(email: String, completion: @escaping ([String: Any]?) -> Void) {
database.collection("users").document(email).getDocument { (document, err) in
if let document = document, document.exists {
let userData = document.data()
print("Document data: \(String(describing: userData))")
completion(userData)
} else {
print("Document does not exist")
completion(nil)
}
}
}
}
// swiftlint:enable all
| true
|
ae6f786f63b82879ea361ab1031bf20d393771e9
|
Swift
|
BoshiLee/SocialTextField
|
/SocialTextField/NSRangeHelper.swift
|
UTF-8
| 2,678
| 2.921875
| 3
|
[] |
no_license
|
//
// NSRangeHelper.swift
// SocialLabel
//
// Created by Boshi Li on 2018/11/14.
// Copyright © 2018 Boshi Li. All rights reserved.
//
import CoreText
import Foundation
extension String {
func nsRange(from range: Range<String.Index>) -> NSRange {
return NSRange(range, in: self)
}
func ranges(of searchString: String, options mask: NSString.CompareOptions = [], locale: Locale? = nil) -> [Range<String.Index>] {
var ranges: [Range<String.Index>] = []
while let range = range(of: searchString, options: mask, range: (ranges.last?.upperBound ?? startIndex)..<endIndex, locale: locale) {
ranges.append(range)
}
return ranges
}
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex) else { return nil }
guard let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex) else { return nil }
guard let from = String.Index(from16, within: self) else { return nil }
guard let to = String.Index(to16, within: self) else { return nil }
return from ..< to
}
func nsRanges(of searchString: String, options mask: NSString.CompareOptions = [], locale: Locale? = nil) -> [NSRange] {
let ranges = self.ranges(of: searchString, options: mask, locale: locale)
return ranges.map { nsRange(from: $0) }
}
func subString(with nsRange: NSRange) -> String {
return String(self[nsRange.lowerBound..<nsRange.upperBound])
}
mutating func removeSubrange(_ bound: NSRange) {
guard let range = self.range(from: bound) else { return }
self.removeSubrange(range)
}
mutating func replaceSubrange(_ subrange: NSRange, withReplacementText text: String) {
guard let range = self.range(from: subrange) else { return }
self = self.replacingCharacters(in: range, with: text)
}
}
extension String {
func removeHTMLTags() -> String {
return self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
}
func int(of stringIndex: String.Index) -> Int {
return self.distance(from: self.startIndex, to: stringIndex)
}
func rangeOfEndIndex(from stratIndex: String.Index) -> NSRange {
return NSRange(location: self.int(of: startIndex), length: self.int(of: self.endIndex))
}
func isLastCharcter(is string: Character) -> Bool {
guard let lastString = self.last, lastString == string else { return false }
return true
}
}
| true
|
582be797cbdc7f8ed61110607cdb5d3078d84273
|
Swift
|
codepath-cita/Cita
|
/Cita/CitaButton.swift
|
UTF-8
| 2,032
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// CitaButton.swift
// Cita
//
// Created by Sara Hender on 12/5/16.
// Copyright © 2016 codepath. All rights reserved.
//
import UIKit
class CitaButton: UIButton {
func style(borderColor: UIColor, backgroundColor: UIColor) {
self.clipsToBounds = true
self.layer.cornerRadius = 7
self.layer.borderWidth = 1
self.layer.shadowRadius = 1
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowColor = borderColor.cgColor
self.clipsToBounds = false
self.layer.masksToBounds = false
self.backgroundColor = backgroundColor
self.layer.borderColor = borderColor.cgColor
}
func animate(completion: @escaping () -> Void) {
self.layer.shadowOpacity = 1
UIView.animate(withDuration: 0.1, animations: { [weak self] in
self?.frame = CGRect(x: (self?.frame.origin.x)! + 2, y: (self?.frame.origin.y)! + 2, width: (self?.frame.width)! - 5, height: (self?.frame.height)! - 5)
}, completion: { success in
self.layer.shadowOpacity = 0
self.frame = CGRect(x: (self.frame.origin.x) - 2, y: (self.frame.origin.y) - 2, width: (self.frame.width) + 5, height: (self.frame.height) + 5)
// run closure here
completion()
UIView.animate(withDuration: 0.1, animations: { [weak self] in
self?.layer.shadowOpacity = 0
}, completion: { success in
self.layer.shadowOpacity = 0
})
})
}
override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
print(#function)
}
override func pressesChanged(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
print(#function)
}
override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
print(#function)
}
}
| true
|
4217c3aba7a495de13f6948163a89323647b03a6
|
Swift
|
zainanjum100/PacketTracker
|
/PacketTracker/UIViews/ContentView.swift
|
UTF-8
| 2,842
| 2.53125
| 3
|
[] |
no_license
|
//
// ContentView.swift
// SwiftUIDemo
//
// Created by Zeeshan Dar on 4/7/20.
// Copyright © 2020 Zeeshan Dar. All rights reserved.
//
import SwiftUI
import Combine
import Foundation
struct ContentView: View {
@State var showDetail = false
@State var showingAlert = false
@State var isShowingAlert = false
@State var inputNumber = ""
@State var inputCarrier = ""
@State var title = ""
@EnvironmentObject var apiService: ApiService
@State var selectedOrder: Order!
init(){
UINavigationBar.appearance().barTintColor = #colorLiteral(red: 0.981870234, green: 0.7615160346, blue: 0.1441443861, alpha: 1)
UINavigationBar.appearance().tintColor = .red
UINavigationBar.appearance().titleTextAttributes = [
.font : UIFont(name: "D-DIN-Bold", size: 24)!,
.foregroundColor: UIColor.red]
}
var body: some View {
return NavigationView {
VStack{
if apiService.showLoading{
ActivityIndicator(isAnimating: apiService.showLoading) { (indicator: UIActivityIndicatorView) in
indicator.color = .red
indicator.hidesWhenStopped = false
}
}else{
if apiService.orders.count == 0{
VStack{
Text("No data found")
Button(action: {
self.apiService.loadData()
}) {
Text("Reload")
.foregroundColor(Color.blue)
}
}
}else{
List(apiService.orders, id: \.id) { order in
NavigationLink(destination: DetailView(order: order)) {
HomeCell(order: order)
}
}.listRowBackground(Color.init(#colorLiteral(red: 0.862745098, green: 0.862745098, blue: 0.862745098, alpha: 1)))
}
}
}
.navigationBarTitle("HOME", displayMode: .inline).foregroundColor(.red)
.navigationBarItems(trailing:
NavigationLink(destination: PostRequestView().environmentObject(self.apiService), label: {
Image("ico_add")
.accentColor(.red)
.aspectRatio(contentMode: .fit)
})
)
}.navigationViewStyle(StackNavigationViewStyle())
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
c93227459cce029895bce76cddf5c9f9289163ea
|
Swift
|
turb0charged/NISTValidator
|
/NISTValidator/Extensions/StringProtocolExtension.swift
|
UTF-8
| 336
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// StringProtocolExtension.swift
// NISTValidator
//
// Created by Hector Castillo on 3/8/19.
// Copyright © 2019 Hector Castillo. All rights reserved.
//
import Foundation
extension StringProtocol where Index == String.Index {
var validNIST : Bool {
return self.range(of: "[ -~]{8,64}", options: .regularExpression) != nil
}
}
| true
|
b94c52a68aff4f2d6b90018f9b60733de40bf8ef
|
Swift
|
Wsewlad/SimpleListApp
|
/SimpleListApp/SimpleListApp/Utilities/API/Errors/ServerError.swift
|
UTF-8
| 1,128
| 2.9375
| 3
|
[] |
no_license
|
//
// ServerError.swift
// SimpleListApp
//
// Created by Vladyslav Fil on 07.08.2021.
//
import Foundation
struct ServerError: LocalizedError {
private let errorsDescription: String
init?(data: Data) {
guard let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
return nil
}
errorsDescription = Self.mapJsonToErrorString(json)
}
var errorDescription: String? {
return errorsDescription
}
private static func mapJsonToErrorString(_ json: [String: Any]) -> String {
json.compactMap { tuple in
if let jsonValue = tuple.value as? [String: Any] {
return mapJsonToErrorString(jsonValue)
} else if let string = tuple.value as? String {
return tuple.key + " - " + string
} else if let array = tuple.value as? [String] {
return tuple.key + " - " + array.joined(separator: ",")
}
return nil
}
.joined(separator: "\n")
}
}
| true
|
61f9af38527273ea1ea2045d3b6333f4ea2eb49e
|
Swift
|
swiftcodeshow/CheckCameraPermission
|
/CheckCameraPermission/ContentView.swift
|
UTF-8
| 1,580
| 3.1875
| 3
|
[] |
no_license
|
//
// ContentView.swift
// CheckCameraPermission
//
// Created by 米国梁 on 2021/5/1.
//
import SwiftUI
import AVFoundation
struct ContentView: View {
@State var title = ""
@State var message = ""
var body: some View {
VStack {
if title != "" {
Text(title)
Text(message)
}
Button("Check camera permission") {
let status = AVCaptureDevice.authorizationStatus(for: .video)
switch status {
case .authorized:
title = "Authorized"
message = "You can use camera"
case .notDetermined:
AVCaptureDevice.requestAccess(for: .video) { granted in
if granted {
title = "Authorized"
message = "User allows app to access camera"
}
}
case .denied:
title = "Denied"
message = "User rejected app to access camera"
case .restricted:
title = "Restricted"
message = "User is limited by Parent settings to access camera"
@unknown default:
fatalError("Unknown status: \(status.rawValue)")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
f55050d37458953891ceac725142597a4bdeab32
|
Swift
|
sungyoungPark/Programmers_Solution
|
/Programmers_Solution/main06.swift
|
UTF-8
| 1,746
| 3.09375
| 3
|
[] |
no_license
|
import Foundation
var result1 : [Int] = []
var result2 : [Int] = []
func solution(_ nodeinfo:[[Int]]) -> [[Int]] {
var answer = [[Int]]()
var graph = nodeinfo
for i in 0...graph.count-1{
graph[i].append(i+1)
//print(graph[i])
}
VLR(graph)
LRV(graph)
answer.append(result2)
answer.append(result1)
return answer
}
func LRV(_ graph :[[Int]]){ //후위
if graph.count <= 1 {
if graph.count == 1{
result1.append(graph[0][2])
}
}
else{
let sort = graph.sorted(by: { $0[1] > $1[1] })
let rootNode = sort[0]
var L_Node = [[Int]]()
var R_Node = [[Int]]()
for i in 1...graph.count-1{
//print(sort[i][0])
if sort[i][0] < rootNode[0]{
L_Node.append(sort[i])
}
else{
R_Node.append(sort[i])
}
}
LRV(L_Node)
LRV(R_Node)
result1.append(rootNode[2])
}
}
func VLR(_ graph :[[Int]]){ //전위
if graph.count <= 1 {
if graph.count == 1{
result2.append(graph[0][2])
}
}
else{
let sort = graph.sorted(by: { $0[1] > $1[1] })
let rootNode = sort[0]
var L_Node = [[Int]]()
var R_Node = [[Int]]()
for i in 1...graph.count-1{
//print(sort[i][0])
if sort[i][0] < rootNode[0]{
L_Node.append(sort[i])
}
else{
R_Node.append(sort[i])
}
}
result2.append(rootNode[2])
VLR(L_Node)
VLR(R_Node)
}
}
print(solution([[5, 3], [11, 5], [13, 3], [3, 5], [6, 1], [1, 3], [8, 6], [7, 2], [2, 2]]))
| true
|
cf4dc3317ad69a2b8c98efd8d9e38fd016298cac
|
Swift
|
dicass/iOSandSwift
|
/10.Collection/Tuple.swift
|
UTF-8
| 1,212
| 4.65625
| 5
|
[] |
no_license
|
//
// 튜플(Tuple)
//
// 튜플 선언. 타입 생략 가능
var one = (1, "one", "일")
// 투플 원소에 접근해서 값 얻기
print("one.2 :", one.2)
// 튜플 값 수정
one.2 = "하나"
print("one.2 = 하나", one) // (1, "one", "하나")
// 튜플 타입 선언, 튜플 원소 접근 이름
let two: (Int, String, String) = (2, "two", "둘")
print("two.0:", two.0, "two.1:", two.1)
// 튜플 원소에 이름 설정
let three: (num: Int, eng: String, kor: String) = (num : 3, eng : "three", kor : "삼")
print("three.0 :", three.0, "three.1 :", three.1)
print("three.num : \(three.num), three.kor : \(three.kor)")
// 원소 접근 에러
//print("one.3 :", one.3, "three.esp :", three.esp)
// 튜플 원소 대입
let (two1, two2, two3) = two
print("(two1, two2, two3) = two :", two2)
// 튜플 원소 중 일부만 대입
let (_, _, korOne) = one
print("(_, _, korOne) = one :", korOne)
// 투플 간 비교
print("(1,1) == (1,1) : ",(1, "1") == (1, "1"))
print("(1, one) < (2, two) : ", (1, "one") < (2, "two"))
print("(1, one) < (1, first)", (1, "one") < (1, "first"))
// 새로운 튜플에 값 대입 - 복사된다. 밸류타입
var sam = three
sam.eng = "Third"
sam.kor = "세번째"
| true
|
e1917d8e3ad1355293519f53331b6f64315ab6bc
|
Swift
|
okdolly-001/Flourish_Money2020
|
/Flourish/LoanDetailViewController/LoanDetailViewController.swift
|
UTF-8
| 6,864
| 2.640625
| 3
|
[] |
no_license
|
//
// LoanDetailViewController.swift
// Flourish
//
// Created by Jason Du on 10/21/17.
// Copyright © 2017 Jason Du. All rights reserved.
//
import Foundation
import UIKit
class LoanDetailViewController: UIViewController {
var data: Loan?
@IBOutlet weak var tableView: UITableView!
var paymentIndex = 0
var offset = 0
override func viewDidLoad() {
let fromAnimation = AnimationType.from(direction: .right, offset: 30.0)
let zoomAnimation = AnimationType.zoom(scale: 0.2)
tableView.animateViews(animations: [fromAnimation, zoomAnimation], duration: 0.5)
if let data = data {
var index = 0
for slot in data.slots {
if isPayment(slot: slot) {
paymentIndex = index
if isComplete(slot: slot) {
offset = 3
} else {
offset = 0
}
}
if slot.netAmount > 0 {
paymentIndex = index
if let status = slot.loanStatus {
if status == "COMPLETED" {
offset = 3
} else {
offset = 0
}
}
}
index += 1
}
self.title = data.purpose
}
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.navigationBar.setBackgroundImage(GradientNavBar.create(size: self.navigationController!.navigationBar.bounds), for: .default)
self.navigationController?.navigationBar.isTranslucent = false
}
func isComplete(slot: Slot?) -> Bool {
if let slot = slot {
if let status = slot.loanStatus {
if status == "COMPLETED" {
return true
} else if let _ = slot.settlementHash {
return true
}
}
}
return false
}
func isPayment(slot: Slot?) -> Bool {
if let slot = slot {
if slot.netAmount > 0 {
return true
}
}
return false
}
}
extension LoanDetailViewController: UITableViewDelegate, UITableViewDataSource {
// 8 rows 0 - 7
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowCount = 0
if let data = data {
for slot in data.slots {
if !isPayment(slot: slot) {
rowCount += 1
} else if isComplete(slot: slot) {
rowCount += 4
} else {
rowCount += 1
}
}
}
print("ROW COUNT: \(rowCount)")
return rowCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let data = data else { return UITableViewCell() }
if indexPath.row < paymentIndex {
if !isComplete(slot: data.slots[indexPath.row]) {
let cell = tableView.dequeueReusableCell(withIdentifier: "LoanDetailsUnscheduledCell") as! LoanDetailsUnscheduledCell
cell.slot = data.slots[indexPath.row]
cell.weekLabel.text = "Week \(indexPath.row + 1)"
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "LoanDetailsHeaderCell") as! LoanDetailsHeaderCell
cell.slot = data.slots[indexPath.row]
return cell
}
} else if indexPath.row == paymentIndex {
if isComplete(slot: data.slots[indexPath.row]) {
let cell = tableView.dequeueReusableCell(withIdentifier: "LoanDetailsHeaderCell") as! LoanDetailsHeaderCell
cell.slot = data.slots[indexPath.row]
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "LoanDetailsUnscheduledCell") as! LoanDetailsUnscheduledCell
cell.slot = data.slots[indexPath.row]
cell.weekLabel.text = "Week \(indexPath.row + 1)"
return cell
}
} else if indexPath.row <= paymentIndex + offset {
print("indexPath.row < paymentIndex + offset \(indexPath.row)")
if isComplete(slot: data.slots[paymentIndex]) {
let cell = tableView.dequeueReusableCell(withIdentifier: "LoanDetailsCell") as! LoanDetailsCell
cell.slot = data.slots[paymentIndex]
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "LoanDetailsUnscheduledCell") as! LoanDetailsUnscheduledCell
cell.slot = data.slots[paymentIndex]
cell.weekLabel.text = "Week \(indexPath.row + 1)"
return cell
}
} else {
if !isComplete(slot: data.slots[indexPath.row - offset]) {
let cell = tableView.dequeueReusableCell(withIdentifier: "LoanDetailsUnscheduledCell") as! LoanDetailsUnscheduledCell
cell.slot = data.slots[indexPath.row - offset]
cell.weekLabel.text = "Week \(indexPath.row - offset)"
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "LoanDetailsHeaderCell") as! LoanDetailsHeaderCell
cell.slot = data.slots[indexPath.row - offset]
print("\(indexPath.row) - \(offset)")
return cell
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let data = data else { return 0.0 }
if indexPath.row < paymentIndex {
if !isComplete(slot: data.slots[indexPath.row]) {
return 120.0
} else {
return 190.0
}
} else if indexPath.row < paymentIndex + offset && indexPath.row >= paymentIndex {
if indexPath.row == paymentIndex {
if isComplete(slot: data.slots[indexPath.row]) {
return 190.0
} else {
return 120.0
}
} else {
if isComplete(slot: data.slots[paymentIndex]) {
return 150.0
} else {
return 120.0
}
}
} else {
if !isComplete(slot: data.slots[indexPath.row - offset]) {
return 120.0
} else {
return 190.0
}
}
}
}
| true
|
511e5aba12f674e689cb0a8252d79b0d0b8fb021
|
Swift
|
berikkadanTeam/diplomAiOS
|
/BookMe/Views/RestaurantTableViewCell.swift
|
UTF-8
| 838
| 2.734375
| 3
|
[] |
no_license
|
//
// RestaurantTableViewCell.swift
// BookMe
//
// Created by Dmitriy Pak on 2/3/19.
// Copyright © 2019 Alikhan Ilyassov. All rights reserved.
//
import UIKit
import Kingfisher
class RestaurantTableViewCell: UITableViewCell {
@IBOutlet weak var restaurantImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
var restaurant: Restaurant? {
didSet {
if let res = restaurant {
restaurantImage.kf.setImage(with: URL(string: res.fileName.toUrl(.restaurantAvatar)))
nameLabel.text = res.name
addressLabel.text = res.addres
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
restaurantImage.layer.cornerRadius = restaurantImage.frame.size.height / 2
}
}
| true
|
bf37dc9139000dd6a6f0e4152ea091ef81b9aedc
|
Swift
|
nicoWang/store
|
/Store/Store/Core/Entity/ItemDetail.swift
|
UTF-8
| 780
| 3
| 3
|
[] |
no_license
|
//
// ItemDetail.swift
// Store
//
// Created by Nicolas Wang on 07/10/2020.
//
import Foundation
// MARK: - ItemDetail
struct ItemDetail: Codable {
var id: Int?
var imageURL: String?
var brand, title, tags: String?
var favoriteCount: Double?
var itemDetailDescription: String?
var price: Price?
var expiration, redemptionsCap: String?
var favoriteCountFormatted: String {
return favoriteCount?.kmFormatted ?? "0"
}
enum CodingKeys: String, CodingKey {
case id
case imageURL = "imageUrl"
case brand, title, tags, favoriteCount
case itemDetailDescription = "description"
case price, expiration, redemptionsCap
}
}
// MARK: - Price
struct Price: Codable {
var old, new: String?
}
| true
|
42e079fb28243d6a040f0fa09630ce7f429f6058
|
Swift
|
MoacirParticular/ios-financial-goal
|
/financialGoal/financialGoal/Sources/Model/Provider/MonthlyAndYearly/RequestMonthly.swift
|
UTF-8
| 1,167
| 2.71875
| 3
|
[] |
no_license
|
//
// RequestMonthly.swift
// financialGoal
//
// Created by Jonattan Moises Sousa on 01/07/21.
//
import Foundation
typealias returnMonthlyCompletion = (Result<ReturnMonthlyCalc, Error>) -> Void
protocol RequestMonthlyCalcProtocol {
func calc(_ dataCalc: StructApplicationCalc, completionHandler: @escaping returnMonthlyCompletion)
}
final class RequestMonthlyCalc: RequestMonthlyCalcProtocol {
func calc(_ dataCalc: StructApplicationCalc, completionHandler: @escaping returnMonthlyCompletion) {
let bodyTask = RequestBuilderMonthly().monthy(dataCalc: dataCalc)
let session = URLSession.shared
let task = session.dataTask(with: bodyTask) { (data, response, error) in
if let error = error {
completionHandler(.failure(error))
} else if let data = data {
do {
let dataCalc = try JSONDecoder().decode(ReturnMonthlyCalc.self, from: data)
completionHandler(.success(dataCalc))
} catch let error as NSError {
completionHandler(.failure(error))
}
}
}
task.resume()
}
}
| true
|
d4762b2e5bc7183f57eabbd66bef33fb6d06dbaa
|
Swift
|
xchenLee/AQI
|
/AQIDemo/TransitioningMedia.swift
|
UTF-8
| 2,556
| 2.75
| 3
|
[] |
no_license
|
//
// TransitioningMedia.swift
// AQIDemo
//
// Created by danlan on 2017/9/28.
// Copyright © 2017年 lxc. All rights reserved.
//
import UIKit
class TransitioningMedia: NSObject, UIViewControllerTransitioningDelegate {
//实际动画效果类
var animator = AnimatorMedia()
var interact = SwipeVerticalTransition()
//如果presented viewcontroller的 transitioningDelegate 设置了
//1.UIKit 调用这个方法去拿到custom animator
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
//用来标示是开启还是消失
self.animator.presenting = true
//self.interact.prepareGesture(presented)
return self.animator
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
//用来标示是开启还是消失
animator.presenting = false
return animator
}
//2.如果custom animator不为空
// UIKit 会调用这个方法,看是否interactive animator是否可用,nil的话,就执行动画,不涉及用户交互
func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
interact.presenting = true
return nil
//不为空
//2.1 UIKit 调用 animator 的 transitionDuration:方法去获取duration
//2.2 UIKit 调用适当的方法来开始动画
//2.2.1 非可交互的动画 调用animator的animateTransition方法
//2.2.3 可交互的动画 调用animator的startInteractiveTransition方法
//2.3 UIKit 等待animator调用 context transitioning object的 completeTransition方法
//2.3.1 自定义的animator在动画结束的时候,调用这个方法
// 调用这个方法来结束 transition,并且可以让UIKit知道它可以调用
// presentViewController:animated:completion: 的completionHandler
// 并且可以调用animator的 animationEnded:方法
}
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
interact.presenting = false
return interact
}
}
| true
|
f26e9e5bae7b92cd7da5432c2263b89479ac54ee
|
Swift
|
chester39/CCWeibo
|
/CCWeiboSwiftApp/CCWeiboSwiftApp/Classes/Home/Popover/PopoverPresentationController.swift
|
UTF-8
| 1,363
| 2.546875
| 3
|
[] |
no_license
|
//
// PopoverPresentationController.swift
// CCWeiboSwiftApp
// Chen Chen @ November 18th, 2016
//
import UIKit
class PopoverPresentationController: UIPresentationController {
/// 弹出框尺寸
var presentFrame = CGRect.zero
/// 蒙版按钮
private lazy var coverButton: UIButton = {
let button = UIButton(type: .system)
button.frame = kScreenFrame
button.backgroundColor = kClearColor
return button
}()
// MARK: - 初始化方法
/**
自定义初始化方法
*/
override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) {
super.init(presentedViewController: presentedViewController, presenting: presentingViewController)
}
/**
容器视图将要布局子视图方法
*/
override func containerViewWillLayoutSubviews() {
presentedView?.frame = presentFrame
containerView?.insertSubview(coverButton, at: 0)
coverButton.addTarget(self, action: #selector(coverButtonDidClick), for: .touchUpInside)
}
// MARK: - 按钮方法
/**
蒙版按钮点击方法
*/
@objc private func coverButtonDidClick() {
presentedViewController.dismiss(animated: true, completion: nil)
}
}
| true
|
5f9e4256fe76044ef7c76a50bcd22bce3ca407f8
|
Swift
|
carlosmesac/Books
|
/Books/Model/MisLibrosModel.swift
|
UTF-8
| 1,037
| 2.796875
| 3
|
[] |
no_license
|
//
// MisLibrosModel.swift
// Books
//
// Created by alumno on 23/12/2019.
// Copyright © 2019 Carlos. All rights reserved.
//
import Foundation
import FirebaseDatabase
import FirebaseStorage
import FirebaseAuth
class MisLibrosModel {
var bookItemArrayList: [BookItem] = []
func fillArray(completion: @escaping (Bool, [BookItem]) -> Void){
let currentUser = Auth.auth().currentUser?.uid
let ref = Database.database().reference().child("booksUser").child(currentUser!)
ref.observe(.value, with: { (snapshot) in
var bookItemArrayList1 : [BookItem] = []
for child in snapshot.children{
if let snapshot = child as? DataSnapshot,
let book = BookItem(snapshot: snapshot){
bookItemArrayList1.append(book)
}
}
self.bookItemArrayList = bookItemArrayList1
completion(false,self.bookItemArrayList)
})
}
}
| true
|
27741cc1ef2eaee6b53db40618b75f748bbb9d9f
|
Swift
|
Tszhim/iOSAppDevelopment
|
/PlannerApp/PlannerApp/FilteredGroupViewController.swift
|
UTF-8
| 3,508
| 2.859375
| 3
|
[] |
no_license
|
//
// FilteredGroupViewController.swift
// PlannerApp
//
// Created by user198300 on 6/20/21.
//
import UIKit
class FilteredGroupViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
// Setting up values of FilteredGroupViewController.
@IBOutlet var tableView: UITableView!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
private var itemCells = [PlannerItem]()
// Setting up view.
override func viewDidLoad()
{
super.viewDidLoad()
let nib = UINib(nibName: "itemCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "itemCell")
populateTableItems()
tableView.delegate = self
tableView.dataSource = self
colorConfigs()
}
// Checks if a date is past due.
func pastDue(date: Date) -> (Bool)
{
let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)!
if(date < yesterday)
{
return true
}
else
{
return false
}
}
// Determining color of cell based on proximity to deadline.
func cellColor(date: Date) -> UIColor
{
let today = Date()
let nextDay = Calendar.current.date(byAdding: .day, value: 1, to: today)!
if (Calendar.current.isDate(today, inSameDayAs: date))
{
return UIColor(rgb: 0xFF577F)
}
else if (Calendar.current.isDate(nextDay, inSameDayAs: date))
{
return UIColor(rgb: 0xFF884B)
}
else
{
return UIColor(rgb: 0xFFC764)
}
}
// Configuring color of UI componenets.
func colorConfigs()
{
tableView.backgroundColor = UIColor(rgb: 0x51C2D5)
navigationController?.navigationBar.barTintColor = UIColor(rgb: 0x51C2D5)
}
// Returns number of cells.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemCells.count
}
// Returns desired cell height.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cellHeight = CGFloat(70.0)
return cellHeight
}
// Setting up cells.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let item = itemCells[indexPath.row]
let itemCell = tableView.dequeueReusableCell(withIdentifier: "itemCell", for: indexPath) as! itemCell
itemCell.titleLabel.text = item.title
itemCell.categoryLabel.text = item.category
let date = item.dueDate!
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
itemCell.dateLabel.text = dateFormatter.string(from: date)
itemCell.contentView.backgroundColor = cellColor(date: item.dueDate!)
return itemCell
}
// Populates backing array of items.
func populateTableItems()
{
do
{
itemCells = try context.fetch(PlannerItem.fetchRequest())
itemCells = itemCells.filter {
cell in return cell.category == title && !(pastDue(date: cell.dueDate!))
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
catch
{
}
}
}
| true
|
97620953b8ccd0aef55bc05278dabcee0a342a35
|
Swift
|
abrahamrohde/class-schedule
|
/ClassSchedule/FirstViewController.swift
|
UTF-8
| 11,361
| 2.625
| 3
|
[] |
no_license
|
//
// FirstViewController.swift
// ClassSchedule
//
// Created by Abraham Rohde on 10/27/15.
// Copyright © 2015 Abraham Rohde. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
@IBOutlet weak var collectionView: UICollectionView!
var defaultSize : CGFloat = 18
var focusedSize : CGFloat = 40
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
collectionView.dataSource = self
collectionView.delegate = self
}
override func viewWillAppear(animated: Bool) {
self.collectionView.reloadData()
print("in viewWillAppear")
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("ClassCell", forIndexPath: indexPath) as? ClassCell
{
if(indexPath.section == 0)
{
Singleton.configurePrereq(Singleton.classes[indexPath.row], cell: cell, cellIndex: 0, indexPathRow: indexPath.row)
}
else if(indexPath.section == 1)
{
Singleton.configurePrereq(Singleton.classes[indexPath.row + 5], cell: cell, cellIndex: 5, indexPathRow: indexPath.row)
//var oClass = Singleton.classes[indexPath.row + 5]
//cell.configureCell(oClass)
//cell.index = indexPath.row + 5
//print(indexPath.row + 5)
/*
var index = -1
if (oClass.prereq.characters.count > 0)
{
oClass.display()
index = Singleton.checkClass(oClass.prereq)
}
if(index == -1)
{
//no prereq, or prereq was taken
cell.configureCell(oClass)
cell.index = indexPath.row + 5
}
else
{
//There is a prereq for this class so we need to move this on to another semester
if((5 - index) <= indexPath.row)
{
Singleton.shiftRight(oClass)
oClass = Singleton.classes[indexPath.row + 5]
}
cell.configureCell(oClass)
cell.index = indexPath.row
}
*/
}
else if(indexPath.section == 2)
{
Singleton.configurePrereq(Singleton.classes[indexPath.row + 10], cell: cell, cellIndex: 10, indexPathRow: indexPath.row)
/*
let oClass = Singleton.classes[indexPath.row + 10]
cell.configureCell(oClass)
cell.index = indexPath.row + 10
//print(Singleton.classes.indexOf(oClass))
print(indexPath.row + 10)
*/
}
else if(indexPath.section == 3)
{
Singleton.configurePrereq(Singleton.classes[indexPath.row + 15], cell: cell, cellIndex: 15, indexPathRow: indexPath.row)
/*
let oClass = Singleton.classes[indexPath.row + 15]
cell.configureCell(oClass)
cell.index = indexPath.row + 15
print(indexPath.row + 15)
*/
}
else if(indexPath.section == 4)
{
Singleton.configurePrereq(Singleton.classes[indexPath.row + 21], cell: cell, cellIndex: 21, indexPathRow: indexPath.row)
/*
let oClass = Singleton.classes[indexPath.row + 21]
cell.configureCell(oClass)
cell.index = indexPath.row + 21
print(indexPath.row + 21
*/
}
else if(indexPath.section == 5)
{
Singleton.configurePrereq(Singleton.classes[indexPath.row + 27], cell: cell, cellIndex: 27, indexPathRow: indexPath.row)
/*
let oClass = Singleton.classes[indexPath.row + 27]
cell.configureCell(oClass)
cell.index = indexPath.row + 27
print(indexPath.row + 27)
*/
}
else if(indexPath.section == 6)
{
Singleton.configurePrereq(Singleton.classes[indexPath.row + 33], cell: cell, cellIndex: 33, indexPathRow: indexPath.row)
/*
let oClass = Singleton.classes[indexPath.row + 33]
cell.configureCell(oClass)
cell.index = indexPath.row + 33
print(indexPath.row + 33)
*/
}
else if(indexPath.section == 7)
{
Singleton.configurePrereq(Singleton.classes[indexPath.row + 39], cell: cell, cellIndex: 39, indexPathRow: indexPath.row)
/*
let oClass = Singleton.classes[indexPath.row + 39]
cell.configureCell(oClass)
cell.index = indexPath.row + 39
print(indexPath.row + 39)
*/
}
if cell.gestureRecognizers?.count == nil
{
let tap = UITapGestureRecognizer(target: self, action: "tapped:")
tap.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)]
cell.addGestureRecognizer(tap)
}
return cell
}
else
{
return ClassCell()
}
}
func tapped(gesture: UIGestureRecognizer)
{
if let cell = gesture.view as? ClassCell
{
if let secondView = self.storyboard?.instantiateViewControllerWithIdentifier("secondViewController") as? SecondViewController
{
secondView.oClass = cell.oClass
secondView.index = cell.index
self.presentViewController(secondView, animated: true, completion: {() -> Void in
//self.collectionView.reloadData()
})
}
//self.navigationController?.pushViewController(secondView, animated: true)
//secondView.performSegueWithIdentifier("secondViewController", sender: self)
//self.presentViewController(SVC, animated: true, completion: {() -> Void in
//})
//self.performSegueWithIdentifier("secondViewController", sender: "SENDER")
}
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return 8
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
//return Singleton.classes.count
if(section == 0)
{
if(Singleton.classes.count >= 5)
{
return 5
}
else
{
return Singleton.classes.count
}
}
else if(section == 1)
{
if(Singleton.classes.count >= 10)
{
return 5
}
else if(Singleton.classes.count < 10 && Singleton.classes.count >= 5)
{
return Singleton.classes.count - 5
}
else
{
return 0
}
}
else if(section == 2)
{
if(Singleton.classes.count >= 15)
{
return 5
}
else if(Singleton.classes.count < 15 && Singleton.classes.count >= 10)
{
return Singleton.classes.count - 10
}
else
{
return 0
}
}
else if(section == 3)
{
if(Singleton.classes.count >= 21)
{
return 6
}
else if(Singleton.classes.count < 21 && Singleton.classes.count >= 15)
{
return Singleton.classes.count - 15
}
else
{
return 0
}
}
else if(section == 4)
{
if(Singleton.classes.count >= 27)
{
return 6
}
else if(Singleton.classes.count < 27 && Singleton.classes.count >= 21)
{
return Singleton.classes.count - 21
}
else
{
return 0
}
}
else if(section == 5)
{
if(Singleton.classes.count >= 33)
{
return 6
}
else if(Singleton.classes.count < 33 && Singleton.classes.count >= 27)
{
return Singleton.classes.count - 27
}
else
{
return 0
}
}
else if(section == 6)
{
if(Singleton.classes.count >= 39)
{
return 6
}
else if(Singleton.classes.count < 39 && Singleton.classes.count >= 33)
{
return Singleton.classes.count - 33
}
else
{
return 0
}
}
else if(section == 7)
{
if(Singleton.classes.count >= 44)
{
return 5
}
else if(Singleton.classes.count < 44 && Singleton.classes.count >= 39)
{
return Singleton.classes.count - 39
}
else
{
return 0
}
}
return 0
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
return CGSizeMake(336, 285)
}
override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator)
{
if let prev = context.previouslyFocusedView as? ClassCell
{
UIView.animateWithDuration(0.1, animations: {() -> Void in
prev.classTitle.font = UIFont(name: prev.classTitle.font.fontName, size: self.defaultSize)
})
}
if let next = context.nextFocusedView as? ClassCell
{
UIView.animateWithDuration(0.1, animations: {() -> Void in
next.classTitle.font = UIFont(name: next.classTitle.font.fontName, size: self.focusedSize)
})
}
}
}
| true
|
fcba7467f5311459528665ca9a1b3f2f2ff08205
|
Swift
|
yanglhan/SwiftFFmpeg
|
/Sources/SwiftFFmpeg/AVFilter.swift
|
UTF-8
| 23,913
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// AVFilter.swift
// SwiftFFmpeg
//
// Created by sunlubo on 2018/7/18.
//
#if swift(>=4.2)
import CFFmpeg
// MARK: - AVFilterPad
public struct AVFilterPad {
let cPadsPtr: OpaquePointer
let index: Int32
init(cPadsPtr: OpaquePointer, index: Int32) {
self.cPadsPtr = cPadsPtr
self.index = index
}
/// The name of the filter pad.
public var name: String {
String(cString: avfilter_pad_get_name(cPadsPtr, index))
}
/// The media type of the filter pad.
public var mediaType: AVMediaType {
avfilter_pad_get_type(cPadsPtr, index)
}
}
extension AVFilterPad: CustomStringConvertible {
public var description: String {
"\(name) - \(mediaType))"
}
}
// MARK: - AVFilter
typealias CAVFilter = CFFmpeg.AVFilter
public struct AVFilter {
let cFilterPtr: UnsafePointer<CAVFilter>
var cFilter: CAVFilter { cFilterPtr.pointee }
init(cFilterPtr: UnsafePointer<CAVFilter>) {
self.cFilterPtr = cFilterPtr
}
/// Get a filter definition matching the given name.
///
/// - Parameter name: the filter name to find
/// - Returns: the filter definition, or `nil` if none found
public init?(name: String) {
guard let filterPtr = avfilter_get_by_name(name) else {
return nil
}
self.cFilterPtr = filterPtr
}
/// The name of the filter.
public var name: String {
String(cString: cFilter.name)
}
/// The inputs of the filter.
///
/// `nil` if there are no (static) inputs.
/// Instances of filters with `AVFilter.Flag.dynamicInputs` set may have more inputs
/// than present in this list.
public var inputs: [AVFilterPad]? {
guard let start = cFilter.inputs else {
return nil
}
let count = avfilter_pad_count(cFilter.inputs)
let list = (0..<count).map({ AVFilterPad(cPadsPtr: start, index: $0) })
return list
}
/// The outputs of the filter.
///
/// `nil` if there are no (static) outputs.
/// Instances of filters with `AVFilter.Flag.dynamicOutputs` set may have more outputs
/// than present in this list.
public var outputs: [AVFilterPad]? {
guard let start = cFilter.outputs else {
return nil
}
let count = avfilter_pad_count(cFilter.outputs)
let list = (0..<count).map({ AVFilterPad(cPadsPtr: start, index: $0) })
return list
}
/// The flags of the filter.
public var flags: Flag {
Flag(rawValue: cFilter.flags)
}
/// Get all registered filters.
public static var supportedFilters: [AVFilter] {
var list = [AVFilter]()
var state: UnsafeMutableRawPointer?
while let filter = av_filter_iterate(&state) {
list.append(AVFilter(cFilterPtr: filter))
}
return list
}
}
extension AVFilter: CustomStringConvertible {
public var description: String {
"\(name): \(String(cString: cFilter.description) ?? "")"
}
}
// MARK: - AVFilter.Flag
extension AVFilter {
public struct Flag: OptionSet {
/// The number of the filter inputs is not determined just by `AVFilter.inputs`.
/// The filter might add additional inputs during initialization depending on the
/// options supplied to it.
public static let dynamicInputs = Flag(rawValue: AVFILTER_FLAG_DYNAMIC_INPUTS)
/// The number of the filter outputs is not determined just by `AVFilter.outputs`.
/// The filter might add additional outputs during initialization depending on
/// the options supplied to it.
public static let dynamicOutputs = Flag(rawValue: AVFILTER_FLAG_DYNAMIC_OUTPUTS)
/// The filter supports multithreading by splitting frames into multiple parts
/// and processing them concurrently.
public static let sliceThreads = Flag(rawValue: AVFILTER_FLAG_SLICE_THREADS)
/// Some filters support a generic "enable" expression option that can be used
/// to enable or disable a filter in the timeline. Filters supporting this
/// option have this flag set. When the enable expression is false, the default
/// no-op `filter_frame()` function is called in place of the `filter_frame()`
/// callback defined on each input pad, thus the frame is passed unchanged to
/// the next filters.
public static let supportTimelineGeneric = Flag(
rawValue: AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC)
/// Same as `supportTimelineGeneric`, except that the filter will
/// have its `filter_frame()` callback(s) called as usual even when the enable
/// expression is false. The filter will disable filtering within the
/// `filter_frame()` callback(s) itself, for example executing code depending on
/// the `AVFilterContext->is_disabled` value.
public static let supportTimelineInternal = Flag(
rawValue: AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL)
/// Handy mask to test whether the filter supports or no the timeline feature
/// (internally or generically).
public static let supportTimeline = Flag(rawValue: AVFILTER_FLAG_SUPPORT_TIMELINE)
public let rawValue: Int32
public init(rawValue: Int32) { self.rawValue = rawValue }
}
}
extension AVFilter.Flag: CustomStringConvertible {
public var description: String {
var str = "["
if contains(.dynamicInputs) { str += "dynamicInputs, " }
if contains(.dynamicOutputs) { str += "dynamicOutputs, " }
if contains(.sliceThreads) { str += "sliceThreads, " }
if contains(.supportTimelineGeneric) { str += "supportTimelineGeneric, " }
if contains(.supportTimelineInternal) { str += "supportTimelineInternal, " }
if contains(.supportTimeline) { str += "supportTimeline, " }
if str.suffix(2) == ", " {
str.removeLast(2)
}
str += "]"
return str
}
}
extension AVFilter: AVOptionSupport {
public func withUnsafeObjectPointer<T>(_ body: (UnsafeMutableRawPointer) throws -> T) rethrows
-> T
{
var tmp = cFilter.priv_class
return try withUnsafeMutablePointer(to: &tmp) { ptr in
try body(ptr)
}
}
}
// MARK: - AVFilterContext
typealias CAVFilterContext = CFFmpeg.AVFilterContext
/// An instance of a filter.
public final class AVFilterContext {
let cContextPtr: UnsafeMutablePointer<CAVFilterContext>
var cContext: CAVFilterContext { cContextPtr.pointee }
init(cContextPtr: UnsafeMutablePointer<CAVFilterContext>) {
self.cContextPtr = cContextPtr
}
/// Create a new filter instance in a filter graph.
///
/// - Parameters:
/// - graph: graph in which the new filter will be used
/// - filter: the filter to create an instance of
/// - name: Name to give to the new instance (will be copied to `AVFilterContext.name`).
/// This may be used by the caller to identify different filters, libavfilter itself
/// assigns no semantics to this parameter. May be `nil`.
/// - Returns: the context of the newly created filter instance (note that it is also
/// retrievable directly through `AVFilterGraph.filters` or with `avfilter_graph_get_filter()`).
public init(graph: AVFilterGraph, filter: AVFilter, name: String? = nil) {
guard let ctxPtr = avfilter_graph_alloc_filter(graph.cGraphPtr, filter.cFilterPtr, name)
else {
abort("avfilter_graph_alloc_filter")
}
self.cContextPtr = ctxPtr
}
/// The `AVFilter` of which this is an instance.
public var filter: AVFilter {
get { AVFilter(cFilterPtr: cContext.filter) }
set { cContextPtr.pointee.filter = newValue.cFilterPtr }
}
/// The name of this filter instance.
public var name: String {
String(cString: cContext.name)
}
/// The input links of this filter instance.
public var inputs: [AVFilterLink] {
var list = [AVFilterLink]()
for i in 0..<inputCount {
list.append(AVFilterLink(cLinkPtr: cContext.inputs[i]!))
}
return list
}
/// The number of input pads.
public var inputCount: Int {
Int(cContext.nb_inputs)
}
/// The output links of this filter instance.
public var outputs: [AVFilterLink] {
var list = [AVFilterLink]()
for i in 0..<outputCount {
list.append(AVFilterLink(cLinkPtr: cContext.outputs[i]!))
}
return list
}
/// The number of input pads.
public var outputCount: Int {
Int(cContext.nb_outputs)
}
/// The filtergraph this filter belongs to.
public var graph: AVFilterGraph {
AVFilterGraph(cGraphPtr: cContext.graph)
}
/// Initialize a filter with the supplied parameters.
///
/// - Parameter args: Options to initialize the filter with.
/// This must be a ':'-separated list of options in the 'key=value' form.
/// May be `nil` if the options have been set directly using the AVOptions API
/// or there are no options that need to be set. The default is `nil`.
/// - Throws: AVError
public func initialize(args: String? = nil) throws {
try throwIfFail(avfilter_init_str(cContextPtr, args))
}
/// Initialize a filter with the supplied dictionary of options.
///
/// - Note: This function and `avfilter_init_str()` do essentially the same thing,
/// the difference is in manner in which the options are passed. It is up to the
/// calling code to choose whichever is more preferable. The two functions also
/// behave differently when some of the provided options are not declared as
/// supported by the filter. In such a case, `avfilter_init_str()` will fail, but
/// this function will dump those extra options and continue as usual.
///
/// - Parameter args: A Dictionary filled with options for this filter.
/// - Throws: AVError
public func initialize(args: [String: String]) throws {
var pm: OpaquePointer? = args.toAVDict()
defer { av_dict_free(&pm) }
try throwIfFail(avfilter_init_dict(cContextPtr, &pm))
dumpUnrecognizedOptions(pm)
}
/// Link two filters together.
///
/// - Parameters:
/// - srcPad: The index of the output pad on the source filter. The default is 0.
/// - dst: The destination filter.
/// - dstPad: The index of the input pad on the destination filter. The default is 0.
/// - Returns: The destination filter.
/// - Throws: AVError
@discardableResult
public func link(
srcPad: UInt = 0,
dst: AVFilterContext,
dstPad: UInt = 0
) throws -> AVFilterContext {
try throwIfFail(avfilter_link(cContextPtr, UInt32(srcPad), dst.cContextPtr, UInt32(dstPad)))
return dst
}
}
extension AVFilterContext: AVClassSupport, AVOptionSupport {
public static let `class` = AVClass(cClassPtr: avfilter_get_class())
public func withUnsafeObjectPointer<T>(
_ body: (UnsafeMutableRawPointer) throws -> T
) rethrows -> T {
try body(cContextPtr)
}
}
// MARK: - AVBufferSourceFlag
public struct AVBufferSourceFlag: OptionSet {
/// Do not check for format changes.
public static let noCheckFormat = AVBufferSourceFlag(
rawValue: Int32(AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT))
// Immediately push the frame to the output.
public static let push = AVBufferSourceFlag(rawValue: Int32(AV_BUFFERSRC_FLAG_PUSH))
/// Keep a reference to the frame.
/// If the frame if reference-counted, create a new reference; otherwise copy the frame data.
public static let keepReference = AVBufferSourceFlag(
rawValue: Int32(AV_BUFFERSRC_FLAG_KEEP_REF))
public let rawValue: Int32
public init(rawValue: Int32) { self.rawValue = rawValue }
}
extension AVBufferSourceFlag: CustomStringConvertible {
public var description: String {
var str = "["
if contains(.noCheckFormat) { str += "noCheckFormat, " }
if contains(.push) { str += "push, " }
if contains(.keepReference) { str += "keepReference, " }
if str.suffix(2) == ", " {
str.removeLast(2)
}
str += "]"
return str
}
}
// MARK: - Buffer Source
extension AVFilterContext {
/// Add a frame to the buffer source.
///
/// By default, if the frame is reference-counted, this function will take ownership of
/// the reference(s) and reset the frame. Otherwise the frame data will be copied.
/// This can be controlled using the flags.
///
/// If this function throws an error, the input frame is not touched.
///
/// - Parameters:
/// - frame: a frame, or `nil` to mark EOF
/// - flags: a combination of `AVBufferSourceFlag` flags
/// - Throws: AVError
public func addFrame(_ frame: AVFrame?, flags: AVBufferSourceFlag = .init(rawValue: 0)) throws {
try throwIfFail(av_buffersrc_add_frame_flags(cContextPtr, frame?.cFramePtr, flags.rawValue))
}
}
// MARK: - AVBufferSinkFlag
public struct AVBufferSinkFlag: OptionSet {
/// Tell av_buffersink_get_buffer_ref() to read video/samples buffer
/// reference, but not remove it from the buffer. This is useful if you
/// need only to read a video/samples buffer, without to fetch it.
public static let peek = AVBufferSinkFlag(rawValue: Int32(AV_BUFFERSINK_FLAG_PEEK))
/// Tell av_buffersink_get_buffer_ref() not to request a frame from its input.
/// If a frame is already buffered, it is read (and removed from the buffer),
/// but if no frame is present, return AVERROR(EAGAIN).
public static let noRequest = AVBufferSinkFlag(rawValue: Int32(AV_BUFFERSINK_FLAG_NO_REQUEST))
public let rawValue: Int32
public init(rawValue: Int32) { self.rawValue = rawValue }
}
extension AVBufferSinkFlag: CustomStringConvertible {
public var description: String {
var str = "["
if contains(.peek) { str += "peek, " }
if contains(.noRequest) { str += "noRequest, " }
if str.suffix(2) == ", " {
str.removeLast(2)
}
str += "]"
return str
}
}
// MARK: - Buffer Sink
extension AVFilterContext {
/// The media type of the buffer sink.
public var mediaType: AVMediaType {
av_buffersink_get_type(cContextPtr)
}
/// The timebase of the buffer sink.
public var timebase: AVRational {
av_buffersink_get_time_base(cContextPtr)
}
/// The pixel format of the video buffer sink.
public var pixelFormat: AVPixelFormat {
AVPixelFormat(rawValue: av_buffersink_get_format(cContextPtr))
}
/// The frame rate of the video buffer sink.
public var frameRate: AVRational {
av_buffersink_get_frame_rate(cContextPtr)
}
/// The width of the video buffer sink.
public var width: Int {
Int(av_buffersink_get_w(cContextPtr))
}
/// The height of the video buffer sink.
public var height: Int {
Int(av_buffersink_get_h(cContextPtr))
}
/// The sample aspect ratio of the video buffer sink.
public var sampleAspectRatio: AVRational {
av_buffersink_get_sample_aspect_ratio(cContextPtr)
}
/// The sample format of the audio buffer sink.
public var sampleFormat: AVSampleFormat {
AVSampleFormat(rawValue: av_buffersink_get_format(cContextPtr))
}
/// The sample rate of the audio buffer sink.
public var sampleRate: Int {
Int(av_buffersink_get_sample_rate(cContextPtr))
}
/// The number of channels in the audio buffer sink.
public var channelCount: Int {
Int(av_buffersink_get_channels(cContextPtr))
}
/// The channel layout of the audio buffer sink.
public var channelLayout: AVChannelLayout {
AVChannelLayout(rawValue: av_buffersink_get_channel_layout(cContextPtr))
}
/// Get a frame with filtered data from sink and put it in frame.
///
/// - Parameters:
/// - frame: pointer to an allocated frame that will be filled with data.
/// The data must be freed using `av_frame_unref() / av_frame_free()`.
/// - flags: a combination of `AVBufferSinkFlag` flags
/// - Throws:
/// - `AVError.tryAgain` if no frames are available at this point;
/// more input frames must be added to the filtergraph to get more output.
/// - `AVError.eof` if there will be no more output frames on this sink.
/// - A different `AVError` in other failure cases.
public func getFrame(_ frame: AVFrame, flags: AVBufferSinkFlag = .init(rawValue: 0)) throws {
try throwIfFail(av_buffersink_get_frame_flags(cContextPtr, frame.cFramePtr, flags.rawValue))
}
}
// MARK: - AVFilterLink
typealias CAVFilterLink = CFFmpeg.AVFilterLink
/// A link between two filters. This contains pointers to the source and destination filters
/// between which this link exists, and the indexes of the pads involved.
/// In addition, this link also contains the parameters which have been negotiated and
/// agreed upon between the filter, such as image dimensions, format, etc.
public struct AVFilterLink {
let cLinkPtr: UnsafeMutablePointer<CAVFilterLink>
init(cLinkPtr: UnsafeMutablePointer<CAVFilterLink>) {
self.cLinkPtr = cLinkPtr
}
/// The source filter.
public var source: AVFilterContext {
AVFilterContext(cContextPtr: cLinkPtr.pointee.src)
}
/// The destination filter.
public var destination: AVFilterContext {
AVFilterContext(cContextPtr: cLinkPtr.pointee.dst)
}
/// The filter's media type.
public var mediaType: AVMediaType {
cLinkPtr.pointee.type
}
/// Define the timebase used by the PTS of the frames/samples which will pass through this link.
/// During the configuration stage, each filter is supposed to change only the output timebase,
/// while the timebase of the input link is assumed to be an unchangeable property.
public var timebase: AVRational {
cLinkPtr.pointee.time_base
}
}
// MARK: - Video
extension AVFilterLink {
/// agreed upon pixel format
public var pixelFormat: AVPixelFormat {
AVPixelFormat(cLinkPtr.pointee.format)
}
/// agreed upon image width
public var width: Int {
Int(cLinkPtr.pointee.w)
}
/// agreed upon image height
public var height: Int {
Int(cLinkPtr.pointee.h)
}
/// agreed upon sample aspect ratio
public var sampleAspectRatio: AVRational {
cLinkPtr.pointee.sample_aspect_ratio
}
}
// MARK: - Audio
extension AVFilterLink {
/// agreed upon sample format
public var sampleFormat: AVSampleFormat {
AVSampleFormat(cLinkPtr.pointee.format)
}
/// channel layout of current buffer
public var channelLayout: AVChannelLayout {
AVChannelLayout(rawValue: cLinkPtr.pointee.channel_layout)
}
/// samples per second
public var sampleRate: Int {
Int(cLinkPtr.pointee.sample_rate)
}
}
// MARK: - AVFilterGraph
typealias CAVFilterGraph = CFFmpeg.AVFilterGraph
public final class AVFilterGraph {
let cGraphPtr: UnsafeMutablePointer<CAVFilterGraph>
var cGraph: CAVFilterGraph { cGraphPtr.pointee }
init(cGraphPtr: UnsafeMutablePointer<CAVFilterGraph>) {
self.cGraphPtr = cGraphPtr
}
/// Create a filter graph.
public init() {
guard let ptr = avfilter_graph_alloc() else {
abort("avfilter_graph_alloc")
}
self.cGraphPtr = ptr
}
/// The filter list in the graph.
public var filters: [AVFilterContext] {
var list = [AVFilterContext]()
for i in 0..<filterCount {
let filter = cGraph.filters.advanced(by: i).pointee!
list.append(AVFilterContext(cContextPtr: filter))
}
return list
}
/// The number of filters in the graph.
public var filterCount: Int {
Int(cGraph.nb_filters)
}
/// Create and add a filter instance into an existing graph.
/// The filter instance is created from the filter filt and inited with the parameters.
///
/// - Parameters:
/// - filter: the filter to create an instance of
/// - name: the instance name to give to the created filter instance
/// - args: Options to initialize the filter with. This must be a
/// ':'-separated list of options in the 'key=value' form.
/// May be NULL if the options have been set directly using the
/// AVOptions API or there are no options that need to be set.
/// - Returns: newly created filter instance
/// - Throws: AVError
public func addFilter(_ filter: AVFilter, name: String, args: String? = nil) throws
-> AVFilterContext
{
var ctxPtr: UnsafeMutablePointer<CAVFilterContext>!
let ret = avfilter_graph_create_filter(&ctxPtr, filter.cFilterPtr, name, args, nil, cGraphPtr)
try throwIfFail(ret)
return AVFilterContext(cContextPtr: ctxPtr)
}
/// Add a graph described by a string to a graph.
///
/// In the graph filters description,
/// if the input label of the first filter is not specified, "in" is assumed;
/// if the output label of the last filter is not specified, "out" is assumed.
///
/// - Parameters:
/// - filters: string to be parsed
/// - inputs: pointer to a linked list to the inputs of the graph, may be `nil`.
/// If non-NULL, *inputs is updated to contain the list of open inputs
/// after the parsing, should be freed with avfilter_inout_free().
/// - outputs: pointer to a linked list to the outputs of the graph, may be NULL.
/// If non-NULL, *outputs is updated to contain the list of open outputs
/// after the parsing, should be freed with avfilter_inout_free().
/// - Throws: AVError
public func parse(filters: String, inputs: AVFilterInOut, outputs: AVFilterInOut) throws {
inputs.freeWhenDone = false
outputs.freeWhenDone = false
var inputsPtr: UnsafeMutablePointer<CAVFilterInOut>? = inputs.cInOutPtr
var outputPtr: UnsafeMutablePointer<CAVFilterInOut>? = outputs.cInOutPtr
try throwIfFail(avfilter_graph_parse_ptr(cGraphPtr, filters, &inputsPtr, &outputPtr, nil))
}
/// Check validity and configure all the links and formats in the graph.
///
/// - Throws: AVError
public func configure() throws {
try throwIfFail(avfilter_graph_config(cGraphPtr, nil))
}
deinit {
var pb: UnsafeMutablePointer<CAVFilterGraph>? = cGraphPtr
avfilter_graph_free(&pb)
}
}
extension AVFilterGraph: CustomStringConvertible {
public var description: String {
let cstr = avfilter_graph_dump(cGraphPtr, nil)
defer { av_free(cstr) }
return String(cString: cstr)!
}
}
extension AVFilterGraph: AVOptionSupport {
public func withUnsafeObjectPointer<T>(_ body: (UnsafeMutableRawPointer) throws -> T) rethrows
-> T
{
try body(cGraphPtr)
}
}
// MARK: - AVFilterInOut
typealias CAVFilterInOut = CFFmpeg.AVFilterInOut
/// A linked-list of the inputs/outputs of the filter chain.
///
/// This is mainly useful for `avfilter_graph_parse()` / `avfilter_graph_parse2()`,
/// where it is used to communicate open (unlinked) inputs and outputs from and
/// to the caller.
/// This struct specifies, per each not connected pad contained in the graph, the
/// filter context and the pad index required for establishing a link.
public final class AVFilterInOut {
let cInOutPtr: UnsafeMutablePointer<CAVFilterInOut>
var cInOut: CAVFilterInOut { cInOutPtr.pointee }
var freeWhenDone: Bool = false
init(cInOutPtr: UnsafeMutablePointer<CAVFilterInOut>) {
self.cInOutPtr = cInOutPtr
}
/// Create a single `AVFilterInOut` entry.
public init() {
guard let inOutPtr = avfilter_inout_alloc() else {
abort("avfilter_inout_alloc")
}
self.cInOutPtr = inOutPtr
self.freeWhenDone = true
}
/// The unique name for this input/output in the list.
public var name: String {
get { String(cString: cInOut.name) }
set { cInOutPtr.pointee.name = av_strdup(newValue) }
}
/// The filter context associated to this input/output.
public var filterContext: AVFilterContext {
get { AVFilterContext(cContextPtr: cInOut.filter_ctx) }
set { cInOutPtr.pointee.filter_ctx = newValue.cContextPtr }
}
/// The index of the filter context pad to use for linking.
public var padIndex: Int {
get { Int(cInOut.pad_idx) }
set { cInOutPtr.pointee.pad_idx = Int32(newValue) }
}
/// The next input/input in the list, `nil` if this is the last.
public var next: AVFilterInOut? {
get {
if let ptr = cInOut.next {
return AVFilterInOut(cInOutPtr: ptr)
}
return nil
}
set { cInOutPtr.pointee.next = newValue?.cInOutPtr }
}
deinit {
if freeWhenDone {
var pb: UnsafeMutablePointer<CAVFilterInOut>? = cInOutPtr
avfilter_inout_free(&pb)
}
}
}
#endif
| true
|
7caf2295d780b5feb9c4871cb7b5f6d462aaf17c
|
Swift
|
nguyenhuudat98bn/SplitViewGetImageFromAcsess
|
/SplitViewController/MasterTableViewController.swift
|
UTF-8
| 4,337
| 2.8125
| 3
|
[] |
no_license
|
//
// MasterTableViewController.swift
// SplitViewController
//
// Created by nguyễn hữu đạt on 5/28/18.
// Copyright © 2018 nguyễn hữu đạt. All rights reserved.
//
import UIKit
protocol MonsterSelectionDelegate: class {
func monsterSelected(_ newMonster: Monster)
}
class MasterTableViewController: UITableViewController {
var monsters = [
Monster(name: "Phạm Thị Hà", description: "1 Tuổi",
iconName: "meetcatbot", weapon: .sword),
Monster(name: "Thrers", description: "2 Tuổi",
iconName: "meetdogbot", weapon: .blowgun),
Monster(name: "Thrers", description: "3 Tuổi",
iconName: "meetexplodebot", weapon: .smoke),
Monster(name: "Thrers", description: "4 Tuổi",
iconName: "meetfirebot", weapon: .ninjaStar),
Monster(name: "Thrers ", description: "5 Tuổi",
iconName: "meeticebot", weapon: .fire),
]
weak var delegate: MonsterSelectionDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.splitViewController?.preferredDisplayMode = UISplitViewControllerDisplayMode.primaryOverlay
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedMonster = monsters[indexPath.row]
delegate?.monsterSelected(selectedMonster)
if let detailViewController = delegate as? DetailViewController,
let detailNavigationController = detailViewController.navigationController {
splitViewController?.showDetailViewController(detailNavigationController, sender: nil)
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return monsters.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let monter = monsters[indexPath.row]
cell.textLabel?.text = monter.name
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 {
monsters.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
22f5f2559ea928dd3562b78a1456c7d3bf15c3aa
|
Swift
|
maweefeng/XMGBaseUICommonet
|
/XMGBaseUICommonet/Classes/ColorTool.swift
|
UTF-8
| 587
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
import UIKit
public class ColorTool{
class func pureColorImageWithSize(size:CGSize,color:UIColor,cornerRadius:CGFloat)->UIImage{
let view = UIView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
view.backgroundColor = color
view.layer.cornerRadius = cornerRadius;
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
return image!
}
}
| true
|
d1ec1f4a48c0ea9eedeb05242bc1caf3947239e1
|
Swift
|
rudrik21/NoteAppIos
|
/NoteApp/Models/FolderData.swift
|
UTF-8
| 723
| 2.84375
| 3
|
[] |
no_license
|
//
// NoteData.swift
// NoteApp
//
// Created by Rudrik Panchal on 2020-01-23.
// Copyright © 2020 Back benchers. All rights reserved.
//
import Foundation
import CoreData
@objc(FolderData)
public class FolderData: NSManagedObject{
@NSManaged var folderName: String
@NSManaged var folderIndex: Int32
@NSManaged var strNotes: String
var folder: Folder{
get{
return Folder(folderName: self.folderName, index: Int(self.folderIndex), notes: stringTojson(str: strNotes))
}
set{
self.folderName = newValue.folderName
self.folderIndex = Int32(newValue.index)
self.strNotes = jsonTostring(notes: newValue.notes)
}
}
}
| true
|
03d80c0310cb11a3b632b1afab95b59b8311f0c6
|
Swift
|
geor-kasapidi/HappyData
|
/Sources/SwormTools/ProgressiveMigration.swift
|
UTF-8
| 4,572
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
import CoreData
public final class SQLiteProgressiveMigration {
public enum Error: Swift.Error {
case storeCompatibleModelNotFound
}
public typealias Progress = (Int, Int) -> Void
final class Step {
enum Source {
case auto
case bundle(Bundle, String)
}
let sourceModel: NSManagedObjectModel
let destinationModel: NSManagedObjectModel
let mappingModel: NSMappingModel
init(
sourceModel: NSManagedObjectModel,
destinationModel: NSManagedObjectModel,
source: Source
) throws {
switch source {
case .auto:
self.mappingModel = try NSMappingModel.inferredMappingModel(
forSourceModel: sourceModel,
destinationModel: destinationModel
)
case let .bundle(bundle, name):
self.mappingModel = try bundle.mappingModel(name: name)
}
self.sourceModel = sourceModel
self.destinationModel = destinationModel
}
func migrate(from sourceURL: URL, to destinationURL: URL) throws {
try NSMigrationManager(
sourceModel: self.sourceModel,
destinationModel: self.destinationModel
).migrateStore(
from: sourceURL,
sourceType: NSSQLiteStoreType,
options: nil,
with: self.mappingModel,
toDestinationURL: destinationURL,
destinationType: NSSQLiteStoreType,
destinationOptions: nil
)
}
}
let originalStoreURL: URL
let metadata: [String: Any]
let currentModel: NSManagedObjectModel
let bundle: Bundle
let steps: [Step]
public init?(store: SQLiteStoreDescription, bundle: Bundle) throws {
guard let metadata = try? NSPersistentStoreCoordinator.metadataForPersistentStore(
ofType: NSSQLiteStoreType,
at: store.url,
options: nil
) else {
return nil
}
let models: [NSManagedObjectModel] = try store.modelVersions.map { version in
try bundle.managedObjectModel(versionName: version.name, modelName: store.modelName)
}
guard let currentModelIndex = models.firstIndex(where: {
$0.isConfiguration(withName: nil, compatibleWithStoreMetadata: metadata)
}) else {
throw Error.storeCompatibleModelNotFound
}
let modelIndicesToMigrate = models.indices.dropFirst(currentModelIndex)
let steps = try zip(modelIndicesToMigrate.dropLast(), modelIndicesToMigrate.dropFirst()).map {
try Step(
sourceModel: models[$0],
destinationModel: models[$1],
source: store.modelVersions[$1].mappingModelName.flatMap { .bundle(bundle, $0) } ?? .auto
)
}
guard !steps.isEmpty else {
return nil
}
self.originalStoreURL = store.url
self.metadata = metadata
self.currentModel = models[currentModelIndex]
self.bundle = bundle
self.steps = steps
}
public var stepCount: Int {
self.steps.count
}
public func performMigration(progress: Progress?) throws {
let storeCoordinator = NSPersistentStoreCoordinator(
managedObjectModel: self.currentModel
)
try storeCoordinator.checkpointWAL(at: self.originalStoreURL)
progress?(0, self.steps.count)
var currentStoreURL = self.originalStoreURL
for (index, step) in self.steps.enumerated() {
let newStoreURL = URL(
fileURLWithPath: NSTemporaryDirectory(),
isDirectory: true
).appendingPathComponent(
UUID().uuidString
)
try step.migrate(
from: currentStoreURL,
to: newStoreURL
)
if currentStoreURL != self.originalStoreURL {
try storeCoordinator.destroySQLiteStore(at: currentStoreURL)
}
currentStoreURL = newStoreURL
progress?(index + 1, self.steps.count)
}
try storeCoordinator.replaceSQLiteStore(
at: self.originalStoreURL,
with: currentStoreURL
)
if currentStoreURL != self.originalStoreURL {
try storeCoordinator.destroySQLiteStore(at: currentStoreURL)
}
}
}
| true
|
3c4692dc0df2662e2b2a367b3b5c728a5d70f7c2
|
Swift
|
alexkbsoft/TrySwift
|
/PropertyObservers.playground/Contents.swift
|
UTF-8
| 518
| 3.375
| 3
|
[] |
no_license
|
import UIKit
class SecretLabEmployee {
var accessLevel = 0 {
willSet {
print("new boss is about to come")
print("new access level is \(newValue)")
}
didSet {
dbAccess = accessLevel > 0
print("new boss just come. last time access level \(oldValue)")
}
}
var dbAccess = false
}
var employee = SecretLabEmployee()
employee.accessLevel
employee.dbAccess
employee.accessLevel = 1
employee.accessLevel
employee.dbAccess
| true
|
d7a691c57819c85e88031bbfbd0d5886892aa45e
|
Swift
|
jhardy3/XCodeLifeLongLearning
|
/CloudKitTest/CloudKitTest/CloudKitController.swift
|
UTF-8
| 2,434
| 2.625
| 3
|
[] |
no_license
|
//
// CloudKitController.swift
// CloudKitTest
//
// Created by Jake Hardy on 4/21/16.
// Copyright © 2016 NSDesert. All rights reserved.
//
import Foundation
import CloudKit
class CloudKitController {
static let sharedController = CloudKitController()
let publicDB = CKContainer.defaultContainer().publicCloudDatabase
func createNSOperationDependency() {
let firstFetch = CKFetchRecordsOperation()
let secondFetch = CKFetchRecordsOperation()
secondFetch.addDependency(firstFetch)
let queue = NSOperationQueue()
queue.addOperations([firstFetch, secondFetch], waitUntilFinished: false)
}
func saveRecordToPublicDatabase(record: CKRecord) {
publicDB.saveRecord(record) { (record, error) in
if let retryAfterValue = error?.userInfo[CKErrorRetryAfterKey] as? NSTimeInterval {
let retryAfterDate = NSDate(timeIntervalSinceNow: retryAfterValue)
}
guard let record = record else { return }
// Do Something with record
}
}
func readRecordFromPublicDatabase(recordID: CKRecordID) {
publicDB.fetchRecordWithID(recordID) { (record, error) in
if let error = error {
print(error)
}
guard let record = record else { return }
// Do Something with record
}
}
func editRecordFromPublicDatabase(recordID: CKRecordID) {
// ???
createNSOperationDependency()
publicDB.fetchRecordWithID(recordID) { (record, error) in
if let error = error {
print(error)
}
guard let record = record else { return }
// Do stuff here
self.publicDB.saveRecord(record, completionHandler: { (record, error) in
// Saved
})
}
}
func queryWithPredicateAndType(type: String, predicate: NSPredicate) {
let query = CKQuery(recordType: type, predicate: predicate)
publicDB.performQuery(query, inZoneWithID: nil) { (records, error) in
if let error = error {
print("Error in \(#function) - \(error.localizedDescription)")
}
}
// Do something with records
}
}
| true
|
d239f921ddaa168de6f27ff17d4777f4292a79ed
|
Swift
|
PerfectlySoft/Perfect-Stripe
|
/Sources/PerfectStripe/Methods/CustomerCreate.swift
|
UTF-8
| 1,952
| 2.859375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// CustomerCreate.swift
// PerfectStripe
//
// Created by Jonathan Guthrie on 2017-05-30.
//
//
import PerfectHTTP
import codableRequest
extension Stripe {
/// Creates a new customer object
/// Follows conventions at https://stripe.com/docs/api/curl#create_customer
/// - coupon is not part of the customer object, therefore it is specified as an incoming parameter
public static func customerCreate(_ customer: Customer, coupon: String = "") throws -> Customer {
var params = [String: Any]()
/// An integer amount in cents that is the starting account balance for your customer. A negative amount represents a credit that will be used before attempting any charges to the customer’s card; a positive amount will be added to the next invoice.
if customer.account_balance != 0 {
params["account_balance"] = customer.account_balance
}
if customer.business_vat_id != nil {
params["business_vat_id"] = customer.business_vat_id
}
/// If you provide a coupon code, the customer will have a discount applied on all recurring charges. Charges you create through the API will not have the discount.
if !coupon.isEmpty { params["coupon"] = coupon }
if customer.default_source != nil {
params["default_source"] = customer.default_source
}
if customer.description != nil {
params["description"] = customer.description
}
if customer.email != nil {
params["email"] = customer.email
}
if customer.metadata != nil {
params["metadata"] = customer.metadata
}
guard params.count > 0 else {
throw StripeInputError.invalidInput(description: "At least one parameter must be specified.")
}
// execute request
do {
let response: Customer = try CodableRequest.request(
.post,
"\(Stripe.server)/customers",
to: Customer.self,
error: ErrorResponse.self,
params: params,
encoding: "form",
bearerToken: Stripe.apiKey
)
return response
} catch {
throw error
}
}
}
| true
|
cd77b8da07b280b66e40a4a6794b33453ae122e8
|
Swift
|
venj/Remote-Helper
|
/Remote Helper/URLConverter.swift
|
UTF-8
| 2,228
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
//
// URLConverter.swift
// Video Player
//
// Created by Venj Chu on 15/11/3.
// Copyright © 2015年 Home. All rights reserved.
//
import Foundation
@objc
public enum URLConverterType: Int {
case thunder
case qq
case flashget
case unknown
}
@objc
public enum URLConverterConvertError: Int, Error {
case invalidURL
case unknownScheme
}
@objc
open class URLConverter : NSObject {
class func encode(_ urlString: String, type: URLConverterType) -> String {
var template = "", scheme = ""
switch type {
case .thunder:
template = "AA\(urlString)ZZ"
scheme = "thunder"
case .qq:
template = urlString
scheme = "qqdl"
case .flashget:
template = "[FLASHGET]\(urlString)[FLASHGET]"
scheme = "Flashget"
case .unknown: // Return original url string while type unknown
return urlString
}
return "\(scheme)://" + (template.data(using: .utf8)?.base64EncodedString() ?? "")
}
class func decode(_ urlString: String) throws -> String {
let components = urlString.components(separatedBy: "//")
guard components.count == 2 else { throw URLConverterConvertError.invalidURL }
var type:URLConverterType = .unknown
if components[0].lowercased() == "thunder:" {
type = .thunder
}
else if components[0].lowercased() == "qqdl:" {
type = .qq
}
else if components[0].lowercased() == "flashget:" {
type = .flashget
}
guard let decodedString = components[1].decodedBase64String() else { throw URLConverterConvertError.invalidURL }
var pattern = ""
switch type {
case .thunder:
pattern = "AA(.+?)ZZ"
case .qq:
return decodedString
case .flashget:
pattern = "\\[FLASHGET\\](.+?)\\[FLASHGET\\]"
case .unknown: // Return original url string while type unknown
throw URLConverterConvertError.unknownScheme
}
guard let url = decodedString.stringByMatching(pattern) else { throw URLConverterConvertError.invalidURL }
return url
}
}
| true
|
de87b507e8671383c411b8407c6ae3f4e5c224c6
|
Swift
|
JennessaMa/MDB_MP
|
/WeatherDB/WeatherDB/WeatherPageVC.swift
|
UTF-8
| 10,848
| 2.609375
| 3
|
[] |
no_license
|
//
// WeatherPageVC.swift
// WeatherDB
//
// Created by Jennessa Ma on 3/24/21.
//
import UIKit
import GooglePlaces
class WeatherPageVC: UIViewController {
var loc: CLLocation? {
didSet {
print("set location in weatherpagevc: \(loc!.description)")
}
}
var mainVC: MainVC?
var isCurrent = false
var weather: Weather? {
didSet {
guard let weather = weather else { return }
cityName.text = weather.name
currTemp.text = weather.main.temperature.description + "°"
currCondition.text = weather.condition.first!.description
let url: URL = URL(string: "http://openweathermap.org/img/wn/\(weather.condition.first!.icon)@2x.png")!
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
self.icon.image = image
}
}
feelsLike.setInfo(info: weather.main.heatIndex.description + "°")
pressure.setInfo(info: weather.main.pressure.description)
humidity.setInfo(info: weather.main.humidity.description
)
}
}
var cityName: UILabel = {
let lbl = UILabel()
lbl.font = .systemFont(ofSize: 35, weight: .medium)
lbl.textAlignment = .center
lbl.textColor = .white
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
var currTemp: UILabel = {
let lbl = UILabel()
lbl.font = .systemFont(ofSize: 50, weight: .medium)
lbl.textAlignment = .center
lbl.textColor = .white
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
var icon: UIImageView = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
var currCondition: UILabel = {
let lbl = UILabel()
lbl.font = .systemFont(ofSize: 22, weight: .regular)
lbl.textColor = .white
lbl.textAlignment = .left
lbl.translatesAutoresizingMaskIntoConstraints = false
return lbl
}()
var infoStack: UIStackView = {
let stack = UIStackView()
stack.axis = .horizontal
stack.distribution = .equalSpacing
stack.translatesAutoresizingMaskIntoConstraints = false
return stack
}()
var feelsLike: WeatherInfo = {
let fl = WeatherInfo(title: "Feels Like", info: "")
fl.translatesAutoresizingMaskIntoConstraints = false
return fl
}()
var pressure: WeatherInfo = {
let p = WeatherInfo(title: "Pressure", info: "")
p.translatesAutoresizingMaskIntoConstraints = false
return p
}()
var humidity: WeatherInfo = {
let h = WeatherInfo(title: "Humidity", info: "")
h.translatesAutoresizingMaskIntoConstraints = false
return h
}()
var deleteLoc: UIButton = {
let btn = UIButton()
btn.setImage(UIImage(systemName: "minus"), for: .normal)
let config = UIImage.SymbolConfiguration(font: .systemFont(ofSize: 25, weight: .regular))
btn.setPreferredSymbolConfiguration(config, forImageIn: .normal)
btn.layer.cornerRadius = 41 / 2
btn.layer.borderWidth = 3
btn.layer.borderColor = .init(red: 1, green: 1, blue: 1, alpha: 1)
btn.tintColor = .white
btn.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
btn.translatesAutoresizingMaskIntoConstraints = false
return btn
}()
override func viewDidLoad() {
super.viewDidLoad()
let isDark = self.traitCollection.userInterfaceStyle == UIUserInterfaceStyle.dark
if (isCurrent) { //can't delete current controller
deleteLoc.isHidden = true
}
view.addSubview(deleteLoc)
deleteLoc.addTarget(self, action: #selector(didTapDeleteLoc(_:)), for: .touchUpInside)
NSLayoutConstraint.activate([
deleteLoc.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 15),
deleteLoc.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 25),
])
view.addSubview(cityName)
view.addSubview(icon)
view.addSubview(currCondition)
view.addSubview(currTemp)
infoStack.addArrangedSubview(feelsLike)
infoStack.addArrangedSubview(pressure)
infoStack.addArrangedSubview(humidity)
view.addSubview(infoStack)
NSLayoutConstraint.activate([
cityName.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50),
cityName.centerXAnchor.constraint(equalTo: view.centerXAnchor),
icon.topAnchor.constraint(equalTo: cityName.bottomAnchor, constant: 10),
icon.trailingAnchor.constraint(equalTo: view.centerXAnchor),
currCondition.topAnchor.constraint(equalTo: icon.topAnchor, constant: 35),
currCondition.leadingAnchor.constraint(equalTo: view.centerXAnchor),
currTemp.topAnchor.constraint(equalTo: icon.bottomAnchor, constant: 20),
currTemp.centerXAnchor.constraint(equalTo: view.centerXAnchor),
infoStack.topAnchor.constraint(equalTo: currTemp.bottomAnchor, constant: 35),
infoStack.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 35),
infoStack.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -35)
])
let orangeColor = UIColor(red: 255/255, green: 183/255, blue: 3/255, alpha: 1)
let darkColor = UIColor(red: 52/255, green: 58/255, blue: 64/255, alpha: 1)
let cond = weather!.condition.first!.name
var iconID = weather!.condition.first!.icon
if (!isDark) { //light mode: day icon, bg color and text depend on condition
if (iconID.contains("n")) {
let i = iconID.firstIndex(of: "n")
iconID = iconID[..<i!] + "d"
}
let url: URL = URL(string: "http://openweathermap.org/img/wn/\(iconID)@2x.png")!
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
self.icon.image = image
}
}
if (cond == "Thunderstorm") {
view.backgroundColor = UIColor(red: 25/255, green: 25/255, blue: 25/255, alpha: 1)
} else if (cond == "Drizzle") {
view.backgroundColor = UIColor(red: 119/255, green: 141/255, blue: 169/255, alpha: 1)
} else if (cond == "Rain") {
view.backgroundColor = UIColor(red: 65/255, green: 90/255, blue: 119/255, alpha: 1)
feelsLike.setTextColor(titleColor: darkColor)
pressure.setTextColor(titleColor: darkColor)
humidity.setTextColor(titleColor: darkColor)
} else if (cond == "Snow") {
view.backgroundColor = UIColor(red: 248/255, green: 249/255, blue: 250/255, alpha: 1)
let blueColor = UIColor(red: 193/255, green: 211/255, blue: 254/255, alpha: 1)
cityName.textColor = blueColor
currTemp.textColor = blueColor
currCondition.textColor = blueColor
feelsLike.setTextColor(infoColor: blueColor)
pressure.setTextColor(infoColor: blueColor)
humidity.setTextColor(infoColor: blueColor)
} else if (cond == "Atmosphere") {
view.backgroundColor = UIColor(red: 206/255, green: 212/255, blue: 218/255, alpha: 1)
cityName.textColor = darkColor
currTemp.textColor = darkColor
currCondition.textColor = darkColor
feelsLike.setTextColor(titleColor: UIColor(red: 33/255, green: 37/255, blue: 41/255, alpha: 1), infoColor: darkColor)
pressure.setTextColor(titleColor: UIColor(red: 33/255, green: 37/255, blue: 41/255, alpha: 1), infoColor: darkColor)
humidity.setTextColor(titleColor: UIColor(red: 33/255, green: 37/255, blue: 41/255, alpha: 1), infoColor: darkColor)
} else if (cond == "Clear") {
view.backgroundColor = UIColor(red: 33/255, green: 158/255, blue: 188/255, alpha: 1)
currCondition.textColor = orangeColor
feelsLike.setTextColor(titleColor: darkColor, infoColor: orangeColor)
pressure.setTextColor(titleColor: darkColor, infoColor: orangeColor)
humidity.setTextColor(titleColor: darkColor, infoColor: orangeColor)
} else if (cond == "Clouds") {
view.backgroundColor = UIColor(red: 167/255, green: 194/255, blue: 211/255, alpha: 1)
cityName.textColor = darkColor
currTemp.textColor = darkColor
currCondition.textColor = darkColor
feelsLike.setTextColor(titleColor: UIColor(red: 33/255, green: 37/255, blue: 41/255, alpha: 1), infoColor: darkColor)
pressure.setTextColor(titleColor: UIColor(red: 33/255, green: 37/255, blue: 41/255, alpha: 1), infoColor: darkColor)
humidity.setTextColor(titleColor: UIColor(red: 33/255, green: 37/255, blue: 41/255, alpha: 1), infoColor: darkColor)
} else {
view.backgroundColor = .black
}
} else { //dark mode: icon to night version, bg color + text, and pc tint colors
if (iconID.contains("d")) {
let i = iconID.firstIndex(of: "d")
iconID = iconID[..<i!] + "n"
}
let url: URL = URL(string: "http://openweathermap.org/img/wn/\(iconID)@2x.png")!
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
self.icon.image = image
}
}
let text = UIColor(red: 224/255, green: 225/255, blue: 221/255, alpha: 1)
view.backgroundColor = UIColor(red: 13/255, green: 27/255, blue: 42/255, alpha: 1)
cityName.textColor = text
currTemp.textColor = text
currCondition.textColor = text
feelsLike.setTextColor(infoColor: text)
pressure.setTextColor(infoColor: text)
humidity.setTextColor(infoColor: text)
mainVC?.pageControl.currentPageIndicatorTintColor = .white
mainVC?.pageControl.pageIndicatorTintColor = .darkGray
}
}
@objc func didTapDeleteLoc(_ sender: UIButton) {
guard let mainVC = mainVC else { return }
mainVC.deleteLoc(location: loc!)
}
}
| true
|
0fa74498bb67f8b6f4f7e650e00ecbbbde9ba437
|
Swift
|
ChangeNOW-lab/ChangeNow_Integration_iOS
|
/CNIntegration/Basic/Extensions/NSDictionary+Extensions.swift
|
UTF-8
| 541
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// NSDictionary+Extensions.swift
// CNIntegration
//
// Created by Pavel Pronin on 04/02/2020.
// Copyright © 2020 Pavel Pronin. All rights reserved.
//
import Foundation
extension NSDictionary {
var swiftDictionary: [String: AnyObject] {
var swiftDictionary: [String: AnyObject] = [:]
let keys = self.allKeys.compactMap { $0 as? String }
for key in keys {
let keyValue = self.value(forKey: key) as AnyObject
swiftDictionary[key] = keyValue
}
return swiftDictionary
}
}
| true
|
bab24cc77164674c4e48abbae5660fc54fc58d1a
|
Swift
|
mrasyidhaikal/iCol
|
/iCol/ViewControllers/DescriptionViewController.swift
|
UTF-8
| 2,348
| 2.6875
| 3
|
[] |
no_license
|
//
// ViewController3.swift
// iCol
//
// Created by Windy on 12/10/20.
//
import UIKit
class DescriptionViewController: UIViewController {
let descriptionLabel = UILabel()
var challengeDescription: String = ""
var type: Type?
override func viewDidLoad() {
super.viewDidLoad()
setupNavigation()
setupBackground()
setupDescription()
setupButton()
}
private func setupNavigation() {
navigationController?.navigationBar.prefersLargeTitles = true
}
private func setupBackground() {
view.backgroundColor = Color.background
}
private func setupDescription() {
descriptionLabel.text = challengeDescription
descriptionLabel.font = UIFont.preferredFont(forTextStyle: .body)
descriptionLabel.numberOfLines = 0
view.addSubview(descriptionLabel)
descriptionLabel.setConstraint(topAnchor: view.safeAreaLayoutGuide.topAnchor, topAnchorConstant: 8,
leadingAnchor: view.layoutMarginsGuide.leadingAnchor,
trailingAnchor: view.layoutMarginsGuide.trailingAnchor)
}
private func setupButton() {
let takeBtn = UIButton(type: .system)
takeBtn.backgroundColor = Color.primary
takeBtn.setTitleColor(UIColor.white, for: .normal)
takeBtn.setTitle("Let's start", for: .normal)
takeBtn.titleLabel?.font = .boldSystemFont(ofSize: 18)
takeBtn.layer.cornerRadius = 8
view.addSubview(takeBtn)
takeBtn.setConstraint(bottomAnchor: view.safeAreaLayoutGuide.bottomAnchor, bottomAnchorConstant: -16,
leadingAnchor: view.layoutMarginsGuide.leadingAnchor,
trailingAnchor: view.layoutMarginsGuide.trailingAnchor,
heighAnchorConstant: 50)
takeBtn.addTarget(self, action: #selector(handlePlanning(_:)), for: .touchUpInside)
}
@objc private func handlePlanning(_ button:UIButton) {
let vc = PlanningViewController()
guard let title = navigationItem.title else { return }
vc.titleHabit = title
vc.type = self.type
navigationController?.pushViewController(vc, animated: true)
}
}
| true
|
8f1a67dcba231dc208dbe2836dbeb6fe944cc3b7
|
Swift
|
joon-so/SmartphoneGameProgramming
|
/Anagrams Part1 Starter/Anagrams/TargetView.swift
|
UTF-8
| 713
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// TargetView.swift
// Anagrams
//
// Created by KPUGAME on 2021/04/25.
// Copyright © 2021 Caroline. All rights reserved.
//
import Foundation
import UIKit
class TargetView: UIImageView {
var letter: Character
var isMatched: Bool = false
required init?(coder aDecoder: NSCoder) {
fatalError("use init(letter:, sideLength:)")
}
init(letter: Character, sideLength: CGFloat) {
self.letter = letter
let image = UIImage(named: "slot")!
super.init(image: image)
let scale = sideLength / image.size.width
self.frame = CGRect(x: 0, y: 0, width: image.size.width * scale, height: image.size.height * scale)
}
}
| true
|
79a9acf46b21b09170ae1252260bef03acdcd2b2
|
Swift
|
ShrifDarwish7/TheBest-Restaurant
|
/TheBest-iOS-Restaurant/UI-Helpers/Drawer.swift
|
UTF-8
| 988
| 2.671875
| 3
|
[] |
no_license
|
import Foundation
import UIKit
class Drawer{
static func open(_ constraint: NSLayoutConstraint, _ vc: UIViewController){
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
constraint.constant = 0
vc.view.layoutIfNeeded()
NotificationCenter.default.post(name: NSNotification.Name("opened"), object: nil)
}) { (_) in
}
}
static func close(_ constraint: NSLayoutConstraint, _ vc: UIViewController){
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseInOut, animations: {
constraint.constant = "lang".localized == "ar" ? vc.view.frame.width : -vc.view.frame.width
vc.view.layoutIfNeeded()
}) { (_) in
}
}
}
| true
|
1d5d2b90b517ccf4718d55a7e4ae28d435cd7761
|
Swift
|
corbin-r/Plug
|
/Plug/SectionHeader.swift
|
UTF-8
| 111
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
import Cocoa
final class SectionHeader {
let title: String
init(title: String) {
self.title = title
}
}
| true
|
dc9c06411f0de0b6bfcf83fc50f72b09491b93dd
|
Swift
|
thomas-e-cowern/CocktailTime
|
/CocktailTime/CocktailTime/Resources/CustomAlertViewController.swift
|
UTF-8
| 2,198
| 2.59375
| 3
|
[] |
no_license
|
//
// CustomAlertViewController.swift
// CocktailTime
//
// Created by Thomas Cowern New on 2/19/20.
// Copyright © 2020 Thomas Cowern New. All rights reserved.
//
import UIKit
class CustomAlertViewController: UIViewController {
// Outlets
@IBOutlet weak var alertView: UIView!
@IBOutlet weak var alertLabel: UILabel!
@IBOutlet weak var alertTextField: UITextField!
@IBOutlet weak var alertSearchButton: UIButton!
@IBOutlet weak var alertSearchCancelButton: UIButton!
@IBOutlet weak var searchErrorLable: UILabel!
@IBOutlet weak var searchErrorView: UIView!
// MARK: - Properties
var delegate: CustomAlertViewDelegate?
override func viewDidLoad() {
super.viewDidLoad()
alertTextField.becomeFirstResponder()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupView()
animateView()
}
// MARK: - Methods
func setupView() {
alertView.layer.cornerRadius = 15
searchErrorView.layer.cornerRadius = 15
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.4)
}
func animateView() {
alertView.alpha = 0;
self.alertView.frame.origin.y = self.alertView.frame.origin.y + 50
UIView.animate(withDuration: 0.4, animations: { () -> Void in
self.alertView.alpha = 1.0;
self.alertView.frame.origin.y = self.alertView.frame.origin.y - 50
})
}
@IBAction func searchButtonPressed(_ sender: Any) {
alertTextField.resignFirstResponder()
if alertTextField.text == "" {
searchErrorView.isHidden = false
} else {
delegate?.searchButtonTapped(alertTextFieldValue: alertTextField.text ?? "")
self.dismiss(animated: true, completion: nil)
}
}
@IBAction func searchCancelButtonPresses(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
@IBAction func errorOkButtonPressed(_ sender: Any) {
searchErrorView.isHidden = true
}
}
protocol CustomAlertViewControllerDelegate : NSObjectProtocol {
func searchButtonTapped(data: String)
}
| true
|
d5f043dd792f913aeaca03f1832701ac68144df7
|
Swift
|
poafernandes/TarefasApp
|
/TarefasApp/ViewController.swift
|
UTF-8
| 3,175
| 3.0625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TarefasApp
//
// Created by Alexandre on 07/08/21.
//
import UIKit
//Adiciona os métodos para alimentar a Table View com os dados
class ViewController: UIViewController, UITableViewDataSource {
//Definindo o componente básico da lista, a tabela
private let tabela: UITableView = {
let tabela = UITableView()
tabela.register(UITableViewCell.self,
forCellReuseIdentifier: "celula")
return tabela
}()
var items = [String]()
override func viewDidLoad() {
super.viewDidLoad()
//Resgata as notas do usuário ou cria uma array vazia
self.items = UserDefaults.standard.stringArray(forKey: "items") ?? []
title = "Lista de Tarefas"
//Cria a subview para utilizar a tabela
view.addSubview(tabela)
tabela.dataSource = self
//Botão de adicionar nova nota
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(apertouAdd))
}
//Função de abrir o alerta para registrar a nota
@objc private func apertouAdd(){
let modal = UIAlertController(title: "Novo Item", message: "Escreva o item", preferredStyle: .alert)
modal.addTextField{campoTexto in campoTexto.placeholder = "Escreva aqui..."}
//Registra os botões do alerta
modal.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: nil))
modal.addAction(UIAlertAction(title: "Salvar", style: .default, handler: { [weak self] (_) in
if let campoTexto = modal.textFields?.first {
if let texto = campoTexto.text, !texto.isEmpty {
//Busca as notas já salvas do usuário e adiciona a nova, se não tiver cria uma string vazia e começa
DispatchQueue.main.async {
var notas = UserDefaults.standard.stringArray(forKey: "items") ?? []
notas.append(texto)
UserDefaults.standard.setValue(notas, forKey: "items")
self?.items.append(texto)
self?.tabela.reloadData()
}
}
}
}))
present(modal,animated: true)
}
//Atribui a tabela para toda tela
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tabela.frame = view.bounds
}
//Define a quantidade de linhas que a tabela vai ter baseada na quantidade de itens salvos
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
//Cria a celula e alimenta com o texto
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let celula = tableView.dequeueReusableCell(withIdentifier: "celula",
for: indexPath)
celula.textLabel?.text = items[indexPath.row]
return celula
}
}
| true
|
82bc170a80a1be496fe2dcb5ae65c366e3b88628
|
Swift
|
ahmedk92/SlidingWindow
|
/SlidingWindow/ViewController.swift
|
UTF-8
| 4,798
| 2.90625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Prefetched
//
// Created by Ahmed Khalaf on 5/24/19.
// Copyright © 2019 Ahmed Khalaf. All rights reserved.
//
import UIKit
class Cell: UITableViewCell {
@IBOutlet var label: UILabel!
}
struct MyData: ElementType {
let id: Int
let string: String
}
class ViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var nextButton: UIButton!
@IBOutlet private weak var prevButton: UIButton!
@IBOutlet private weak var jumpButton: UIButton!
var jumpIndex = 0
private let step = 10
var currentIndex = 0 {
didSet {
nextButton.setTitle("Forward to \(currentIndex + step)", for: .normal)
prevButton.setTitle("Backward to \(currentIndex - step)", for: .normal)
}
}
@IBAction private func jumpButtonTapped(_ sender: UIButton) {
tableView.scrollToRow(at: IndexPath(row: jumpIndex, section: 0), at: .top, animated: false)
currentIndex = jumpIndex
jumpIndex = (0..<ids.count).randomElement()!
jumpButton.setTitle("Jump to \(jumpIndex)", for: .normal)
}
@IBAction private func nextButtonTapped(_ sender: UIButton) {
guard currentIndex + step < ids.count else { return }
tableView.scrollToRow(at: IndexPath(row: currentIndex + step, section: 0), at: .top, animated: true)
currentIndex += step
}
@IBAction private func prevButtonTapped(_ sender: UIButton) {
guard currentIndex - step >= 0 else { return }
tableView.scrollToRow(at: IndexPath(row: currentIndex - step, section: 0), at: .top, animated: true)
currentIndex -= step
}
private let ids = Array(0...10000)
private lazy var dataWindow = DataWindow<MyData>(ids: ids, windowSize: 50, dataFetcher: { (ids) in
Thread.sleep(forTimeInterval: TimeInterval((2...10).randomElement()!) / 10) // Simulate Heavy Work
return ids.map({ MyData(id: $0, string: "\($0) \(randomText(length: Int.random(in: 100...1000)))") })
}, errorHandler: { error in
print(error)
}, onElementsReadyHandler: {
DispatchQueue.main.async {
self.tableView.reloadData()
}
})
override func viewDidLoad() {
super.viewDidLoad()
jumpButtonTapped(jumpButton)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// tableView.scrollToRow(at: IndexPath(row: 5000, section: 0), at: .top, animated: false)
}
}
extension ViewController: UITableViewDataSource, UITableViewDataSourcePrefetching {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataWindow.ids.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! Cell
cell.label.text = dataWindow[indexPath.row, block: true]?.string
return cell
}
func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
for indexPath in indexPaths {
let peek = 10
let indicesToPrefetch = [indexPath.row + peek, indexPath.row - peek]
for indexToPrefetch in indicesToPrefetch {
print("Will prefetch \(indexToPrefetch)")
dataWindow.prefetch(index: indexToPrefetch)
}
}
}
}
//extension ViewController: UITableViewDelegate {
// func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// return 50
// }
//}
// Credits: https://gist.github.com/skreutzberger/eac3edc7918d0251f366
func randomText(length: Int, justLowerCase: Bool = false) -> String {
var text = ""
for _ in 1...length {
var decValue = 0 // ascii decimal value of a character
var charType = 3 // default is lowercase
if justLowerCase == false {
// randomize the character type
charType = Int(arc4random_uniform(4))
}
switch charType {
case 1: // digit: random Int between 48 and 57
decValue = Int(arc4random_uniform(10)) + 48
case 2: // uppercase letter
decValue = Int(arc4random_uniform(26)) + 65
case 3: // lowercase letter
decValue = Int(arc4random_uniform(26)) + 97
default: // space character
decValue = 32
}
// get ASCII character from random decimal value
let char = String(UnicodeScalar(decValue)!)
text = text + char
// remove double spaces
text = text.replacingOccurrences(of: " ", with: " ")
}
return text
}
| true
|
df4f5723388a6b9f3c422099dc5f0f89de992508
|
Swift
|
ashishbl86/World-Weather
|
/World Weather/Weather.swift
|
UTF-8
| 4,821
| 3.1875
| 3
|
[] |
no_license
|
//
// Weather.swift
// World Weather
//
// Created by Ashish Bansal on 07/09/20.
// Copyright © 2020 Ashish Bansal. All rights reserved.
//
import Foundation
struct Location {
var latitude: Float
var longitude: Float
}
class Weather {
private (set) var temp = 0.0
private (set) var feelsLikeTemp = 0.0
private (set) var humidity = 0.0
private (set) var isAvailable = false
private (set) var iconData = Data()
private (set) var description = ""
private var weatherService: WeatherService
private var sortedCitiesList = [String]()
private var cityNameToId = [String:Int]()
private func loadCityList() -> (cityNameToIdMap: [String:Int], sortedCitiesList: [String]) {
let startTime = Date()
var cities = [String:Int]()
let cityListFileUrl = Bundle.main.url(forResource: "city.list", withExtension: "json")
if let cityListFileUrl = cityListFileUrl,
let fileData = try? Data(contentsOf: cityListFileUrl),
let jsonData = try? JSONSerialization.jsonObject(with: fileData) {
let cityInfoList = jsonData as! [Any]
for cityInfo in cityInfoList {
let cityDict = cityInfo as! [String:Any]
let cityName = cityDict["name"] as! String
if cityName.count > 1 {
let countryName = cityDict["country"] as! String
let cityId = cityDict["id"] as! Int
cities[cityName+","+countryName] = cityId
}
}
}
var cityList = cities.map { $0.key }
cityList.sort()
let elapsedTime = DateInterval(start: startTime, end: Date()).duration
print("Time taken to load city list \(elapsedTime)")
return (cities,cityList)
}
init(weatherService: WeatherService) {
self.weatherService = weatherService
let cityData = loadCityList()
self.cityNameToId = cityData.cityNameToIdMap
self.sortedCitiesList = cityData.sortedCitiesList
}
func getCities(withNamePrefix prefix: String, searchResultLimit: Int) -> [String] {
let searchPredicate: (String) -> Bool = { cityName in
let lowercasedCityName = cityName.lowercased()
return lowercasedCityName.hasPrefix(prefix.lowercased())
}
if let firstIndex = sortedCitiesList.firstIndex(where: searchPredicate) {
let lastIndex = sortedCitiesList.lastIndex(where: searchPredicate)!
let searchLimitIndex = sortedCitiesList.index(firstIndex, offsetBy: searchResultLimit - 1, limitedBy: lastIndex) ?? lastIndex
return [String](sortedCitiesList[firstIndex...searchLimitIndex])
}
return []
}
func update(forCity cityName: String, _ completionHandler: @escaping (Bool) -> Void) {
weatherService.getWeatherData(forCityId: cityNameToId[cityName]!) { result in
switch result {
case .success(let weatherData):
self.parseAndRetrieveWeatherData(from: weatherData, completionHandler)
case .failure(_):
self.isAvailable = false
completionHandler(false)
}
}
}
private func parseAndRetrieveWeatherData(from jsonDict: [String: Any], _ completion: @escaping (Bool) -> Void) {
guard let mainWeatherData = jsonDict["main"] as? [String:Double] else {
self.isAvailable = false
completion(false)
return
}
guard let weatherData = jsonDict["weather"] as? [Any],
let primaryWeatherData = weatherData.first as? [String:Any],
let weatherIconName = primaryWeatherData["icon"] as? String,
let weatherDescription = primaryWeatherData["description"] as? String else {
self.isAvailable = false
completion(false)
return
}
guard let temp = mainWeatherData["temp"],
let feelsLikeTemp = mainWeatherData["feels_like"],
let humidity = mainWeatherData["humidity"] else {
self.isAvailable = false
completion(false)
return
}
self.temp = temp
self.feelsLikeTemp = feelsLikeTemp
self.humidity = humidity
self.description = weatherDescription
weatherService.getWeatherIcon(forIconName: weatherIconName) { result in
switch result {
case .success(let iconData):
self.iconData = iconData
self.isAvailable = true
completion(true)
case .failure(_):
completion(false)
}
}
}
}
| true
|
0f4061434cfdac47ad966755ee545597caae5175
|
Swift
|
seenashafai/Sorting-Algorithms
|
/Sorting Algorithms/Numbers.swift
|
UTF-8
| 751
| 3.296875
| 3
|
[] |
no_license
|
//
// Numbers.swift
// Sorting Algorithms
//
// Created by Seena Shafai on 06/05/2018.
// Copyright © 2018 Seena Shafai. All rights reserved.
//
import Foundation
class Numbers
{
//MARK: Random Number Generator
func randNumGenerator() -> [Int]
{
var a = [Int]()
for _ in 0...9
{
let randNum = Int(arc4random_uniform(21))
a.append(randNum)
}
return a
}
//MARK: Array Concatenator
func joinArray(array: [Int]) -> String
{
var string: String = ""
var a = array
let len = a.count
for i in 0 ..< len
{
string = string + String(a[i]) + ", "
}
return string
}
}
| true
|
51d808c1139a64094a5a1d84f5b96803fc9a1c26
|
Swift
|
fileio/FLTickerSlider
|
/FLTickerSlider/src/FLSliderTick.swift
|
UTF-8
| 3,366
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// FLSliderChunk.swift
// fileio
//
// Created by TsuzukiTomoaki on 2016/09/13.
// Copyright © 2016年 fileio. All rights reserved.
//
import UIKit
open class FLSliderTick {
public enum Shape {
case rect
case round
}
/// shadow attribute
public struct Shadow {
var color: UIColor
var offset: CGSize
var opacity: Float
var radius: CGFloat
public init(color: UIColor, offset: CGSize, opacity: Float, radius: CGFloat) {
self.color = color
self.offset = offset
self.opacity = opacity
self.radius = radius
}
}
open var height: CGFloat
open var width: CGFloat
open var offset: CGFloat
open var color: UIColor
open var shape: Shape
open var shadow: Shadow?
open var alpha: CGFloat = 1.0
/// create ticker
/// - parameter offset: must be between FLTickerSlider min max value
public init(offset: CGFloat) {
self.shape = Shape.round
self.height = 10
self.width = 10
self.offset = offset
self.color = UIColor(red: 0.718, green: 0.718, blue: 0.718, alpha: 1)
}
/// create ticker
/// - parameter offset: must be between FLTickerSlider min max value
/// - parameter color: ticker color
/// - parameter shadow: ticker shadow
public init(offset: CGFloat, color: UIColor, shadow: Shadow?) {
self.shadow = shadow
self.shape = Shape.round
self.height = 10
self.width = 10
self.offset = offset
self.color = color
}
/// create ticker
/// - parameter width: width of ticker in px
/// - parameter height: height of ticker in px
/// - parameter offset: must be between FLTickerSlider min max value
/// - parameter color: ticker color
/// - parameter shadow: ticker shadow
public init(offset: CGFloat, color: UIColor, shadow: Shadow?, width: CGFloat, height: CGFloat, shape: Shape) {
self.shape = shape
self.shadow = shadow
self.height = height
self.width = width
self.offset = offset
self.color = color
}
func createTickView(slider: FLTickerSlider, thumbRect: CGRect) -> UIView {
let thumbWidth = thumbRect.size.width
let sliderWidth = slider.frame.size.width - thumbWidth
let sliderHeight = slider.frame.size.height
let offset = self.offset * sliderWidth - self.width / 2 + thumbWidth / 2
let tickerView = UIView()
tickerView.backgroundColor = self.color
tickerView.alpha = self.alpha
if self.shape == FLSliderTick.Shape.round {
tickerView.layer.cornerRadius = self.height / 2;
}
if self.shadow != nil {
tickerView.layer.shadowColor = self.shadow!.color.cgColor
tickerView.layer.shadowOffset = self.shadow!.offset
tickerView.layer.shadowOpacity = self.shadow!.opacity
tickerView.layer.shadowRadius = self.shadow!.radius
}
tickerView.frame = CGRect(x: offset,
y: sliderHeight / 2 - self.height / 2,
width: self.width,
height: self.height)
return tickerView
}
}
| true
|
e7f88cadc3330b335c866ebf5698e906d7cf0ca3
|
Swift
|
ZuopanYao/swift-utils
|
/Sources/Utils/geom/svg/graphic/SVGPolygon.swift
|
UTF-8
| 1,731
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
/**
* Draws a polygon based on points, closes it self to the first point
*/
class SVGPolygon:SVGGraphic,SVGPolyLineKind{
var points:[CGPoint]
init(_ points:[CGPoint], _ style : SVGStyle? = nil, _ id : String? = nil) {
self.points = points
super.init(style, id)
}
/**
* NOTE: Miter-limit is hard: you have the complete set of math tools to solve this in the reserach-paper named: BodySegment with acompaning file called BodySegment Tail Head etc. The code works.
* NOTE: this method calls two sub methods so that SVGPolyLine can use this class as a base method
*/
override func draw() {
guard let style = style else {return}
let boundingBox:CGRect = CGPointParser.rectangle(points)/*Fill, We need the bounding box in order to set the frame*/
if style.fill != nil {/*Fill*/
fillShape.path = CGPathParser.lines(points,true,CGPoint(-boundingBox.x,-boundingBox.y))/*<--We offset so that the lines draw from 0,0 relative to the frame*/
fillShape.frame = boundingBox/*The positioning happens in the frame*/
}
if style.stroke != nil {/*Line,checks if there is a stroke in style*/
let strokeBoundingBox:CGRect = SVGStyleUtils.boundingBox(fillShape.path, style)// + boundingBox.origin
let linePathOffset:CGPoint = CGPointParser.difference(strokeBoundingBox.origin,CGPoint(0,0))
lineShape.frame = (strokeBoundingBox + boundingBox.origin).copy()
lineShape.path = CGPathParser.polyLine(points,true,CGPoint(-boundingBox.x,-boundingBox.y) + linePathOffset)
}
}
required init(coder: NSCoder) {fatalError("init(coder:) has not been implemented")}
}
| true
|
f8dea8157566bd4268084d6d7e8f6c53927925ef
|
Swift
|
Sagarpatil3339/RapptrLabsApp
|
/iOSTest/View Controllers/LoginViewController.swift
|
UTF-8
| 5,339
| 2.765625
| 3
|
[] |
no_license
|
//
// LoginViewController.swift
// iOSTest
//
// Copyright © 2020 Rapptr Labs. All rights reserved.
import UIKit
extension UITextField {
func setLeftPaddingPoints(_ amount:CGFloat){
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
self.leftView = paddingView
self.leftViewMode = .always
}
func setRightPaddingPoints(_ amount:CGFloat) {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: amount, height: self.frame.size.height))
self.rightView = paddingView
self.rightViewMode = .always
}
}
class LoginViewController: UIViewController {
/**
* =========================================================================================
* INSTRUCTIONS
* =========================================================================================
* 1) Make the UI look like it does in the mock-up.
*
* 2) Take email and password input from the user
*
* 3) Use the endpoint and paramters provided in LoginClient.m to perform the log in
*
* 4) Calculate how long the API call took in milliseconds
*
* 5) If the response is an error display the error in a UIAlertController
*
* 6) If the response is successful display the success message AND how long the API call took in milliseconds in a UIAlertController
*
* 7) When login is successful, tapping 'OK' in the UIAlertController should bring you back to the main menu.
**/
// MARK: - Properties
private var client: LoginClient?
@IBOutlet weak var userName: UITextField!
@IBOutlet weak var passWord: UITextField!
@IBOutlet weak var login: UIButton!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = "Login"
setUp()
}
func setUp(){
let backgroundImage1 = UIImageView(frame: UIScreen.main.bounds)
backgroundImage1.image = UIImage(named: "img_login")
backgroundImage1.contentMode = UIView.ContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage1, at: 0)
userName.backgroundColor = UIColor.init(white: 1, alpha: 0.5)
userName.borderStyle = .none
userName.layer.cornerRadius = 6
userName.setLeftPaddingPoints(24)
passWord.backgroundColor = UIColor.init(white: 1, alpha: 0.5)
passWord.borderStyle = .none
passWord.layer.cornerRadius = 6
passWord.setLeftPaddingPoints(24)
login.backgroundColor = UIColor(hexString: "#0E5C89")
login.setTitleColor(UIColor.white, for: .normal)
}
@IBAction func didPressLoginButton(_ sender: Any) {
guard let userName = self.userName.text , let passWord = self.passWord.text else {
return;
}
let endPoint = "http://dev.rapptrlabs.com/Tests/scripts/login.php"
guard let endpointUrl = URL(string: endPoint) else {
return;
}
var params = [String:Any]();
params.updateValue(userName, forKey: "email")
params.updateValue(passWord, forKey: "password");
do {
let data = try JSONSerialization.data(withJSONObject: params, options: []);
var request = URLRequest(url: endpointUrl)
request.httpMethod = "POST";
request.httpBody = data;
request.setValue("text/html", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept");
let methodStart = Date()
httpResponse(request: request) { (received_data, error) in
let methodFinish = Date()
guard received_data != nil else {
let executionTime = methodFinish.timeIntervalSince(methodStart)
DispatchQueue.main.async{
let alert = UIAlertController(title: error as? String, message: "Server Unavailable: Timer Count: \(executionTime)", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
return
}
let executionTime = methodFinish.timeIntervalSince(methodStart)
let alert = UIAlertController(title: "Success", message: "Timer Count: \(executionTime)", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
catch {
print(error.localizedDescription as Any);
}
}
}
| true
|
701e62e024add191786770a32edca7efeff57d4c
|
Swift
|
elvismetaphor/todo-os-swift
|
/ToDoList/Controllers/AddToDoItemViewController.swift
|
UTF-8
| 1,246
| 2.84375
| 3
|
[] |
no_license
|
//
// AddToDoItemViewController.swift
// ToDoList
//
// Created by Peter Cheng on 26/4/2018.
// Copyright © 2018 d. All rights reserved.
//
import UIKit
class AddToDoItemViewController: UIViewController {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func save(_ sender: Any) {
saveValidTask()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textField.returnKeyType = UIReturnKeyType.done
textField.delegate = self
textField.becomeFirstResponder()
}
private func saveValidTask() {
if let taskName = textField.text, !taskName.isEmpty {
TodoList.shared.addTask(taskName)
dismiss(animated: true, completion: nil)
}
}
}
extension AddToDoItemViewController: UITextFieldDelegate {
func textFieldDidEndEditing(_ textField: UITextField) {
saveValidTask()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| true
|
42a630bf9262a40f971537e417fdbcbb1a3003ca
|
Swift
|
angryscorp/Swedbank
|
/Swedbank/CoreData/CoreDataStack/CoreDataStack.swift
|
UTF-8
| 1,356
| 2.765625
| 3
|
[] |
no_license
|
//
// CoreDataStack.swift
// Swedbank
//
// Created by Antony Karpov on 08/07/2018.
// Copyright © 2018 Antony Karpov. All rights reserved.
//
import CoreData
/// Provides the basic functionality of Core Data Stack.
class CoreDataStack: CoreDataStackProtocol {
/// Returns a shared singleton of Core Data Stack, that gives a reasonable default behavior.
static let shared = CoreDataStack()
private init() { }
// MARK: CORE DATA STACK
/// Main Persistent container of Core Data Stack.
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Swedbank")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
if let sourceURL = error.userInfo["sourceURL"] as? URL {
if FileManager.default.fileExists(atPath: sourceURL.path) {
try? FileManager.default.removeItem(atPath: sourceURL.path)
print("Error of initialize database, the storage is deleted [\(sourceURL.path)]")
}
}
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
return container
}()
}
| true
|
cf0cee0de41ff21df8c11920ac6a99824d46beb5
|
Swift
|
konekoya/assess-app
|
/Assess/Components/Login.swift
|
UTF-8
| 1,698
| 3.21875
| 3
|
[] |
no_license
|
//
// Login.swift
// Assess
//
// Created by Joshua on 2021/4/19.
//
import SwiftUI
struct UsernameTextField: View {
@Binding var username: String
var body: some View {
TextField("帳號", text: $username)
.font(.subheadline)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
struct PasswordTextField: View {
@Binding var password: String
var body: some View {
SecureField("密碼", text: $password)
.font(.subheadline)
.textFieldStyle(RoundedBorderTextFieldStyle())
}
}
struct Login: View {
@State private var username = ""
@State private var password = ""
@State var authenticationDidFail = false
@State var isLinkActive = false
var body: some View {
VStack{
Text("登入系統")
.fontWeight(/*@START_MENU_TOKEN@*/.bold/*@END_MENU_TOKEN@*/)
.foregroundColor(Color.black.opacity(0.8))
.font(.title)
.padding(.bottom, 30)
UsernameTextField(username: $username)
PasswordTextField(password: $password)
if authenticationDidFail {
Text("Information not correct. Try again.")
.font(.subheadline)
.foregroundColor(.red)
}
NavigationLink(destination: Settings(), isActive: $isLinkActive) {
Button(action: {
self.isLinkActive = true
}) {
Text("登入")
}
.foregroundColor(.white)
.padding(8)
.frame(maxWidth: .infinity)
.background(Color.blue)
.cornerRadius(5)
}.disabled(self.username.isEmpty || self.password.isEmpty)
}
}
}
struct Login_Previews: PreviewProvider {
static var previews: some View {
Login()
}
}
| true
|
dce63ceab7a94414b5f0bce43d5649c6ea0898a1
|
Swift
|
magic-IOS/leetcode-swift
|
/0172. Factorial Trailing Zeroes.swift
|
UTF-8
| 742
| 3.15625
| 3
|
[
"Apache-2.0"
] |
permissive
|
class Solution {
// 172. Factorial Trailing Zeroes
// Given an integer n, return the number of trailing zeroes in n!.
// Follow up: Could you write a solution that works in logarithmic time complexity?
// Example 1:
// Input: n = 3
// Output: 0
// Explanation: 3! = 6, no trailing zero.
// Example 2:
// Input: n = 5
// Output: 1
// Explanation: 5! = 120, one trailing zero.
// Example 3:
// Input: n = 0
// Output: 0
// Constraints:
// 0 <= n <= 10^4
func trailingZeroes(_ n: Int) -> Int {
var num = n
var count = 0
while num > 0 {
count += num / 5
num /= 5
}
return count
}
}
| true
|
711ca9d524b69a5dac36a9ed4594dba40b6c67fd
|
Swift
|
ricardorachaus/ios-recruiting-brazil
|
/Movs/Movs/Scenes/Filters/Views/Filters/TableView/FiltersTableView.swift
|
UTF-8
| 1,391
| 2.546875
| 3
|
[] |
no_license
|
//
// FiltersTableView.swift
// Movs
//
// Created by Ricardo Rachaus on 02/11/18.
// Copyright © 2018 Ricardo Rachaus. All rights reserved.
//
import UIKit
class FiltersTableView: UITableView {
lazy var date: FiltersTableViewCell = {
let view = FiltersTableViewCell(frame: .zero)
view.accessoryType = .disclosureIndicator
view.detailTextLabel?.text = ""
view.detailTextLabel?.textColor = UIColor.Movs.lightYellow
view.textLabel?.text = "Date"
return view
}()
lazy var genre: FiltersTableViewCell = {
let view = FiltersTableViewCell(frame: .zero)
view.accessoryType = .disclosureIndicator
view.detailTextLabel?.text = ""
view.detailTextLabel?.textColor = UIColor.Movs.lightYellow
view.textLabel?.text = "Genres"
return view
}()
override init(frame: CGRect = .zero, style: UITableView.Style) {
super.init(frame: frame, style: style)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
}
extension FiltersTableView: CodeView {
func buildViewHierarchy() {
addSubview(date)
addSubview(genre)
}
func setupConstraints() {}
func setupAdditionalConfiguration() {
backgroundColor = .clear
isScrollEnabled = false
}
}
| true
|
47d6df8c54bed7b7a4ba2249012880c810ef91b3
|
Swift
|
cocoatoucher/Glide
|
/Sources/Collisions/Models/CollisionTileMapRepresentation.swift
|
UTF-8
| 9,436
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// CollisionTileMapRepresentation.swift
// glide
//
// Copyright (c) 2019 cocoatoucher user on github.com (https://github.com/cocoatoucher/)
//
// 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 SpriteKit
/// Represents a tile map populated with collider tiles.
struct CollisionTileMapRepresentation {
let mapSize: CGSize
let tileSize: CGSize
private let tileRepresentations: [[ColliderTileRepresentation?]]
private(set) var cornerJumps: [TiledPoint] = []
private(set) var columnsToGaps: [Int: [(Int, Int)]] = [:]
private(set) var slopeContexts: [SlopeContext] = []
var numberOfColumns: Int {
return tileRepresentations.count
}
var numberOfRows: Int {
return tileRepresentations.first?.count ?? 0
}
init(tileMap: SKTileMapNode) {
self.init(tileRepresentations: tileMap.tileRepresentations, tileSize: tileMap.tileSize)
}
init(tileRepresentations: [[ColliderTileRepresentation?]], tileSize: CGSize) {
let columnCount = tileRepresentations.count
let rowCount = tileRepresentations.first?.count ?? 0
assert(tileRepresentations.allSatisfy { $0.count == rowCount })
self.mapSize = TiledSize(columnCount, rowCount).size(with: tileSize)
self.tileSize = tileSize
self.tileRepresentations = tileRepresentations
self.slopeContexts = slopeContextsFromTileRepresentations()
self.cornerJumps = cornerJumpsAndGaps.cornerJumps
self.columnsToGaps = cornerJumpsAndGaps.columnsToGaps
}
func slopeContext(at location: TiledPoint) -> SlopeContext? {
return slopeContexts.first { $0.tilePositions.first { $0 == location } != nil }
}
/// Returns tiled range of tiles around a given frame.
func tileRangeAroundFrame(_ frame: CGRect) -> TiledRange {
var leftwardsTileColumnIndex = tileColumnIndex(at: frame.origin.x) - 1
leftwardsTileColumnIndex = leftwardsTileColumnIndex.clamped(0 ..< numberOfColumns)
var rightwardsTileColumnIndex = tileColumnIndex(at: frame.maxX) + 1
rightwardsTileColumnIndex = rightwardsTileColumnIndex.clamped(0 ..< numberOfColumns)
var upwardsTileRowIndex = tileRowIndex(at: frame.maxY) + 1
upwardsTileRowIndex = upwardsTileRowIndex.clamped(0 ..< numberOfRows)
var downwardsTileRowIndex = tileRowIndex(at: frame.origin.y) - 1
downwardsTileRowIndex = downwardsTileRowIndex.clamped(0 ..< numberOfRows)
return TiledRange(left: leftwardsTileColumnIndex,
right: rightwardsTileColumnIndex,
top: upwardsTileRowIndex,
bottom: downwardsTileRowIndex)
}
func tileRepresentationAt(column: Int, row: Int) -> ColliderTileRepresentation? {
return tileRepresentations[column][row]
}
// MARK: - Private
private func tileColumnIndex(at xPosition: CGFloat) -> Int {
return Int(xPosition / tileSize.width)
}
private func tileRowIndex(at yPosition: CGFloat) -> Int {
return Int(yPosition / tileSize.height)
}
private func slopeContextsFromTileRepresentations() -> [SlopeContext] {
class TemporarySlopeContext {
var tilePositions: [TiledPoint] = []
let isInverse: Bool
init(isInverse: Bool) {
self.isInverse = isInverse
}
}
var result = [SlopeContext]()
var lastSlopeContext: TemporarySlopeContext?
for column in 0 ..< numberOfColumns {
for row in 0 ..< numberOfRows {
guard let tileRepresentation = tileRepresentations[column][row] else {
continue
}
if tileRepresentation.tile.isSlope == true {
let leftValue = tileRepresentation.tile.slopeLeftValue
let rightValue = tileRepresentation.tile.slopeRightValue
let direction = (leftValue < rightValue) ? -1 : 1
let isInverseSlope = direction == -1
if direction == 1 && leftValue == 15 || direction == -1 && leftValue == 0 {
if
let lastContext = lastSlopeContext,
let slopeContext = SlopeContext(tilePositions: lastContext.tilePositions, isInverse: lastContext.isInverse)
{
result.append(slopeContext)
}
lastSlopeContext = TemporarySlopeContext(isInverse: isInverseSlope)
lastSlopeContext?.tilePositions.append(TiledPoint(column, row))
} else {
if let lastContext = lastSlopeContext {
lastContext.tilePositions.append(TiledPoint(column, row))
} else {
lastSlopeContext = TemporarySlopeContext(isInverse: isInverseSlope)
lastSlopeContext?.tilePositions.append(TiledPoint(column, row))
}
}
}
}
}
if
let lastContext = lastSlopeContext,
let slopeContext = SlopeContext(tilePositions: lastContext.tilePositions, isInverse: lastContext.isInverse)
{
result.append(slopeContext)
lastSlopeContext = nil
}
return result
}
private lazy var cornerJumpsAndGaps: (cornerJumps: [TiledPoint], columnsToGaps: [Int: [(Int, Int)]]) = {
var columnsToGaps: [Int: [(Int, Int)]] = [:]
var cornerJumps: [TiledPoint] = []
for column in 0 ..< tileRepresentations.count {
var currentGaps: [(Int, Int)] = []
var lastGapStartRow: Int?
let tileRepresentationsForCurrentColumn = tileRepresentations[column]
for row in 0 ..< tileRepresentationsForCurrentColumn.count {
let tileRepresentation = tileRepresentationsForCurrentColumn[row]
if let tileRep = tileRepresentation, tileRep.tile.isGroundOrOneWay {
if column - 1 >= 0 && row + 1 < tileRepresentationsForCurrentColumn.count {
let leftTileRepresentation = tileRepresentations[column - 1][row]
let upTileRepresentation = tileRepresentations[column][row + 1]
if leftTileRepresentation == nil && upTileRepresentation == nil {
if cornerJumps.contains(TiledPoint(column - 1, row)) == false {
cornerJumps.append(TiledPoint(column - 1, row))
}
}
}
if column + 1 < tileRepresentations.count && row + 1 < tileRepresentationsForCurrentColumn.count {
let rightTileRepresentation = tileRepresentations[column + 1][row]
let upTileRepresentation = tileRepresentations[column][row + 1]
if rightTileRepresentation == nil && upTileRepresentation == nil {
if cornerJumps.contains(TiledPoint(column + 1, row)) == false {
cornerJumps.append(TiledPoint(column + 1, row))
}
}
}
}
if tileRepresentation == nil {
if lastGapStartRow == nil {
lastGapStartRow = row
}
} else {
if let startRow = lastGapStartRow {
currentGaps.append((startRow, row - 1))
lastGapStartRow = nil
}
}
}
if let startRow = lastGapStartRow {
currentGaps.append((startRow, tileRepresentationsForCurrentColumn.count - 1))
}
columnsToGaps[column] = currentGaps
}
return (cornerJumps: cornerJumps, columnsToGaps: columnsToGaps)
}()
}
| true
|
9538e06064862b0babdb12e003e20ac2db268e38
|
Swift
|
dlewanda/DailyMemories
|
/Daily Memories/Views/YearNavigationView.swift
|
UTF-8
| 1,862
| 2.5625
| 3
|
[] |
no_license
|
//
// YearListView.swift
// Daily Memories
//
// Created by David Lewanda on 2/22/20.
// Copyright © 2020 LewandaCode. All rights reserved.
//
import Photos.PHAsset
import SwiftUI
import DailyMemoriesSharedCode
struct YearNavigationView: View {
@ObservedObject var contentFetcher = ContentFetcher.shared
var yearlyAssetsArray: [YearlyAssets] {
contentFetcher.yearlyAssets
}
@State var showingNotificationSettings = false
var body: some View {
NavigationView {
Group {
if yearlyAssetsArray.isEmpty {
VStack {
ImageView(image: ImageView.defaultImage())
Text("No Memories for Today").font(.largeTitle)
}
.padding()
}
else {
YearListView()
}
}
.navigationBarTitle(Text("Daily Memories"))
.navigationBarItems(
leading: Button(action: {
self.contentFetcher.refreshAssets()
}) {
Image(systemName:"arrow.up.arrow.down.circle.fill").font(.largeTitle)
},
trailing: Button(action: {
self.showingNotificationSettings.toggle()
NotificationsManager.shared.requestNotificationAccess()
}) {
Image(systemName: "bell.circle.fill").font(.largeTitle)
}.sheet(isPresented: $showingNotificationSettings){
return NotificationSettingsView(showSettings: self.$showingNotificationSettings)
})
}
.phoneOnlyStackNavigationView()
}
}
struct YearNavigationView_Previews: PreviewProvider {
static var previews: some View {
YearNavigationView()
}
}
| true
|
9783047e80144b86db43e151188f01e455c8af0d
|
Swift
|
ryan-strom/flowers_iosdev
|
/Species.swift
|
UTF-8
| 753
| 2.5625
| 3
|
[] |
no_license
|
//
// Species.swift
// flowers
//
// Created by Ryan Stromberg on 4/10/16.
// Copyright © 2016 Ryan Stromberg. All rights reserved.
//
import UIKit
class Species: NSObject {
var id : Int
var common_name : String
var scientific_name : String = ""
var locations : Array<String> = Array<String>()
var flower_color: String = ""
var growth_form: String = ""
var growth_habit: String = ""
var growth_duration: Array<String> = Array<String>()
var growth_rate: String = ""
var active_growth_period: String = ""
var shape: String = ""
var lifespan: String = ""
var toxicity: String = ""
init(id:Int, common_name:String){
self.id = id
self.common_name = common_name
}
}
| true
|
4b09db99dc1c3202d316427fca486b6ab794b7fd
|
Swift
|
Gonzalo9823/Space-Fighter
|
/Space Fighter/GameScene.swift
|
UTF-8
| 29,312
| 2.53125
| 3
|
[] |
no_license
|
//
// GameScene.swift
// NoName
//
// Created by Gonzalo Caballero on 7/6/16.
// Copyright (c) 2016 Gonzalo Caballero. All rights reserved.
//
import SpriteKit
import GameplayKit
import AVFoundation
struct Fisica {
static let none : UInt32 = 0 //00000000
static let player : UInt32 = 0b1 //00000001
static let object : UInt32 = 0b10 //00000011
static let bullets : UInt32 = 0b100 //00000111
static let objectPowerUp : UInt32 = 0b1000 //00001111
static let labelOption : UInt32 = 0b10000 //00011111
}
class GameScene: SKScene, SKPhysicsContactDelegate {
//MARK: - Variables
let defaults = NSUserDefaults.standardUserDefaults()
var viewController: GameViewController!
var hero : SKSpriteNode!
var controllerAfuera : SKSpriteNode!
var controllerAdentro : SKSpriteNode!
var fireButtonAfuera : SKSpriteNode!
var fireButtonAdentro : SKSpriteNode!
var disparo : SKSpriteNode!
var meteor : SKSpriteNode!
var powerUpMeteor : SKSpriteNode!
var timerFirstLevel = NSTimer()
var timerSecondLevel = NSTimer()
var timer2 = NSTimer()
var selectedNodes = [UITouch:SKSpriteNode]()
var meteorAnimation = Array<SKTexture>()
var powerUpMeteorAnimation = Array<SKTexture>()
var numberOfHits = 0
var gameOver: SKLabelNode!
var restartButton: SKSpriteNode!
var uploadRecord: SKSpriteNode!
var timesFire: SKSpriteNode!
var fireNumber = 0
var score = 0
var scoreLabel : SKLabelNode!
var canFire = true
var alive = true
var speedOfMeteor : NSTimeInterval = 5
var seconds = 1.8
var gameMusic: AVAudioPlayer!
var menuButton: SKSpriteNode!
let halfPie = CGFloat(M_PI / 2)
var preferredLanguages : NSLocale!
var espanol = false
enum Dificulty: String{
case Easy = "Easy"
case Medium = "Medium"
case Hard = "Hard"
}
var currentDificulty: Dificulty = .Medium
//MARK: - GAME LIFE CYCLE
override func didMoveToView(view: SKView) {
// This way it knows at what size should show the nodes
let scaleRatio = self.frame.width / 667
let scaleRatioiPhone5 = self.frame.width / 568
let scaleRatioiPhone4 = self.frame.width / 480
//Gets the language of the device if it's spanish shows everything on spanish
let pre = NSLocale.preferredLanguages()[0]
if (pre.rangeOfString("es") != nil) {
espanol = true
}
// Get's the saved value for the music
let playMusic = defaults.boolForKey("Musica")
// See if it should play the background music
func playBackGroundMusic() {
let path = NSBundle.mainBundle().pathForResource("Juegoiphone.wav", ofType:nil)!
let url = NSURL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOfURL: url)
gameMusic = sound
sound.numberOfLoops = -1
sound.play()
} catch {
// couldn't load file :(
}
}
if playMusic == false {
playBackGroundMusic()
}
//Gets the dificulty
if let estado = defaults.objectForKey("Dificultad") as? String {
currentDificulty = Dificulty(rawValue: estado)!
}
switch currentDificulty {
case .Easy:
speedOfMeteor = 6
case .Medium:
speedOfMeteor = 5
case .Hard:
speedOfMeteor = 3.5
}
//Animacion de meteoro
for i in 1...30 {
meteorAnimation.append(SKTexture(imageNamed: "rocks-\(i)"))
}
//Animacion de meteoro Power Up
for i in 1...30 {
powerUpMeteorAnimation.append(SKTexture(imageNamed: "small-rocks-\(i)"))
}
//Barra de disparo
timesFire = SKSpriteNode(imageNamed: "0fires")
timesFire.setScale(0.1 * scaleRatio)
if scaleRatioiPhone5 == 1 {
timesFire.position = CGPoint(x: self.frame.width / 2 - 150, y: self.frame.height / 2 + 120)
}
else if scaleRatioiPhone4 == 1 {
timesFire.position = CGPoint(x: self.frame.width / 2 - 150, y: self.frame.height / 2 + 110)
}
else {
timesFire.position = CGPoint(x: self.frame.width / 2 - 150, y: self.frame.height / 2 + 150)
}
addChild(timesFire)
//Para la Fisica
physicsWorld.contactDelegate = self
//Timer para bajar la barra de disparo
timer2 = NSTimer.scheduledTimerWithTimeInterval(0.3, target:self, selector: #selector(GameScene.bajarFireNumber), userInfo: nil, repeats: true)
//Score
scoreLabel = SKLabelNode(fontNamed: "VCR OSD Mono")
if espanol {
scoreLabel.text = "Puntaje \(score)"
}
else {
scoreLabel.text = "Score \(score)"
}
scoreLabel.horizontalAlignmentMode = .Center
scoreLabel.fontSize = 40
if scaleRatioiPhone5 == 1 {
scoreLabel.position = CGPoint(x: self.frame.width / 2 + 150, y: self.frame.height / 2 + 105)
}
else if scaleRatioiPhone4 == 1 {
scoreLabel.position = CGPoint(x: self.frame.width / 2 + 150, y: self.frame.height / 2 + 95)
}
else {
scoreLabel.position = CGPoint(x: self.frame.width / 2 + 150, y: self.frame.height / 2 + 135)
}
addChild(scoreLabel)
//Hero
hero = SKSpriteNode(imageNamed: "hero")
hero.setScale(0.03)
hero.name = "hero"
hero.anchorPoint = CGPoint(x: 0.5, y: 0.5)
hero.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
addChild(hero)
hero.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 30, height: 30))
hero.physicsBody?.dynamic = true
hero.physicsBody?.affectedByGravity = false
hero.physicsBody?.categoryBitMask = Fisica.player
hero.physicsBody?.contactTestBitMask = Fisica.object
hero.physicsBody?.collisionBitMask = Fisica.none
//Control
controllerAfuera = SKSpriteNode(color: UIColor.brownColor() , size: CGSize(width: 75, height: 75))
controllerAfuera.position = CGPoint(x: self.frame.width / 2 + 200, y: self.frame.height / 2 - 100)
addChild(controllerAfuera)
controllerAdentro = SKSpriteNode(color: UIColor.greenColor(), size: CGSize(width: 55, height: 55))
controllerAdentro.position = CGPoint(x: self.frame.width / 2 + 200, y: self.frame.height / 2 - 100)
controllerAdentro.name = "adentro"
addChild(controllerAdentro)
//Fire
fireButtonAfuera = SKSpriteNode(color: UIColor.brownColor() , size: CGSize(width: 75, height: 75))
fireButtonAfuera.position = CGPoint(x: self.frame.width / 2 - 200, y: self.frame.height / 2 - 100)
addChild(fireButtonAfuera)
fireButtonAdentro = SKSpriteNode(color: UIColor.greenColor(), size: CGSize(width: 55, height: 55))
fireButtonAdentro.position = CGPoint(x: self.frame.width / 2 - 200, y: self.frame.height / 2 - 100)
fireButtonAdentro.name = "fire"
addChild(fireButtonAdentro)
// Timer para crear el obstaculo cada vez mas rapido
let crearObstaculo = SKAction.runBlock {
self.createMeteor()
self.randomPowerUp()
}
let moveFaster = SKAction.runBlock {
self.moverMasRapido()
}
let waitToMoveFaster = SKAction.waitForDuration(6)
runAction(SKAction.sequence([waitToMoveFaster, moveFaster]))
let wait = SKAction.waitForDuration(1)
let sq = SKAction.sequence([crearObstaculo, wait])
let repeatForever = SKAction.repeatActionForever(sq)
runAction(repeatForever)
}
var tiempoEntreCreacion : NSTimeInterval = 1.3
func moverMasRapido() {
switch currentDificulty {
case .Easy:
tiempoEntreCreacion = 1.8
case .Medium:
tiempoEntreCreacion = 1.3
case .Hard:
tiempoEntreCreacion = 0.6
}
print("First time : \(tiempoEntreCreacion)")
removeActionForKey("meteors")
tiempoEntreCreacion *= 0.8
print("Second time : \(tiempoEntreCreacion)")
let meteorWait = SKAction.waitForDuration(tiempoEntreCreacion)
let crear = SKAction.runBlock {
self.createMeteor()
}
let meteorSq = SKAction.sequence([crear, meteorWait])
let repetir = SKAction.repeatActionForever(meteorSq)
runAction(repetir, withKey: "meteors")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
if let node = self.nodeAtPoint(location) as? SKSpriteNode {
// Assumes sprites are named "sprite"
if (node.name == "adentro") {
selectedNodes[touch] = node
}
else if (node.name == "fire") {
fireButtonAfuera.alpha = 0.5
fireBullet()
}
else if (node.name == "restart") {
restartButton.alpha = 0.4
let transition = SKTransition.fadeWithDuration(1)
let nextScene = GameScene(size: scene!.size)
nextScene.scaleMode = .AspectFill
scene?.view?.presentScene(nextScene, transition: transition)
nextScene.viewController = viewController
}
else if (node.name == "menu") {
let transition = SKTransition.fadeWithDuration(1)
let nextScene = MenuScene2(size: scene!.size)
nextScene.scaleMode = .AspectFill
scene?.view?.presentScene(nextScene, transition: transition)
nextScene.viewController = viewController
}
else if (node.name == "Upload Record") {
let vc = viewController.storyboard?.instantiateViewControllerWithIdentifier("upload")
viewController.presentViewController(vc!, animated: true, completion: nil)
}
}
}
}
var physicsObjectsToRemove = [SKNode]()
let explosion = SKAction.playSoundFileNamed("explsoion", waitForCompletion: false)
func didBeginContact(contact: SKPhysicsContact) {
let playMusic = defaults.boolForKey("Musica")
let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask
if collision == Fisica.bullets | Fisica.object {
if contact.bodyA.node!.name == "meteor" {
physicsObjectsToRemove.append(contact.bodyA.node!)
physicsObjectsToRemove.append(disparo)
let particles = SKEmitterNode(fileNamed: "Smoke")!
particles.position = contact.bodyA.node!.position
particles.numParticlesToEmit = 20
addChild(particles)
if playMusic == false {
self.runAction(explosion)
}
if alive {
score += 1
}
}
else if contact.bodyB.node!.name == "meteor" {
physicsObjectsToRemove.append(contact.bodyB.node!)
disparo.removeFromParent()
let particles = SKEmitterNode(fileNamed: "Smoke")!
particles.position = contact.bodyB.node!.position
particles.numParticlesToEmit = 20
addChild(particles)
if playMusic == false {
self.runAction(explosion)
}
if alive {
score += 1
}
}
}
if collision == Fisica.bullets | Fisica.objectPowerUp {
if contact.bodyA.node!.name == "powerUpMeteor" {
physicsObjectsToRemove.append(contact.bodyA.node!)
physicsObjectsToRemove.append(disparo)
let sound = SKAction.playSoundFileNamed("powerUp", waitForCompletion: false)
if playMusic == false {
self.runAction(sound)
}
let particles = SKEmitterNode(fileNamed: "Smoke")!
particles.position = contact.bodyA.node!.position
particles.numParticlesToEmit = 20
addChild(particles)
if alive {
score += 1
}
numberOfHits = 0
objectAndPlayerCollides()
}
else if contact.bodyB.node!.name == "powerUpMeteor" {
physicsObjectsToRemove.append(contact.bodyB.node!)
physicsObjectsToRemove.append(disparo)
let sound = SKAction.playSoundFileNamed("powerUp", waitForCompletion: false)
if playMusic == false {
self.runAction(sound)
}
let particles = SKEmitterNode(fileNamed: "Smoke")!
particles.position = contact.bodyB.node!.position
particles.numParticlesToEmit = 20
addChild(particles)
if alive {
score += 1
}
numberOfHits = 0
objectAndPlayerCollides()
}
}
if collision == Fisica.player | Fisica.object {
print("Se tocan")
if contact.bodyA.node!.name == "hero" {
numberOfHits += 1
physicsObjectsToRemove.append(contact.bodyB.node!)
let fire = SKEmitterNode(fileNamed: "Fire")!
fire.position = contact.bodyA.node!.position
fire.numParticlesToEmit = 50
addChild(fire)
if alive {
if playMusic == false {
self.runAction(explosion)
}
}
objectAndPlayerCollides()
}
}
else if contact.bodyB.node!.name == "hero" {
numberOfHits += 1
physicsObjectsToRemove.append(contact.bodyA.node!)
let fire = SKEmitterNode(fileNamed: "Fire")!
fire.position = contact.bodyB.node!.position
fire.numParticlesToEmit = 50
addChild(fire)
if alive {
if playMusic == false {
self.runAction(explosion)
}
}
objectAndPlayerCollides()
}
if collision == Fisica.player | Fisica.objectPowerUp {
if contact.bodyA.node!.name == "hero" {
physicsObjectsToRemove.append(contact.bodyB.node!)
let fire = SKEmitterNode(fileNamed: "Fire")!
fire.position = contact.bodyA.node!.position
fire.numParticlesToEmit = 50
addChild(fire)
if alive {
if playMusic == false {
self.runAction(explosion)
}
}
}
} else if contact.bodyB.node!.name == "hero" {
physicsObjectsToRemove.append(contact.bodyA.node!)
let fire = SKEmitterNode(fileNamed: "Fire")!
fire.position = contact.bodyB.node!.position
fire.numParticlesToEmit = 50
addChild(fire)
if alive {
if playMusic == false {
self.runAction(explosion)
}
}
}
}
override func didSimulatePhysics() {
for node in physicsObjectsToRemove {
node.removeFromParent()
}
}
override func update(currentTime: CFTimeInterval) {
if espanol {
scoreLabel.text = "Puntaje \(score)"
}
else {
scoreLabel.text = "Score \(score)"
}
switch fireNumber {
case 0:
timesFire.texture = SKTexture(imageNamed: "0fires")
canFire = true
case 1:
timesFire.texture = SKTexture(imageNamed: "1fire")
canFire = true
//Andrew has a lot of porn on his computer
case 2:
timesFire.texture = SKTexture(imageNamed: "2fire")
canFire = true
case 3:
timesFire.texture = SKTexture(imageNamed: "3fire")
canFire = false
default:
timesFire.texture = SKTexture(imageNamed: "3fire")
canFire = false
}
destroyShootOutsideTheScreen()
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
let location = touch.locationInNode(self)
// Update the position of the sprites
if let node = selectedNodes[touch] {
node.position = location
let touchedNode = nodeAtPoint(location)
if touchedNode.name == "adentro" {
controllerAdentro.position = location
hero.zRotation = getAngle()
}
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch in touches {
if selectedNodes[touch] != nil {
controllerAdentro.position = CGPoint(x: self.frame.width / 2 + 200, y: self.frame.height / 2 - 100)
selectedNodes[touch] = nil
}
fireButtonAfuera.alpha = 1
}
}
func createMeteor() {
let meteor = SKSpriteNode(texture: meteorAnimation[0])
let animateAction = SKAction.animateWithTextures(self.meteorAnimation, timePerFrame: 0.10);
let repeatAction = SKAction.repeatActionForever(animateAction)
meteor.runAction(repeatAction)
meteor.name = "meteor"
meteor.position = getMeteorPosition()
meteor.zPosition = 2
meteor.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 30, height: 30))
meteor.physicsBody?.dynamic = false
meteor.physicsBody?.affectedByGravity = false
meteor.physicsBody?.categoryBitMask = Fisica.object
meteor.physicsBody?.contactTestBitMask = Fisica.player | Fisica.bullets
meteor.physicsBody?.collisionBitMask = Fisica.none
addChild(meteor)
moveToCenter(meteor)
}
func createPowerUpMeteor() {
let powerUpMeteor = SKSpriteNode(texture: powerUpMeteorAnimation[0])
let animateAction = SKAction.animateWithTextures(self.powerUpMeteorAnimation, timePerFrame: 0.10);
let repeatAction = SKAction.repeatActionForever(animateAction)
powerUpMeteor.runAction(repeatAction)
powerUpMeteor.name = "powerUpMeteor"
powerUpMeteor.position = getMeteorPosition()
powerUpMeteor.zPosition = 2
powerUpMeteor.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 30, height: 30))
powerUpMeteor.physicsBody?.dynamic = true
powerUpMeteor.physicsBody?.affectedByGravity = false
powerUpMeteor.physicsBody?.categoryBitMask = Fisica.objectPowerUp
powerUpMeteor.physicsBody?.contactTestBitMask = Fisica.player | Fisica.bullets
powerUpMeteor.physicsBody?.collisionBitMask = Fisica.none
addChild(powerUpMeteor)
moveToCenter(powerUpMeteor)
}
func moveToCenter(meteor: SKSpriteNode) {
let location = CGPoint (x: self.frame.width / 2, y: self.frame.height / 2)
let gotoXY = SKAction.moveTo(location, duration: speedOfMeteor)
meteor.runAction(gotoXY)
}
func getMeteorPosition() -> CGPoint {
let degrees = GKRandomSource.sharedRandom().nextIntWithUpperBound(361)
let radiants = Double(degrees) * M_PI / 180
let x = getX(CGFloat(radiants))
let y = getY(CGFloat(radiants))
return CGPoint(x: x, y: y)
}
func getAngle() -> CGFloat {
let punto1 = CGVector(point: controllerAfuera.position)
let punto2 = CGVector(point: controllerAdentro.position)
let p = punto2 - punto1
let angle = atan2(p.dy, p.dx) - CGFloat(M_PI/2)
return angle
}
func getX(number : CGFloat) -> CGFloat {
return cos(number) * self.frame.width * 2
}
func getY(number : CGFloat) -> CGFloat {
return sin(number) * self.frame.width * 2
}
func fireBullet() {
disparo = SKSpriteNode(color: UIColor.yellowColor(), size: CGSize(width: 3, height: 9))
disparo.position = CGPoint(x: self.frame.width / 2 , y: self.frame.height / 2)
disparo.zRotation = hero.zRotation
disparo.physicsBody = SKPhysicsBody(rectangleOfSize: CGSize(width: 3, height: 9))
disparo.physicsBody?.dynamic = true
disparo.physicsBody?.affectedByGravity = false
disparo.physicsBody?.categoryBitMask = Fisica.bullets
disparo.physicsBody?.contactTestBitMask = Fisica.object
disparo.physicsBody?.collisionBitMask = Fisica.none
let angle = CGVector(angle: hero.zRotation + halfPie)
let vector = angle * 800
print(angle, vector)
disparo.physicsBody!.velocity = vector
let fireSFX = SKAction.playSoundFileNamed("fireSound", waitForCompletion: false)
if fireNumber < 4 {
fireNumber += 1
}
if canFire == true {
let playMusic = defaults.boolForKey("Musica")
addChild(disparo)
if playMusic == false {
self.runAction(fireSFX)
}
}
}
func lost() {
removeAllActions()
stopBackGroundMusic()
alive = false
gameOver = SKLabelNode(fontNamed: "VCR OSD Mono")
if espanol {
gameOver.text = "¡Perdiste!"
}
else {
gameOver.text = "Game Over!"
}
gameOver.horizontalAlignmentMode = .Center
gameOver.fontSize = 50
gameOver.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 + 50)
addChild(gameOver)
if espanol {
restartButton = SKSpriteNode(imageNamed: "jugarDeNuevo")
}
else {
restartButton = SKSpriteNode(imageNamed: "restart")
}
restartButton.name = "restart"
restartButton.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 - 60)
restartButton.setScale(0.08)
addChild(restartButton)
menuButton = SKSpriteNode(imageNamed: "menu")
menuButton.name = "menu"
menuButton.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 - 120)
menuButton.setScale(0.08)
addChild(menuButton)
updateBestScore(score)
loadAd()
}
func updateBestScore(score: Int) {
func crearaBotonSubirNuevoRecord(idioma: String) {
if idioma == "Es" {
uploadRecord = SKSpriteNode(imageNamed: "subirMejorPuntaje")
uploadRecord.name = "Upload Record"
uploadRecord.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
uploadRecord.setScale(0.08)
uploadRecord.zPosition = 4
addChild(uploadRecord)
}
else {
uploadRecord = SKSpriteNode(imageNamed: "uploadHighScore")
uploadRecord.name = "Upload Record"
uploadRecord.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2)
uploadRecord.setScale(0.08)
uploadRecord.zPosition = 4
addChild(uploadRecord)
}
}
switch currentDificulty {
case .Easy:
let actualBestScore = defaults.integerForKey("bestScoreEasy")
if score > actualBestScore {
defaults.setInteger(score, forKey: "bestScoreEasy")
gameOver.fontColor = UIColor.redColor()
if espanol {
gameOver.text = "¡Nuevo Record!"
crearaBotonSubirNuevoRecord("Es")
} else {
crearaBotonSubirNuevoRecord("En")
gameOver.text = "New Record!"
}
}
case .Medium:
let actualBestScore = defaults.integerForKey("bestScore")
if score > actualBestScore {
defaults.setInteger(score, forKey: "bestScore")
gameOver.fontColor = UIColor.redColor()
if espanol {
gameOver.text = "¡Nuevo Record!"
crearaBotonSubirNuevoRecord("Es")
} else {
gameOver.text = "New Record!"
crearaBotonSubirNuevoRecord("En")
}
}
case .Hard:
let actualBestScore = defaults.integerForKey("bestScoreHard")
if score > actualBestScore {
defaults.setInteger(score, forKey: "bestScoreHard")
gameOver.fontColor = UIColor.redColor()
if espanol {
gameOver.text = "¡Nuevo Record!"
crearaBotonSubirNuevoRecord("Es")
} else {
gameOver.text = "New Record!"
crearaBotonSubirNuevoRecord("En")
}
}
}
}
func loadAd() {
viewController.add()
}
func stopBackGroundMusic() {
let path = NSBundle.mainBundle().pathForResource("backgroundSound.mp3", ofType:nil)!
let url = NSURL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOfURL: url)
gameMusic = sound
sound.stop()
} catch {
// couldn't load file :(
}
}
func bajarFireNumber() {
if fireNumber >= 1 {
fireNumber -= 1
}
}
func randomPowerUp() {
let randomNumber = GKRandomSource.sharedRandom().nextIntWithUpperBound(10)
if randomNumber == 8 {
createPowerUpMeteor()
}
}
func objectAndPlayerCollides() {
switch numberOfHits {
case 0:
hero.texture = SKTexture(imageNamed: "hero")
case 1:
hero.texture = SKTexture(imageNamed: "heroOneHit")
case 2:
hero.texture = SKTexture(imageNamed: "heroTwoHits")
case 3:
hero.texture = SKTexture(imageNamed: "heroThreeHits")
case 4:
hero.texture = SKTexture(imageNamed: "heroDead")
lost()
default:
print("Ya perdiste")
}
}
func destroyShootOutsideTheScreen() {
if disparo?.position.x > self.frame.width {
removeFromParent()
}
else if disparo?.position.y > self.frame.height {
removeFromParent()
}
}
}
| true
|
b2de6e9966728bb4cf874dc187b210080a2f3223
|
Swift
|
kichikuchi/swift_nlp_100
|
/chapter1/03.swift
|
UTF-8
| 286
| 2.953125
| 3
|
[] |
no_license
|
import Foundation
let text = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
let countArray = text.split(separator: " ").map { $0.replacingOccurrences(of: ",", with: "").replacingOccurrences(of: ".", with: "").count }
print(countArray)
| true
|
9ffaf2cd9b1170cfbca180b6e500a0fe4f92594f
|
Swift
|
daniavram/qlh-ios
|
/qlh-ios/Model/GradientPoint.swift
|
UTF-8
| 1,424
| 3.234375
| 3
|
[] |
no_license
|
//
// GradientPoint.swift
// qlh-ios
//
// Created by Daniel Avram on 20/04/2019.
// Copyright © 2019 Daniel Avram. All rights reserved.
//
import UIKit
struct GradientPoint {
private(set) var from: CGPoint
private(set) var to: CGPoint
init(from: CGPoint) {
self.from = from.clamped(within: 0 ... 1)
to = GradientPoint.newTo(from: self.from)
}
static func newTo(from: CGPoint) -> CGPoint {
let newX = 1 - from.x
let newY = 1 - from.y
return CGPoint(x: newX, y: newY)
}
mutating func advance(by angle: CGFloat) {
let originX = from.x - 0.5
let originY = from.y - 0.5
var radians = atan2(originY, originX)
while radians < 0 {
radians += CGFloat(2 * Double.pi)
}
radians = radians + angle
let newX = 0.5 + cos(radians)
let newY = 0.5 + sin(radians)
let newFrom = CGPoint(x: newX, y: newY)
from = newFrom.clamped(within: 0 ... 1)
to = GradientPoint.newTo(from: from)
}
static var top: GradientPoint = .init(from: .init(x: 0.5, y: 0))
static var bottom: GradientPoint = .init(from: .init(x: 0.5, y: 1))
static func == (lhs: GradientPoint, rhs: GradientPoint) -> Bool {
let fromEq = lhs.from.x == rhs.from.x && lhs.from.y == rhs.from.y
let toEq = lhs.to.x == rhs.to.x && lhs.to.y == rhs.to.y
return fromEq && toEq
}
}
| true
|
479730196da2d7521e2f71a27e48d45e85ac906d
|
Swift
|
bogus/ios-sandbox
|
/GithubSearch/GithubSearch/MasterViewController.swift
|
UTF-8
| 2,955
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// MasterViewController.swift
// GithubSearch
//
// Created by Burak Oguz on 11/26/17.
// Copyright © 2017 Bogus. All rights reserved.
//
import UIKit
import CoreData
protocol TableViewControllerDelegate {
func item(at:IndexPath) -> TableCellViewModelDelegate?
func numberOfRows(in:Int) -> Int
func search(query:String?)
}
class MasterViewController: UITableViewController {
private var detailViewController: DetailViewController? = nil
private var viewModel:TableViewControllerDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
viewModel = MasterViewModel(delegate:self)
if let split = splitViewController {
let controllers = split.viewControllers
detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(_ animated: Bool) {
clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed
super.viewWillAppear(animated)
}
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
let _ = viewModel?.item(at: indexPath)
let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
//controller.detailItem = object
controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel?.numberOfRows(in: section) ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = viewModel?.item(at: indexPath)?.getTitle() ?? ""
cell.detailTextLabel?.text = viewModel?.item(at: indexPath)?.getSubtitle() ?? ""
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
}
extension MasterViewController : TableViewModelDelegate {
func reload() {
tableView.reloadData()
}
}
extension MasterViewController : UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
viewModel?.search(query: searchBar.text)
searchBar.resignFirstResponder()
}
}
| true
|
737b641b351212178fc58aff77d8e2c0191fd372
|
Swift
|
nobleidea/CGLogInOutAPI
|
/Sources/CGLogInOutAPI/UseCases/FaceLogInUseCase.swift
|
UTF-8
| 791
| 2.609375
| 3
|
[] |
no_license
|
//
// FaceLogInUseCase.swift
// LogInOutAPI
//
// Created by gyun on 2021/02/03.
//
import Foundation
import CGDomains
final class FaceLogInUseCase: CGDomains.LogInUseCase {
private let request: LogInAPIRequest<LogIn>
init(request: LogInAPIRequest<LogIn>) {
self.request = request
}
func login(parameters: Dictionary<String, Any>, completion: @escaping ((LogIn?, Error?) -> Void)) {
request.observer { response in
switch response.result {
case .success(let logIn):
completion(logIn, nil)
case .failure(let error):
completion(nil, error)
}
}.observer { _ in
}.observer { _ in
}.send(parameters: parameters)
}
}
| true
|
0ad6e572f000490825055658874b19c08293fa78
|
Swift
|
Gashelopodo/project_ios
|
/mxcircuit/Setting.swift
|
UTF-8
| 1,303
| 2.59375
| 3
|
[] |
no_license
|
//
// Setting.swift
// mxcircuit
//
// Created by Mario alcazar on 10/9/17.
// Copyright © 2017 Mario alcazar. All rights reserved.
//
import Foundation
import UIKit
class Setting: NSObject{
var id : String?
var register_id : String?
var circuit_id : String?
var send : String?
var created_at : String?
var name_circuit : String?
var name_city : String?
var id_city : String?
var control : Bool?
init(pId : String, pRegisterId : String, pCircuitId : String, send : String, created_at : String, name_circuit : String, name_city : String, id_city : String){
self.id = pId
self.register_id = pRegisterId
self.circuit_id = pCircuitId
self.send = send
self.created_at = created_at
self.name_circuit = name_circuit
self.name_city = name_city
self.id_city = id_city
self.control = false
super.init()
}
func params() -> Any{
return [
"id": id!,
"register_id": register_id!,
"circuit_id": circuit_id!,
"send": send!,
"created_at": created_at!,
"name_circuit": name_circuit!,
"id_city": id_city!,
"control": control!,
"language": "swift"
]
}
}
| true
|
4bcc82a8db0cf5ca3ce73d1c5d3293febe504643
|
Swift
|
28th-SOPT-iOS-CloneCoding/LeeInAe
|
/pencake-iOS-clone/pencake-iOS-clone/View/Story/ViewModel/WritingViewModel.swift
|
UTF-8
| 527
| 2.796875
| 3
|
[] |
no_license
|
//
// WritingViewModel.swift
// pencake-iOS-clone
//
// Created by inae Lee on 2021/06/09.
//
import Foundation
protocol writingViewModelDelegate {
func didChangedWriting(writing: Writing)
}
class WritingViewModel {
// MARK: - property
var writing: Writing? {
willSet(newWriting) {
guard let writing = newWriting else { return }
writingDelegate?.didChangedWriting(writing: writing)
}
}
// MARK: - delegate
var writingDelegate: writingViewModelDelegate?
}
| true
|
8f59f5c02c1787ad48b49cf8401eeb43f6c5db86
|
Swift
|
fiqriachmada/CustomNavigationAndViewSwiftUI
|
/CustomNavigationView/CustomNavigationView/ContentView.swift
|
UTF-8
| 6,831
| 2.875
| 3
|
[] |
no_license
|
//
// ContentView.swift
// CustomNavigationView
//
// Created by Achmada Fiqri A Rasyad on 20/09/20.
//
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack{
TabView{
Home()
.tabItem {
Image(systemName: "house.fill")
Text("Beranda")
}
Home()
.tabItem {
Image(systemName: "paperplane.fill")
Text("Eksplorasi")
}
Home()
.tabItem {
Image(systemName: "tray.fill")
Text("Subscription")
}
Home()
.tabItem {
Image(systemName: "envelope.fill")
Text("Notifikasi")
}
Home()
.tabItem {
Image(systemName: "play.rectangle.fill")
Text("Koleksi")
}
}
.accentColor(.red)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct Home: View {
var body: some View{
NavigationView(){
Content()
.navigationBarItems(leading: HStack{
Button(action: {print("Hello Button")}){
Image("youtube")
.resizable()
.frame(width: 90, height: 25)
}
},
trailing:
HStack{
Button(action: {print("Hello Print")}){
Image(systemName: "tray.full")
.foregroundColor(.secondary)
}
Button(action: {print("Hello Print")}){
Image(systemName: "video.fill")
.foregroundColor(.secondary)
}
Button(action: {print("Hello Print")}){
Image(systemName: "magnifyingglass")
.foregroundColor(.secondary)
}
Button(action: {print("Hello Print")}){
Image("profile")
.resizable()
.frame(width: 20, height: 20)
.clipShape(/*@START_MENU_TOKEN@*/Circle()/*@END_MENU_TOKEN@*/)
}
}
)
.navigationBarTitle("", displayMode: .inline)
}
.navigationViewStyle(StackNavigationViewStyle())
}
}
struct Content: View {
var body: some View{
List{
//content1
VStack{
ZStack(alignment: .bottomTrailing){
Image("content1")
.resizable()
.aspectRatio(contentMode: .fill)
Text("10:00")
.padding(.all, 5)
.foregroundColor(.white)
.background(Color.black)
.font(.caption)
.cornerRadius(5)
.padding(.trailing, 5)
.padding(.bottom, 5)
}
HStack(spacing: 20){
Image("profile")
.resizable()
.frame(width: 30, height: 30)
.clipShape(Circle())
VStack(alignment: .leading){
Text("Simple View SwiftUI")
.font(.headline)
HStack{
Text("Achmada Fiqri A • Rasyad 6x • 1 hari yang lalu")
.font(.caption)
}
}
Spacer()
Image(systemName: "list.bullet")
}
}
//content2
VStack{
ZStack(alignment: .bottomTrailing){
Image("content2")
.resizable()
.aspectRatio(contentMode: .fill)
Text("7:39")
.padding(.all, 5)
.foregroundColor(.white)
.background(Color.black)
.font(.caption)
.cornerRadius(5)
.padding(.trailing, 5)
.padding(.bottom, 5)
}
HStack(spacing: 20){
Image("profile")
.resizable()
.frame(width: 30, height: 30)
.clipShape(Circle())
VStack(alignment: .leading){
Text("Tugas Akhir Praktikum")
.font(.headline)
HStack{
Text("Achmada Fiqri A • Rasyad 600x • 1 hari yang lalu")
.font(.caption)
}
}
Spacer()
Image(systemName: "list.bullet")
}
}
//content 3
VStack{
ZStack(alignment: .bottomTrailing){
Image("content1")
.resizable()
.aspectRatio(contentMode: .fill)
Text("10:00")
.padding(.all, 5)
.foregroundColor(.white)
.background(Color.black)
.font(.caption)
.cornerRadius(5)
.padding(.trailing, 5)
.padding(.bottom, 5)
}
HStack(spacing: 20){
Image("profile")
.resizable()
.frame(width: 30, height: 30)
.clipShape(Circle())
VStack(alignment: .leading){
Text("Simple View SwiftUI")
.font(.headline)
HStack{
Text("Achmada Fiqri A • Rasyad 60x • 5 hari yang lalu")
.font(.caption)
}
}
Spacer()
Image(systemName: "list.bullet")
}
}
}
}
}
| true
|
437484cd6adbec01d5ce8db537c3a38ae0af80eb
|
Swift
|
MikeTradr/DictateNew
|
/Dictate/MailComposer.swift
|
UTF-8
| 2,415
| 2.875
| 3
|
[] |
no_license
|
//
// MessageComposer.swift
// WatchInput
//
// Created by Mike Derr on 6/30/15.
// Copyright (c) 2015 ThatSoft.com. All rights reserved.
//
// from: http://www.andrewcbancroft.com/2014/10/28/send-text-message-in-app-using-mfmessagecomposeviewcontroller-with-swift/
import Foundation
import MessageUI
let textMessageRecipients = ["1-608-242-7700"] // for pre-populating the recipients list (optional, depending on your needs)
class MessageComposer: NSObject, MFMessageComposeViewControllerDelegate {
let defaults = NSUserDefaults(suiteName: "group.com.thatsoft.dictateApp")!
// A wrapper function to indicate whether or not a text message can be sent from the user's device
func canSendText() -> Bool {
return MFMessageComposeViewController.canSendText()
}
// Configures and returns a MFMessageComposeViewController instance
func configuredMessageComposeViewController() -> MFMessageComposeViewController {
println("p29 We in MessageComposer")
let output:String = defaults.stringForKey("output")!
//TODO fix the forced downcast below
let tempPhone:String = defaults.stringForKey("toPhone")!
var toPhone:[String] = []
toPhone.append(tempPhone)
println("p41 toPhone: \(toPhone)")
let newOutput = "\(output) - sent from Dictate™ App"
let messageBody = newOutput
//let toPhone:[String] = [defaults.stringForKey("toPhone") as! String]
let testBody = "Hey friend - Just sending a text message in-app using Swift!"
let messageComposeVC = MFMessageComposeViewController()
messageComposeVC.messageComposeDelegate = self // Make sure to set this property to self, so that the controller can be dismissed!
//messageComposeVC.recipients = textMessageRecipients
messageComposeVC.recipients = toPhone
messageComposeVC.body = messageBody
return messageComposeVC
}
// MFMessageComposeViewControllerDelegate callback - dismisses the view controller when the user is finished with it
func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
| true
|
b0ea41d5333b52b4fea6235df4fdd5606ba16309
|
Swift
|
zjs630/MySortTest
|
/MySortTest/Algorithm/数组/MaxSubArray.swift
|
UTF-8
| 1,224
| 3.609375
| 4
|
[] |
no_license
|
//
// MaxSubArray.swift
// MySortTest
//
// Created by 张京顺 on 2019/8/7.
// Copyright © 2019 zjs. All rights reserved.
//
import Foundation
/*
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
思路:
1.首先对数组进行遍历,当前最大连续子序列和为 sum,结果为 max
2.如果 sum > 0,则说明 sum 对结果有增益效果,则 sum 保留并加上当前遍历数字
3.如果 sum <= 0,则说明 sum 对结果无增益效果,需要舍弃,则 sum 直接更新为0
4.每次比较 sum 和 max的大小,将最大值置为max,遍历结束返回结果
时间复杂度:O(n)
*/
class MaxSubArray {
static func sum(_ nums: [Int]) -> Int {
/// 求和的中间结果
var sum = 0
/// 子数组最大和
var max = Int.min
for i in nums {
sum += i
if sum > max {
max = sum
}
if sum < 0 {
sum = 0
}
}
return max
}
}
| true
|
f09b3987314df2eb976daa071a9c22de211307e6
|
Swift
|
AhmedNasserSh/iOSCleanArchitecture
|
/iOS Clean Architecture/Network/Response.swift
|
UTF-8
| 1,187
| 2.96875
| 3
|
[] |
no_license
|
//
// Response.swift
// iOS Clean Architecture
//
// Created by Ahmed Nasser on 12/5/19.
// Copyright © 2019 AvaVaas. All rights reserved.
//
import Foundation
public enum Response {
case json(_: NSDictionary)
case data(_: Data)
case error(_: Int?, _: Error?)
init(_ response: (r: HTTPURLResponse?, data: Data?, error: Error?), for request: NetworkRequest) {
guard response.r?.statusCode == 200, response.error == nil else {
self = .error(response.r?.statusCode, response.error)
return
}
guard let data = response.data else {
self = .error(response.r?.statusCode, NetworkErrors.noData)
return
}
switch request.dataType {
case .data:
self = .data(data)
case .json:
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary
self = .json(json ?? [:])
}
}
var response :Any? {
switch self {
case .json(let dic):
return dic
case .data(let data) :
return data
default:
return nil
}
}
}
| true
|
d90236212ed836a8b0093a0b852fac8752af7617
|
Swift
|
liuxiangyu-kx/CreateMLDemo
|
/SentimentAnalysis.playground/Contents.swift
|
UTF-8
| 1,590
| 2.953125
| 3
|
[] |
no_license
|
import CreateML
import Foundation
//1
//
//let url = URL(fileURLWithPath: "/Users/Moon/2swift/self/CreateMLDemo/SentimentDataset")
//
//print("Start loading data")
//let sentimentClassifier = try MLTextClassifier(trainingData: .labeledDirectories(at: url))
//
////4
//let metadata = MLModelMetadata(author: "Marvin Lin", shortDescription: "Using mazon's cell data to make sentiment classifer", version: "1.0")
//try sentimentClassifier.write(to: URL(fileURLWithPath: "/Users/Moon/2swift/self/CreateMLDemo/SentimentClassifer.mlmodel"), metadata: metadata)
//1
let url = URL(fileURLWithPath: "/Users/Moon/2swift/self/CreateMLDemo/SentimentJSONData/sentiment.json")
print("Start loading data")
let data = try MLDataTable(contentsOf: url)
let (trainingData, testingData) = data.randomSplit(by: 0.8, seed: 5)
print("Classifier is training")
let sentimentClassifier = try MLTextClassifier(trainingData: trainingData, textColumn: "text", labelColumn: "label")
//2
let trainingAccuracy = (1.0 - sentimentClassifier.trainingMetrics.classificationError) * 100
let validationAccuracy = (1.0 - sentimentClassifier.validationMetrics.classificationError) * 100
//3
let evaluationMetrics = sentimentClassifier.evaluation(on: testingData)
let evaluationAccuracy = (1.0 - evaluationMetrics.classificationError) * 100
//4
let metadata = MLModelMetadata(author: "Marvin Lin", shortDescription: "Using Appcoda's spam json file to train ML model", version: "1.0")
try sentimentClassifier.write(to: URL(fileURLWithPath: "/Users/Moon/2swift/self/CreateMLDemo/SentimentClassifer.mlmodel"), metadata: metadata)
| true
|
930c8d7a2bd0a602e298fe239924b110e8c3d53e
|
Swift
|
Cyklet/Cardimation
|
/Cardimation/Cardimation/Configurations/OverlayConfiguration.swift
|
UTF-8
| 962
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
//
// CardsPositionCalculator.swift
// CardAnimation
//
// Created by Petre.
// Copyright © 2019 Petre. All rights reserved.
//
import UIKit
public struct OverlayConfiguration {
let type: OverlayType
let animationStyle: OverlayAnimationStyle
/// - Parameter type: The type of overlay that will be placed above card
/// - Parameter animationStyle: Animation style of the overlay
public init(type: OverlayType = .color(.init(white: 0, alpha: 0.8)),
animationStyle: OverlayAnimationStyle = .animated(.init(duration: 1))) {
self.type = type
self.animationStyle = animationStyle
}
}
public enum OverlayType {
/// No overlay will be added above card
case none
/// Simple overlay with color
case color(UIColor)
/// Custom overlay view
case custom(() -> OverlayViewable?)
}
public enum OverlayAnimationStyle {
case animated(CardViewAnimationsConfiguration)
case unanimated
}
| true
|
5095bbce14267720134b28079eb469acda467bb2
|
Swift
|
cloneforyou/social-hues
|
/iOS/Social Hues/ViewControllers/ConvoPageViewController.swift
|
UTF-8
| 3,487
| 2.71875
| 3
|
[] |
no_license
|
//
// ConvoViewController.swift
// Social Hues
//
// Created by Sarah Zhou on 5/19/18
// Copyright © 2018 Social Hues. All rights reserved.
//
import UIKit
protocol ConvoPageViewControllerDelegate: class {
func userDidFinishOnBoard()
func returnToDetails()
}
class ConvoPageViewController : UIPageViewController {
weak var detailsDelegate: DetailsBeforeDelegate?
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
if let firstControl = controllers.first {
setViewControllers([firstControl],
direction: .forward,
animated: true,
completion: nil)
}
self.view.backgroundColor = .gray
}
init() {
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
}
required init?(coder: NSCoder) {
super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
}
// The three view controllers referred by their names
private(set) lazy var controllers: [UIViewController] = {
return [self.newColoredViewController(order: "One"),
self.newColoredViewController(order: "Two"),
self.newColoredViewController(order: "Three"),
self.newColoredViewController(order: "Four")]
//self.getPromptVC()]
}()
private func getPromptVC() -> UIViewController {
let newVC = UIStoryboard(name: "Prompt", bundle: nil).instantiateInitialViewController() as! PromptViewController
newVC.delegate = self
return newVC
}
private func newColoredViewController(order: String) -> UIViewController {
let newVC = UIStoryboard(name: "ConvoOnboard", bundle: nil).instantiateViewController(withIdentifier:"Convo\(order)") as! ConvoScreenViewController
newVC.delegate = self
return newVC
}
}
extension ConvoPageViewController: ConvoPageViewControllerDelegate {
func userDidFinishOnBoard() {
self.dismiss(animated: true, completion: nil)
self.detailsDelegate?.startPrompts()
}
func returnToDetails() {
self.dismiss(animated: true, completion: nil)
}
}
extension ConvoPageViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let vcIndex = controllers.index(of:viewController) else {
return nil
}
let prevIndex = vcIndex - 1
guard prevIndex >= 0 else {
return nil
}
guard controllers.count > prevIndex else {
return nil
}
return controllers[prevIndex]
}
func pageViewController(_ pageViewController: UIPageViewController,
viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let vcIndex = controllers.index(of:viewController) else {
return nil
}
let nextIndex = vcIndex + 1
guard nextIndex != controllers.count else {
return nil
}
guard controllers.count > nextIndex else {
return nil
}
return controllers[nextIndex]
}
}
| true
|
6f36c2f9bfc4165f218bb6c6be900c826c91ac4d
|
Swift
|
soppysonny/Truck
|
/Truck/Extension/Decodable+Extension.swift
|
UTF-8
| 1,046
| 2.71875
| 3
|
[] |
no_license
|
import Foundation
import CleanJSON
extension Decodable {
public static func decode(data: Data, format: DateFormat? = nil) throws -> Self {
let decoder = CleanJSONDecoder()
if data.isEmpty {
return try decoder.decode(self, from: "{}".data(using: .utf8) ?? Data())
}
if let format = format {
let formatter = DateFormatter()
formatter.dateFormat = format.rawValue
formatter.locale = Locale(identifier: "en_US_POSIX")
decoder.dateDecodingStrategy = .formatted(formatter)
}
let string = String.init(data: data, encoding: .utf8)
if var dict = string?.toDictionary() {
if let number = dict["msg"] as? Int {
dict["msg"] = String.init(format: "%d", number)
if let modifiedData = dict.toString()?.data(using: .utf8) {
return try decoder.decode(self, from: modifiedData)
}
}
}
return try decoder.decode(self, from: data)
}
}
| true
|
8f779c6ba6f59fdd1d005877a8f561f75d3e0bd9
|
Swift
|
westinfunk/QuickInspectPro
|
/Quick Inspect Pro/Model/Note.swift
|
UTF-8
| 773
| 3.28125
| 3
|
[] |
no_license
|
//
// Note.swift
// Quick Inspect Pro
//
// Created by Westin Funk on 10/21/19.
// Copyright © 2019 Grey Nexus. All rights reserved.
//
import Foundation
enum NoteType: String, Codable {
case deficiency = "Deficiency"
case information = "Information"
}
class Note: Codable, Identifiable, NSCopying {
var id: String?
var text: String
var type: NoteType?
init(text: String, type: NoteType? = nil, id: String? = nil) {
self.text = text
self.type = type
if (id != nil) {
self.id = id
} else {
self.id = generateId("note-")
}
}
func copy(with zone: NSZone? = nil) -> Any {
let note = Note(text: self.text, type: self.type, id: self.id)
return note
}
}
| true
|
7385e635518d764e959f2e97da375286d014b573
|
Swift
|
MerouaneBellaha/TD.CoreData
|
/CoreDataManager/CoreDataManagerTests.swift
|
UTF-8
| 1,717
| 2.671875
| 3
|
[] |
no_license
|
//
// CoreDataManager.swift
// CoreDataManager
//
// Created by Merouane Bellaha on 25/06/2020.
// Copyright © 2020 Merouane Bellaha. All rights reserved.
//
@testable import TDL
import XCTest
class CoreDataManagerTests: XCTestCase {
var coreDataStack: FakeCoreDataStack!
var coreDataManager: CoreDataManager!
override func setUp() {
super.setUp()
coreDataStack = FakeCoreDataStack()
coreDataManager = CoreDataManager(with: coreDataStack)
}
override func tearDown() {
super.tearDown()
coreDataStack = nil
coreDataManager = nil
}
func testGivenCoreDataManagerIsEmpty_WhenCreateAnItem_ThenCoreDataManagerShouldHaveOneTaskNamedATask() {
coreDataManager.createItem(named: "A task")
XCTAssertTrue(coreDataManager.loadItems().count == 1)
XCTAssertTrue(coreDataManager.loadItems().first?.taskName == "A task")
}
func testGivenCoreDataManagerIsNotEmpty_WhenDeleteAllTasks_ThenCoreDataManagerShouldBeEmpty() {
coreDataManager.createItem(named: "A task")
coreDataManager.deleteItems()
XCTAssertTrue(coreDataManager.loadItems().isEmpty)
}
func testGivenCoreDataManagerContainsTwoTasks_WhenDeleteTheFirstTask_ThenCoreDataManagerShouldContainsOnlyTheSecondTask() {
coreDataManager.createItem(named: "First Task")
coreDataManager.createItem(named: "Second Task")
guard let firstTask = coreDataManager.loadItems(containing: "First Task").first else { return }
coreDataManager.deleteItem(item: firstTask)
XCTAssertTrue(coreDataManager.loadItems().count == 1)
XCTAssertTrue(coreDataManager.loadItems().first?.taskName == "Second Task")
}
}
| true
|
9bd4d58609b7192eade86f323e1b2b83e1d623a8
|
Swift
|
PedanIhor/iOS_Advanced_HW2
|
/ScrollViewPaging/MainViewModel.swift
|
UTF-8
| 1,548
| 2.84375
| 3
|
[] |
no_license
|
//
// MainViewModel.swift
// ScrollViewPaging
//
// Created by Ihor Pedan on 17.12.2019.
// Copyright © 2019 Ihor Pedan. All rights reserved.
//
import Foundation
final class MainViewModel: ObservableObject {
private let newsService: NewsServiceInput
@Published var articles = [Article]()
@Published var searchKey: String = ""
@Published var pageNumber: Int = 1
@Published var isLoadingPage = false
@Published var selectedScope: SearchBar.Scope = .swiftUI
init(newsService: NewsServiceInput) {
self.newsService = newsService
}
func performSearch() {
if searchKey.isEmpty {
articles = []
return
}
guard !isLoadingPage else { return }
isLoadingPage = true
pageNumber = 1
newsService.loadNewsForKey(searchKey, page: pageNumber) { [weak self] (result) in
guard let self = self else { return }
switch result {
case .success(let list):
self.articles = list
case .failure(let error):
print(error)
}
self.isLoadingPage = false
}
}
func loadNewPage(_ success: (([Article]) -> Void)? = nil) {
guard !isLoadingPage else { return }
isLoadingPage = true
pageNumber += 1
newsService.loadNewsForKey(searchKey, page: pageNumber) { [weak self] (result) in
guard let self = self else {
return
}
switch result {
case .success(let list):
self.articles.append(contentsOf: list)
case .failure(let error):
print(error)
}
self.isLoadingPage = false
}
}
}
| true
|
b4abd410d9dc1a91f3a06c7764227c9cfe39f8a0
|
Swift
|
BNazh/CurrencyTest
|
/Currency/Helper/Global/Global.swift
|
UTF-8
| 1,559
| 2.53125
| 3
|
[] |
no_license
|
import UIKit
class Global {
class func pathFor(key: String) -> String
{
if let path = Bundle.main.path(forResource: "api", ofType: "plist"),
let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
let path = dict[key] as! String
// let domen = dict["root"] as! String
let link = "\(path)"
return link
}
else { return "" }
}
class func navigationBackgroundColor() -> UIColor {
return #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
}
class func backgroundColor() -> UIColor {
return #colorLiteral(red: 0.9607843137, green: 0.9647058824, blue: 0.968627451, alpha: 1)
}
class func grayColor() -> UIColor {
return #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
}
class func regularFont(size: CGFloat) -> UIFont {
return UIFont.systemFont(ofSize: size)
}
class func boldFont(size: CGFloat) -> UIFont {
return UIFont.boldSystemFont(ofSize: size)
}
}
struct ScreenSize {
static let SCREEN_BOUNDS = UIScreen.main.bounds
static let SCREEN_WIDTH = ScreenSize.SCREEN_BOUNDS.size.width
static let SCREEN_HEIGHT = ScreenSize.SCREEN_BOUNDS.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
| true
|
a95b07b6e676b5bbd5a2bb2d36dee2f6d15e0222
|
Swift
|
Blubberpie/game-vessel
|
/Game Vessel/Services/APIService.swift
|
UTF-8
| 1,835
| 3.03125
| 3
|
[] |
no_license
|
//
// APIService.swift
// Project
//
// Created by blubberpie on 17/02/2020.
// Copyright © 2020 blubberpie. All rights reserved.
//
import Foundation
class APIService {
// Query parameters:
// - page = page number
// - page_size = number of games to get
// TODO (if possible): Randomize page numbers?
let baseUrlString: String = "https://api.rawg.io/api/games"
func fetchGames(completionHandler: @escaping ([Game]?) -> Void) {
guard let url = URL(string: baseUrlString + "?page_size=10") else {
return
}
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if let error = error {
print(error)
completionHandler(nil)
}
if let httpResponse = response as? HTTPURLResponse {
print("HTTP response code: \(httpResponse.statusCode)")
}
if let data = data, let gameResults = try? JSONDecoder().decode(GameResult.self, from: data) {
completionHandler(gameResults.results)
} else {
print("Failed to decode JSON!")
}
})
task.resume()
}
func fetchGameDetails(gameID: Int, completionHandler: @escaping (GameDetail) -> Void) {
guard let url = URL(string: baseUrlString + "/\(gameID)") else {
return
}
let task = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if let data = data, let gameDetail = try? JSONDecoder().decode(GameDetail.self, from: data) {
completionHandler(gameDetail)
} else {
print("JSON fail!")
}
})
task.resume()
}
}
| true
|
3bbdf410e452b9db0b106348d1a9caf826a276f8
|
Swift
|
manhnn/FastSlowmo
|
/FastSlowmo/SubView/MusicView.swift
|
UTF-8
| 1,262
| 2.796875
| 3
|
[] |
no_license
|
//
// MusicView.swift
// FastSlowmo
//
// Created by Manh Nguyen Ngoc on 12/02/2021.
//
import UIKit
protocol MusicViewDelegate: class {
func musicViewDidTapDelete(_ view: MusicView)
func musicViewDidTapVolumeAudio(_ view: MusicView)
func musicViewDidTapChangeMusic(_ view: MusicView)
func musicViewDidTapAcceptedMusic(_ view: MusicView)
}
class MusicView: UIView {
@IBOutlet weak var changeSlider: UISlider!
@IBOutlet weak var volumeAudioButton: UIButton!
weak var delegate: MusicViewDelegate?
var playerVolume : Float = 1
@IBAction func deletePressed(_ sender: Any) {
delegate?.musicViewDidTapDelete(self)
}
@IBAction func changeMusicPressed(_ sender: Any) {
delegate?.musicViewDidTapChangeMusic(self)
}
@IBAction func acceptedPressed(_ sender: Any) {
delegate?.musicViewDidTapAcceptedMusic(self)
}
@IBAction func volumeAudioPressed(_ sender: UIButton) {
changeSlider.isHidden = !changeSlider.isHidden
}
@IBAction func changeValueSlider(_ sender: UISlider) {
playerVolume = sender.value
volumeAudioButton.setTitle("\(Int(playerVolume * 100))", for: .normal)
delegate?.musicViewDidTapVolumeAudio(self)
}
}
| true
|
152577ad283e28fe3a1011755bbf28c863194b37
|
Swift
|
jy6vd/AdvanceMealPrep
|
/FinalProject/ViewController.swift
|
UTF-8
| 9,119
| 2.734375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// FinalProject
//
// Created by Jonathan Yee on 3/13/18.
// Copyright © 2018 Jonathan Yee. All rights reserved.
//
import UIKit
import CoreData
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var meal_type: [String] = ["Breakfast", "Lunch", "Dinner", "Dessert", "Snack"]
var breakfast: [Recipes] = []
var lunch: [Recipes] = []
var dinner: [Recipes] = []
var dessert: [Recipes] = []
var snack: [Recipes] = []
var recipes: [Recipes] = []
var ingredients: [Ingredients] = []
@IBOutlet weak var tableview: UITableView!
override func viewWillAppear(_ animated: Bool) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else{
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest2: NSFetchRequest<Ingredients> = Ingredients.fetchRequest()
let fetchRequet = NSFetchRequest<NSFetchRequestResult>(entityName: "Recipes")
do{
let result = try managedContext.fetch(fetchRequet)
ingredients = try managedContext.fetch(fetchRequest2)
recipes = result as! [Recipes]
seperateRecipes()
}
catch{
print("Could not fetch")
}
}
func seperateRecipes(){
for recipe in recipes{
if (recipe.name != nil){
if(recipe.meal! == "breakfast"){
breakfast.append(recipe)
}
else if(recipe.meal! == "lunch" ){
lunch.append(recipe)
}
else if(recipe.meal! == "dinner" ){
dinner.append(recipe)
}else if(recipe.meal! == "dessert" ){
dessert.append(recipe)
}else if (recipe.meal! == "snack" ){
snack.append(recipe)
}
}else{
print("deleted")
}
}
breakfast = uniqueElementsFrom(array: breakfast)
lunch = uniqueElementsFrom(array: lunch)
dinner = uniqueElementsFrom(array: dinner)
dessert = uniqueElementsFrom(array: dessert)
snack = uniqueElementsFrom(array: snack)
tableview.reloadData()
}
func uniqueElementsFrom(array: [Recipes]) -> [Recipes]{
var set = Set<String>()
var unique = [Recipes]()
for uniqueRecipe in array{
if(uniqueRecipe.name != nil){
if !set.contains(uniqueRecipe.name!) {
unique.append(uniqueRecipe)
set.insert(uniqueRecipe.name!)
}
}
}
return unique
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch(section){
case 0:
return breakfast.count
case 1:
return lunch.count
case 2:
return dinner.count
case 3:
return dessert.count
case 4:
return snack.count
default:
return 0
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return meal_type.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if(!recipes.isEmpty){
return meal_type[section]
}
else{
return nil
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableview.dequeueReusableCell(withIdentifier: "recipeCell", for: indexPath) as! SavedRecipeTableViewCell
if(recipes.count > 0){
switch(indexPath.section){
case 0:
cell.foodTitle.text = breakfast[indexPath.row].name
cell.foodDescription.text = breakfast[indexPath.row].descriptions
if let url = NSURL(string: breakfast[indexPath.row].picture!){
if let data = NSData(contentsOf: url as URL){
cell.foodImage.image = UIImage(data: data as Data)
}
}
case 1:
cell.foodTitle.text = lunch[indexPath.row].name
cell.foodDescription.text = lunch[indexPath.row].descriptions
if let url = NSURL(string: lunch[indexPath.row].picture!){
if let data = NSData(contentsOf: url as URL){
cell.foodImage.image = UIImage(data: data as Data)
}
}
case 2:
cell.foodTitle.text = dinner[indexPath.row].name
cell.foodDescription.text = dinner[indexPath.row].descriptions
if let url = NSURL(string: dinner[indexPath.row].picture!){
if let data = NSData(contentsOf: url as URL){
cell.foodImage.image = UIImage(data: data as Data)
}
}
case 3:
cell.foodTitle.text = dessert[indexPath.row].name
cell.foodDescription.text = dessert[indexPath.row].descriptions
if let url = NSURL(string: dessert[indexPath.row].picture!){
if let data = NSData(contentsOf: url as URL){
cell.foodImage.image = UIImage(data: data as Data)
}
}
default:
cell.foodTitle.text = snack[indexPath.row].name
cell.foodDescription.text = snack[indexPath.row].descriptions
if let url = NSURL(string: snack[indexPath.row].picture!){
if let data = NSData(contentsOf: url as URL){
cell.foodImage.image = UIImage(data: data as Data)
}
}
}
}
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "allSavedSeque"{
let indexPath = self.tableview.indexPathForSelectedRow!
let sectionNumber = indexPath.section
let secondViewController = segue.destination as? SavedRecipeInfoViewController
let passName: String?
let passDirection: String?
let pasDescription: String?
let passImage: String?
let passServing: String?
switch sectionNumber{
case 0:
passName = breakfast[indexPath.row].name
passDirection = breakfast[indexPath.row].direction
pasDescription = breakfast[indexPath.row].descriptions
passImage = breakfast[indexPath.row].picture
passServing = breakfast[indexPath.row].serving
case 1:
passName = lunch[indexPath.row].name
passDirection = lunch[indexPath.row].direction
pasDescription = lunch[indexPath.row].descriptions
passImage = lunch[indexPath.row].picture
passServing = lunch[indexPath.row].serving
case 2:
passName = dinner[indexPath.row].name
passDirection = dinner[indexPath.row].direction
pasDescription = dinner[indexPath.row].descriptions
passImage = dinner[indexPath.row].picture
passServing = dinner[indexPath.row].serving
case 3:
passName = dessert[indexPath.row].name
passDirection = dessert[indexPath.row].direction
pasDescription = dessert[indexPath.row].descriptions
passImage = dessert[indexPath.row].picture
passServing = dessert[indexPath.row].serving
default:
passName = snack[indexPath.row].name
passDirection = snack[indexPath.row].direction
pasDescription = snack[indexPath.row].descriptions
passImage = snack[indexPath.row].picture
passServing = snack[indexPath.row].serving
}
secondViewController?.imageString = passImage!
secondViewController?.servingSize = passServing!
secondViewController?.foodname = passName!
secondViewController?.hugeDirection = passDirection!
secondViewController?.foodDescription = pasDescription!
secondViewController?.ingredients = ingredients
}
}
override func viewDidLoad() {
tableview.delegate = self
tableview.dataSource = self
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
e03ca1bac9f5a24d17bfb234a90055e14ffcd0ba
|
Swift
|
ashishvpatel123/Weather-JSON-App
|
/Weather JSON App/ViewController.swift
|
UTF-8
| 2,525
| 3.15625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Weather JSON App
//
// Created by IMCS2 on 2/21/19.
// Copyright © 2019 IMCS2. All rights reserved.
// URL : https://api.openweathermap.org/data/2.5/weather?q=Dallas&appid=4e50d2279e5b4d7501d1092f83ea5345
import UIKit
struct WelcomeData: Codable {
let coord: Coord
let weather: [Weather]
let base: String
let main: Main
let visibility: Int
let wind: Wind
let clouds: Clouds
let dt: Int
let sys: Sys
let id: Int
let name: String
let cod: Int
}
struct Clouds: Codable {
let all: Int
}
struct Coord: Codable {
let lon, lat: Double
}
struct Main: Codable {
let temp: Double
let pressure, humidity: Int
let tempMin, tempMax: Double
enum CodingKeys: String, CodingKey {
case temp, pressure, humidity
case tempMin = "temp_min"
case tempMax = "temp_max"
}
}
struct Sys: Codable {
let type, id: Int
let message: Double
let country: String
let sunrise, sunset: Int
}
struct Weather: Codable {
let id: Int
let main, description, icon: String
}
struct Wind: Codable {
let speed: Double
let deg: Int
}
class ViewController: UIViewController {
@IBOutlet weak var cityName: UITextField!
@IBOutlet weak var weatherLable: UILabel!
@IBOutlet weak var submitButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func submitButtonClicked(_ sender: Any) {
let city = cityName.text
guard let url = URL(string: "https://api.openweathermap.org/data/2.5/weather?q=\(city!)&appid=4e50d2279e5b4d7501d1092f83ea5345") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
let data = try JSONDecoder().decode(WelcomeData.self , from: dataResponse)
print("data from api \(data)")
DispatchQueue.main.async {
self.weatherLable.text = "Description : " + data.weather[0].description + " \n Humidity : " + String(data.main.humidity)
}
}catch let parsingError{
print("parsing error \(parsingError)")
}
}
task.resume()
}
}
| true
|
212e3d4b85eaaf237144914db8475ace5fe57768
|
Swift
|
BlanchardJeremie/ProjectSanteSwift
|
/ProjectIOsSante/Personne.swift
|
UTF-8
| 1,848
| 3.296875
| 3
|
[] |
no_license
|
//
// Personne.swift
// ProjectIOsSante
//
// Created by Admin on 20/06/2017.
// Copyright © 2017 Admin. All rights reserved.
//
import Foundation
extension PersonneData{
func afficherNomString() -> String{
return lastname!
}
func afficherPrenomString() -> String{
return firstname!
}
func afficherNomComplet() -> String{
if isfemale {
return "Mme. \(lastname!) \(firstname!)"
}else{
return "M. \(lastname!) \(firstname!)"
}
}
}
class Personne {
let prenom: String
var nom: String
// var nomcomplet: String
// let nomcomplet = "\(nom)" + "\(prenom)"
var pere: Personne?
var mere: Personne?
var enfants : [Personne]
let genre: Gender
init(prenom: String, nom: String,genre:Gender) {
self.nom = nom
self.prenom = prenom
self.enfants = [Personne]()
self.genre = genre
}
func afficherNomString() -> String{
return nom
}
func afficherPrenomString() -> String{
return prenom
}
func afficherNom(){
print(nom)
}
func afficherNomComplet() -> String{
if genre == Gender.Female {
return "Mme. \(nom) \(prenom)"
}else{
return "M. \(nom) \(prenom)"
}
}
func afficherenfant(){
for enfant in enfants{
enfant.afficherNom()
print(enfant.afficherNomComplet())
}
}
func afficherNomParent(){
guard let pere = pere,let mere = mere else {
return
}
pere.afficherNom()
mere.afficherNom()
}
enum Gender {
case Male
case Female
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.