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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
97450c7aefc916cd33d3a602410319b86b37d157
|
Swift
|
cleonps/Coding-Samples
|
/Coding Sample/Controllers/Menu/MenuViewController.swift
|
UTF-8
| 2,443
| 2.625
| 3
|
[] |
no_license
|
//
// MenuViewController.swift
// Coding Sample
//
// Created by Christian Leรณn Pรฉrez Serapio on 06/04/20.
// Copyright ยฉ 2020 christianleon. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController {
let samples = [
Sample(name: "Geolocalizaciรณn", imageName: .location, segue: .location),
Sample(name: "Covid19 Map", imageName: .covid, segue: .covid),
Sample(name: "Placeholder", imageName: .none, segue: .location),
Sample(name: "Placeholder", imageName: .none, segue: .location),
Sample(name: "Placeholder", imageName: .none, segue: .location),
Sample(name: "Placeholder", imageName: .none, segue: .location),
Sample(name: "Placeholder", imageName: .none, segue: .location),
Sample(name: "Placeholder", imageName: .none, segue: .location),
Sample(name: "Placeholder", imageName: .none, segue: .location),
Sample(name: "Placeholder", imageName: .none, segue: .location)
]
@IBOutlet var sampleCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
sampleCollectionView.register(nibName: .sample, cellName: .sample)
}
}
extension MenuViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return samples.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeReusableCell(withReuseIdentifier: .sample, for: indexPath) as! SampleCollectionViewCell
let sample = samples[indexPath.row]
cell.titleLabel.text = sample.name
if sample.imageName != .none {
cell.iconImage.image = UIImage(named: sample.imageName)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
performSegue(withIdentifier: samples[indexPath.row].segue)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let sideSize = view.frame.width / 4
return CGSize(width: sideSize, height: sideSize)
}
}
| true
|
69acaf61825888a1af10da1684713be4be8a4a8e
|
Swift
|
trinhttt/Study_KP
|
/BauCuaGame/BauCuaGame/ViewController.swift
|
UTF-8
| 2,042
| 2.84375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// BauCuaGame
//
// Created by Trinh Thai on 9/15/19.
// Copyright ยฉ 2019 Trinh Thai. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVAudioPlayer = AVAudioPlayer()
@IBOutlet var ibResultImages: [UIImageView]!
var arr: [UIImage?] = [UIImage(named: "bau"), UIImage(named: "ca"), UIImage(named: "cua"), UIImage(named: "ga"), UIImage(named: "nai"), UIImage(named: "tom")]
override func viewDidLoad() {
super.viewDidLoad()
}
override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if event?.subtype == .motionShake {
// Put in code here to handle shake
ring()
let rotate = CABasicAnimation(keyPath: "transform.rotation.z")
rotate.fromValue = 0
rotate.toValue = CFloat.pi * 2
rotate.duration = 0.5
rotate.repeatCount = 3
self.ibResultImages[0].layer.add(rotate, forKey: nil)
self.ibResultImages[1].layer.add(rotate, forKey: nil)
self.ibResultImages[2].layer.add(rotate, forKey: nil)
UIView.animate(withDuration: 1, delay: 1, options: .curveEaseIn, animations: {
self.ibResultImages[0].image = self.arr.randomElement() ?? UIImage()
self.ibResultImages[1].image = self.arr.randomElement() ?? UIImage()
self.ibResultImages[2].image = self.arr.randomElement() ?? UIImage()
}, completion: nil)
}
if super.responds(to: #selector(UIResponder.motionEnded(_:with:))) {
super.motionEnded(motion, with: event)
}
}
func ring() {
let path: String = Bundle.main.path(forResource: "door", ofType: "wav") ?? ""
let url = URL(fileURLWithPath: path)
do {
player = try AVAudioPlayer(contentsOf: url)
player.play()
} catch {
print("\(error)")
}
}
}
| true
|
91b0ec3a1491e160485e1e4b2c3fd30b0f7bcaf9
|
Swift
|
slabgorb/Tiler
|
/Tiler/MapList.swift
|
UTF-8
| 1,590
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// MapList.swift
// Tiler
//
// Created by Keith Avery on 3/27/16.
// Copyright ยฉ 2016 Keith Avery. All rights reserved.
//
import Foundation
class MapList: NSObject, NSCoding {
// MARK:- Properties
var list:[Map] = []
private let file:FileSaveHelper = FileSaveHelper(fileName: "Maps", fileExtension: .JSON)
var count:Int {
return list.count
}
// MARK:- Archiving Paths
static let DocumentsDirectory = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("mapList")
// MARK:- Initializers
init(maps:[Map]) {
list = maps
}
// MARK:- NSCoding
required init?(coder aDecoder: NSCoder) {
if let rawList = aDecoder.decodeObjectForKey("list") as? NSArray {
self.list = rawList.map({$0 as! Map})
}
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(list, forKey:"list")
}
// MARK:- Methods
func get(index:Int) -> Map {
return list[index]
}
func set(index:Int, map:Map) -> Void {
list[index] = map
}
subscript(index: Int) -> Map {
get {
return get(index)
}
set(newValue) {
set(index, map:newValue)
}
}
func append(map:Map) {
list.append(map)
}
func remove(index:Int) {
list.removeAtIndex(index)
}
func swapItems(from:Int, _ to:Int) {
swap(&list[from], &list[to])
}
}
| true
|
833a9ecd7d52842ce9504686e3a3082b6b9be523
|
Swift
|
Mackarous/BuildKit
|
/RxBuildKit/Classes/RxDataDetector.swift
|
UTF-8
| 943
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
import BuildKit
import RxSwift
public final class RxDataDetector: ReactiveCompatible {
fileprivate let dataDetector: DataDetector
fileprivate init(_ dataDetector: DataDetector) {
self.dataDetector = dataDetector
}
}
public extension DataDetector {
var rx: Reactive<RxDataDetector> {
return RxDataDetector(self).rx
}
}
public extension Reactive where Base: RxDataDetector {
func convert(string: String, into attributedString: NSAttributedString) -> Single<DataDetector.Info> {
return .create { observer in
self.base.dataDetector.convert(string: string, into: attributedString) { result in
switch result {
case .success(let info):
observer(.success(info))
case .error(let error):
observer(.error(error))
}
}
return Disposables.create()
}
}
}
| true
|
e2295afa76c61e1708fac801afbe35f088a24ea6
|
Swift
|
LHBosssss/iPod-Player
|
/iPod Player/Models/SongModel.swift
|
UTF-8
| 456
| 2.875
| 3
|
[] |
no_license
|
//
// SongModel.swift
// iPod Player
//
// Created by Ho Duy Luong on 5/25/20.
// Copyright ยฉ 2020 Ho Duy Luong. All rights reserved.
//
import Foundation
import UIKit
struct SongModel {
let id: String
let title: String
let singer: String
let image: UIImage
init(id: String, title: String, singer: String, image: UIImage) {
self.id = id
self.title = title
self.singer = singer
self.image = image
}
}
| true
|
42dda6a51527732f6bf2a73a0ac4397cd79376b9
|
Swift
|
danijelkecman/hello-fresh
|
/HelloFresh/Common/Validation/ValidationError.swift
|
UTF-8
| 851
| 2.640625
| 3
|
[] |
no_license
|
//
// ValidationError.swift
// Sandoz
//
// Created by Danijel Kecman on 26/5/19.
// Copyright ยฉ 2017 danijel. All rights reserved.
//
import Foundation
import UIKit
class ValidationError: NSObject {
let textField: UITextField
var errorTextField: UITextField?
var errorLabel: UILabel?
let errorMessage: String
init(textField: UITextField, error: String) {
self.textField = textField
self.errorMessage = error
}
init(textField: UITextField, errorLabel: UILabel?, error: String) {
self.textField = textField
self.errorLabel = errorLabel
self.errorMessage = error
}
init(textField: UITextField, errorTextField: UITextField?, error: String) {
self.textField = textField
self.errorTextField = errorTextField
self.errorMessage = error
}
}
| true
|
cad9a9bde5c11f6ab76d62f1ac7b0e99ad1a5f4e
|
Swift
|
SungPyo/RxSwiftStudy_Basic
|
/RxSwift_Book.playground/Pages/Declarative Programming.xcplaygroundpage/Contents.swift
|
UTF-8
| 1,294
| 3.484375
| 3
|
[] |
no_license
|
/*:
[Previous](Imperative%20Programming)
# Declarative Programming
๊ทธ๋ผ ์ด์ ์ ์ธํ ํ๋ก๊ทธ๋๋ฐ์ ๋ํด์ ์์๋ด
์๋ค.
์ด์ ์ ์ค๋ช
ํ ๋ช
๋ นํ ํ๋ก๊ทธ๋๋ฐ๊ณผ๋ ์ ํ ๋ค๋ฅธ ๊ฐ๋
์ ๊ฐ์ง๊ณ ์๋๋ฐ์.
์ด๋ป๊ฒ ํ ๊ฒ์ธ์ง(How)์ ํจ๋ฌ๋ค์์ ๊ฐ๋ ๋ช
๋ นํ ํ๋ก๊ทธ๋๋ฐ๊ณผ๋ ๋ฌ๋ฆฌ ์ ์ธํ ํ๋ก๊ทธ๋๋ฐ์ ๋ฌด์์ ํ ๊ฒ์ธ์ง(What)์ ๋ํ ํจ๋ฌ๋ค์์ ๊ฐ์ง๊ณ ์์ต๋๋ค.
์ด์ ์ ํ๋ ์ผ๊ฒน์ด ๊ตฝ๊ธฐ๋ฅผ ์๋ก ๋ค์ด๋ณผ๊น์?
* ์ผ๊ฒน์ด์ ๋์ฅ๊ณ ์ ์๋ค.
* ์ผ๊ฒน์ด์ด ์ต๋ ์๊ฐ์ 10๋ถ์ด๋ค.
์ฐจ์ด๊ฐ ์์ฃ ?!
๋ฌผ๋ก ์์๊ฐ์ ์ ์ธํ ํ๋ก๊ทธ๋๋ฐ๋ ์ฌ๋ฐ๋ฅด๊ฒ ๋์ํ๊ธฐ ์ํด์๋ 'ํ๋ผ์ดํฌ์ ๊ณ ๊ธฐ๊ฐ ์ฌ๋ผ์ค๋ฉด ๋ถ์ ์ผ ๋ค' ๊ฐ์ ๋์๋ค์ด ์ถ์ํ ๋์ด์์ด์ผ ํฉ๋๋ค.
๋ช
๋ นํ ํ๋ก๊ทธ๋๋ฐ์ ์ด๋ป๊ฒ ํ ๊ฒ์ธ์ง์ ๋ํ ์๊ณ ๋ฆฌ์ฆ์ด ๋ช
์๋์ด ์๋ ๋ฐ๋ฉด ์ ์ธํ ํ๋ก๊ทธ๋๋ฐ์ ์ด๋ป๊ฒ ํ ๊ฒ์ธ์ง์ ๋ํ ์๊ณ ๋ฆฌ์ฆ์ ๋ช
์๋์ด ์์ง ์๊ณ , ์ค๋ก์ง ์ผ๊ฒน์ด์ ๊ตฝ๋๋ฐ ํ์ํ ์ ๋ณด๋ง์ ๋ช
์ํ๊ณ ์์ต๋๋ค.
์ด์ ๊ฐ๋จํ ๊ธฐ๋ณธ ๊ฐ๋
์ด ๋๋ฌ์ต๋๋ค. ๋ค์๋ถํฐ๋ RxSwift์ ๋ํด์ ํ๋์ฉ ์์๊ฐ ๋ณด๋๋ก ํฉ์๋ค.
[Next](RxSwift%20Components)
*/
| true
|
b1de46ad61c881cfd99145c82d8a869e22d6bb52
|
Swift
|
CatWatcher/Swift-projects
|
/Lesson 8/Lesson 8/ViewController.swift
|
UTF-8
| 1,161
| 2.90625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Lesson 8
//
// Created by ะคะตะปะธะบั ะคะธะผะฑะตัะณ on 08.10.2020.
//
import UIKit
class ViewController: UIViewController {
let images = ["img1", "img2", "img3", "img4", "img5", "img6", "img7", "img8", "img9", "img10"]
var currentIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
imageView.image = UIImage.init(named: "img1")
}
@IBOutlet weak var imageView: UIImageView!
@IBAction func nextBtn(_ sender: UIButton) {
currentIndex += 1
if currentIndex == 10 {
currentIndex = 0
imageView.image = UIImage.init(named: images[currentIndex])
} else {
imageView.image = UIImage.init(named: images[currentIndex])
}
}
@IBAction func previousBtn(_ sender: UIButton) {
currentIndex -= 1
if currentIndex == -1 {
currentIndex = 9
imageView.image = UIImage.init(named: images[currentIndex])
} else {
imageView.image = UIImage.init(named: images[currentIndex])
}
}
}
| true
|
9d9a4282ab79f4cd50542b2a544d761a84242838
|
Swift
|
xmliteworkltd/WaniKani-iOS
|
/WaniKani/Views/Views/SliceView.swift
|
UTF-8
| 1,089
| 2.859375
| 3
|
[] |
no_license
|
//
// SliceView.swift
// WaniKani
//
// Created by Andriy K. on 9/23/15.
// Copyright ยฉ 2015 Andriy K. All rights reserved.
//
import UIKit
class SliceView: UIView {
private var path: UIBezierPath!
private func recalculateMask(){
let p0 = CGPoint(x: bounds.width, y: 0)
let p1 = CGPoint(x: bounds.width, y: bounds.height)
let p2 = CGPoint(x: 0, y: bounds.height)
let points = [p0, p1, p2]
let p = CGPathCreateMutable()
if points.count > 0 {
let point = points.first!
CGPathMoveToPoint(p, nil, point.x, point.y)
for var i = 1; i < points.count; i++ {
let point = points[i]
CGPathAddLineToPoint(p, nil, point.x, point.y)
}
}
path = UIBezierPath(CGPath: p)
}
override func drawRect(rect: CGRect) {
UIColor.whiteColor().setStroke()
path.lineWidth = 0
path.stroke()
}
override func layoutSubviews() {
super.layoutSubviews()
recalculateMask()
let mask = CAShapeLayer()
mask.frame = bounds
mask.path = path.CGPath
layer.mask = mask
}
}
| true
|
186de240c1d7cf0c74dec6b8ae6ec6fbf974b19d
|
Swift
|
Nirajpaul2/MVVM_Swift
|
/WeatherApp/ViewModel/WeathListingViewModel.swift
|
UTF-8
| 847
| 2.796875
| 3
|
[] |
no_license
|
//
// WeathListingViewModel.swift
// WeatherApp
//
// Created by niraj paul on 01/02/20.
// Copyright ยฉ 2020 administrator. All rights reserved.
//
import Foundation
protocol SuccessResult {
func getSuccessResult()
}
class WeatherViewModel{
var delegate: SuccessResult!
var todayWeatherModules :[TodayWeatherViewModel] = [TodayWeatherViewModel]()
func getWeatherData() {
JsonResponse.singleton.getWeatherJsonObject { (weatherModule) in
let todayWeatherViewModel = TodayWeatherViewModel(wearherData: weatherModule)
self.todayWeatherModules.append(todayWeatherViewModel)
self.delegate.getSuccessResult()
}
}
}
class TodayWeatherViewModel{
var todayWeather: String!
init(wearherData: Weather) {
self.todayWeather = wearherData.todayWeatherReport
}
}
| true
|
5a689c10fb6095ab615ae1eea8c0405fdf5e3403
|
Swift
|
Redhatfour1/TwitterClient
|
/Swift-lab-6/Swift-lab-6/TweetCell.swift
|
UTF-8
| 807
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
//
// TweetCell.swift
// Swift-lab-6
//
// Created by Louis W. Haywood on 7/22/17.
// Copyright ยฉ 2017 Louis W. Haywood. All rights reserved.
//
import UIKit
class TweetCell: UITableViewCell {
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var tweetLabel: UILabel!
@IBOutlet weak var profileImage: UIImageView!
var tweet : Tweet! {
didSet {
self.tweetLabel.text = tweet.text
if let user = tweet.user {
self.usernameLabel.text = user.name
UIImage.fetchImagewith(urlString: user.profileImageURL, completion: {
(profileImage) in
self.profileImage.layer.cornerRadius = 10
self.profileImage.image = profileImage
})
}
}
}
}
| true
|
2a621d92301b036a8ac6549bd4c22882faabe26e
|
Swift
|
Gman9855/On-The-Map
|
/On The Map/StudentPin.swift
|
UTF-8
| 517
| 2.8125
| 3
|
[] |
no_license
|
//
// Student.swift
// On The Map
//
// Created by Gershy Lev on 5/24/15.
// Copyright (c) 2015 Gershy Lev. All rights reserved.
//
import Foundation
import MapKit
class StudentPin: NSObject, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var title: String
var subtitle: String?
init(student: Student) {
self.coordinate = student.locationCoordinate
self.title = student.firstName + " " + student.lastName
self.subtitle = student.mediaURL?.absoluteString
}
}
| true
|
86ffe7029df436c2d5f545312f40c8ce6f482460
|
Swift
|
lerbysha/studentApp
|
/Student/Stats/View/BarView.swift
|
UTF-8
| 911
| 2.84375
| 3
|
[] |
no_license
|
//
// BarView.swift
// Student
//
// Created by ะัััั ะะฐะนัะธะฝ on 08.12.2020.
// Copyright ยฉ 2020 Artur gaisin. All rights reserved.
//
import SwiftUI
struct BarView: View {
var value: CGFloat = 0
var week: String = ""
@available(iOS 13.0.0, *)
var body: some View {
VStack {
ZStack(alignment: .bottom) {
Capsule().frame(width: 30, height: value)
.foregroundColor(Color(#colorLiteral(red: 0.6666070223, green: 0.6667048931, blue: 0.6665855646, alpha: 1)))
Capsule().frame(width: 30, height: value)
.foregroundColor(Color(.white))
Capsule().frame(width: 30, height: value)
.foregroundColor(Color(.white))
Capsule().frame(width: 20, height: value)
.foregroundColor(Color(.white))
Capsule().frame(width: 20, height: value)
.foregroundColor(Color(.white))
}
Text(week)
}
}
}
struct BarView_Previews: PreviewProvider {
@available(iOS 13.0.0, *)
static var previews: some View {
BarView()
}
}
| true
|
404c397de8ecffe09b548bcb4d63d9fc6be1977f
|
Swift
|
JoshuaSullivan/EasyVision
|
/Sources/EasyVision/Protocol/Device.swift
|
UTF-8
| 291
| 2.734375
| 3
|
[] |
no_license
|
import UIKit
/// A wrapper for UIDevice so that it can be mocked.
///
public protocol Device {
var orientation: UIDeviceOrientation { get }
func beginGeneratingDeviceOrientationNotifications()
func endGeneratingDeviceOrientationNotifications()
}
extension UIDevice: Device {}
| true
|
6c86c371b665ba8bcb1ceda5021c7ccf32efef6a
|
Swift
|
injun0701/foodBook
|
/FoodBook/SettingsPage/UserPasswordUpdateViewController.swift
|
UTF-8
| 5,497
| 2.828125
| 3
|
[] |
no_license
|
//
// UserPasswordUpdateViewController.swift
// FoodBook
//
// Created by HongInJun on 2021/05/21.
//
import UIKit
class UserPasswordUpdateViewController: UIViewController {
@IBOutlet var tfCurrentPasswd: UITextField!
@IBOutlet var lblCurrentPasswd: UILabel!
@IBOutlet var tfNewPasswd: UITextField!
@IBOutlet var tfNewPasswdAgain: UITextField!
@IBOutlet var lblNewPasswd: UILabel!
@IBOutlet var btnPasswdUpdate: DisabledBtn!
//์๋ฒ ๊ฐ์ฒด
var req = URLRequest()
//ํ
์คํธํ๋ ์
๋ ฅ์ ๋ง์ณค์๋ ์ํ
@IBAction func tfCurrentPasswdAction(_ sender: UITextField) {
//์ ํจ์ฑ ๊ฒ์ฌ
isCurrentPasswordValid()
}
//ํ์ฌ ๋น๋ฐ๋ฒํธ ์ ํจ์ฑ ๊ฒ์ฌ - ๋น๋ฐ๋ฒํธ ๊ธ์ ์ฒดํฌ
func isCurrentPasswordValid() {
//์ ํจ์ฑ ๊ฒ์ฌ
let cleanedPassword = tfCurrentPasswd.text?.trimmingCharacters(in: .whitespacesAndNewlines)//๊ณต๋ฐฑ ์ ๊ฑฐ
if isPasswordValidCheck(cleanedPassword ?? "") == true {
//๋คํธ์ํฌ ํ์ธ
networkCheck {
//ํ์ฌ ๋น๋ฐ๋ฒํธ๊ฐ ๋ง๋์ง ์๋ฒ์ ์กฐํ
self.currentPasswordCheck()
}
} else {
self.lblCurrentPasswd.text = "์ํ๋ฒณ, ํน์๋ฌธ์๋ฅผ ํฌํจ, 6~12์ ์์ฑํด์ผ ํฉ๋๋ค."
self.lblCurrentPasswd.textColor = UIColor.orange
}
}
//ํ์ฌ ๋น๋ฐ๋ฒํธ๊ฐ ๋ง๋์ง ์๋ฒ์ ์กฐํ
func currentPasswordCheck() {
let passwd = tfCurrentPasswd.text?.trimmingCharacters(in: .whitespacesAndNewlines)//๊ณต๋ฐฑ ์ ๊ฑฐ
//์๋ฒ์ ์กฐํ
req.apiUserPasswordCheck(passwd: passwd!) {
self.lblCurrentPasswd.text = "ํ์ฌ ๋น๋ฐ๋ฒํธ๋ฅผ ์ฑ๊ณต์ ์ผ๋ก ํ์ธ ์๋ฃํ์ต๋๋ค."
self.lblCurrentPasswd.textColor = UIColor().mainColor
//๋ฒํผ ํ์ฑํ
self.btnSignUpIsOn()
} fail: {
self.lblCurrentPasswd.text = "ํ์ฌ ๋น๋ฐ๋ฒํธ๋ฅผ ํ์ธํด์ฃผ์ธ์."
self.lblCurrentPasswd.textColor = UIColor.orange
}
}
//ํ
์คํธํ๋ ์
๋ ฅ์ ๋ง์ณค์๋ ์ํ
@IBAction func tfNewPasswdAction(_ sender: UITextField) {
//๋คํธ์ํฌ ์ฒดํฌ
networkCheck { [self] in
//๋น๋ฐ๋ฒํธ ์ ํจ์ฑ ๊ฒ์ฌ
isNewPasswordValid()
}
}
//ํ
์คํธํ๋ ์
๋ ฅ์ ๋ง์ณค์๋ ์ํ
@IBAction func tfNewPasswdAgainAction(_ sender: UITextField) {
//๋คํธ์ํฌ ์ฒดํฌ
networkCheck { [self] in
//๋น๋ฐ๋ฒํธ ์ ํจ์ฑ ๊ฒ์ฌ
isNewPasswordValid()
}
}
//๋น๋ฐ๋ฒํธ ์ ํจ์ฑ ๊ฒ์ฌ - ๋น๋ฐ๋ฒํธ ๊ธ์ ์ฒดํฌ, ์ผ์น ์ฒดํฌ
func isNewPasswordValid() {
//์ ํจ์ฑ ๊ฒ์ฌ
let cleanedPassword = tfNewPasswd.text?.trimmingCharacters(in: .whitespacesAndNewlines)//๊ณต๋ฐฑ ์ ๊ฑฐ
if isPasswordValidCheck(cleanedPassword ?? "") == true {
if tfNewPasswd.text != tfNewPasswdAgain.text {
lblNewPasswd.text = "์ ๋น๋ฐ๋ฒํธ๊ฐ ์ผ์นํ์ง ์์ต๋๋ค."
lblNewPasswd.textColor = UIColor.orange
} else {
lblNewPasswd.text = "์ฌ์ฉ ๊ฐ๋ฅํ ๋น๋ฐ๋ฒํธ์
๋๋ค."
lblNewPasswd.textColor = UIColor().mainColor
//๋ฒํผ ํ์ฑํ
btnSignUpIsOn()
}
} else {
self.lblNewPasswd.text = "์ํ๋ฒณ, ํน์๋ฌธ์๋ฅผ ํฌํจ, 6~12์๋ก ์์ฑํด์ผ ํฉ๋๋ค."
self.lblNewPasswd.textColor = UIColor.orange
}
}
//๋น๋ฐ๋ฒํธ ์ ํจ์ฑ ๊ฒ์ฌ - ๋น๋ฐ๋ฒํธ ๊ธ์ ์ฒดํฌ
func isPasswordValidCheck(_ password : String) -> Bool{
let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[a-z])(?=.*[$@$#!%*?&])[A-Za-z\\d$@$#!%*?&]{6,12}")
return passwordTest.evaluate(with: password)
}
//๋ฒํผ ํ์ฑํ
func btnSignUpIsOn() {
let btnColor = UIColor().mainColor
if lblCurrentPasswd.textColor == btnColor && lblNewPasswd.textColor == btnColor {
btnPasswdUpdate.isOn = .On
}
}
//์ ์ฅ ๋ฒํผ
@IBAction func btnPasswdUpdateAction(_ sender: DisabledBtn) {
//๋คํธ์ํฌ ํ์ธ
networkCheck {
self.passwdUpdate()
}
}
func passwdUpdate() {
LoadingHUD.show()
guard let cleanedPassword = tfNewPasswd.text?.trimmingCharacters(in: .whitespacesAndNewlines) else { return }
// //AES.swift์ ์๋ ๊ธฐ๋ฅ ์ด์ฉ, ์ฌ์ฉ์๊ฐ ์
๋ ฅํ ํ
์คํธ๋ฅผ ์ํธํํ๋ค.
let encryptPassword = AES256CBC.encryptString(cleanedPassword, password: AESkey().defaultKey)!
//๋น๋ฐ๋ฒํธ ์์
req.apiUserPasswordUpdate(passwd: encryptPassword) {
LoadingHUD.hide()
self.showAlertBtn1(title: "๋น๋ฐ๋ฒํธ ๋ณ๊ฒฝ", message: "๋น๋ฐ๋ฒํธ ๋ณ๊ฒฝ์ด ์ฑ๊ณต์ ์ผ๋ก ์๋ฃ๋์์ต๋๋ค.", btnTitle: "ํ์ธ") {
self.navigationController?.popViewController(animated: true)
}
} fail: {
LoadingHUD.hide()
self.showAlertBtn1(title: "๋น๋ฐ๋ฒํธ ๋ณ๊ฒฝ", message: "๋น๋ฐ๋ฒํธ ๋ณ๊ฒฝ์ ์คํจํ์ต๋๋ค. ๋ค์ ์๋ํด์ฃผ์ธ์.", btnTitle: "ํ์ธ") {
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
navbarSetting(title: "๋น๋ฐ๋ฒํธ ๋ณ๊ฒฝ")
}
}
| true
|
af5da466015c42d27ee2581e6ce6146030f935e9
|
Swift
|
fivechjr/MangaReader-iOS
|
/mangaReader/mangaReader/MangaSources/Protocols/MangaProtocol.swift
|
UTF-8
| 815
| 2.59375
| 3
|
[] |
no_license
|
//
// MangaProtocol.swift
// mangaReader
//
// Created by Yiming Dong on 2018/11/10.
// Copyright ยฉ 2018 Yiming Dong. All rights reserved.
//
import Foundation
protocol MangaProtocol {
var mangaSource: String? {get set}
var mangaId: String? {get set}
var mangaName: String? {get set}
var mangaAuthor: String? {get set}
var mangaDescription: String? {get}
var mangaCreateDate: Double {get}
var mangaUpdateDate: Double {get}
var mangaCategories: [String] {get}
var coverImageUrl: String? {get set}
var topImageUrl: String? {get}
var placeHolderImage: UIImage? {get}
var hits: Int? {get set}
var lastChapterDate: Double? {get set}
func canPublish() -> Bool
var isCompleted: Bool {get}
var chapterObjects: [ChapterProtocol]? {get}
}
| true
|
661747a794d76202bd6a7ef6ff9ceaca375bf887
|
Swift
|
assaft753/Prospera
|
/Prospera/Protocols/MovieFavoriteable.swift
|
UTF-8
| 308
| 2.859375
| 3
|
[] |
no_license
|
//
// MovieFavoriteable.swift
// Prospera
//
// Created by Assaf Tayouri on 09/12/2020.
//
import Foundation
// Protocol (function as delegate) for set favorite movie event
protocol MovieFavoriteable: class {
func addFavoriteMovie(with movieId: String)
func removeFavoriteMovie(with movieId: String)
}
| true
|
d7c10ac5adb8616e80dc491be15929944c71b43d
|
Swift
|
patsluth/Sluthware
|
/Sluthware/Classes/UIKit/UIColor+HSBA.swift
|
UTF-8
| 777
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
//
// UIColor+HSBA.swift
// Sluthware
//
// Created by Pat Sluth on 2017-11-02.
// Copyright ยฉ 2017 patsluth. All rights reserved.
//
import Foundation
public extension UIColor
{
/**
Hue, Saturation, Brightness, Alpha
*/
struct HSBA: Codable, ReflectedStringConvertible
{
var h: CGFloat
var s: CGFloat
var b: CGFloat
var a: CGFloat
public var uiColor: UIColor {
return UIColor(hue: self.h,
saturation: self.s,
brightness: self.b,
alpha: self.a)
}
}
func getHSBA() throws -> HSBA
{
var hsba = HSBA(h: 0.0, s: 0.0, b: 0.0, a: 0.0)
if !self.getHue(&hsba.h, saturation: &hsba.s, brightness: &hsba.b, alpha: &hsba.a) {
throw Errors.Message("\(#function) failed")
}
return hsba
}
}
| true
|
cc034f067740ce61306f40331d7978be390e7996
|
Swift
|
baonhan88/Digital-Signage-iOS
|
/SDSS IOS CLIENT/Features/Dataset/Views/DatasetListCell.swift
|
UTF-8
| 1,463
| 2.65625
| 3
|
[] |
no_license
|
//
// DatasetListCell.swift
// SDSS IOS CLIENT
//
// Created by Nhan on 21/06/2017.
// Copyright ยฉ 2017 SLab. All rights reserved.
//
import UIKit
protocol DatasetListCellDelegate {
func handleTapOnEditButton(dataset: Dataset)
func handleTapOnDeleteButton(dataset: Dataset)
}
class DatasetListCell: UITableViewCell {
@IBOutlet weak var contentVIew: UIView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descLabel: UILabel!
var dataset: Dataset?
var delegate: DatasetListCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.contentVIew.layer.borderColor = UIColor.lightGray.cgColor
self.contentVIew.layer.borderWidth = 1
self.contentVIew.layer.cornerRadius = 8
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func initViewWithDataset(_ dataset: Dataset) {
self.dataset = dataset
nameLabel.text = dataset.name
descLabel.text = dataset.app
}
@IBAction func editButtonClicked(_ sender: UIButton) {
delegate?.handleTapOnEditButton(dataset: self.dataset!)
}
@IBAction func deleteButtonClicked(_ sender: UIButton) {
delegate?.handleTapOnDeleteButton(dataset: self.dataset!)
}
}
| true
|
11f152402ee49959f44312009030314c7bb05cbf
|
Swift
|
TMinusApp/ios-app
|
/TMinus/Model/Rocket.swift
|
UTF-8
| 563
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// Rocket.swift
// TMinus
//
// Created by Dalton Claybrook on 3/18/17.
// Copyright ยฉ 2017 Claybrook Software. All rights reserved.
//
import Foundation
struct Rocket: Codable {
enum CodingKeys: String, CodingKey {
case id
case name
case configuration
case familyName = "familyname"
case agencies
case wikiURL
case imageURL
}
let id: Int
let name: String
let configuration: String
let familyName: String
let agencies: [Agency]
let wikiURL: URL?
let imageURL: URL
}
| true
|
76d5a0c164095284863308ada57320799c400f7d
|
Swift
|
ThePowerOfSwift/Archive
|
/Color/Color/Color.swift
|
UTF-8
| 745
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
//
// Color.swift
// Color
//
// Created by James Bean on 6/10/16.
//
//
import QuartzCore
public struct Color {
public static let red = Color(1, 0, 0, 1)
public static let green = Color(0, 1, 0, 1)
public static let blue = Color(0, 0, 1, 1)
public var cgColor: CGColor
public init(_ red: CGFloat, _ green: CGFloat, _ blue: CGFloat, _ alpha: CGFloat) {
self.cgColor = CGColor(
colorSpace: CGColorSpaceCreateDeviceRGB(),
components: [red, green, blue, alpha]
)!
}
public init(gray: CGFloat, alpha: CGFloat) {
self.cgColor = CGColor(
colorSpace: CGColorSpaceCreateDeviceGray(),
components: [gray, alpha]
)!
}
}
| true
|
678e10bf3a11af981c1ddc9e550a72c9bce18346
|
Swift
|
odnaks/Workplaces
|
/WorkplacesAPITests/Common/Asserts.swift
|
UTF-8
| 2,878
| 2.515625
| 3
|
[] |
no_license
|
//
// Asserts.swift
// WorkplacesAPITests
//
// Created by Kseniya Lukoshkina on 03.05.2021.
//
import Apexy
import XCTest
func assertGET(_ urlRequest: URLRequest, file: StaticString = #file, line: UInt = #line) {
guard let method = urlRequest.httpMethod else {
return XCTFail("The request doesn't have HTTP method", file: file, line: line)
}
XCTAssertEqual(method, "GET", file: file, line: line)
XCTAssertNil(urlRequest.httpBody, "GET request must not have body", file: file, line: line)
}
func assertPOST(_ urlRequest: URLRequest, file: StaticString = #file, line: UInt = #line) {
guard let method = urlRequest.httpMethod else {
return XCTFail("The request doesn't have HTTP method", file: file, line: line)
}
XCTAssertEqual(method, "POST", file: file, line: line)
}
func assertDELETE(_ urlRequest: URLRequest, file: StaticString = #file, line: UInt = #line) {
guard let method = urlRequest.httpMethod else {
return XCTFail("The request doesn't have HTTP method", file: file, line: line)
}
XCTAssertEqual(method, "DELETE", file: file, line: line)
}
func assertPATCH(_ urlRequest: URLRequest, file: StaticString = #file, line: UInt = #line) {
guard let method = urlRequest.httpMethod else {
return XCTFail("The request doesn't have HTTP method", file: file, line: line)
}
XCTAssertEqual(method, "PATCH", file: file, line: line)
}
func assertPath(_ urlRequest: URLRequest, _ path: String, file: StaticString = #file, line: UInt = #line) {
guard let url = urlRequest.url else {
return XCTFail("The request doesn't have URL", file: file, line: line)
}
XCTAssertEqual(url.path, path, "Request's path doesn't match", file: file, line: line)
}
func assertURL(_ urlRequest: URLRequest, _ urlString: String, file: StaticString = #file, line: UInt = #line) {
guard let url = urlRequest.url else {
return XCTFail("The request doesn't have URL", file: file, line: line)
}
XCTAssertEqual(url.absoluteString, urlString, "Request's URL doesn't match", file: file, line: line)
}
func assertHTTPHeaders(_ urlRequest: URLRequest, _ headers: [String: String], file: StaticString = #file) {
XCTAssertEqual(urlRequest.allHTTPHeaderFields, headers)
}
func assertJsonBody(_ urlRequest: URLRequest, _ jsonBody: HTTPBody, file: StaticString = #file, line: UInt = #line) {
guard let body = urlRequest.httpBody else {
return XCTFail("The request doesn't have body", file: file, line: line)
}
if let contentType = urlRequest.value(forHTTPHeaderField: "Content-Type") {
XCTAssertTrue(contentType.contains("application/json"), "Content-Type ะทะฐะฟัะพั ะฝะต json")
} else {
XCTFail("The request doesn't have HTTP Header Content-Type", file: file, line: line)
}
XCTAssertEqual(body, jsonBody.data, file: file, line: line)
}
| true
|
a1c26f6148b961bd610241efe3944d376be268a0
|
Swift
|
justinshuls/iOS-Extended-Library
|
/Extensions.swift
|
UTF-8
| 4,069
| 2.921875
| 3
|
[] |
no_license
|
//
// Extensions.swift
// Extentions Master
//
// Created by Justin Shulman on 10/1/18.
//
import Foundation
//MARK:- string
extension String {
func copyText() {
UIPasteboard.general.string = self
}
var isBackspace: Bool {
let char = self.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
return isBackSpace == -92
}
var hasText: Bool {
return !self.isEmpty
}
func trimWhiteSpace() -> String {
return self.trimmingCharacters(in: .whitespaces)
}
var filteredNumbers: String {
return components(separatedBy: CharacterSet.decimalDigits.inverted)
.joined()
}
var filteredPhoneDigits: String {
let including = CharacterSet.decimalDigits.union(CharacterSet(charactersIn: "+:;"))
return components(separatedBy: including.inverted)
.joined()
}
var filteredSpaces: String {
return self.replacingOccurrences(of: " ", with: "")
}
}
//MARK:- float
extension Float {
func decimialPlaces(count: Int) -> String {
return String(format: "%.\(count)f", self)
}
var clean: String {
return self.truncatingRemainder(dividingBy: 1) == 0 ? String(format: "%.0f", self) : String(self)
}
}
//MARK:- image
extension UIImage {
func rotate(degrees: CGFloat) -> UIImage {
let rad = degrees/57.2958
let rotatedSize = CGRect(origin: .zero, size: size)
.applying(CGAffineTransform(rotationAngle: CGFloat(rad)))
.integral.size
UIGraphicsBeginImageContext(rotatedSize)
if let context = UIGraphicsGetCurrentContext() {
let origin = CGPoint(x: rotatedSize.width / 2.0,
y: rotatedSize.height / 2.0)
context.translateBy(x: origin.x, y: origin.y)
context.rotate(by: rad)
draw(in: CGRect(x: -origin.x, y: -origin.y,
width: size.width, height: size.height))
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return rotatedImage ?? self
}
return self
}
func imageSize(size: CGSize) -> UIImage {
let hasAlpha = true
let scale: CGFloat = 0.0
UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
self.draw(in: CGRect(origin: .zero, size: size))
let sizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return sizedImage!
}
func imageColor(color: UIColor) -> UIImage {
self.withRenderingMode(.alwaysTemplate)
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
if let context = UIGraphicsGetCurrentContext() {
context.setBlendMode(.normal)
context.translateBy(x: 0, y: self.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.draw(self.cgImage!, in: rect)
context.clip(to: rect, mask: self.cgImage!)
context.setFillColor(color.cgColor)
context.fill(rect)
}
let colorizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return colorizedImage!
}
}
//MARK:- application
extension UIApplication {
var statusBarView: UIView? {
return value(forKey: "statusBar") as? UIView
}
}
//MARK:- haptic
func haptic(type: UINotificationFeedbackGenerator.FeedbackType) {
UINotificationFeedbackGenerator().notificationOccurred(type)
}
func haptic(intensity: UIImpactFeedbackGenerator.FeedbackStyle) {
let generator = UIImpactFeedbackGenerator(style: intensity)
generator.impactOccurred()
}
| true
|
90a40cb468a1373cb4c2eefd700f4fe45ac833d0
|
Swift
|
yigitkader/Starting-Swift
|
/Images/Images/ViewController.swift
|
UTF-8
| 668
| 2.59375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Images
//
// Created by calzom on 24.08.2019.
// Copyright ยฉ 2019 YigitKader. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var num = 0
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func changeButton(_ sender: Any) {
if num % 2 == 0 {
imageView.image = UIImage(named: "james.jpg")
num += 1
}
else{
imageView.image = UIImage(named: "kirk.jpg")
num += 1
}
}
}
| true
|
e91420dc42d082103940c6fd631883002e457004
|
Swift
|
rozenamah/Zearh
|
/Rozenamah/Scenes/Session/Common/Validators/EmailValidation.swift
|
UTF-8
| 460
| 2.75
| 3
|
[] |
no_license
|
//
// EmailValidation.swift
// Rozenamah
//
// Created by Dominik Majda on 13.03.2018.
// Copyright ยฉ 2018 Dominik Majda. All rights reserved.
//
import Foundation
class EmailValidation {
class func validate(email testString: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: testString)
}
}
| true
|
3dee08b676a6262f38155f5a1ddaa93b2011fdd5
|
Swift
|
jok886/weibodemo
|
/weibodemo/classes/main/OAuth/WBOAuthViewController.swift
|
UTF-8
| 7,380
| 2.59375
| 3
|
[] |
no_license
|
//
// WBOAuthViewController.swift
// weibodemo
//
// Created by macliu on 2021/1/23.
//
import UIKit
import SVProgressHUD
class WBOAuthViewController: UIViewController {
private lazy var webView = UIWebView()
override func loadView() {
view = webView
view.backgroundColor = UIColor.white
//ๅๆถ้กต้ขๆปๅจ
webView.scrollView.isScrollEnabled = false
//่ฎพ็ฝฎไปฃ็
webView.delegate = self
// ่ฎพ็ฝฎๅฏผ่ชๆ
title = "็ป้ๆฐๆตชๅพฎๅ"
//ๅฏผ่ชๆ ๆ้ฎ
// navigationItem.leftBarButtonItem = UIBarButtonItem(title: "่ฟๅ", target: self, action: #selector(close), isBack: true)
// navigationItem.rightBarButtonItem = UIBarButtonItem(title: "่ชๅจๅกซๅ
", target: self, action: #selector(autoFill))
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "ๅ
ณ้ญ", style: .plain,target: self,action: "close")
//2่ฎพ็ฝฎๅณ
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "ๅกซๅ
", style: .plain,target: self,action: "autoFill")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_uri)"
//1> ็กฎๅฎ่ฆ่ฎฟ้ฎ็ๅฏน่ฑก
guard let url = URL(string: urlString) else {
return
}
//2> ๅปบ็ซ่ฏทๆฑ
let request = URLRequest(url:url)
//3> ๅ ่ฝฝ่ฏทๆฑ
webView.loadRequest(request)
}
//MARK: - ็ๅฌๆนๆณ
@objc private func close(){
SVProgressHUD.dismiss()
dismiss(animated: true, completion: nil)
}
/// ่ชๅจๅกซๅ
็จๆทๅๅๅฏ็
@objc private func autoFill() {
//ๅๅคjs
let js = "document.getElementById('userId').value = '13532265108';" + "document.getElementById('passwd').value = 'Kk2615391';"
//่ฎฉwebviewๆง่ก js
webView.stringByEvaluatingJavaScript(from: js)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension OAuthViewController {
}
extension WBOAuthViewController : UIWebViewDelegate {
/// webViewๅฐ่ฆๅ ่ฝฝ่ฏทๆฑ
/// - Parameters:
/// - webView: webView
/// - request: j่ฆๅ ่ฝฝ็่ฏทๆฑ
/// - navigationType: ๅฏผ่ช็ฑปๅ
///
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
if request.url?.absoluteString.hasPrefix(redirect_uri) == false {
return true
}
print("ๅ ่ฝฝ่ฏทๆฑ ---- \(String(describing: request.url?.absoluteString))")
print("ๅ ่ฝฝ่ฏทๆฑ ---- \(String(describing: request.url?.query))")
if request.url?.query?.hasPrefix("code=") == false {
print("ๅๆถๆๆ")
close()
return false
}
let code = String(request.url?.query?["code=".endIndex...] ?? "")
print("่ทๅๆๆ็ \(code)")
//4> ไฝฟ็จๆๆๅ ่ทๅAccessToken
loadAccessToken(code: code)
/* WBNetworkManager.shared().getAccessToken(code: code) { (isSuccess) in
if !isSuccess {
SVProgressHUD.showInfo(withStatus: "็ป้ๅคฑ่ดฅ")
}else {
SVProgressHUD.showInfo(withStatus: "็ป้ๆๅ")
//1> ้่ฟ้็ฅ่ทณ่ฝฌ ๅ้็ป้ๆๅๆถๆฏ
NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
self.close()
}
}*/
return false
}
func webViewDidStartLoad(_ webView: UIWebView) {
SVProgressHUD.show()
}
func webViewDidFinishLoad(_ webView: UIWebView) {
SVProgressHUD.dismiss()
}
func loadAccessToken(code : String) {
NetWorkTool.shareIntance.loadAccessToken(code: code) { (result, error) in
//
if error != nil {
print(error)
return
}
/* {
"access_token": "ACCESS_TOKEN",
"expires_in": 157679999, //access_token็็ๅฝๅจๆ๏ผๅไฝๆฏ็งๆฐ
"remind_in":"798114",
"uid":"12341234" //ๆๆ็จๆท็UID๏ผๆฌๅญๆฎตๅชๆฏไธบไบๆนไพฟๅผๅ่
}
*/
//ๆฟๅฐ็ปๆ
guard let accountDict = result else {
print("no data")
return
}
//
let account = UserAccount(dict: result! as [String : AnyObject])
//่ฏทๆฑ็จๆทไฟกๆฏ
self.loadUserInfo(account: account)
}
}
//
private func loadUserInfo(account : UserAccount) {
//1
guard let accesstoken = account.access_token else {
return
}
//2
guard let uid = account.uid else {
return
}
//3
NetWorkTool.shareIntance.loadUserInfo(access_token: accesstoken, uid: uid) { (result, error) in
if error != nil {
//ๅบ้
print(error)
return
}
//ๆฟๅฐ็จๆทไฟกๆฏ
//screen_name string ็จๆทๆต็งฐ
// profile_image_url string ็จๆทๅคดๅๅฐๅ๏ผไธญๅพ๏ผ๏ผ50ร50ๅ็ด
// avatar_large string ็จๆทๅคดๅๅฐๅ๏ผๅคงๅพ๏ผ๏ผ180ร180ๅ็ด
// avatar_hd string ็จๆทๅคดๅๅฐๅ๏ผ้ซๆธ
๏ผ๏ผ้ซๆธ
ๅคดๅๅๅพ
guard let userInfoDict = result else {
return
}
//ๅๅบๆต็งฐๅๅคดๅๅฐๅ
account.screen_name = userInfoDict["screen_name"] as? String
account.avatar_large = userInfoDict["avatar_large"] as? String
//4. account ๅฏน่ฑกไฟๅญ
//4.1ๆฒ็
// var accountPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
// accountPath = (accountPath as NSString).appendingPathComponent("account.plist")
// print(accountPath)
//4.2ไฟๅญ
NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewMode.shareInstance.accountPath)
//4.3
UserAccountViewMode.shareInstance.account = account;
//5 ้ๅบๅฝๅๆงๅถๅจ
self.dismiss(animated: true) {
UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
}
//5. ๆพ็คบๆฌข่ฟ็้ข
}
}
}
| true
|
2ae0d7e5fee628e3265c840df58bcb78217a6496
|
Swift
|
Vyeczorny/mgr
|
/Benchmarks/Benchmarks/Framework/Exporters/TerminalExporter.swift
|
UTF-8
| 555
| 2.5625
| 3
|
[] |
no_license
|
//
// Created by Karol on 21.08.2018.
// Copyright (c) 2018 Karol Wieczorek. All rights reserved.
//
import Foundation
class TerminalExporter {
func export(testSuiteResult: TestSuiteResult) {
print("WYNIKI TESTรW:")
for testResult in testSuiteResult.testResults {
print("Test: \(testResult.name)")
for testInstanceResult in testResult.testResults {
print("\(testInstanceResult.n) -> \(String(format: "%.5f", testInstanceResult.averageTime)) s")
}
print("\n")
}
}
}
| true
|
f397b7471539432221c43f4a252f6e30d7c2d7f3
|
Swift
|
iandundas/HotTakeDemo
|
/Carthage/Checkouts/HotTakeCore/HotTakeCore/Sources/DataSources/PostSort.swift
|
UTF-8
| 1,048
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
//
// PostSort.swift
// HotTakeCore
//
// Created by Ian Dundas on 30/11/2016.
// Copyright ยฉ 2016 Ian Dundas. All rights reserved.
//
import Foundation
import ReactiveKit
/* Wraps an existing DataSource allowing a sort order to be applied to it */
public class PostSortDataSource<Item: Equatable>: DataSourceType {
public func items() -> [Item] {
return collection.sort(isOrderedBefore)
}
public func mutations() -> Stream<CollectionChangeset<[Item]>>{
return collection.sort(isOrderedBefore)
}
private let internalDataSource: AnyDataSource<Item>
private let collection: CollectionProperty<Array<Item>>
private let isOrderedBefore: (Item, Item) -> Bool
public init(datasource: AnyDataSource<Item>, isOrderedBefore: (Item, Item)->Bool){
self.internalDataSource = datasource
self.isOrderedBefore = isOrderedBefore
collection = CollectionProperty<[Item]>(datasource.items())
internalDataSource.mutations().bindTo(collection)
}
}
| true
|
2adffb14c7d2a26cef7e148b2f33cb8bc86bfff4
|
Swift
|
rysmende/Domkom
|
/Domkom/NewsCell.swift
|
UTF-8
| 769
| 2.515625
| 3
|
[] |
no_license
|
//
// NewsCell.swift
// Domkom
//
// Created by Nurzhan Ababakirov on 2/12/20.
// Copyright ยฉ 2020 Nurzhan Ababakirov. All rights reserved.
//
import UIKit
class NewsCell: UITableViewCell {
@IBOutlet weak var newsTitle: UILabel!
@IBOutlet weak var newsDate: UILabel!
@IBOutlet weak var newsImage: UIImageView!
@IBOutlet weak var newsComs: UILabel!
func configure(news: NewsCellStruct) {
newsTitle.text = news.title
newsDate.text = news.date
ServerManager.shared.getImage(url: news.image, { (image) in
self.newsImage.image = image
}, { (error) in
self.newsImage.image = UIImage(named: "LaunchBackground")
})
newsComs.text = "ะะพะปะธัะตััะฒะพ ะบะพะผะผะตะฝัะฐัะธะตะฒ: "
}
}
| true
|
404fb85b43cdd39390930a88134848c8d2547c8c
|
Swift
|
nick262/SwiftStudyRoom
|
/ThirdWeek/Project03-CollectionViewWithNavgationBarAndTabBar/Project03-CollectionViewWithNavgationBarAndTabBar/Model.swift
|
UTF-8
| 439
| 2.625
| 3
|
[] |
no_license
|
//
// Model.swift
// Project03-CollectionViewWithNavgationBarAndTabBar
//
// Created by Nick Wang on 04/11/2017.
// Copyright ยฉ 2017 Nick Wang. All rights reserved.
//
import UIKit
class Model {
var width: Int
var height: Int
var tag: Bool
var img: String
init(width:Int, height:Int, tag:Bool, img: String) {
self.width = width
self.height = height
self.tag = tag
self.img = img
}
}
| true
|
1a03a3b5de516496ba851cf8d7439a12c8342821
|
Swift
|
tonylibra/FacebookAlgorithm
|
/FacebookInterview/PopulatingNextRightPointersinEachNode.swift
|
UTF-8
| 1,708
| 3.203125
| 3
|
[] |
no_license
|
//
// PopulatingNextRightPointersinEachNode.swift
// FacebookInterview
//
// Created by YangYusheng on 6/12/17.
// Copyright ยฉ 2017 yusheng. All rights reserved.
//
import Foundation
class TreeLinkNode {
var val: Int
var left: TreeLinkNode?
var right: TreeLinkNode?
var next: TreeLinkNode?
init(_ val: Int) {
self.val = val
}
}
class PopulatingNextRightPointersinEachNode {
//I, a perfect tree
//simply level order traverse, and connect each node in a level
func connectI(_ root: TreeLinkNode) {
}
//II: not a perfect tree
func connectII(_ root: TreeLinkNode) {
var parent: TreeLinkNode? = root
while parent != nil {
var pNext: TreeLinkNode?
var pre: TreeLinkNode?
while let currentParent = parent {
if pNext == nil {
pNext = currentParent.left ?? currentParent.right
}
if let left = currentParent.left {
if let curtPre = pre {
curtPre.next = left
pre = curtPre.next
} else {
pre = left
}
}
if let right = currentParent.right {
if let curtPre = pre {
curtPre.next = right
pre = curtPre.next
} else {
pre = right
}
}
parent = currentParent.next
}
//parent?.next = pNext
parent = pNext
}
}
}
| true
|
21f069450f46a541574f4fb3f8eb6e38590d94fd
|
Swift
|
Shlomi610/Culture
|
/Culture/Networking/Download image API/DownloadImage.swift
|
UTF-8
| 527
| 3.03125
| 3
|
[] |
no_license
|
//
// DownloadImage.swift
// Culture
//
// Created by Shlomi Sharon on 04/11/2020.
//
import UIKit
import Alamofire
protocol DownloadImageProtocol {
func getImage(with url: URL, completion: @escaping (UIImage?)->())
}
class DownloadImage: NSObject, DownloadImageProtocol {
func getImage(with url: URL, completion: @escaping (UIImage?) -> ()) {
AF.request(url).response { response in
guard let data = response.data else { return }
let image = UIImage(data: data, scale: 1)
completion(image)
}
}
}
| true
|
39bdb992dd705f079a2069c9638bf3dfda66e161
|
Swift
|
hetansh9/Recipes
|
/Shared/Graphics/BlobShapeTop.swift
|
UTF-8
| 1,251
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// BlobShapeTop.swift
// Onboarding 1
//
// Created by Sourany on 2021-04-01.
//
import SwiftUI
struct BlobShapeTop: Shape {
func path(in rect: CGRect) -> Path {
var path = Path()
let width = rect.size.width
let height = rect.size.height
path.move(to: CGPoint(x: 0.66498*width, y: 0.70619*height))
path.addCurve(to: CGPoint(x: 0.38191*width, y: 0.89473*height), control1: CGPoint(x: 0.48737*width, y: 0.70619*height), control2: CGPoint(x: 0.46229*width, y: 0.78158*height))
path.addCurve(to: CGPoint(x: 0.03778*width, y: 0.35427*height), control1: CGPoint(x: 0.17654*width, y: 1.18381*height), control2: CGPoint(x: -0.06879*width, y: 0.78664*height))
path.addCurve(to: CGPoint(x: 0.89255*width, y: 0.27257*height), control1: CGPoint(x: 0.17099*width, y: -0.18619*height), control2: CGPoint(x: 0.63723*width, y: 0.01491*height))
path.addCurve(to: CGPoint(x: 0.66498*width, y: 0.70619*height), control1: CGPoint(x: 1.14787*width, y: 0.53023*height), control2: CGPoint(x: 0.887*width, y: 0.70619*height))
path.closeSubpath()
return path
}
}
struct BlobShapeTop_Previews: PreviewProvider {
static var previews: some View {
BlobShapeTop()
}
}
| true
|
6a4007fe16fc27fd945357a79f8230d86013781a
|
Swift
|
theFreelancer198/DiagnalMovies
|
/DiagnalMovies/ViewModel/DMMoviesListViewModel.swift
|
UTF-8
| 2,678
| 2.9375
| 3
|
[] |
no_license
|
//
// DMMoviesListViewModel.swift
// DiagnalMovies
//
// Created by Abhishek on 30/04/20.
// Copyright ยฉ 2020 Abhishek. All rights reserved.
//
import Foundation
protocol MoviesViewModelDelegate: class {
func onFetchCompleted(with newIndexPathsToReload: [IndexPath]?)
func onFetchFailed(with reason: String)
}
final class MoviesViewModel {
private weak var delegate: MoviesViewModelDelegate?
var movies: [Movie] = []
var title: String = ""
private var currentPage = 1
private var total = 0
private var isFetchInProgress = false
init(delegate: MoviesViewModelDelegate) {
self.delegate = delegate
}
var totalCount: Int {
return total
}
var currentCount: Int {
return movies.count
}
func movie(at index: Int) -> Movie {
return movies[index]
}
func fetchMovies() {
guard !isFetchInProgress else {
return
}
isFetchInProgress = true
if let path = Bundle.main.path(forResource: "CONTENTLISTINGPAGE-PAGE\(currentPage)", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
let apiResponse = try JSONDecoder().decode(MovieApiResponse.self, from: data)
self.currentPage += 1
self.isFetchInProgress = false
self.total = Int(apiResponse.responseDetails.totalItems)!
self.title = apiResponse.responseDetails.title
self.movies.append(contentsOf: apiResponse.responseDetails.contentItem.content)
if Int(apiResponse.responseDetails.currentPage)! > 1 {
let indexPathsToReload = self.calculateIndexPathsToReload(from: apiResponse.responseDetails.contentItem.content)
self.delegate?.onFetchCompleted(with: indexPathsToReload)
} else {
self.delegate?.onFetchCompleted(with: .none)
}
} catch {
self.isFetchInProgress = false
self.delegate?.onFetchFailed(with: error.localizedDescription)
}
}
else{
self.isFetchInProgress = false
self.delegate?.onFetchFailed(with: "Json file not found.")
}
}
private func calculateIndexPathsToReload(from newMovies: [Movie]) -> [IndexPath] {
let startIndex = movies.count - newMovies.count
let endIndex = startIndex + newMovies.count
return (startIndex..<endIndex).map { IndexPath(row: $0, section: 0) }
}
}
| true
|
a46c2df7e4841d3ea63d63149ec335060dda55e0
|
Swift
|
diegosalazarCO/Swift-Series
|
/03. Novedades Swift 2/Parte 1 - Manejo de Errores.playground/Contents.swift
|
UTF-8
| 3,066
| 4.25
| 4
|
[] |
no_license
|
/*:
#### What's New in Swift 2 Video Tutorial Series - raywenderlich.com
#### Error Handling Challenge
**Note:** If you're seeing this text as comments rather than nicely-rendered text, select Editor\Show Rendered Markup in the Xcode menu.
In this challenge, you'll try handling the `InsufficientFunds` error case. We already added the enum case to `CoinWalletError` in the demo, so scroll down to `makePurchase(_:seller:)` to continue.
*/
import Foundation
enum CoinWalletError: ErrorType {
case ExceedsMaximumBalance
case InsufficientFunds(shortAmount: Int)
}
class CoinWallet: CustomStringConvertible {
private let maximumBalance = 1000
private(set) var balance: Int = 0
var description: String {
return "CoinWallet with \(balance) balance"
}
func deposit(amount: Int) throws {
if balance + amount > maximumBalance {
throw CoinWalletError.ExceedsMaximumBalance
}
balance += amount
}
/*:
Just as you did for `deposit(_:)` in the demo, you'll need to edit this method to throw an error.
1. Remove the existing error handling code that calls `fatalError(_:)`
2. Add a check to the top of the method. You'll need to throw an error if the purchase `amount` is greater than the current balance. Remember, the `InsufficientFunds` case also has an associated `Int` value with the amount of coins short.
3. Mark the method as `throws`.
Once you've finished, scroll down to the bottom of the playground to test!
*/
func makePurchase(amount: Int, seller: String) throws {
if amount > balance {
let difference = amount - balance
throw CoinWalletError.InsufficientFunds(shortAmount: difference)
}
balance -= amount
}
}
func starterWallet() -> CoinWallet {
let myWallet = CoinWallet()
try! myWallet.deposit(100)
return myWallet
}
let wallet = starterWallet()
do {
try wallet.deposit(9500)
} catch CoinWalletError.ExceedsMaximumBalance {
print("You cannot deposit that many coins!")
}
wallet
/*:
Now it's time to test your code! At this point, you have 100 coins in your wallet. Try making a purchase for 50 coins and ensure it works. Then, try making a purchase for 200 coins and make sure you catch the error correctly!
You can have a look above at the `deposit(_:)` example if you need a reminder on the do/try/catch syntax. Good luck!
As a first try, make sure you're catching the `InsufficientFunds` error correctly. Remember, there's also that `shortAmount` associated value that can help you print out a more helpful error message such as "You need n more coins to make that purchase". If you've forgotten how to bind an associated value, check out the challenge solution.
*/
do {
try wallet.makePurchase(50, seller: "Zara")
} catch CoinWalletError.InsufficientFunds(let shortAmount) {
print("You cannot purchase that in Zara. You need \(shortAmount)")
}
wallet
do {
try wallet.makePurchase(200, seller: "Zara")
} catch CoinWalletError.InsufficientFunds(let shortAmount) {
print("You cannot purchase that in Zara. You need \(shortAmount)")
}
wallet
| true
|
b452cdaae728a064a19be8fc924831c09c985059
|
Swift
|
PabloRb2X/MarvelSH
|
/MarvelSH/DescriptionSuperhero/UI/ViewController/DescriptionSuperheroViewController.swift
|
UTF-8
| 2,536
| 2.578125
| 3
|
[] |
no_license
|
//
// DescriptionSuperheroViewController.swift
// MarvelSH
//
// Created by Pablo Ramirez on 10/31/19.
// Copyright ยฉ 2019 Pablo Ramirez. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
protocol DescriptionSuperheroViewOutput {
var title: String { get }
var realName: String { get }
var height: String { get }
var power: String { get }
var abilities: String { get }
var groups: String { get }
var photo: String { get }
var groupsDataSource: BehaviorRelay<[String]> { get }
func didLoad()
}
class DescriptionSuperheroViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet private weak var titleLabel: UILabel! {
didSet {
titleLabel.text = presenter.title
}
}
@IBOutlet private weak var superheroImageView: UIImageView! {
didSet {
superheroImageView.imageFromServerURL(presenter.photo, placeHolder: superheroImageView.image)
}
}
@IBOutlet private weak var realNameLabel: UILabel! {
didSet {
realNameLabel.text = presenter.realName
}
}
@IBOutlet private weak var heightLabel: UILabel! {
didSet {
heightLabel.text = presenter.height
}
}
@IBOutlet private weak var powerLabel: UILabel! {
didSet {
powerLabel.text = presenter.power
}
}
@IBOutlet private weak var abilitiesLabel: UILabel! {
didSet {
abilitiesLabel.text = presenter.abilities
}
}
private let presenter: DescriptionSuperheroViewOutput
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
setup()
presenter.didLoad()
}
init(presenter: DescriptionSuperheroViewOutput) {
self.presenter = presenter
super.init(nibName: "DescriptionSuperheroViewController", bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private extension DescriptionSuperheroViewController {
func setup() {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "TableViewCell")
presenter.groupsDataSource.asObservable().bind(to: tableView.rx.items(cellIdentifier: "TableViewCell")) { index, group, cell in
cell.textLabel?.text = group
}.disposed(by: disposeBag)
}
}
| true
|
d472c321d14bdbb3ecef81ec7fe5832088523ef0
|
Swift
|
YauheniYarotski/ExchageAgregator
|
/Sources/App/Api/Http/BitfinexRest.swift
|
UTF-8
| 2,396
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// BitstampRest.swift
// App
//
// Created by Yauheni Yarotski on 4/9/19.
//
import Foundation
import Vapor
class BitfinexRest {
let hostname = "api-pub.bitfinex.com"
let secondHostName = "api.bitfinex.com"
let apiOrderBook = "/v2/book/t"
let apiPairs = "/v1/symbols"
var didGetFullBook: ((_ bookResponse: BitfinexBookAllPricesSnapshotResponse)->())?
var didGetPairs: ((_ reposen: [String])->())?
func getFullBook(for pair: String) {
let httpReq = HTTPRequest(method: .GET, url: apiOrderBook + pair + "/P2")
let _ = HTTPClient.connect(scheme: .https, hostname: hostname, on: wsClientWorker).do { client in
let _ = client.send(httpReq).do({ response in
//if let bookResponse: BitstampBookResponse = try? JSONDecoder().decode(BitstampBookResponse.self, from: jsonData)
//geting snap of all prices or single snape
if let jsonData = response.body.data,
let parsedAny = try? JSONSerialization.jsonObject(with:
jsonData, options: []),
let draftPricesSnap = parsedAny as? [[Double]],
draftPricesSnap.count > 0 {
var pricesSnapshor = [BitfinexBookPrice]()
for draftPriceSnap in draftPricesSnap {
let priceSnap = BitfinexBookPrice(price: draftPriceSnap[0], count: Int(draftPriceSnap[1]), amount: draftPriceSnap[2])
pricesSnapshor.append(priceSnap)
}
let bitfinexBookAllPricesSnapshotResponse = BitfinexBookAllPricesSnapshotResponse.init(chanId: -99, prices: pricesSnapshor, pair: pair)
self.didGetFullBook?(bitfinexBookAllPricesSnapshotResponse)
} else {
print("\(self), annown answer from server", response.body)
}
})
}
}
func getPairs() {
let httpReq = HTTPRequest(method: .GET, url: apiPairs)
let _ = HTTPClient.connect(scheme: .https, hostname: secondHostName, on: wsClientWorker).do { client in
let _ = client.send(httpReq).do({ response in
if let jsonData = response.body.data,
let parsedAny = try? JSONSerialization.jsonObject(with:
jsonData, options: []),
let pairs = parsedAny as? [String],
pairs.count > 0 {
self.didGetPairs?(pairs)
} else {
print("\(self), annown answer from server", response.body)
}
})
}
}
}
| true
|
e3a1506d08b7a3b6d24999d7495d74ceb9e85d6a
|
Swift
|
AnneBlair/captureDemo
|
/captureDemo/CaptureSessionCoordinator.swift
|
UTF-8
| 4,420
| 2.640625
| 3
|
[] |
no_license
|
//
// CaptureSessionCoordinator.swift
// captureDemo
//
// Created by ๅบๅๅฝ้
๏ผyin on 2017/3/22.
// Copyright ยฉ 2017ๅนด blog.aiyinyu.com. All rights reserved.
//
import UIKit
import AVFoundation
/// ็บฟ็จๅ ้
///
/// - Parameters:
/// - lock: ๅ ้ๅฏน่ฑก
/// - dispose: ๆง่ก้ญๅ
ๅฝๆฐ,
func synchronized(_ lock: AnyObject,dispose: ()->()) {
objc_sync_enter(lock)
dispose()
objc_sync_exit(lock)
}
protocol captureSessionCoordinatorDelegate: class {
func coordinatorDidBeginRecording(coordinator: CaptureSessionCoordinator)
func didFinishRecording(coordinator: CaptureSessionCoordinator,url: URL)
}
class CaptureSessionCoordinator: NSObject {
var captureSession: AVCaptureSession?
var cameraDevice: AVCaptureDevice?
var delegateCallQueue: DispatchQueue?
weak var delegate: captureSessionCoordinatorDelegate?
private var sessionQueue = DispatchQueue(label: "coordinator.Session")
private var previewLayer: AVCaptureVideoPreviewLayer?
override init() {
super.init()
captureSession = setupCaptureSession()
}
public func setDelegate(capDelegate: captureSessionCoordinatorDelegate,queue: DispatchQueue) {
synchronized(self) {
delegate = capDelegate
if delegateCallQueue != queue {
delegateCallQueue = queue
}
}
}
//MARK: ________________Session Setup________________
private func setupCaptureSession() -> AVCaptureSession {
let session = AVCaptureSession()
// session.sessionPreset = AVCaptureSessionPresetiFrame1280x720
if !addDefaultCameraInputToCaptureSession(capSession: session) {
printLogDebug("failed to add camera input to capture session")
}
if !addDefaultMicInputToCaptureSession(capSession: session) {
printLogDebug("failed to add mic input to capture session")
}
return session
}
private func addDefaultCameraInputToCaptureSession(capSession: AVCaptureSession) -> Bool {
do {
let cameraInput = try AVCaptureDeviceInput(device: AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo))
let success = addInput(input: cameraInput, capSession: capSession)
cameraDevice = cameraInput.device
return success
} catch let error as NSError {
printLogDebug("error configuring camera input: \(error.localizedDescription)")
return false
}
}
private func addDefaultMicInputToCaptureSession(capSession: AVCaptureSession) -> Bool {
do {
let micInput = try AVCaptureDeviceInput(device: AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeAudio))
let success = addInput(input: micInput, capSession: capSession)
return success
} catch let error as NSError {
printLogDebug("error configuring mic input: \(error.localizedDescription)")
return false
}
}
//MARK: ________________Public Api________________
func addInput(input: AVCaptureDeviceInput,capSession: AVCaptureSession) -> Bool {
if capSession.canAddInput(input) {
capSession.addInput(input)
return true
}
printLogDebug("input error")
return false
}
func addOutput(output: AVCaptureOutput,capSession: AVCaptureSession) -> Bool {
if capSession.canAddOutput(output) {
capSession.addOutput(output)
return true
}
printLogDebug("output error")
return false
}
func startRunning() {
sessionQueue.async {
self.captureSession?.startRunning()
}
}
func stopRunning() {
sessionQueue.async {
self.stopRunning()
self.captureSession?.stopRunning()
}
}
func startRecording() {
// ๅญ็ฑป็ปงๆฟๅ้ๅ
}
func stopRecording() {
// ๅญ็ฑป็ปงๆฟๅ้ๅ
}
func previewLayerSetting() -> AVCaptureVideoPreviewLayer {
let existPer = (previewLayer == nil)
let existCap = (captureSession != nil)
let initPer = existPer && existCap
if initPer {
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
}
return previewLayer!
}
}
| true
|
9c9af42fe430d7c7fa38f0becb38d2a169acc6a8
|
Swift
|
SonMoHam/todo-iOS
|
/todo-iOS/Sources/ViewControllers/AddTodoViewController.swift
|
UTF-8
| 2,701
| 2.625
| 3
|
[] |
no_license
|
//
// AddTodoViewController.swift
// todo-iOS
//
// Created by ์๋ํ on 2021/07/04.
//
import UIKit
import Alamofire
import SwiftyJSON
class AddTodoViewController: UIViewController {
@IBOutlet weak var pickerView: UIDatePicker!
@IBOutlet weak var contentTextField: UITextField!
@IBOutlet weak var deadlineLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
config()
// Do any additional setup after loading the view.
}
@IBAction func doneButtonClicked(_ sender: Any) {
let content = contentTextField.text ?? ""
let deadline = deadlineLabel.text ?? ""
if content.count == 0 {
let alert = UIAlertController(title: "content", message: "todo ๋ด์ฉ์ ์
๋ ฅํด์ฃผ์ธ์.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "ํ์", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
let parameters = [
"content": content,
"deadline": deadline
]
TodoAlamofireManager.shared.postTodo(parameters: parameters) { [weak self] in
guard let self = self else { return }
self.navigationController?.popViewController(animated: true)
}
//
// AF.request("http://3.37.62.54:3000/todo", method: .post, parameters: parameters).responseJSON { (response) in
// self.navigationController?.popViewController(animated: true)
// }
}
fileprivate func config() {
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd"
deadlineLabel.layer.borderWidth = 1
deadlineLabel.layer.borderColor = #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)
deadlineLabel.layer.cornerRadius = 5
deadlineLabel.text = format.string(from: Date())
pickerView.minimumDate = Date()
}
@IBAction func deadlineDatePickerValueChanged(_ sender: UIDatePicker) {
let dateformatter = DateFormatter()
dateformatter.dateStyle = .short
dateformatter.timeStyle = .none
dateformatter.dateFormat = "yyyy-MM-dd"
let date = dateformatter.string(from: pickerView.date)
deadlineLabel.text = date
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
4cfa1a5e1fc4ed9ebc2a01d0dd8be084abcc67ff
|
Swift
|
MonaQora/NearByHaversine
|
/NearByCustomers/Models/DataSouce/TableViewDataSource.swift
|
UTF-8
| 1,442
| 2.84375
| 3
|
[] |
no_license
|
//
// TableViewDataSource.swift
// NearByCustomers
//
// Created by Mona Qora on 1/28/20.
// Copyright ยฉ 2020 Mona Qora. All rights reserved.
//
import UIKit
class TableViewDataSource<CellType,DataModel>: NSObject, UITableViewDataSource where CellType: UITableViewCell {
let cellIdentifier: String
let configureCell: (CellType, DataModel) -> ()
let viewPresnter: BaseListViewPresnter
init(cellIdentifier: String, viewPresnter: BaseListViewPresnter, configureCell: @escaping (CellType,DataModel) -> ()) {
self.cellIdentifier = cellIdentifier
self.viewPresnter = viewPresnter
self.configureCell = configureCell
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewPresnter.numberOfRows(section: section)!
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath) as? CellType else {
fatalError("Cell with identifier \(self.cellIdentifier) not found")
}
let dataModel = self.viewPresnter.modelAt(index: indexPath.row)! as DataModel
self.configureCell(cell, dataModel)
return cell
}
}
| true
|
c53cad2e7800610fd5410226a80eff8ceeec3ad9
|
Swift
|
displayio/ios-sample
|
/display.io Sample App/Util/Constants.swift
|
UTF-8
| 1,813
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// StaticValues.swift
// display.io Sample App
//
// Created by akrat on 7/25/18.
// Copyright ยฉ 2018 akrat. All rights reserved.
//
class StringConstants {
static let pageTitle = "display.io Sample app"
static let predefinedPlacementsTitle = "display.io Pre-Defined Placements"
static let userDefinedPlacementsTitle = "My Placements"
static let adsKey = "ads"
static let adKey = "ad"
static let typeKey = "type"
static let noFillKey = "noFill"
static let okKey = "OK"
static let messageAdWasLoaded = "Ad was loaded"
static let messageAdIsLoading = "Ad is loading"
static let errAppIdIsNotDefined = "App ID is not defined"
static let errAppIdIsTooShort = "App ID must contain at least two numbers"
static let errAppInactive = "App is inactive"
static let errNoFill = "No fill"
static let dialogTitleRemovePlacement = "Remove placement"
static let dialogMessageRemovePlacement = "Are you sure you want to remove \"%@\" placement?"
static let dialogButtonRemovePlacementRemove = "Remove"
static let dialogButtonRemovePlacementCancel = "Cancel"
static let adTypes = ["interstitial" : "[Interstitial]", noFillKey : "No fill"]
}
class ColorScheme {
static let colorPrimary = "2C3E50"
static let colorAccent = "1ABC9C"
static let colorBody = "edf0f1"
static let colorLightGrey = "bdc3c7"
static let colorDarkGrey = "7f8c8d"
static let colorLightRed = "C34A4A"
static let colorLightGreen = "8BC34A"
static let colorLightBlue = "4080D8"
}
class FontScheme {
static let MontserratLight = "Montserrat-Light"
static let MontserratMedium = "Montserrat-Medium"
static let MontserratRegular = "Montserrat-Regular"
static let MontserratThin = "Montserrat-Thin"
}
| true
|
eb065b6dd2b95554484d3901a211a6016b237a8e
|
Swift
|
FullMetalFist/TDDFirstDemo
|
/TDDFirstDemo/ViewController.swift
|
UTF-8
| 1,326
| 3.21875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TDDFirstDemo
//
// Created by Michael Vilabrera on 5/6/16.
// Copyright ยฉ 2016 Michael Vilabrera. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfVowelsInString(string: String) -> Int {
let vowels: [Character] = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
return string.characters.reduce(0) { $0 + (vowels.contains($1) ? 1 : 0) }
}
func makeHeadline(string: String) -> String {
// 1
let words = string.componentsSeparatedByString(" ")
// 2
//
// var parameters are deprecated and will not be used in Swift 3
// how to satisfy the need for a mutable parameter? (jibestream)
//
let headline = words.map { (var word) -> String in let firstCharacter = word.removeAtIndex(word.startIndex)
return "\(String(firstCharacter).uppercaseString)\(word)"
}.joinWithSeparator(" ")
return headline
}
}
| true
|
2312a30c5fc4bb7cc8910d9506a1b52a712f1514
|
Swift
|
marciovcampos/IOS-Projects
|
/Exercicio-4/Calculator/Calculator/Calculator.swift
|
UTF-8
| 992
| 4.21875
| 4
|
[
"MIT"
] |
permissive
|
import Foundation
struct Calculator {
var partialValue: Int = 0
var numClicks: Int = 0
var op: String = ""
enum Operation {
case sum
case times
case divide
case subtract
}
/// Realiza uma operaรงรฃo matemรกtica.
/// - Parameter operation: Enum com a operaรงรฃo a ser realizada.
/// - Parameter firstValue: Primeiro valor.
/// - Parameter secondValue: Segundo valor.
/// - Returns: Resultado do calculo.
func perform(operation: Calculator.Operation,
firstValue: Int,
secondValue: Int) -> Int {
var result = 0
switch operation{
case .sum:
result = firstValue + secondValue
case .subtract:
result = firstValue - secondValue
case .times:
result = firstValue * secondValue
case .divide:
result = firstValue / secondValue
}
return result
}
}
| true
|
1adc83c8ae857a1ab36a3b379c19d308f3921df9
|
Swift
|
romadhon-razzan/swift-news
|
/News/ViewController.swift
|
UTF-8
| 3,770
| 2.71875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// News
//
// Created by Romadhon Akbar Sholeh on 06/03/20.
// Copyright ยฉ 2020 sevima. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20+1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionview.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! NewsCell
cell.btnTapAction = {
(_ type: String) in
print("Comment tapped in cell", indexPath, " Type : ", type)
}
if indexPath.item == 0{
let mainMenu = collectionview.dequeueReusableCell(withReuseIdentifier: cellMainMenu, for: indexPath) as! MainMenuCell
return mainMenu
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("CLICK ",indexPath.item)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
layout.estimatedItemSize = CGSize(width: view.bounds.size.width, height: 10)
super.traitCollectionDidChange(previousTraitCollection)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
layout.estimatedItemSize = CGSize(width: view.bounds.size.width, height: 10)
layout.invalidateLayout()
super.viewWillTransition(to: size, with: coordinator)
}
var collectionview : UICollectionView!
var cellId = "cell"
var cellMainMenu = "cellMainMenu"
var layout: UICollectionViewFlowLayout = {
let layout = UICollectionViewFlowLayout()
let width = UIScreen.main.bounds.size.width
layout.estimatedItemSize = CGSize(width: width, height: 10)
return layout
}()
override func viewDidLoad() {
super.viewDidLoad()
let height: CGFloat = 75
let navBar = UINavigationBar(frame: CGRect(x: 0, y: 30, width: UIScreen.main.bounds.width, height: height))
navBar.backgroundColor = .white
self.view.addSubview(navBar)
let navItem = UINavigationItem()
navItem.title = "News"
let profileItem = UIBarButtonItem(title: "Profile", style: .plain, target: self, action: nil)
navItem.leftBarButtonItem = profileItem
let addItem = UIBarButtonItem(title: "Post", style: .plain, target: self, action: #selector(createPost))
navItem.rightBarButtonItem = addItem
navBar.setItems([navItem], animated: false)
collectionview = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionview?.frame = CGRect(x: 0, y: height, width: UIScreen.main.bounds.width, height: (UIScreen.main.bounds.height - height))
collectionview.dataSource = self
collectionview.delegate = self
collectionview.register(NewsCell.self, forCellWithReuseIdentifier: cellId)
collectionview.register(MainMenuCell.self, forCellWithReuseIdentifier: cellMainMenu)
collectionview.showsVerticalScrollIndicator = false
collectionview.backgroundColor = UIColor.white
self.view.addSubview(collectionview)
}
@objc func createPost(){
let window = UIWindow()
let nav1 = UINavigationController()
let mainView = PostCreatorController()
nav1.viewControllers = [mainView]
window.rootViewController = nav1
window.makeKeyAndVisible()
}
}
| true
|
e44d48b8531144c28842fce114aa47b88446aa94
|
Swift
|
zjjzmw1/SwiftPushTransition
|
/SwiftPushTransition/่ชๅฎไน่ฝฌๅบๅจ็ป/ๅธๅฎ่ฝฌๅบ/PointTransitionPop.swift
|
UTF-8
| 3,410
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// PointTransitionPop.swift
// SwiftPushTransition
//
// Created by zhangmingwei on 2018/2/7.
// Copyright ยฉ 2018ๅนด zhangmingwei. All rights reserved.
//
import UIKit
/// ็ผฉๅฐๅฐๆไธไธช็น็ๅจ็ป
class PointTransitionPop: NSObject, UIViewControllerAnimatedTransitioning {
/// ๅผๅงๅจ็ป็frame
var startFrame = CGRect.init(x: 0, y: 0, width: 0, height: 0)
// MARK: ๅจ็ปๆถ้ด
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.8
}
// MARK: ๅจ็ปๆ ธๅฟๆนๆณ
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// ่ทๅๅฎนๅจ็่งๅพ
let contentV = transitionContext.containerView
// ๅผๅง็UIBezierPath
// let maskStartBP = UIBezierPath.init(ovalIn: startFrame)
let maskStartBP = UIBezierPath.init(ovalIn: startFrame.insetBy(dx: startFrame.width/2.0, dy: startFrame.width/2.0))
// ่ทๅๅจ็ป็ๆบๆงๅถๅจๅ็ฎๆ ๆงๅถๅจ
if let fromVC = transitionContext.viewController(forKey: .from), let toVC = transitionContext.viewController(forKey: .to) {
// ้ฝๆทปๅ ๅฐcontentVไธญ๏ผ้กบๅบไธ่ฝ้ --- ๅpush็ๆญฃๅฅฝ็ธๅ
contentV.addSubview(toVC.view)
contentV.addSubview(fromVC.view)
//ๅๅปบไธคไธชๅๅฝข็ UIBezierPath ๅฎไพ๏ผไธไธชๆฏ button ็ size ๏ผๅฆๅคไธไธชๅๆฅๆ่ถณๅค่ฆ็ๅฑๅน็ๅๅพใๆ็ป็ๅจ็ปๅๆฏๅจ่ฟไธคไธช่ดๅกๅฐ่ทฏๅพไน้ด่ฟ่ก็
// ่งฆๅ็น็point
let startPoint = CGPoint.init(x: startFrame.origin.x + startFrame.size.width/2.0, y: startFrame.origin.y + startFrame.size.height/2.0)
let width = UIScreen.main.bounds.width
let height = UIScreen.main.bounds.height
let x = (width/2.0 > startPoint.x ? width - startPoint.x : startPoint.x)
let y = (height/2.0 > startPoint.y ? height - startPoint.y : startPoint.y)
let finalRadius = sqrt((x * x) + (y * y))
// ๆ็ป็UIBezierPath
let maskFinalBP = UIBezierPath.init(ovalIn: startFrame.insetBy(dx: -finalRadius, dy: -finalRadius))
// ๅๅปบไธไธชCAShapeLayer่ด่ดฃๅฑ็คบๅๅฝข็้ฎ็
let maskLayer = CAShapeLayer()
maskLayer.path = maskStartBP.cgPath
fromVC.view.layer.mask = maskLayer
// ็ปๅๅจ็ปๅผๅง
let animation1 = CABasicAnimation.init(keyPath: "path")
animation1.beginTime = 0.0
animation1.fromValue = maskFinalBP.cgPath
animation1.toValue = maskStartBP.cgPath
animation1.duration = self.transitionDuration(using: transitionContext)
animation1.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseIn)
maskLayer.add(animation1, forKey: "PointTransitionPop")
// ็ปๆๅ็งป้ค
/// ๅปถ่ฟanimationGroup.duration็งๅๆง่ก - double็ฑปๅ
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(animation1.duration * 1000))) {
transitionContext.completeTransition(true)
fromVC.view.layer.mask = nil
toVC.view.layer.mask = nil
}
}
}// ๆ ธๅฟๅจ็ปๆนๆณ็ปๆ
}
| true
|
dec3846d19a555b65acb71c16deac6dc45012113
|
Swift
|
BigZhanghan/DouYuLive
|
/DouYuLive/DouYuLive/Classes/Main/View/PageTitleView.swift
|
UTF-8
| 5,001
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// PageTitleView.swift
// DouYuLive
//
// Created by zhanghan on 2017/9/28.
// Copyright ยฉ 2017ๅนด zhanghan. All rights reserved.
//
import UIKit
protocol PageTitleViewDelegate : class {
func pageTitleView(titleView : PageTitleView, selectIndex index : Int)
}
private let ScrollLineH : CGFloat = 2
private let NormalColor : (CGFloat, CGFloat, CGFloat) = (85,85,85)
private let SelectColor : (CGFloat, CGFloat, CGFloat) = (253,119,34)
class PageTitleView: UIView {
var titles : [String];
var currentIndex : Int = 0
weak var delegate : PageTitleViewDelegate?
lazy var titleLabels : [UILabel] = [UILabel]()
lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView();
scrollView.showsHorizontalScrollIndicator = false
scrollView.bounces = false
scrollView.scrollsToTop = false
return scrollView
}()
lazy var scrollLine : UIView = {
let scrollLine = UIView()
scrollLine.backgroundColor = UIColor.mainColor()
return scrollLine
}()
init(frame : CGRect, titles : [String]) {
self.titles = titles;
super.init(frame: frame);
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
func setupUI() {
addSubview(scrollView)
scrollView.frame = bounds;
setTitleLabels();
setupBottomLine()
}
private func setTitleLabels() {
let labelW : CGFloat = frame.width / CGFloat(titles.count)
let labelH : CGFloat = frame.height - ScrollLineH;
let labelY : CGFloat = 0
for (index, title) in titles.enumerated() {
let label = UILabel();
label.text = title
label.tag = index
label.font = UIFont.systemFont(ofSize: 16)
label.textColor = UIColor(r: NormalColor.0, g: NormalColor.1, b: NormalColor.2)
label.textAlignment = .center
let labelX : CGFloat = CGFloat(index) * labelW
label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH)
scrollView.addSubview(label)
titleLabels.append(label)
label.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelTap(tap:)))
label.addGestureRecognizer(tapGesture)
}
}
private func setupBottomLine() {
let bottomLine = UIView()
bottomLine.backgroundColor = UIColor.lightGray
let lineH : CGFloat = 0.5
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
guard let firstLabel = titleLabels.first else {
return
}
firstLabel.textColor = UIColor.mainColor()
scrollView.addSubview(scrollLine)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y:frame.height - ScrollLineH, width: firstLabel.frame.width, height: ScrollLineH)
}
}
extension PageTitleView {
func titleLabelTap(tap:UITapGestureRecognizer) {
guard let currentLabel = tap.view as? UILabel else {
return
}
//ไฟฎๅค้ๅค็นๅป้ไธญๅคฑๆ
if currentLabel.tag == currentIndex {
return
}
let oldLabel = titleLabels[currentIndex]
currentLabel.textColor = UIColor.mainColor()
oldLabel.textColor = UIColor(r: NormalColor.0, g: NormalColor.1, b: NormalColor.2)
currentIndex = currentLabel.tag
let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width
UIView.animate(withDuration: 0.2) {
self.scrollLine.frame.origin.x = scrollLineX
}
delegate?.pageTitleView(titleView: self, selectIndex: currentIndex)
}
}
//Public-Method
extension PageTitleView {
func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) {
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
let moveTotal = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveX = progress * moveTotal
scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX
let colorDelte = (SelectColor.0 - NormalColor.0, SelectColor.1 - NormalColor.1, SelectColor.2 - NormalColor.2)
sourceLabel.textColor = UIColor(r: SelectColor.0 - colorDelte.0 * progress, g: SelectColor.1 - colorDelte.1 * progress, b: SelectColor.2 - colorDelte.2 * progress)
targetLabel.textColor = UIColor(r: NormalColor.0 + colorDelte.0 * progress, g: NormalColor.1 + colorDelte.1 * progress, b: NormalColor.2 + colorDelte.2 * progress)
currentIndex = targetIndex
}
}
| true
|
5eaf912e0b5c4c0c76570922563066db85301c72
|
Swift
|
nbnitin/CLEAN_CODE_SAMPLE_ARCH
|
/CleanCodeArchitectureSample/CleanCodeArchitectureSample/Services/ApiRouter/GetAllPhotosApiRouter.swift
|
UTF-8
| 668
| 2.59375
| 3
|
[] |
no_license
|
//
// GetAllPhotosRouter.swift
// CleanCodeArchitectureSample
//
// Created by Nitin Bhatia on 4/8/21.
//
import Foundation
import Alamofire
enum GetAllPhotosApiRouter: APIRouter {
case getPhotos
// MARK: - HTTPMethod
var method: HTTPMethod {
switch self {
case .getPhotos:
return .get
}
}
// MARK: - Path
var endPoint: String {
switch self {
case .getPhotos:
return EndPoint.getAllPhotos.rawValue
}
}
// MARK: - Parameters
var parameters: Parameters? {
switch self {
case .getPhotos:
return nil
}
}
}
| true
|
3f352f7484fe3059f2d2d75f0df662b9b643e404
|
Swift
|
patsluth/Sluthware
|
/Sluthware/Classes/Foundation/Decodable+SW.swift
|
UTF-8
| 1,300
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// Decodable+SW.swift
// Sluthware
//
// Created by Pat Sluth on 2017-10-08.
// Copyright ยฉ 2017 patsluth. All rights reserved.
//
import Foundation
public extension Decodable
{
static func decode<T>(_ value: T, decoder: (inout JSONDecoder) -> Void) throws -> Self
{
var _decoder = JSONDecoder()
_decoder.dateDecodingStrategy = .formatted(DateFormatter.properISO8601)
decoder(&_decoder)
return try self.decode(value, decoder: _decoder)
}
static func decode<T>(_ value: T, decoder: JSONDecoder? = nil) throws -> Self
{
let decoder = decoder ?? {
let _decoder = JSONDecoder()
_decoder.dateDecodingStrategy = .formatted(DateFormatter.properISO8601)
return _decoder
}()
switch value {
case let value as Self:
return value
case let data as Data:
return try decoder.decode(Self.self, from: data)
case let string as String:
if let data = string.removingPercentEncodingSafe.data(using: .utf8) {
return try Self.decode(data, decoder: decoder)
}
default:
if JSONSerialization.isValidJSONObject(value) {
let data = try JSONSerialization.data(withJSONObject: value)
return try Self.decode(data, decoder: decoder)
}
}
throw Errors.Decoding(T.self, codingPath: [])
}
}
| true
|
b0c0839a301fbcb46c79840683460ca0c6e40fdd
|
Swift
|
Kyle-Shal/MemorizeApp
|
/MemorizeApp/Memory Game.swift
|
UTF-8
| 2,591
| 3.484375
| 3
|
[] |
no_license
|
//
// Memory Game.swift
// Stanford Lesson01-Memorize app
//
// Created by Kyle Shal on 2021-02-25.
// This is the model
import Foundation
struct MemoryGame<CardContent> where CardContent: Equatable{
private(set) var cards: Array<Card>
private var indexOfTheOneAndOnlyOne: Int?{
get{ //cards.indices.filter { cards[$0].isFaceUp}.only} // Equivalent to the following 11 lines of code
var faceUpCardIndices = [Int]()
for index in cards.indices{
if cards[index].isFaceUp{
faceUpCardIndices.append(index)
}
}
if faceUpCardIndices.count == 1{
return faceUpCardIndices.first //equivalent to faceUpCardIndices[0]
}else{
return nil
}
}
set{
for index in cards.indices{
//cards[index].isFaceUp = index == newValue // this is one line of code that is equivalent to the following 5 for minimalistic code
if index == newValue {
cards[index].isFaceUp = true
}else{
cards[index].isFaceUp = false
}
}
}
}
mutating func choose (card: Card) {
print("card chosen: \(card)")
//var to store the index of the chosen card in the array from the func
//only going to touch on cards that are facedown and not matched
if let chosenIndex: Int = cards.firstIndex(matching: card), !cards[chosenIndex].isFaceUp, !cards[chosenIndex].isMatched{
if let potentialMatchIndex = indexOfTheOneAndOnlyOne {
if cards[chosenIndex].content == cards[potentialMatchIndex].content{
cards[chosenIndex].isMatched = true
cards[potentialMatchIndex].isMatched = true
}
self.cards[chosenIndex].isFaceUp = true
}else{
indexOfTheOneAndOnlyOne = chosenIndex
}
}
}
init(numberOfPairsOfCards: Int, cardContentFactory: (Int) ->CardContent) {
cards = Array<Card>()
for pairIndex in 0..<numberOfPairsOfCards{
let content = cardContentFactory(pairIndex)
cards.append(Card(content: content, id: pairIndex*2))
cards.append(Card(content: content, id: pairIndex*2+1))
}
}
struct Card: Identifiable {
var isFaceUp: Bool = false
var isMatched: Bool = false
var content: CardContent
var id: Int
}
}
| true
|
a24bc1f8c96c2fe8512c67d765803d3e9554eeb3
|
Swift
|
kris-skierniewski/colour-run-map
|
/colour-run-map/colour-run-map/Views/TabBarView.swift
|
UTF-8
| 1,285
| 2.515625
| 3
|
[] |
no_license
|
//
// TabBarView.swift
// colour-run-map
//
// Created by Luke on 13/05/2020.
// Copyright ยฉ 2020 Kris Skierniewski. All rights reserved.
//
import SwiftUI
struct TabBarView: View {
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(fetchRequest: Activity.fetchRequest()) var activities: FetchedResults<Activity>
@EnvironmentObject var userData: UserData
var body: some View {
TabView {
ActivityList()
.environment(\.managedObjectContext, self.managedObjectContext)
.environmentObject(self.userData)
.tabItem {
Image(systemName: "book.fill")
Text("Activities")
}.tag(0)
LiveRecorderView()
.environment(\.managedObjectContext, self.managedObjectContext)
.environmentObject(self.userData)
.tabItem {
Image(systemName: "pin")
Text("Now")
}.tag(1)
}
}
}
struct TabBarView_Previews: PreviewProvider {
static var previews: some View {
return TabBarView()
.environment(\.managedObjectContext, MockHelper.mockContext)
.environmentObject(UserData())
}
}
| true
|
73d43ca9f12bacd769ff3c06df83db30449490d2
|
Swift
|
yoichitgy/Swinject
|
/Tests/SwinjectTests/LazyTests.swift
|
UTF-8
| 4,046
| 2.609375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// Copyright ยฉ 2021 Swinject Contributors. All rights reserved.
//
import XCTest
import Swinject
class LazyTests: XCTestCase {
var container: Container!
override func setUpWithError() throws {
container = Container()
}
// MARK: Instance production
func testContainerProvidesInstanceFromContainer() {
container.register(Animal.self) { _ in Dog() }
let lazy = container.resolve(Lazy<Animal>.self)
XCTAssert(lazy?.instance is Dog)
}
func testContainerDoesNotCreateInstanceUntilRequested() {
var created = false
container.register(Animal.self) { _ in created = true; return Dog() }
_ = container.resolve(Lazy<Animal>.self)
XCTAssertFalse(created)
}
func testContainerResolveInstanceFromContainerOnlyOnce() {
var created = 0
container.register(Animal.self) { _ in created += 1; return Dog() }
let lazy = container.resolve(Lazy<Animal>.self)
_ = lazy?.instance
_ = lazy?.instance
XCTAssertEqual(created, 1)
}
func testContainerDoesNotResolveLazyIfBaseTypeIsNotRegistered() {
let lazy = container.resolve(Lazy<Animal>.self)
XCTAssertNil(lazy)
}
// MARK: Object scopes
func testContainerAlwaysProducesDifferentInstanceForRelatedObjectsInTransientScope() {
EmploymentAssembly(scope: .transient).assemble(container: container)
let employer = container.resolve(Employer.self)!
XCTAssert(employer.lazyCustomer.instance !== employer.employee.lazyCustomer.instance)
XCTAssert(employer.lazyCustomer.instance !== employer.customer)
}
func testContainerAlwaysProducesTheSameInstanceForRelatedObjectsInContainerScope() {
EmploymentAssembly(scope: .container).assemble(container: container)
let employer = container.resolve(Employer.self)!
XCTAssert(employer.lazyCustomer.instance === employer.employee.lazyCustomer.instance)
XCTAssert(employer.lazyCustomer.instance === employer.customer)
}
func testContainerAlwaysProducesTheSameInstanceForRelatedObjectsInGraphScope() {
EmploymentAssembly(scope: .graph).assemble(container: container)
let employer = container.resolve(Employer.self)!
XCTAssert(employer.lazyCustomer.instance === employer.employee.lazyCustomer.instance)
XCTAssert(employer.lazyCustomer.instance === employer.customer)
}
// MARK: Complex registrations
func testContainerResolvesLazyWithArguments() {
container.register(Dog.self) { (_, name, _: Int) in Dog(name: name) }
let lazy = container.resolve(Lazy<Dog>.self, arguments: "Hachi", 42)
XCTAssertEqual(lazy?.instance.name, "Hachi")
}
func testContainerResolvesLazyWithName() {
container.register(Dog.self, name: "Hachi") { _ in Dog() }
let lazy = container.resolve(Lazy<Dog>.self, name: "Hachi")
XCTAssertNotNil(lazy)
}
func testContainerDoesNotResolveLazyWithWrongName() {
container.register(Dog.self, name: "Hachi") { _ in Dog() }
let lazy = container.resolve(Lazy<Dog>.self, name: "Mimi")
XCTAssertNil(lazy)
}
func testContainerDoesResolveForwardedLazyType() {
container.register(Dog.self) { _ in Dog() }.implements(Animal.self)
let lazy = container.resolve(Lazy<Animal>.self)
XCTAssertNotNil(lazy)
}
// MARK: Circular dependencies
func testContainerResolvesDependenciesToSameInstance() {
EmploymentAssembly(scope: .graph).assemble(container: container)
let employer = container.resolve(Employer.self)
XCTAssert(employer?.employee.employer === employer)
XCTAssert(employer?.lazyEmployee.instance.employer === employer)
}
func testContainerResolvesCircularDependenciesForLazyInstance() {
EmploymentAssembly(scope: .graph).assemble(container: container)
let employee = container.resolve(Lazy<Employee>.self)
XCTAssertNotNil(employee?.instance.employer)
}
}
| true
|
45f773c7717dea74bfaff78d727b65b2b3a9ae69
|
Swift
|
justinarose/HW-Assassin
|
/HW Assassin/Model/Comment.swift
|
UTF-8
| 1,817
| 2.75
| 3
|
[] |
no_license
|
//
// Comment.swift
// HW Assassin
//
// Created by Justin Rose on 4/3/17.
// Copyright ยฉ 2017 James Kanoff. All rights reserved.
//
import UIKit
import CoreData
class Comment: NSManagedObject {
@discardableResult
class func commentWithCommentInfo(_ commentInfo:[String:Any], inManageObjectContext context: NSManagedObjectContext) -> Comment
{
let request: NSFetchRequest<Comment> = Comment.fetchRequest()
request.predicate = NSPredicate(format: "id=%d", commentInfo["id"] as! Int64)
if let comment = (try? context.fetch(request))?.first{
print("Object already exists")
return comment
}
else{
let comment = Comment(context: context)
comment.id = commentInfo["id"] as! Int64!
comment.text = commentInfo["text"] as? String
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let localDate = formatter.date(from: commentInfo["time"] as! String)
comment.time = localDate as NSDate?//need to fix, but not right now
let commenterRequest: NSFetchRequest<User> = User.fetchRequest()
commenterRequest.predicate = NSPredicate(format: "id=%d", commentInfo["commenter"] as! Int64!)
if let commenter = (try? context.fetch(commenterRequest))?.first{
comment.commenter = commenter
}
let postRequest: NSFetchRequest<Post> = Post.fetchRequest()
postRequest.predicate = NSPredicate(format: "id=%d", commentInfo["post"] as! Int64!)
if let post = (try? context.fetch(postRequest))?.first{
comment.post = post
}
return comment
}
}
}
| true
|
2962c483fb57a3d5bc2cbce48447e9b158f8d96a
|
Swift
|
viniciusmesquitac/UmSimplesDiario
|
/UmSimplesDiario/Coordinators/RegistrosCoordinator.swift
|
UTF-8
| 2,714
| 2.984375
| 3
|
[] |
no_license
|
//
// RegistrosCoordinator.swift
// UmSimplesDiario
//
// Created by Vinicius Mesquita on 08/02/21.
//
import Foundation
import UIKit
enum RegistrosPath {
case search(registros: [Registro])
case compose
case editCompose(registro: Registro)
case showIdea(idea: String)
case config
}
final class RegistrosCoordinator: Coordinator {
var navigationController: UINavigationController!
var currentController: RegistrosViewController?
init(navigationController: UINavigationController) {
self.navigationController = navigationController
}
func start() {
let viewModel = RegistrosViewModel(coordinator: self, registros: [])
let registrosViewController = RegistrosViewController(viewModel: viewModel)
self.currentController = registrosViewController
navigationController.pushViewController(registrosViewController, animated: true)
}
func route(to path: RegistrosPath) {
switch path {
case .compose:
let coordinator = RegistrosCoordinator(navigationController: self.navigationController)
let viewModel = EscreverDiarioViewModel(coordinator: coordinator, registro: nil)
let escreverDiarioViewController = EscreverDiarioViewController(viewModel: viewModel)
let navigationController = UINavigationController(rootViewController: escreverDiarioViewController)
navigationController.modalPresentationStyle = .fullScreen
self.navigationController.present(navigationController, animated: true, completion: nil)
case .search(let registros):
let pesquisarRegistroCoordinator = PesquisarRegistrosCoordinator(
navigationController: self.navigationController)
pesquisarRegistroCoordinator.start(registros: registros)
case .editCompose(let registro):
let editarRegistoCoordinator = EditarRegistroCoordinator(navigationController: self.navigationController)
editarRegistoCoordinator.start(registro: registro)
case .showIdea(let idea):
let modal = UIAlertAction(title: idea, style: .default, handler: nil)
print(modal)
case .config:
coordinate(to: ConfigCoordinator(navigationController: self.navigationController))
}
}
func dismiss() {
navigationController.dismiss(animated: true, completion: {
guard let viewController = self.navigationController
.viewControllers.first as? RegistrosViewController
else { return }
viewController.viewModel.loadRegistros()
self.navigationController.popViewController(animated: true)
})
}
}
| true
|
42e0eb6117b4ed7a2440807f86766d100e548714
|
Swift
|
negibouze/Realm-Register-Initial-Data
|
/Realm-Register-Initial-Data/PrefectureSeed.swift
|
UTF-8
| 1,648
| 2.796875
| 3
|
[] |
no_license
|
//
// PrefectureSeed.swift
// Realm-Register-Initial-Data
//
// Created by ๆฟๅ็พฉๆ on 2017/04/24.
// Copyright ยฉ 2017 ๆฟๅ็พฉๆ. All rights reserved.
//
struct PrefectureSeed: RealmSeed {
typealias SeedType = Prefecture
static var values: [[Any]] {
return PrefectureData.data
}
}
struct PrefectureData {
static let data: [[Any]] = [
[1, "ๅๆตท้"],
[2, "้ๆฃฎ็"],
[3, "ๅฒฉๆ็"],
[4, "ๅฎฎๅ็"],
[5, "็ง็ฐ็"],
[6, "ๅฑฑๅฝข็"],
[7, "็ฆๅณถ็"],
[8, "่จๅ็"],
[9, "ๆ ๆจ็"],
[10, "็พค้ฆฌ็"],
[11, "ๅผ็็"],
[12, "ๅ่็"],
[13, "ๆฑไบฌ้ฝ"],
[14, "็ฅๅฅๅท็"],
[15, "ๆฐๆฝ็"],
[16, "ๅฏๅฑฑ็"],
[17, "็ณๅท็"],
[18, "็ฆไบ็"],
[19, "ๅฑฑๆขจ็"],
[20, "้ท้็"],
[21, "ๅฒ้็"],
[22, "้ๅฒก็"],
[23, "ๆ็ฅ็"],
[24, "ไธ้็"],
[25, "ๆป่ณ็"],
[26, "ไบฌ้ฝๅบ"],
[27, "ๅคง้ชๅบ"],
[28, "ๅ
ตๅบซ็"],
[29, "ๅฅ่ฏ็"],
[30, "ๅๆญๅฑฑ็"],
[31, "้ณฅๅ็"],
[32, "ๅณถๆ น็"],
[33, "ๅฒกๅฑฑ็"],
[34, "ๅบๅณถ็"],
[35, "ๅฑฑๅฃ็"],
[36, "ๅพณๅณถ็"],
[37, "้ฆๅท็"],
[38, "ๆๅช็"],
[39, "้ซ็ฅ็"],
[40, "็ฆๅฒก็"],
[41, "ไฝ่ณ็"],
[42, "้ทๅด็"],
[43, "็ๆฌ็"],
[44, "ๅคงๅ็"],
[45, "ๅฎฎๅด็"],
[46, "้นฟๅ
ๅณถ็"],
[47, "ๆฒ็ธ็"]
]
}
| true
|
19d96cf1c12489dc571cd3c252fa9d650e497d94
|
Swift
|
AWarmHug/iOSLearn
|
/Swift/Basis-POP/Basis-POP/ViewController.swift
|
UTF-8
| 918
| 2.578125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Basis-POP
//
// Created by Warm-mac on 2018/5/10.
// Copyright ยฉ 2018 me.warm. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var personC = PersonClass()
var personS = PersonStruct(name: "ไปปๆ", age: 0, mood: Mood.HAPPY, school: School(name: "ๅธธๅทไฟกๆฏ่ไธๆๆฏๅญฆ้ข", address: "ๅธธๅท"))
print("\(personS.name)ๅทฒ็ปๆๅนดไบๅ?\(personS.adult)")
personS.age = 14
personS.age = 15
personS.age = 19
personC.residence?.numberOfRooms = 1
do {
try personC.goResidence()
} catch is ResidenceError {
} catch {
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
6605b87bc3870bc85099e288696346572e11123f
|
Swift
|
run4jit/MVVMCoordinator
|
/MVVMCSample/MVVMCSample/CreateAccountCoordinater.swift
|
UTF-8
| 1,436
| 2.640625
| 3
|
[] |
no_license
|
//
// CreateAccountCoordinater.swift
// MVVMCSample
//
// Created by Ranjeet Singh on 20/05/20.
// Copyright ยฉ 2020 Ranjeet Singh. All rights reserved.
//
import Foundation
import UIKit
protocol SignupNavigation {
func navigateToSignup(address: Address)
}
class CreateAccountCoordinater: BaseCoordinater, SignupNavigation, Coordinater {
weak var parentVC: UIViewController?
var parentCoordinater: Coordinater?
var navigationController: UINavigationController
var childCoordinaters = [Coordinater]()
func navigate() {
navigateToCreatProfile()
}
init(navigationController: UINavigationController) {
self.navigationController = navigationController
super.init()
navigationController.delegate = self
self.parentVC = navigationController.topViewController
super.didFinish = {[weak self] fromViewController in
guard let self = self, fromViewController is CreateAccountViewController else { return }
self.parentCoordinater?.childDidFinish(self)
}
}
func navigateToSignup(address: Address) {
let vc = SignUpViewController.instantiate()
vc.address = address
vc.coordinater = self
pushVC(vc)
}
func navigateToCreatProfile() {
let vc = CreateAccountViewController.instantiate()
vc.coordinater = self
pushVC(vc)
}
}
| true
|
d80b30345230546cb6e4cd4b017a6bd1348acf0c
|
Swift
|
carabina/DynamicJSON
|
/Example/Tests/Tests.swift
|
UTF-8
| 1,357
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// DynamicJSONTests.swift
// DynamicJSONTests
//
// Created by Andrew Vergunov on 9/26/18.
// Copyright ยฉ 2018 Andrew Vergunov. All rights reserved.
//
import XCTest
@testable import DynoJSON
class DynamicJSONTests: XCTestCase {
func testStringValue() {
let response: JSON = facebookJsonResponse()
let nextPaging: String? = response.comments?.paging?.next
XCTAssert(nextPaging == "https://graph.facebook.com/1809938745705498/comments?access_token=valid_token_goes_here")
}
func testIntValue() {
let response: JSON = facebookJsonResponse()
let intValue: Int? = response.comments?.paging?.integerValue
XCTAssert(intValue == 7)
}
func testArrayJsonValue() {
let response: JSON = facebookJsonResponse()
let arrayJson: [JSON]? = response.comments?.data
XCTAssert(arrayJson?.count == 3)
}
func testValueOfArrayElement() {
let response: JSON = facebookJsonResponse()
let arrayJson: [JSON]? = response.comments?.data
let message: String? = arrayJson?.first?.message
XCTAssert(message == ":) :) :)")
}
func testDoubleValue() {
let response: JSON = facebookJsonResponse()
let doubleValue: Double? = response.comments?.paging?.cursors?.doubleValue
XCTAssert(doubleValue == 12.5)
}
}
| true
|
f70706601ca864d32194e815e7c1c1c9aa24458a
|
Swift
|
pyounes/FightPandemics-iOS-SwiftUI
|
/FightPandemics/Views/Components/Cards/CardSearchResults.swift
|
UTF-8
| 1,888
| 2.890625
| 3
|
[
"MIT"
] |
permissive
|
//
// CardSearchResults.swift
// FightPandemics
//
// Created by Luko on 29/11/2020.
// Copyright ยฉ 2020 Scott. All rights reserved.
//
import SwiftUI
struct CardSearchResults: View {
func viewMore() {}
var body: some View {
VStack(alignment: .leading) {
HStack {
Text("Posted xhrs ago")
.font(.custom("WorkSans-Regular", size: 11))
.foregroundColor(FPColor.brownGrey)
Spacer()
Tag(title: "Groceries")
}
VStack(alignment: .leading) {
Text("This is a title message.")
.font(.custom("Poppins-Bold", size: 16))
Text("Max 3 lines for the preview of the post. Max 3 line for the preview of the post. Max 3 linse for the preview of the post. Max 3 lines")
.font(.custom("WorkSans-Regular", size: 14))
HStack {
Spacer()
Button(action: viewMore) {
Text("View more...")
.font(.custom("WorkSans-Regular", size: 14))
.foregroundColor(FPColor.purpleishBlue)
}
}
}
}.padding()
}
}
struct CardSearchResultsArray: View {
func viewMore() {}
var body: some View {
ScrollView {
VStack {
CardSearchResults()
CardSearchResults()
CardSearchResults()
CardSearchResults()
CardSearchResults()
CardSearchResults()
CardSearchResults()
}
}
}
}
struct CardSearchResults_Previews: PreviewProvider {
static var previews: some View {
CardSearchResults()
}
}
| true
|
29767771b4b691e387d44b7889658dcf4cd7861d
|
Swift
|
bios90/joc_client_ios
|
/jocclient/utils/local_data/LocalData.swift
|
UTF-8
| 2,651
| 2.65625
| 3
|
[] |
no_license
|
import Foundation
import GoogleMaps
enum LocalKeys:String
{
case PushToken
case CurrentUser
case ShowedCovidIntro
case LastLat
case LastLng
}
class LocalData
{
static func getIntroShowed()->Bool
{
return UserDefaults.standard.bool(forKey: LocalKeys.ShowedCovidIntro.rawValue)
}
static func saveIntroShowed(is_showed:Bool = true)
{
UserDefaults.standard.set(is_showed, forKey: LocalKeys.ShowedCovidIntro.rawValue)
}
static func savePushToken(token:String)
{
UserDefaults.standard.set(token, forKey: LocalKeys.PushToken.rawValue)
}
static func getPushToken()->String?
{
guard UserDefaults.standard.hasKey(key: LocalKeys.PushToken.rawValue) else { return nil }
return UserDefaults.standard.string(forKey: LocalKeys.PushToken.rawValue)
}
static func clearPushToken()
{
UserDefaults.standard.removeObject(forKey: LocalKeys.PushToken.rawValue)
}
static func saveCurrentUser(user:ModelUser)
{
let encoder = globalJsonEncoder
if let encoded = try? encoder.encode(user)
{
UserDefaults.standard.set(encoded, forKey: LocalKeys.CurrentUser.rawValue)
}
}
static func clearCurrentUser()
{
UserDefaults.standard.removeObject(forKey: LocalKeys.CurrentUser.rawValue)
}
static func saveUserLocation(location:CLLocationCoordinate2D)
{
UserDefaults.standard.set(location.latitude, forKey: LocalKeys.LastLat.rawValue)
UserDefaults.standard.set(location.longitude, forKey: LocalKeys.LastLng.rawValue)
}
static func getUserLastLocation()->CLLocationCoordinate2D?
{
if UserDefaults.standard.hasKey(key: LocalKeys.LastLat.rawValue)
,UserDefaults.standard.hasKey(key: LocalKeys.LastLng.rawValue)
{
let lat = UserDefaults.standard.double(forKey: LocalKeys.LastLat.rawValue)
let lng = UserDefaults.standard.double(forKey: LocalKeys.LastLng.rawValue)
print("Will return saved locally location!")
return CLLocationCoordinate2D(latitude: lat, longitude: lng)
}
return nil
}
static func getCurrentUser()->ModelUser?
{
if let data = UserDefaults.standard.object(forKey: LocalKeys.CurrentUser.rawValue) as? Data
{
let decoder = globalJsonDecoder
if let user = try? decoder.decode(ModelUser.self, from: data)
{
return user
}
}
return nil
}
}
| true
|
4c54c7e40ce2b50466f6f675d50eb22dd7881e81
|
Swift
|
ladybeitel/CustomControlsReview
|
/CustomControls/CustomControls/Helpers/SignupPage.swift
|
UTF-8
| 5,394
| 2.953125
| 3
|
[] |
no_license
|
//
// SignupPage.swift
// CustomControls
//
// Created by Ciara Beitel on 9/12/19.
// Copyright ยฉ 2019 Mitchell Budge. All rights reserved.
//
// 1. Import UIKIT
import UIKit
// 2. name your class, and set its type
class SignupPage: UIControl {
// MARK: - Properties
// 5. create properties
let backgroundImageView: UIImageView = UIImageView() //go ahead and create an instance
let emailLabel: UILabel = UILabel()
let emailContainerView: UIView = UIView()
let emailTextField: UITextField = UITextField()
let passwordLabel: UILabel = UILabel()
let passwordContainerView: UIView = UIView()
let passwordTextField: UITextField = UITextField()
let loginButton: UIButton = UIButton()
// MARK: - Required Initializers
// 3. create req init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder) // don't forget to call super!
setupSubviews() // call your function
}
// MARK: - Methods and Functions
// 4. create a func
func setupSubviews() {
// 6. add subview for background image view
addSubview(backgroundImageView)
// 7. "turn off" autoresizing
backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
// 8. create constraits (with anchors), and activate
backgroundImageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true // activate!
backgroundImageView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true // self = class view
backgroundImageView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true // don't technically need self
backgroundImageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
// 9. set image to bg
backgroundImageView.image = UIImage(named: "BackgroundPhoto")
// 10. add email label as a property up top and add to subview
addSubview(emailLabel)
// 11. "turn off" autoresizing on label
emailLabel.translatesAutoresizingMaskIntoConstraints = false
// 12. create constraits and activate
emailLabel.topAnchor.constraint(equalTo: topAnchor, constant: 150).isActive = true // ACTIVATE!
emailLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true
emailLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -20).isActive = true // negative: push us back into the view from the trailing edge of view
// 13. customize email label
emailLabel.text = "Enter email here:"
emailLabel.font = UIFont.systemFont(ofSize: 18.0, weight: .light)
// 14. add email container view as a property up top and add to subview
addSubview(emailContainerView)
// 15. "turn off" autoresizing on email container view
emailContainerView.translatesAutoresizingMaskIntoConstraints = false
// 16. create constraits and activate
emailContainerView.topAnchor.constraint(equalToSystemSpacingBelow: emailLabel.bottomAnchor, multiplier: 1).isActive = true
emailContainerView.leadingAnchor.constraint(equalTo: emailLabel.leadingAnchor).isActive = true
emailContainerView.trailingAnchor.constraint(equalTo: emailLabel.trailingAnchor).isActive = true
emailContainerView.heightAnchor.constraint(equalToConstant: 50).isActive = true
// 17. format container view
//container views are hidden, add design elements with LAYER
emailContainerView.layer.borderColor = UIColor.black.cgColor // convert UIColor to CGColor with .cgcolor at the end
emailContainerView.layer.borderWidth = 1
emailContainerView.layer.cornerRadius = 5
emailContainerView.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.3)
// 18. (Put text field into container view.) Add property up top and initialize, add to subview
emailContainerView.addSubview(emailTextField)
// 19. "turn off" autoresizing on email container view
emailTextField.translatesAutoresizingMaskIntoConstraints = false
// 20. create constraits and activate
emailTextField.topAnchor.constraint(equalTo: emailContainerView.topAnchor, constant: 8).isActive = true
emailTextField.leadingAnchor.constraint(equalTo: emailContainerView.leadingAnchor, constant: 8).isActive = true
emailTextField.trailingAnchor.constraint(equalTo: emailContainerView.trailingAnchor, constant: -8).isActive = true // negative: come in from the right side <-- |
emailTextField.bottomAnchor.constraint(equalTo: emailContainerView.bottomAnchor, constant: -8).isActive = true // negative: come up from the bottom side
// 21. format text field
emailTextField.placeholder = "Email"
// Login Button
addSubview(loginButton)
loginButton.translatesAutoresizingMaskIntoConstraints = false
loginButton.topAnchor.constraint(equalToSystemSpacingBelow: emailContainerView.bottomAnchor, multiplier: 1).isActive = true
loginButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true // center horizontally in the view
loginButton.setTitle(" Login ", for: .normal)
loginButton.layer.borderColor = UIColor.black.cgColor
loginButton.layer.borderWidth = 1
loginButton.layer.cornerRadius = 5
loginButton.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)
}
}
| true
|
b2e660f7a2262d24e7eaa37247db1f50c8aec772
|
Swift
|
MarkWarriors/MGExampleApp
|
/LoginModule/Sources/LoginModule/Scenes/RegisterAccount/RegisterAccountViewContract.swift
|
UTF-8
| 1,476
| 2.609375
| 3
|
[] |
no_license
|
//
// RegisterAccountViewContract.swift
//
//
// Created by Marco Guerrieri on 26/03/2021.
//
import UIKit
import CommonComponents
import CommonDomain
protocol RegisterAccountViewPresentable: Trackable {
func configure(with viewModel: RegisterAccountViewModel)
func showError(viewModel: RegisterAccountViewErrorViewModel)
func updateRegisterButton(enabled: Bool)
}
protocol RegisterAccountViewPresenterType {
func setup(with view: RegisterAccountViewPresentable)
func retryOnErrorAlertTapped(answers: RegisterAccountFormAnswers)
func formHasChanged(allFieldsAreValid: Bool)
func didTapOnRegisterButton(answers: RegisterAccountFormAnswers)
}
struct RegisterAccountViewModel {
let titleLabel: String
let nameTextField: RegisterAccountTextFieldViewModel
let surnameTextField: RegisterAccountTextFieldViewModel
let usernameTextField: RegisterAccountTextFieldViewModel
let emailTextField: RegisterAccountTextFieldViewModel
let confirmEmailTextField: RegisterAccountTextFieldViewModel
let passwordTextField: RegisterAccountTextFieldViewModel
let confirmPasswordTextField: RegisterAccountTextFieldViewModel
}
struct RegisterAccountViewErrorViewModel {
let title: String
let message: String
let retryAction: String?
let cancelAction: String
}
struct RegisterAccountFormAnswers {
let name: String
let surname: String
let username: String
let email: String
let confirmEmail: String
let password: String
let confirmPassword: String
}
| true
|
d22e16fa3054959d78f551694d131a6a9dd107cd
|
Swift
|
leonardovargasleffa/weatherapp
|
/wheatherapp/Custom/WebService.swift
|
UTF-8
| 1,690
| 2.59375
| 3
|
[] |
no_license
|
//
// WebService.swift
// wheatherapp
//
// Created by Leonardo Leffa on 08/05/20.
// Copyright ยฉ 2020 Leonardo Leffa. All rights reserved.
//
import UIKit
import RxSwift
import Alamofire
import ObjectMapper
import AlamofireObjectMapper
import SwiftyJSON
class WebService: NSObject {
static let sharedInstance = WebService()
var currentCity: City!
var nearbyCities: [City]!
func getWeatherData(_ lat: Double, _ lng: Double) -> Observable<Request> {
return Observable<Request>.create { observer -> Disposable in
let api_url = Bundle.main.object(forInfoDictionaryKey: "URL_WEATHERAPI") as! String
let api_key = Bundle.main.object(forInfoDictionaryKey: "API_KEY") as! String
Alamofire.request("\(api_url)find/?lat=\(lat)&lon=\(lng)&lang=en&cnt=21&appid=\(api_key)", method: .get).responseObject { (response: DataResponse<Request>) in
guard let request = response.result.value else {
observer.on(.error(WSReturn.error))
return
}
if(Int(request.cod) != WSReturn.success.code || request.list.count == 0){
observer.on(.error(WSReturn.error))
return
}
WebService.sharedInstance.currentCity = request.list.first!
WebService.sharedInstance.nearbyCities = request.list.dropFirst().sorted(by: { $0.main.temp > $1.main.temp });
observer.on(.completed)
}
return Disposables.create()
}
}
}
| true
|
9503aa513fa064cd988c4711c386968c6f203054
|
Swift
|
davidyepez/Verbis
|
/Word/- DefinitionDetailViewController.swift
|
UTF-8
| 2,111
| 2.859375
| 3
|
[] |
no_license
|
//
// DefinitionDetailViewController.swift
// Word
//
// Created by David Yรฉpez on 4/26/19.
// Copyright ยฉ 2019 David Yepez. All rights reserved.
//
import UIKit
class DefinitionDetailViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var topWordLabel: UILabel!
var words = Words()
var word : Word!
var finalWord = ""
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
words.getWords(word: finalWord, apiType: "definitions") {
self.tableView.reloadData()
print(self.words.firebaseWord.word)
print(self.words.firebaseWord.definition)
self.word = self.words.firebaseWord
}
topWordLabel.text = "\(finalWord):"
}
@IBAction func addToFavoritesButtonPressed(_ sender: UIBarButtonItem) {
word.saveData { success in
if success {
self.performSegue(withIdentifier: "definitionToFavoritesSegue", sender: self)
} else {
print("ERROR: data unsaved")
}
}
}
}
extension DefinitionDetailViewController: UITableViewDataSource ,UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return words.definitionArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DefinitionCell", for: indexPath) as! DefinitionTableViewCell
//cell.textLabel?.text = words.definitionArray[indexPath.row].partOfSpeech
var printout = "(\(words.definitionArray[indexPath.row].partOfSpeech)): \(words.definitionArray[indexPath.row].definition)"
cell.definitionLabel.text = printout
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 105
}
}
| true
|
a0a3f8aa65633077177aa8210b09819952b308f3
|
Swift
|
milanpanchal/HackerRank
|
/Problem Solving/Greedy/PermutingTwoArrays.playground/Contents.swift
|
UTF-8
| 599
| 3.84375
| 4
|
[
"MIT"
] |
permissive
|
import Foundation
// Complete the twoArrays function below.
func twoArrays(k: Int, A: [Int], B: [Int]) -> String {
let asceA = A.sorted()
let descB = B.sorted(by: >)
var permutationExists = "YES"
// print(asceA)
// print(descB)
for i in 0..<asceA.count {
if asceA[i] + descB[i] < k {
permutationExists = "NO"
break
}
}
return permutationExists
}
twoArrays(k: 10, A: [2, 1, 3], B: [7, 8, 9]) // YES
twoArrays(k: 5, A: [1, 2, 2, 1], B: [3, 3, 3, 4]) // NO
twoArrays(k: 10, A: [7, 6, 8, 4, 2], B: [5, 2, 6, 3, 1]) // NO
| true
|
853ab898f9f45ddf6c183f978757495e5b034ec6
|
Swift
|
nobleidea/ThenGenerator
|
/ThenGeneratorApp/Sources/Models/UIRefreshControlModel.swift
|
UTF-8
| 941
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// UIRefreshControlModel.swift
// ThenGeneratorApp
//
// Created by Kanz on 2021/01/05.
//
import Foundation
public struct UIRefreshControlModel {
@UserDefaultsWrapper(UserDefaultsKeys.UIRefreshControlKeys.tintColor.key, defaultValue: true)
var tintColor: Bool
@UserDefaultsWrapper(UserDefaultsKeys.UIRefreshControlKeys.attributedTitle.key, defaultValue: true)
var attributedTitle: Bool
}
extension UIRefreshControlModel: ThenModelProtocol {
public func thenStringArray(indent: Int) -> [String] {
let indentString = String(repeating: " ", count: indent)
var strings: [String] = []
if self.tintColor == true {
strings.append("\(indentString)$0.tintColor = <#UIColor!#>")
}
if self.attributedTitle == true {
strings.append("\(indentString)$0.attributedTitle = <#NSAttributedString?#>")
}
return strings
}
}
| true
|
3231dd090f6423052c0fc552490d77e8dd771f2d
|
Swift
|
develician/yolo-holo--Ios
|
/yoloholo/Model/Todo.swift
|
UTF-8
| 386
| 2.765625
| 3
|
[] |
no_license
|
//
// Todo.swift
// yoloholo
//
// Created by killi8n on 2018. 7. 31..
// Copyright ยฉ 2018๋
killi8n. All rights reserved.
//
import Foundation
import SwiftyJSON
struct Todo {
let todo: String
init(json: JSON) {
// print(json)
// guard let todo = json.string else {fatalError("Todo Model todo parsing error")}
//
self.todo = "\(json)"
}
}
| true
|
efc71e6c934a71b14cd4cc4aa0569a6edce423f7
|
Swift
|
galudino/landmarks-swiftui-essentials
|
/Landmarks-tutorial-swiftui/Model/ModelData.swift
|
UTF-8
| 1,585
| 3.15625
| 3
|
[] |
no_license
|
//
// ModelData.swift
// Landmarks-tutorial-swiftui
//
// Created by Gemuele Aludino on 6/15/21.
//
import Foundation
import Combine
///
/// Declare a model type that conforms to the `ObservableObject`
/// protocol from the `Combine` framework.
///
/// SwiftUI subscribes to your observable object, and updates any views that need
/// refreshing when the data changes.
///
final class ModelData: ObservableObject {
///
/// Create an array of landmarks that you initialize from `landmarkData.json`.
///
/// An observable object needs to publish any changes to its data,
/// so that its subscribes can pick up the change.
///
@Published
var landmarks: [Landmark] = load("landmarkData.json")
///
/// Create a `load` function that fetches the JSON data with a given name from the app's main bundle.
/// The `load` function relies on the return type's conformance to the `Decodable` protocol.
///
private static func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else {
fatalError("Couldn't find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldn't load \(filename) from main bundle:\n(error)")
}
do {
return try JSONDecoder().decode(T.self, from: data)
} catch {
fatalError("Couldn't parse \(filename) as \(T.self):\n(error)")
}
}
}
| true
|
80793227ee91fd462da214a3f10b91985387178d
|
Swift
|
johndpope/SwiftRewriter
|
/Sources/SwiftAST/ValueTransformer.swift
|
UTF-8
| 2,264
| 2.9375
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
public struct ValueTransformer<T, U> {
let transformer: (T) -> U?
public init(transformer: @escaping (T) -> U?) {
self.transformer = transformer
}
public init(keyPath: KeyPath<T, U>) {
self.transformer = {
$0[keyPath: keyPath]
}
}
public init(keyPath: KeyPath<T, U?>) {
self.transformer = {
$0[keyPath: keyPath]
}
}
public func transform(value: T) -> U? {
return transformer(value)
}
public func transforming<Z>(_ callback: @escaping (U) -> Z?) -> ValueTransformer<T, Z> {
return ValueTransformer<T, Z> { [transformer] value in
guard let value = transformer(value) else {
return nil
}
return callback(value)
}
}
public func validate(_ predicate: @escaping (U) -> Bool) -> ValueTransformer<T, U> {
return ValueTransformer<T, U> { [transformer] value in
guard let value = transformer(value) else {
return nil
}
return predicate(value) ? value : nil
}
}
public func validate(matcher: ValueMatcher<U>) -> ValueTransformer<T, U> {
return ValueTransformer<T, U> { [transformer] value in
guard let value = transformer(value) else {
return nil
}
return matcher.matches(value) ? value : nil
}
}
}
public extension ValueTransformer where T == U {
public init() {
self.init { (value: T) -> U? in
return value
}
}
}
public extension ValueTransformer where U: MutableCollection {
public func transformIndex(index: U.Index,
transformer: ValueTransformer<U.Element, U.Element>) -> ValueTransformer {
return transforming { value in
guard value.endIndex > index else {
return nil
}
guard let new = transformer.transform(value: value[index]) else {
return nil
}
var value = value
value[index] = new
return value
}
}
}
| true
|
9281f16aeb92a1a6563fa0409b335fc9806e3f81
|
Swift
|
Ajisaputrars/SampleMapKitAndAnnotation
|
/SampleMapKitWithAnnotation/SampleMapKitController.swift
|
UTF-8
| 1,550
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// MapController.swift
// SampleMapKitWithAnnotation
//
// Created by Aji Saputra Raka Siwi on 22/11/20.
//
import UIKit
import MapKit
class SampleMapKitController: UIViewController {
private var sampleMapKitView: SampleMapKitView!
override func viewDidLoad() {
super.viewDidLoad()
self.sampleMapKitView = SampleMapKitView(frame: self.view.frame)
self.view = self.sampleMapKitView
self.view.backgroundColor = .white
let coordinate = CLLocationCoordinate2D(latitude: 1.082828, longitude: 104.030457)
let annotation = SampleMapAnnotation(coordinate: coordinate, title: "Sample Title", subtitle: "Sample Subtitle")
self.sampleMapKitView.mapView.addAnnotation(annotation)
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.navigationBar.barTintColor = .clear
self.navigationController?.navigationBar.shadowImage = UIImage()
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
}
}
extension SampleMapKitController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier) as? MKMarkerAnnotationView {
annotationView.animatesWhenAdded = true
annotationView.titleVisibility = .adaptive
return annotationView
}
return nil
}
}
| true
|
f3258e3e7b5ec384755720c5278afb64216c2a09
|
Swift
|
iOSCommunityUkraine/DataSourceTest
|
/DataSourceExample/Source/Cell/ReusableViewConfig+TableView.swift
|
UTF-8
| 1,610
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// ReusableViewConfig+TableView.swift
// DataSourceExample
//
// Created by Andrew Kochulab on 28.03.2021.
//
import UIKit
extension UITableView: ReusableViewConfig {
func registerItem(
with decorator: ViewDecoratorContext
) {
ReusableViewAnyContext(decorator).apply { context in
register(
context.type,
forCellReuseIdentifier: context.reuseIdentifier
)
}
}
func registerHeader(
with decorator: ViewDecoratorContext
) {
registerHeaderFooter(with: decorator)
}
func registerFooter(
with decorator: ViewDecoratorContext
) {
registerHeaderFooter(with: decorator)
}
private func registerHeaderFooter(
with decorator: ViewDecoratorContext
) {
ReusableViewAnyContext(decorator).apply { context in
register(
context.type,
forHeaderFooterViewReuseIdentifier: context.reuseIdentifier
)
}
}
func dequeue(
item: DataSourceItem,
with decorator: ViewDecoratorContext,
at indexPath: IndexPath
) -> UITableViewCell {
ReusableViewContext(decorator).transform { context in
let cell = dequeueReusableCell(
withIdentifier: context.reuseIdentifier,
for: indexPath
)
cell.selectionStyle = item.selectionEnabled ? .default : .none
decorator.execute(for: cell, with: item)
return cell
}
}
}
| true
|
e25c74245ccf6d44df4cbd51eb2987e251029583
|
Swift
|
TBA-API/tba-api-client-swift
|
/TBAAPIv3Kit/Classes/Swaggers/Models/Media.swift
|
UTF-8
| 3,189
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// Media.swift
//
// Generated by swagger-codegen
// https://github.com/swagger-api/swagger-codegen
//
import Foundation
/** The `Media` object contains a reference for most any media associated with a team or event on TBA. */
open class Media: Codable {
public enum ModelType: String, Codable {
case youtube = "youtube"
case cdphotothread = "cdphotothread"
case imgur = "imgur"
case facebookProfile = "facebook-profile"
case youtubeChannel = "youtube-channel"
case twitterProfile = "twitter-profile"
case githubProfile = "github-profile"
case instagramProfile = "instagram-profile"
case periscopeProfile = "periscope-profile"
case grabcad = "grabcad"
case instagramImage = "instagram-image"
case externalLink = "external-link"
case avatar = "avatar"
}
/** TBA identifier for this media. */
public var key: String
/** String type of the media element. */
public var type: ModelType
/** The key used to identify this media on the media site. */
public var foreignKey: String?
/** If required, a JSON dict of additional media information. */
public var details: Any?
/** True if the media is of high quality. */
public var preferred: Bool?
/** Direct URL to the media. */
public var directUrl: String?
/** The URL that leads to the full web page for the media, if one exists. */
public var viewUrl: String?
public init(key: String, type: ModelType, foreignKey: String?, details: Any?, preferred: Bool?, directUrl: String?, viewUrl: String?) {
self.key = key
self.type = type
self.foreignKey = foreignKey
self.details = details
self.preferred = preferred
self.directUrl = directUrl
self.viewUrl = viewUrl
}
// Encodable protocol methods
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: String.self)
try container.encode(key, forKey: "key")
try container.encode(type, forKey: "type")
try container.encodeIfPresent(foreignKey, forKey: "foreign_key")
try container.encodeIfPresent(details, forKey: "details")
try container.encodeIfPresent(preferred, forKey: "preferred")
try container.encodeIfPresent(directUrl, forKey: "direct_url")
try container.encodeIfPresent(viewUrl, forKey: "view_url")
}
// Decodable protocol methods
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: String.self)
key = try container.decode(String.self, forKey: "key")
type = try container.decode(ModelType.self, forKey: "type")
foreignKey = try container.decodeIfPresent(String.self, forKey: "foreign_key")
details = try container.decodeIfPresent(Any.self, forKey: "details")
preferred = try container.decodeIfPresent(Bool.self, forKey: "preferred")
directUrl = try container.decodeIfPresent(String.self, forKey: "direct_url")
viewUrl = try container.decodeIfPresent(String.self, forKey: "view_url")
}
}
| true
|
705d4aaa0176f3cb6ed01553e922ed218fdf052f
|
Swift
|
WholeCheese/LetterPairSimilarity
|
/LetterPairSimilarityTests/LetterPairSimilarityTests.swift
|
UTF-8
| 7,451
| 2.765625
| 3
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
//
// LetterPairSimilarityTests.swift
// LetterPairSimilarityTests
//
// Created by Allan Hoeltje on 9/2/16.
//
// 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 XCTest
@testable import LetterPairSimilarity
/// Test cases 1 through 4 were taken from the article "How to Strike a Match" by Simon White.
/// See: http://www.catalysoft.com/articles/StrikeAMatch.html
class LetterPairSimilarityTests: XCTestCase
{
struct TestCase
{
var str1: String
var str2: String
var score: Double
}
let test1Cases = [
TestCase(str1: "France", str2: "French", score: 40.0),
TestCase(str1: "France", str2: "Republic of France", score: 56.0),
TestCase(str1: "France", str2: "Quebec", score: 0.0),
TestCase(str1: "French Republic", str2: "Republic of France", score: 72.0),
TestCase(str1: "French Republic", str2: "Republic of Cuba", score: 61.0),
TestCase(str1: "Healed", str2: "Sealed", score: 80.0),
TestCase(str1: "Healed", str2: "Healthy", score: 55.0),
TestCase(str1: "Healed", str2: "Heard", score: 44.0),
TestCase(str1: "Healed", str2: "Herded", score: 40.0),
TestCase(str1: "Healed", str2: "Help", score: 25.0),
TestCase(str1: "Healed", str2: "Sold", score: 0.0),
]
let test2Cases = [
TestCase(str1: "Web Database Applications", str2: "Web Database Applications with PHP & MySQL", score: 82.0),
TestCase(str1: "Web Database Applications", str2: "Creating Database Web Applications with PHP and ASP", score: 71.0),
TestCase(str1: "Web Database Applications", str2: "Building Database Applications on the Web Using PHP3", score: 70.0),
TestCase(str1: "Web Database Applications", str2: "Building Web Database Applications with Visual Studio 6", score: 67.0),
TestCase(str1: "Web Database Applications", str2: "Web Application Development With PHP", score: 51.0),
TestCase(str1: "Web Database Applications", str2: "WebRAD: Building Database Applications on the Web with Visual FoxPro and Web Connection", score: 49.0),
TestCase(str1: "Web Database Applications", str2: "Structural Assessment: The Role of Large and Full-Scale Testing", score: 13.0),
TestCase(str1: "Web Database Applications", str2: "How to Find a Scholarship Online", score: 10.0),
]
let test3Cases = [
TestCase(str1: "PHP Web Applications", str2: "Web Database Applications with PHP & MySQL", score: 68.0),
TestCase(str1: "PHP Web Applications", str2: "Creating Database Web Applications with PHP and ASP", score: 59.0),
TestCase(str1: "PHP Web Applications", str2: "Building Database Applications on the Web Using PHP3", score: 58.0),
TestCase(str1: "PHP Web Applications", str2: "Building Web Database Applications with Visual Studio 6", score: 47.0),
TestCase(str1: "PHP Web Applications", str2: "Web Application Development With PHP", score: 67.0),
TestCase(str1: "PHP Web Applications", str2: "WebRAD: Building Database Applications on the Web with Visual FoxPro and Web Connection", score: 34.0),
TestCase(str1: "PHP Web Applications", str2: "Structural Assessment: The Role of Large and Full-Scale Testing", score: 7.0),
TestCase(str1: "PHP Web Applications", str2: "How to Find a Scholarship Online", score: 11.0),
]
let test4Cases = [
TestCase(str1: "Web Aplications", str2: "Web Database Applications with PHP & MySQL", score: 59.0),
TestCase(str1: "Web Aplications", str2: "Creating Database Web Applications with PHP and ASP", score: 50.0),
TestCase(str1: "Web Aplications", str2: "Building Database Applications on the Web Using PHP3", score: 49.0),
TestCase(str1: "Web Aplications", str2: "Building Web Database Applications with Visual Studio 6", score: 46.0),
TestCase(str1: "Web Aplications", str2: "Web Application Development With PHP", score: 56.0),
TestCase(str1: "Web Aplications", str2: "WebRAD: Building Database Applications on the Web with Visual FoxPro and Web Connection", score: 32.0),
TestCase(str1: "Web Aplications", str2: "Structural Assessment: The Role of Large and Full-Scale Testing", score: 7.0),
TestCase(str1: "Web Aplications", str2: "How to Find a Scholarship Online", score: 12.0),
]
let test5Cases = [
// Thanks to Google Translate for the CJK strings.
// English
TestCase(str1: "You should not do it.", str2: "You can not do it.", score: 63.0),
//Chinese Traditional
TestCase(str1: "ไฝ ไธๆ่ฉฒ้ๆจฃๅใ", str2: "ไฝ ๅฏ่ฝไธ้ๆจฃๅใ", score: 50.0),
// Chinese Simplified
TestCase(str1: "ไฝ ไธๅบ่ฏฅ่ฟๆ ทๅใ", str2: "ไฝ ๅฏ่ฝไธ่ฟๆ ทๅใ", score: 50.0),
// Japanese
TestCase(str1: "ใใชใใฏใใใ่กใในใใงใฏใใใพใใใ", str2: "ใใชใใฏใใใใใชใๅฏ่ฝๆงใใใใพใใ", score: 57.0),
// Korean
TestCase(str1: "๋น์ ์ ๊ทธ๋ ๊ฒ ํด์๋ ์์ต๋๋ค.", str2: "๋น์ ์ ๊ทธ๊ฒ์ ํ์ง ์์ ์ ์์ต๋๋ค.", score: 38.0),
]
override func setUp()
{
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown()
{
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func test1()
{
let lps = LetterPairSimilarity()
for testCase in test1Cases
{
let score = lps.compareStrings( testCase.str1, str2: testCase.str2)
print( "\(testCase.str1) ~ \(testCase.str2) Score: \(score) expected: \(testCase.score)" )
}
}
func test2()
{
let lps = LetterPairSimilarity()
var i = 1
for testCase in test2Cases
{
let score = lps.compareStrings( testCase.str1, str2: testCase.str2)
print( "\(i) Score: \(score) expected: \(testCase.score)" )
i += 1
}
}
func test3()
{
let lps = LetterPairSimilarity()
var i = 1
for testCase in test3Cases
{
let score = lps.compareStrings( testCase.str1, str2: testCase.str2)
print( "\(i) Score: \(score) expected: \(testCase.score)" )
i += 1
}
}
func test4()
{
let lps = LetterPairSimilarity()
var i = 1
for testCase in test4Cases
{
let score = lps.compareStrings( testCase.str1, str2: testCase.str2)
print( "\(i) Score: \(score) expected: \(testCase.score)" )
i += 1
}
}
func test5()
{
let lps = LetterPairSimilarity()
var i = 1
for testCase in test5Cases
{
let score = lps.compareStrings( testCase.str1, str2: testCase.str2)
print( "\(i) Score: \(score) expected: \(testCase.score)" )
i += 1
}
}
}
| true
|
a00e39beadf4b18c674477fd871e2edb9f8ad9c7
|
Swift
|
hughbe/MicrosoftOrganizationChartReader
|
/Tests/MicrosoftOrganizationChartReaderTests/OrganizationChartDumper.swift
|
UTF-8
| 837
| 2.96875
| 3
|
[] |
no_license
|
//
// OrganizationChartDumper.swift
//
//
// Created by Hugh Bellamy on 23/01/2021.
//
import DataStream
import Foundation
import MicrosoftOrganizationChartReader
public struct OrganizationChartDumper {
public static func dumpChart(filePath: String) throws {
let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
var dataStream = DataStream(data)
guard try dataStream.readString(count: 4, encoding: .ascii)! == "UOCF" else {
throw OrganizationChartReadError.corrupted
}
while dataStream.remainingCount > 0 {
var (id, data) = try dataStream.readOrganizationChartRecord()
print("Record: \(id.hexString)")
let bytes = try data.readBytes(count: data.count)
print("Data: \(bytes.hexString)")
}
}
}
| true
|
8fa100825669c376f3c131af37d89c3dd9550f35
|
Swift
|
PGHM/braintrain
|
/swift_ui/NewsSwiftUIDemo/NewsSwiftUIDemo/NewsView.swift
|
UTF-8
| 460
| 2.75
| 3
|
[] |
no_license
|
//
// Copyright ยฉ 2022 Jussi Pรคivinen. All rights reserved.
//
import SwiftUI
struct NewsView: View {
let teasers: [Teaser]
var body: some View {
List(teasers) { teaser in
TeaserView(teaser: teaser)
}
.listStyle(.plain)
}
}
struct NewsView_Previews: PreviewProvider {
static var previews: some View {
NewsView(teasers: TeaserProvider.frontPageTeasers)
.previewLayout(.sizeThatFits)
}
}
| true
|
ceba849317f2f2c05a91644ba608d2326ed4a3d7
|
Swift
|
ParkChanSeon/OurMeal-ios
|
/OurMeal/model/Member.swift
|
UTF-8
| 492
| 2.734375
| 3
|
[] |
no_license
|
class Member :Codable{
var member_id : String?
var member_pw : String?
var member_name : String?
var member_email : String?
var loc_code : String?
var member_address : String?
var member_phone : String?
var member_birth : String?
var member_sex : String?
var member_date : String?
var member_image : String?
var member_type : Int?
var member_grade : String?
}
protocol MemberProtocol {
func setMember(member: Member?)
}
| true
|
b7dd8488534e23e03629bde6179c621f20af0d99
|
Swift
|
johntranx/Learnable-Git-Course
|
/ActivityLogger/FirstViewController.swift
|
UTF-8
| 2,549
| 2.59375
| 3
|
[] |
no_license
|
//
// FirstViewController.swift
// ActivityLogger
//
// Created by Nam Tran on 3/9/16.
// Copyright ยฉ 2016 Nam Tran. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
var timer:NSTimer = NSTimer()
var timerCounter:Int = 0
var currentActivity:Activity?
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var startButton: UIButton!
@IBAction func startTimer_click(sender: AnyObject) {
if startButton.titleLabel?.text == "Start"
{
startButton.setTitle("Stop", forState: UIControlState.Normal)
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "processTimer", userInfo: nil, repeats: true)
}
else
{
startButton.setTitle("Start", forState: UIControlState.Normal)
timer.invalidate()
currentActivity?.totalTime += timerCounter
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
pickerView.reloadAllComponents()
if ActivityManager.activities.count == 1
{
currentActivity = ActivityManager.activities[0]
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
ActivityManager.activities.append(Activity(activityName: "Running", totalTime: 0))
}
func processTimer()
{
timerCounter++
timerLabel.text = String(timerCounter)
}
//delegate
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
currentActivity = ActivityManager.activities[row]
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let activity = ActivityManager.activities[row]
return activity.activityName
}
//datasource
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return ActivityManager.activities.count
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
913190a0b66c05b79b35c7aa00297f40b2b3412e
|
Swift
|
paug/AndroidMakersApp-iOS
|
/RobotConf/Model/Data/Providers/Json/JsonRoomsProvider.swift
|
UTF-8
| 1,165
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// Copyright ยฉ 2020 Paris Android User Group. All rights reserved.
//
import Foundation
import Combine
/// Object that provides rooms from a json file
class JsonRoomsProvider: RoomsProvider {
private struct RoomsContainer: Decodable {
struct Rooms: Decodable {
let allRooms: [RoomData]
}
let rooms: Rooms
}
var roomsPublisher = PassthroughSubject<[String: RoomData], Error>()
init() {
DispatchQueue.main.async {
guard let url = Bundle.main.url(forResource: "schedule-app", withExtension: "json") else {
fatalError("schedule-app.json is not embedded in the app.")
}
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let roomsContainer = try decoder.decode(RoomsContainer.self, from: data)
let rooms = Dictionary(uniqueKeysWithValues: roomsContainer.rooms.allRooms.map { ($0.roomId, $0) })
self.roomsPublisher.send(rooms)
} catch {
self.roomsPublisher.send(completion: .failure(error))
}
}
}
}
| true
|
593a03277da31cd2aebbe85bd7191be38b0a7f34
|
Swift
|
thachgiasoft/SwiftUI_Views
|
/SwiftUI_Views/EffectModifiers/Saturation/Saturation_Intro.swift
|
UTF-8
| 11,036
| 3.296875
| 3
|
[] |
no_license
|
//
// Saturation_Intro.swift
// 100Views
//
// Created by Mark Moeykens on 8/26/19.
// Copyright ยฉ 2019 Mark Moeykens. All rights reserved.
//
import SwiftUI
struct Saturation_Intro: View {
var body: some View {
VStack(spacing: 10) {
Text("Saturation").font(.largeTitle)
Text("Introduction").font(.title).foregroundColor(.gray)
Text("Saturation offers another way to adjust the intensity of colors. One (1) is the default (no change).")
.frame(maxWidth: .infinity)
.font(.title).padding()
.background(Color.orange)
.layoutPriority(1)
.foregroundColor(.black)
VStack(spacing: 8) {
HStack(spacing: 0) {
Color.red
.frame(width: 50, height: 50)
.saturation(0)
.overlay(Text("0"))
Color.red
.frame(width: 50, height: 50)
.saturation(0.1)
.overlay(Text("0.1"))
Color.red
.frame(width: 50, height: 50)
.saturation(0.5)
.overlay(Text("0.5"))
Color.red
.frame(width: 50, height: 50)
.saturation(1)
.overlay(Text("1"))
Color.red
.frame(width: 50, height: 50)
.saturation(2)
.overlay(Text("2"))
Color.red
.frame(width: 50, height: 50)
.saturation(3.5)
.overlay(Text("3.5"))
Color.red
.frame(width: 50, height: 50)
.saturation(50)
.overlay(Text("5"))
}
HStack(spacing: 0) {
Color.pink
.frame(width: 50, height: 50)
.saturation(0)
.overlay(Text("0"))
Color.pink
.frame(width: 50, height: 50)
.saturation(0.1)
.overlay(Text("0.1"))
Color.pink
.frame(width: 50, height: 50)
.saturation(0.5)
.overlay(Text("0.5"))
Color.pink
.frame(width: 50, height: 50)
.saturation(1)
.overlay(Text("1"))
Color.pink
.frame(width: 50, height: 50)
.saturation(2)
.overlay(Text("2"))
Color.pink
.frame(width: 50, height: 50)
.saturation(3.5)
.overlay(Text("3.5"))
Color.pink
.frame(width: 50, height: 50)
.saturation(5)
.overlay(Text("5"))
}
HStack(spacing: 0) {
Color.green
.frame(width: 50, height: 50)
.saturation(0)
.overlay(Text("0"))
Color.green
.frame(width: 50, height: 50)
.saturation(0.1)
.overlay(Text("0.1"))
Color.green
.frame(width: 50, height: 50)
.saturation(0.5)
.overlay(Text("0.5"))
Color.green
.frame(width: 50, height: 50)
.saturation(1)
.overlay(Text("1"))
Color.green
.frame(width: 50, height: 50)
.saturation(2)
.overlay(Text("2"))
Color.green
.frame(width: 50, height: 50)
.saturation(3.5)
.overlay(Text("3.5"))
Color.green
.frame(width: 50, height: 50)
.saturation(5)
.overlay(Text("5"))
}
HStack(spacing: 0) {
Color.purple
.frame(width: 50, height: 50)
.saturation(0)
.overlay(Text("0"))
Color.purple
.frame(width: 50, height: 50)
.saturation(0.1)
.overlay(Text("0.1"))
Color.purple
.frame(width: 50, height: 50)
.saturation(0.5)
.overlay(Text("0.5"))
Color.purple
.frame(width: 50, height: 50)
.saturation(1)
.overlay(Text("1"))
Color.purple
.frame(width: 50, height: 50)
.saturation(2)
.overlay(Text("2"))
Color.purple
.frame(width: 50, height: 50)
.saturation(3.5)
.overlay(Text("3.5"))
Color.purple
.frame(width: 50, height: 50)
.saturation(5)
.overlay(Text("5"))
}
HStack(spacing: 0) {
Color.blue
.frame(width: 50, height: 50)
.saturation(0)
.overlay(Text("0"))
Color.blue
.frame(width: 50, height: 50)
.saturation(0.1)
.overlay(Text("0.1"))
Color.blue
.frame(width: 50, height: 50)
.saturation(0.5)
.overlay(Text("0.5"))
Color.blue
.frame(width: 50, height: 50)
.saturation(1)
.overlay(Text("1"))
Color.blue
.frame(width: 50, height: 50)
.saturation(2)
.overlay(Text("2"))
Color.blue
.frame(width: 50, height: 50)
.saturation(3.5)
.overlay(Text("3.5"))
Color.blue
.frame(width: 50, height: 50)
.saturation(5)
.overlay(Text("5"))
}
HStack(spacing: 0) {
Color.orange
.frame(width: 50, height: 50)
.saturation(0)
.overlay(Text("0"))
Color.orange
.frame(width: 50, height: 50)
.saturation(0.1)
.overlay(Text("0.1"))
Color.orange
.frame(width: 50, height: 50)
.saturation(0.5)
.overlay(Text("0.5"))
Color.orange
.frame(width: 50, height: 50)
.saturation(1)
.overlay(Text("1"))
Color.orange
.frame(width: 50, height: 50)
.saturation(2)
.overlay(Text("2"))
Color.orange
.frame(width: 50, height: 50)
.saturation(3.5)
.overlay(Text("3.5"))
Color.orange
.frame(width: 50, height: 50)
.saturation(5)
.overlay(Text("5"))
}
HStack(spacing: 0) {
Color.yellow
.frame(width: 50, height: 50)
.saturation(0)
.overlay(Text("0"))
Color.yellow
.frame(width: 50, height: 50)
.saturation(0.1)
.overlay(Text("0.1"))
Color.yellow
.frame(width: 50, height: 50)
.saturation(0.5)
.overlay(Text("0.5"))
Color.yellow
.frame(width: 50, height: 50)
.saturation(1)
.overlay(Text("1"))
Color.yellow
.frame(width: 50, height: 50)
.saturation(2)
.overlay(Text("2"))
Color.yellow
.frame(width: 50, height: 50)
.saturation(3.5)
.overlay(Text("3.5"))
Color.yellow
.frame(width: 50, height: 50)
.saturation(5)
.overlay(Text("5"))
}
Text("Gray")
HStack(spacing: 0) {
Color.gray
.frame(width: 50, height: 50)
.saturation(0)
.overlay(Text("0"))
Color.gray
.frame(width: 50, height: 50)
.saturation(1)
.overlay(Text("1"))
Color.gray
.frame(width: 50, height: 50)
.saturation(5)
.overlay(Text("5"))
Color.gray
.frame(width: 50, height: 50)
.saturation(10)
.overlay(Text("10"))
Color.gray
.frame(width: 50, height: 50)
.saturation(20)
.overlay(Text("20"))
Color.gray
.frame(width: 50, height: 50)
.saturation(35)
.overlay(Text("35"))
Color.gray
.frame(width: 50, height: 50)
.saturation(50)
.overlay(Text("50"))
}
}.foregroundColor(.black)
Text("Note: Saturation has no effect on black or white.")
}
}
}
struct Saturation_Intro_Previews: PreviewProvider {
static var previews: some View {
Saturation_Intro()
}
}
| true
|
c8688c9f8e4296b2dfc5d02eebb88198da5712f4
|
Swift
|
MadManLabs/Sub-It
|
/Sub It/dropView.swift
|
UTF-8
| 4,141
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// dropView.swift
// Sub It
//
// Created by Kevin De Koninck on 12/02/2017.
// Copyright ยฉ 2017 Kevin De Koninck. All rights reserved.
//
import Cocoa
class DropView: NSView {
var filePaths = [String]()
let expectedExt = ["AVI","FLV","WMV","MP4","MOV","MKV","QT","HEVC","DIVX","XVID"] // file extensions allowed fornDropping
let backgroundColor = NSColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.05).cgColor
private var allowedArray = [Bool]()
required init?(coder: NSCoder) {
super.init(coder: coder)
register(forDraggedTypes: [NSFilenamesPboardType, NSURLPboardType])
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
self.wantsLayer = true
self.layer?.backgroundColor = backgroundColor
// dash customization parameters
let dashHeight: CGFloat = 5
let dashLength: CGFloat = 10
let dashColor = NSColor.gray
// setup the context
let currentContext = NSGraphicsContext.current()!.cgContext
currentContext.setLineWidth(dashHeight)
currentContext.setLineDash(phase: 0, lengths: [dashLength])
currentContext.setStrokeColor(dashColor.cgColor)
// draw the dashed path
currentContext.addRect(bounds.insetBy(dx: dashHeight-dashHeight/2, dy: dashHeight-dashHeight/2))
currentContext.strokePath()
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
//Reset on new drag
self.allowedArray = [Bool]()
self.filePaths = [String]()
if checkExtension(sender) == true {
self.layer?.backgroundColor = NSColor(red: 50.0/255, green: 140.0/255, blue: 255.0/255, alpha: 0.2).cgColor
return .copy
} else {
self.layer?.backgroundColor = NSColor(red: 255.0/255, green: 0.0/255, blue: 0.0/255, alpha: 0.2).cgColor
return NSDragOperation()
}
}
fileprivate func checkExtension(_ drag: NSDraggingInfo) -> Bool {
guard let board = drag.draggingPasteboard().propertyList(forType: "NSFilenamesPboardType") as? NSArray,
let paths = board as? [String]
else { return false }
for path in paths {
var isAllowed = false
var isDir: ObjCBool = false
let fm = FileManager()
if fm.fileExists(atPath: path, isDirectory: &isDir) {
if(isDir.boolValue){
isAllowed = true
} else {
let suffix = URL(fileURLWithPath: path).pathExtension
for ext in self.expectedExt {
if ext.lowercased() == suffix {
isAllowed = true
}
}
}
}
allowedArray.append(isAllowed)
}
//If one element is allowed, pass everything (we'll handle this un-allowed file later)
for check in allowedArray { if check { return true } }
return false
}
override func draggingExited(_ sender: NSDraggingInfo?) {
self.layer?.backgroundColor = backgroundColor
}
override func draggingEnded(_ sender: NSDraggingInfo?) {
self.layer?.backgroundColor = backgroundColor
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
guard let pasteboard = sender.draggingPasteboard().propertyList(forType: "NSFilenamesPboardType") as? NSArray,
let paths = pasteboard as? [String]
else { return false }
var index = 0
for path in paths {
//Append path to array if the file type was allowed
if allowedArray[index] {
self.filePaths.append(path)
}
index = index + 1
}
//post notification
NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "somethingWasDropped"), object: nil) as Notification)
return true
}
}
| true
|
acf8dc899ef748ded566738df1be29507514aaa8
|
Swift
|
Wistas23/InputBarAccessoryView
|
/Example/Example/InputBarStyleSelectionController.swift
|
UTF-8
| 2,828
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// InputBarStyleSelectionController.swift
// Example
//
// Created by Nathan Tannar on 8/18/17.
// Copyright ยฉ 2017-2019 Nathan Tannar. All rights reserved.
//
import UIKit
class InputBarStyleSelectionController: UITableViewController {
let styles = InputBarStyle.allCases
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
title = "InputBarAccessoryView"
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Styles", style: .plain, target: nil, action: nil)
navigationController?.navigationBar.tintColor = .white
navigationController?.navigationBar.barTintColor = UIColor(red: 0/255, green: 122/255, blue: 1, alpha: 1)
navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "InputBarViewController"
}
return section == 1 ? "InputAccessoryView" : "Subview"
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
return styles.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
if indexPath.section == 0 {
cell.textLabel?.text = "README Preview"
} else {
cell.textLabel?.text = styles[indexPath.row].rawValue
}
cell.accessoryType = .disclosureIndicator
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
navigationController?.pushViewController(READMEPreviewViewController(), animated: true)
} else {
let convo = SampleData.shared.getConversations(count: 1)[0]
if indexPath.section == 1 {
navigationController?.pushViewController(
InputAccessoryExampleViewController(style: styles[indexPath.row],
conversation: convo),
animated: true)
} else if indexPath.section == 2 {
navigationController?.pushViewController(
SubviewExampleViewController(style: styles[indexPath.row],
conversation: convo),
animated: true)
}
}
}
}
| true
|
69ca068800482d6a76b3a27cac8f5ac5328ce942
|
Swift
|
chrispix/swift-poloniex-portfolio
|
/Sources/poloniex/HistoryLoader.swift
|
UTF-8
| 3,236
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
/*
[{ "globalTradeID": 25129732, "tradeID": "6325758", "date": "2016-04-05 08:08:40", "rate": "0.02565498", "amount": "0.10000000", "total": "0.00256549", "fee": "0.00200000", "orderNumber": "34225313575", "type": "sell", "category": "exchange" }, { "globalTradeID": 25129628, "tradeID": "6325741", "date": "2016-04-05 08:07:55", "rate": "0.02565499", "amount": "0.10000000", "total": "0.00256549", "fee": "0.00200000", "orderNumber": "34225195693", "type": "buy", "category": "exchange" }, ... ]
*/
class HistoryLoader {
private static let dateParser: DateFormatter = {
let parser = DateFormatter()
parser.dateFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"
return parser
}()
static func loadOrders(_ holding: Holding, keys: APIKeys) -> [ExecutedOrder] {
let session = URLSession(configuration: URLSessionConfiguration.default)
let poloniexRequest = PoloniexRequest(params: ["command": "returnTradeHistory", "currencyPair": holding.bitcoinMarketKey, "start": "0", "end": "\(Date().timeIntervalSince1970)"], keys: keys)
let request = poloniexRequest.urlRequest
var finished = false
var orders = [ExecutedOrder]()
let historyTask = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
guard let data = data, let responseBody = String(data: data, encoding: .utf8) else {
print("couldn't decode data")
finished = true
return
}
guard error == nil else {
print("error response")
finished = true
return
}
guard !responseBody.isEmpty else {
print("empty response")
finished = true
return
}
do {
let orderDicts: [[AnyHashable: Any?]] = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as! [[AnyHashable: Any?]]
for order in orderDicts {
guard let typeString = order["type"] as? String,
let type = BuySell(rawValue: typeString),
let amount = JSONHelper.double(fromJsonObject: order["amount"] as? String),
let price = JSONHelper.double(fromJsonObject: order["rate"] as? String),
let total = JSONHelper.double(fromJsonObject: order["total"] as? String),
let fee = JSONHelper.double(fromJsonObject: order["fee"] as? String),
let dateString = order["date"] as? String,
let date = dateParser.date(from: dateString)
else { continue }
let thisOrder = ExecutedOrder(price: price, amount: amount, type: type, fee: fee, total: total, date: date)
orders.append(thisOrder)
}
} catch {
print("couldn't decode JSON")
finished = true
return
}
finished = true
})
historyTask.resume()
while(!finished) {}
return orders
}
}
| true
|
0b7219c20b82f84595dad004a22f6b8faec46d0a
|
Swift
|
FernandoZamora/MoviesDB
|
/Movies DB/UI/UICollectionViewCell/MovieCollectionViewCell.swift
|
UTF-8
| 1,386
| 2.78125
| 3
|
[] |
no_license
|
//
// MovieCollectionViewCell.swift
// Movies DB
//
// Created by Fernando Zamora on 11/01/21.
//
import UIKit
import Kingfisher
class MovieCollectionViewCell: UICollectionViewCell, Registrable, Dequeable {
@IBOutlet weak var posterImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
}
extension MovieCollectionViewCell: Configurable{
typealias DataType = Movie
func configure(with data: Movie) {
guard let posterPath = data.poster else{
self.posterImageView.image = UIImage(named: "placeholderImage")
return
}
let posterURL = Endpoint.getPosterURL(path: posterPath).url
if let url = URL(string: posterURL) {
self.posterImageView.kf.indicatorType = .activity
self.posterImageView.kf.setImage(with: url,
placeholder: UIImage(named: "placeholderImage"),
options: [
.scaleFactor(UIScreen.main.scale),
.transition(.fade(1)),
.cacheOriginalImage
])
}
else{
self.posterImageView.image = UIImage(named: "placeholderImage")
}
}
}
| true
|
fe6c2d3d68cb76db9d9c7135ff62f798f4543af4
|
Swift
|
rocontrerasca/Desarrollo-de-aplicaciones-iOS
|
/3.AccediendoALaNubeConiOs/BuscarImagenesCoreData/BuscarImagenesCoreData/Classes/SectionItem.swift
|
UTF-8
| 347
| 2.71875
| 3
|
[] |
no_license
|
//
// SectionItem.swift
// BuscarImagenesCoreData
//
// Created by Developer 1 on 4/12/18.
// Copyright ยฉ 2018 comDeveloper. All rights reserved.
//
import UIKit
struct SectionItem {
var name: String
var images : [UIImage]
init(name:String, images:[UIImage]) {
self.name = name
self.images = images
}
}
| true
|
602df598184a86f13d026ecb60b988a80e68a3be
|
Swift
|
devcraig/holdem101
|
/Hold'em 101/Hold'em 101/cardModel.swift
|
UTF-8
| 25,079
| 3.296875
| 3
|
[] |
no_license
|
//
// cardModel.swift
// Hold'em 101
//
// Created by Devin Craig on 3/14/21.
//
import Foundation
enum CardType: CaseIterable {
case ace
case king
case queen
case jack
case ten
case nine
case eight
case seven
case six
case five
case four
case three
case two
}
class Slider {
var minimumValue = 0
var maximumValue = 140
}
enum CardSuit: CaseIterable {
case hearts
case spades
case clubs
case diamonds
}
struct Card: Equatable {
var type: CardType
var suit: CardSuit
}
func CardToStr(_ cs: [Card]) -> String {
var s = ""
var c = cs[0]
if (c.type == CardType.ace) {
s += "Ace of "
} else if (c.type == CardType.king) {
s += "King of "
} else if (c.type == CardType.queen) {
s += "Queen of "
} else if (c.type == CardType.jack) {
s += "Jack of "
} else if (c.type == CardType.ten) {
s += "Ten of "
} else if (c.type == CardType.nine) {
s += "Nine of "
} else if (c.type == CardType.eight) {
s += "Eight of "
} else if (c.type == CardType.seven) {
s += "Seven of "
} else if (c.type == CardType.six) {
s += "Six of "
} else if (c.type == CardType.five) {
s += "Five of "
} else if (c.type == CardType.four) {
s += "Four of "
} else if (c.type == CardType.three) {
s += "Three of "
} else if (c.type == CardType.two) {
s += "Two of "
} else {
}
if (c.suit == CardSuit.clubs) {
s += "Clubs"
} else if (c.suit == CardSuit.diamonds) {
s += "Diamonds"
} else if (c.suit == CardSuit.hearts) {
s += "Hearts"
} else if (c.suit == CardSuit.spades) {
s += "Spades"
}
else {
}
s += " and the "
c = cs[1]
if (c.type == CardType.ace) {
s += "Ace of "
} else if (c.type == CardType.king) {
s += "King of "
} else if (c.type == CardType.queen) {
s += "Queen of "
} else if (c.type == CardType.jack) {
s += "Jack of "
} else if (c.type == CardType.ten) {
s += "Ten of "
} else if (c.type == CardType.nine) {
s += "Nine of "
} else if (c.type == CardType.eight) {
s += "Eight of "
} else if (c.type == CardType.seven) {
s += "Seven of "
} else if (c.type == CardType.six) {
s += "Six of "
} else if (c.type == CardType.five) {
s += "Five of "
} else if (c.type == CardType.four) {
s += "Four of "
} else if (c.type == CardType.three) {
s += "Three of "
} else if (c.type == CardType.two) {
s += "Two of "
} else {
}
if (c.suit == CardSuit.clubs) {
s += "Clubs"
} else if (c.suit == CardSuit.diamonds) {
s += "Diamonds"
} else if (c.suit == CardSuit.hearts) {
s += "Hearts"
} else if (c.suit == CardSuit.spades) {
s += "Spades"
}
else {
}
return s
}
func opttoint(_ opt: Int?) -> Int {
return opt!
}
struct Player {
//true is cpu
var cpu: Bool
var hand: [Card]
var chips: Int
var strength: Int
var name: String
// fold = true
var fold: Bool = false
mutating func updateStrength(st: Int) {
self.strength = st
}
mutating func updateFold() {
fold = true
}
}
class cardModel {
@Published var cards: [Card]
var strength: Int
var round: Int
var highCard: Int
init(cs: [Card], r: Int) {
cards = cs
strength = 0
highCard = 0
round = r
strength = cardStrength()
}
func reset() { //Same as init? Can probably change idk
cards = []
strength = 0
highCard = 0
}
func cardStrength() -> Int { //calc strength
strength = 0
highCard = 0
if round >= 0 {
//High card
for i in 0...cards.count-1 {
if (rank(c:cards[i]) > highCard) {
highCard = rank(c:cards[i])
strength = highCard
}
}
let pair = isPair(cs: cards)
if pair {
strength = 14+highCard
// print("pair")
}
if round >= 1 {
let twopair = is2Pair(cs: cards)
if twopair {
strength = 28+highCard
// print("twopair")
}
let threekind = is3kind(cs: cards)
if threekind {
strength = 42+highCard
// print("3 kind")
}
let straight = isStraight(cs: cards)
if(straight){
strength = 56+highCard
// print("str")
}
let flush = isFlush(cs: cards)
if (flush) {
strength = 70+highCard
// print("flu")
}
let fullHouse = isFullHouse(cs: cards)
if fullHouse {
strength = 84+highCard
// print("fullh")
}
let isfour = is4kind(cs: cards)
if(isfour){
strength = 98+highCard
// print("4")
}
}
}
return strength
}
func is4kind(cs: [Card]) -> Bool {
let sorted = cs
var valueArray: [Int] = []
for card in sorted {
valueArray.append(rank(c: card))
}
let countedSet = NSCountedSet(array: valueArray)
for i in valueArray {
if countedSet.count(for: i) == 4 {
highCard = i
return true
}
}
return false
}
func is3kind(cs: [Card]) -> Bool {
let sorted = cs
var valueArray: [Int] = []
for card in sorted {
valueArray.append(rank(c: card))
}
let countedSet = NSCountedSet(array: valueArray)
for i in valueArray {
if countedSet.count(for: i) == 3 {
highCard = i
return true
}
}
return false
}
func is2Pair(cs: [Card]) -> Bool {
let sorted = cs
var valueArray: [Int] = []
for card in sorted {
valueArray.append(rank(c: card))
}
let countedSet = NSCountedSet(array: valueArray)
var firstpair = false
var val1: Int = 0
for i in valueArray {
if countedSet.count(for: i) == 2 && i != val1 {
if firstpair {
highCard = max(i,val1)
return true
}
else {
firstpair = true
val1 = i
}
}
}
return false
}
func isFullHouse(cs: [Card]) -> Bool {
let sorted = cs
var valueArray: [Int] = []
for card in sorted {
valueArray.append(rank(c: card))
}
let countedSet = NSCountedSet(array: valueArray)
var firstpair = false
var triples = false
var val1 = 0
for i in valueArray {
if countedSet.count(for: i) == 2 && i != val1{
if triples {
highCard = max(i,val1)
return true
}
firstpair = true
val1 = i
}
if countedSet.count(for: i) == 3 && i != val1{
if firstpair {
highCard = max(i,val1)
return true
}
triples = true
val1 = i
}
}
return false
}
func isPair(cs: [Card]) -> Bool {
let sorted = cs
var valueArray: [Int] = []
for card in sorted {
valueArray.append(rank(c: card))
}
let countedSet = NSCountedSet(array: valueArray)
for i in valueArray {
if countedSet.count(for: i) == 2 {
highCard = i
return true
}
}
return false
}
func isStraight(cs: [Card]) -> Bool {
let temp = cs
if round == 1 {
var valueArray: [Int] = []
for card in temp {
valueArray.append(rank(c: card))
}
valueArray = valueArray.sorted()
//ace
if valueArray.contains(13) {
for i in 1...4 {
if (!valueArray.contains(i)) {
break
}
else {
if i == 4 {
highCard = 4
return true
}
}
}
for i in 9...12 {
if (!valueArray.contains(i)) {
return false
}
}
highCard = 13
return true
}
//no ace
else {
var tester = valueArray[0] + 1
for i in 1...temp.count-1 {
if (valueArray.contains(tester)) {
if i == temp.count - 1 {
highCard = tester
return true
}
tester = tester + 1
}
else {
break
}
}
return false
}
}
if round == 2 {
var valueArray: [Int] = []
for card in temp {
valueArray.append(rank(c: card))
}
valueArray = valueArray.sorted()
var tester = valueArray[0] + 1
for i in 1...valueArray.count-2 {
if (valueArray.contains(tester)) {
if i == temp.count - 2 {
highCard = tester
return true
}
tester = tester + 1
}
else {
break
}
}
tester = valueArray[2] + 1
for i in 2...temp.count-1 {
if (valueArray.contains(tester)) {
if i == temp.count - 2 {
highCard = tester
return true
}
tester = tester + 1
}
else {
break
}
}
if valueArray.contains(13) {
for i in 1...4 {
if (!valueArray.contains(i)) {
break
}
else {
if i == 4 {
highCard = 4
return true
}
}
}
for i in 9...12 {
if (!valueArray.contains(i)) {
return false
}
}
highCard = 13
return true
}
return false
}
if round == 3 {
var valueArray: [Int] = []
for card in temp {
valueArray.append(rank(c: card))
}
valueArray = valueArray.sorted()
var tester = valueArray[0] + 1
for i in 1...temp.count-3 {
if (valueArray.contains(tester)) {
if i == temp.count - 3 {
highCard = tester
return true
}
tester = tester + 1
}
else {
break
}
}
tester = valueArray[1] + 1
for i in 2...temp.count-2 {
if (valueArray.contains(tester)) {
if i == temp.count - 2 {
highCard = tester
return true
}
tester = tester + 1
}
else {
break
}
}
tester = valueArray[2] + 1
for i in 3...temp.count-1 {
if (valueArray.contains(tester)) {
if i == temp.count - 1 {
highCard = tester
return true
}
tester = tester + 1
}
else {
break
}
}
if valueArray.contains(13) {
for i in 1...4 {
if (!valueArray.contains(i)) {
break
}
else {
if i == 4 {
highCard = 4
return true
}
}
}
for i in 9...12 {
if (!valueArray.contains(i)) {
return false
}
}
highCard = 13
return true
}
return false
}
return false
}
func rank(c: Card) -> Int { //get rank of card
if (c.type == CardType.ace) {
return 13
} else if (c.type == CardType.king) {
return 12
} else if (c.type == CardType.queen) {
return 11
} else if (c.type == CardType.jack) {
return 10
} else if (c.type == CardType.ten) {
return 9
} else if (c.type == CardType.nine) {
return 8
} else if (c.type == CardType.eight) {
return 7
} else if (c.type == CardType.seven) {
return 6
} else if (c.type == CardType.six) {
return 5
} else if (c.type == CardType.five) {
return 4
} else if (c.type == CardType.four) {
return 3
} else if (c.type == CardType.three) {
return 2
} else if (c.type == CardType.two) {
return 1
} else {
return -1 //idk
}
}
func isFlush(cs: [Card]) -> Bool {
var hcount = 0
var scount = 0
var dcount = 0
var ccount = 0
for i in 0...cs.count-1 {
if (cs[i].suit == CardSuit.hearts) {
hcount = hcount + 1
} else if (cs[i].suit == CardSuit.spades) {
scount = scount + 1
} else if (cs[i].suit == CardSuit.diamonds) {
dcount = dcount + 1
} else { //clubs
ccount = ccount + 1
}
}
highCard = 0
for i in 0...cards.count-1 {
if (rank(c:cards[i]) > highCard) {
highCard = rank(c:cards[i])
}
}
if (hcount >= 5 || scount >= 5 || dcount >= 5 || ccount >= 5) {
return true
}
return false
}
}
class deck: ObservableObject {
@Published var availableCards: [Card]
@Published var playerHands: [Player]
@Published var sharedCards: [Card]
@Published var players: Int
@Published var round: Int = 0
@Published var playersLeft: Int
var tutorial: Bool
init(numplayers: Int, tut: Bool, buyIn: Int) {
availableCards = resetMain()
playerHands = []
sharedCards = []
playersLeft = numplayers
players = numplayers
tutorial = tut
round = 0
hands(buyin: buyIn)
}
func addChips(_ chips: Int, _ str: String) {
// print(str + "won \(chips)")
for i in 0...playerHands.count - 1 {
if playerHands[i].name == str {
playerHands[i].chips += chips
}
}
}
func betChips(_ chips: Int) {
for i in 0...playerHands.count - 1 {
if playerHands[i].fold == false {
playerHands[i].chips -= chips
}
}
}
func newGame(numplayers: Int, tut: Bool, buyIn: Int) {
players = numplayers
playersLeft = numplayers
tutorial = tut
playerHands = []
sharedCards = []
availableCards = reset1()
round = 0
hands(buyin: buyIn)
}
func getPlayersLeft() -> Int {
return playersLeft
}
func hands(buyin: Int) {
// if tutorial {
let humanhand: [Card] = twoCards()//twoCardsTutorial()
//print(humanhand)
let cModel1 = cardModel(cs: humanhand, r: round)
let playerhand = Player(cpu: false, hand: humanhand, chips: buyin, strength: cModel1.cardStrength(), name: "YOU")
playerHands.append(playerhand)
//print(cModel1.cardStrength())
for i in 0..<players - 1 {
let hand: [Card] = twoCards()
let cModel = cardModel(cs: hand, r:round)
let player = Player(cpu: true, hand: hand, chips: buyin, strength: cModel.cardStrength(), name: "CPU\(i+1)")
playerHands.append(player)
}
}
func handsReset(buyin: [(String, Int)]) {
// if tutorial {
for player in buyin {
if player.0 == "YOU" {
let humanhand: [Card] = twoCards()//twoCardsTutorial()
//print(humanhand)
let cModel1 = cardModel(cs: humanhand, r: round)
let playerhand = Player(cpu: false, hand: humanhand, chips: player.1, strength: cModel1.cardStrength(), name: "YOU")
playerHands.append(playerhand)
}
else {
let hand: [Card] = twoCards()
let cModel = cardModel(cs: hand, r:round)
var player2 = Player(cpu: true, hand: hand, chips: player.1, strength: cModel.cardStrength(), name: player.0)
if player.1 <= 0 {
player2.updateFold()
}
playerHands.append(player2)
}
}
}
func twoCards() -> [Card] {
var cards: [Card] = []
let c1 = availableCards.randomElement()!
availableCards.remove(at: availableCards.firstIndex(of: c1)!)
let c2 = availableCards.randomElement()!
availableCards.remove(at: availableCards.firstIndex(of: c2)!)
cards.append(c1)
cards.append(c2)
return cards
}
func getPlayer() -> Player {
var j: Player = playerHands[0]
for i in playerHands {
if i.cpu == false {
j = i
}
}
return j;
}
func flop() {
let c1 = availableCards.randomElement()!
availableCards.remove(at: availableCards.firstIndex(of: c1)!)
let c2 = availableCards.randomElement()!
availableCards.remove(at: availableCards.firstIndex(of: c2)!)
let c3 = availableCards.randomElement()!
availableCards.remove(at: availableCards.firstIndex(of: c3)!)
sharedCards.append(c1)
sharedCards.append(c2)
sharedCards.append(c3)
round+=1
for i in 0...playerHands.count - 1 {
var h = playerHands[i].hand
h.append(contentsOf: sharedCards)
let cModel = cardModel(cs: h, r:round)
//print(round)
playerHands[i].updateStrength(st: cModel.cardStrength())
//playerHands[i].strength = cModel.cardStrength()
if playerHands[i].cpu && playerHands[i].strength < 14 && playersLeft > 1 && !playerHands[i].fold{
playerHands[i].updateFold()
// print("\(playerHands[i].name) will fold")
playersLeft -= 1
}
}
}
func turn() {
let c1 = availableCards.randomElement()!
availableCards.remove(at: availableCards.firstIndex(of: c1)!)
sharedCards.append(c1)
round+=1
for i in 0...playerHands.count - 1 {
var h = playerHands[i].hand
h.append(contentsOf: sharedCards)
let cModel = cardModel(cs: h, r:round)
//print(round)
playerHands[i].updateStrength(st: cModel.cardStrength())
//playerHands[i].strength = cModel.cardStrength()
if playerHands[i].cpu && playerHands[i].strength < 14 && playersLeft > 1 && !playerHands[i].fold {
playerHands[i].updateFold()
// print("wtfffff")
// print("\(playerHands[i].name) will fold")
playersLeft -= 1
}
}
}
func winner() -> Player {
var strength = 0
var player = playerHands[0]
for hands in playerHands {
if !hands.fold {
if hands.strength > strength || (hands.strength == strength && !hands.cpu ) {
player = hands
strength = hands.strength
}
//handle tie then need deeper check
}
}
// print("winnner is \(player.name)")
return player
}
func getChips(_ str: String) -> Int {
for i in 0...playerHands.count - 1 {
if playerHands[i].name == str {
return playerHands[i].chips
}
}
return 0
}
func foldPlayer() {
for i in 0...playerHands.count - 1 {
if !playerHands[i].cpu {
playerHands[i].updateFold()
playersLeft -= 1
break
}
}
}
func winType(_ strength: Int) -> String {
if strength < 14 {
return "High Card"
}
else if strength < 28 {
return "Pair"
}
else if strength < 42 {
return "Two Pair"
}
else if strength < 56 {
return "Three of a Kind"
}
else if strength < 70 {
return "Straight"
}
else if strength < 84 {
return "Flush"
}
else if strength < 98 {
return "Full House"
}
else if strength < 112 {
return "Four of a Kind"
}
else if strength < 126 {
return "Straight Flush"
}
else if strength < 140 {
return "Royal Flush"
}
return "High Card"
}
// func twoCardsTutorial() -> [Card] {
// var cards: [Card] = []
//
// //give them certain cards
//
// return cards
// }
func reset1() -> [Card] {
var cards: [Card] = []
for type in CardType.allCases {
for suit in CardSuit.allCases {
let card = Card(type: type, suit: suit)
cards.append(card)
}
}
return cards
}
func reset() {
var cards: [Card] = []
for type in CardType.allCases {
for suit in CardSuit.allCases {
let card = Card(type: type, suit: suit)
cards.append(card)
}
}
availableCards = cards
var passDown: [(String, Int)] = []
for hand in playerHands {
passDown.append((hand.name, hand.chips))
}
playerHands = []
sharedCards = []
playersLeft = 4
round = 0
handsReset(buyin: passDown)
}
}
func resetMain() -> [Card] {
var cards: [Card] = []
for type in CardType.allCases {
for suit in CardSuit.allCases {
let card = Card(type: type, suit: suit)
cards.append(card)
}
}
return cards
}
| true
|
2886d8242045f7711490f53a5d2108db2b8c7726
|
Swift
|
map35/BMI-Calculator
|
/CalculatorBrain.swift
|
UTF-8
| 1,326
| 3.15625
| 3
|
[] |
no_license
|
//
// CalculatorBrain.swift
// BMI Calculator
//
// Created by Mohammad Agung on 01/05/20.
// Copyright ยฉ 2020 Angela Yu. All rights reserved.
//
import UIKit
struct CalculatorBrain {
var bmi: BMI?
func getBMIValue() -> String {
let bmiValueString = String(format:"%.2f", bmi?.bmiValue ?? "0.0")
return bmiValueString
}
func getTips() -> String {
let tips = bmi?.tips ?? ""
return tips
}
func getColor() -> UIColor {
let color = bmi?.backgroundColor ?? .green
return color
}
mutating func calculateBMI(height: Float, weight: Float) {
let bmiValue = weight / pow(height, 2)
if bmiValue < 18.5 {
bmi = BMI(bmiValue: bmiValue, tips: "Koe kurang mangan, Mangan!", backgroundColor: #colorLiteral(red: 0.9568627477, green: 0.6588235497, blue: 0.5450980663, alpha: 1))
} else if bmiValue < 24.9 {
bmi = BMI(bmiValue: bmiValue, tips: "Awak mu wes apik, Jos!", backgroundColor: #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1))
} else {
bmi = BMI(bmiValue: bmiValue, tips: "Kelemon awak mu cuk!", backgroundColor: #colorLiteral(red: 0.6666666865, green: 0.6666666865, blue: 0.6666666865, alpha: 1))
}
}
}
| true
|
5ae5bee2c20cb45f420b344098bf70fc3ad50137
|
Swift
|
fwfurtado/Alumni
|
/AlumniTests/Scenes/Courses/Mock/CoursesRepositoryMock.swift
|
UTF-8
| 1,037
| 2.921875
| 3
|
[] |
no_license
|
//
// CoursesRepositoryMock.swift
// AlumniTests
//
// Created by Nando on 30/01/18.
// Copyright ยฉ 2018 Nando. All rights reserved.
//
import Foundation
@testable import Alumni
let defaultBook = Book(url: URL(string: "http://abc.com.br")!, hasDownloaded: true)
let courseWithABook = Course(code: "FJ-21", description: "Java Web", date: "20/05/2017", iconName: "fj21", book: defaultBook)
let courseWithoutABook = Course(code: "FJ-21", description: "Java Web", date: "20/05/2017", iconName: "fj21", book: nil)
class CoursesSuccessRepositoryMock: CoursesRepository {
func requestCourses(completion: @escaping CoursesRepositoryFetchResult) {
let courses: [Course] = [courseWithABook, courseWithoutABook]
completion(.success(courses))
}
}
class CoursesFailRepositoryMock: CoursesRepository {
func requestCourses(completion: @escaping CoursesRepositoryFetchResult) {
completion(.failure(CoursesRepositoryError.requestFailure))
}
}
| true
|
44d1db25e622f5c18fb2b5aba75ad16efdd6f215
|
Swift
|
nathanfrenzel/TopSecret-Practice-
|
/TopSecret/View/TabViews/SettingsView.swift
|
UTF-8
| 654
| 2.59375
| 3
|
[] |
no_license
|
//
// SettingsView.swift
// TopSecret
//
// Created by Bruce Blake on 4/5/21.
//
import SwiftUI
struct SettingsView: View {
@EnvironmentObject var viewModel : UserAuthViewModel
var body: some View {
ZStack{
//Background Color
Color.themeBackground
.ignoresSafeArea(.all)
VStack{
Button(action: {
viewModel.signOut()
}, label: {
Text("Sign Out")
})
}
}
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}
| true
|
e3ce38cf4c48f537a379933cbfb9691bad48067d
|
Swift
|
duanhjlt/QQMusicAnimation
|
/QQMusicAnimation/QQMusicAnimation/ViewController.swift
|
UTF-8
| 1,594
| 2.734375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// QQMusicAnimation
//
// Created by duanhongjin on 6/24/16.
// Copyright ยฉ 2016 duanhongjin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let control: UIControl = UIControl(frame: avatar.bounds)
control.backgroundColor = UIColor.clearColor()
control.addTarget(self, action: #selector(ViewController.onAvatarClicked), forControlEvents: .TouchUpInside)
avatar.addSubview(control)
}
func onAvatarClicked() {
let story: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let secondVC: UIViewController = story.instantiateViewControllerWithIdentifier("secondStory")
secondVC.transitioningDelegate = self
self .presentViewController(secondVC, animated: true, completion: nil)
}
}
extension ViewController: UIViewControllerTransitioningDelegate {
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransitionFromFirstToSecond()
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return TransitionFromSecondToFirst()
}
}
| true
|
75ac6a4eec4572eb0fbf43a9821f9e21585a4ee6
|
Swift
|
developerjet/JetChat
|
/JetChat/FY-IMChat/Classes/Utilites/FPSLabel/FPSLabel.swift
|
UTF-8
| 1,632
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// FPSLabel.swift
// FPSDemo
//
// Created by just so so on 2019/10/7.
// Copyright ยฉ 2019 bruce yao. All rights reserved.
//
import UIKit
class FPSLabel: UILabel {
//CADisplayLink
fileprivate var link: CADisplayLink?
fileprivate var count: UInt = 0
fileprivate var lastTime: TimeInterval = 0
override init(frame: CGRect) {
super.init(frame: frame)
///ๆ ทๅผ
layer.cornerRadius = 5
layer.masksToBounds = true
backgroundColor = UIColor.init(white: 0, alpha: 0.7)
font = UIFont.init(name: "Menlo", size: 14)
self.textAlignment = .center
///้ฒๆญขๅพช็ฏๅผ็จ
link = CADisplayLink.init(target: WeakProxy.init(self), selector: #selector(tick(_:)))
///main runloop ๆทปๅ ๅฐ
link?.add(to: RunLoop.main, forMode: .common)
}
deinit {
link?.invalidate()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
///ๆปด็ญๆปด็ญ
@objc fileprivate func tick(_ link: CADisplayLink) {
if lastTime == 0 {
lastTime = link.timestamp
return
}
count = count + 1
let delta = link.timestamp - lastTime
if delta < 1 {
return
}
lastTime = link.timestamp;
let fps = Double(count) / delta
count = 0
let progress = fps / 60.0
let color = UIColor.init(hue: CGFloat(0.27 * (progress - 0.2)), saturation: 1, brightness: 0.9, alpha: 1)
self.textColor = color
self.text = String.init(format: "%.0lf FPS", round(fps))
}
}
| true
|
62a48ea2f7f48c18c4ebd2b83357d547e2953ca8
|
Swift
|
dasSoumen/ArticleList
|
/NYTimesArticles/APIManager/NYTAPIManager.swift
|
UTF-8
| 3,552
| 2.78125
| 3
|
[] |
no_license
|
//
// NYTAPIManager.swift
// NYTimesArticles
//
// Created by Soumen Das on 21/03/18.
// Copyright ยฉ 2018 NYTimes. All rights reserved.
//
import UIKit
import Reqres
import Alamofire
import SwiftyJSON
func += <K, V> (left: inout [K: V], right: [K: V]) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
struct APIError: Error {
var errorCode: Int?
var errorDetails: String?
}
// MARK: Reachability Check
private let network = NetworkReachabilityManager()
private func isReachable() -> (Bool) {
if network?.isReachable ?? false {
if (network?.isReachableOnEthernetOrWiFi) != nil {
return true
} else if (network?.isReachableOnWWAN)! {
return true
}
} else {
return false
}
return false
}
/**
Creating network listener function which will inform us about the network connection and disconnection every time.
*/
// MARK: Start Listener
func startListening() {
network?.startListening()
network?.listener = { status in
if status == .notReachable {
//NotificationCenter.default.post(name: Notification.Name(rawValue: networkUnreachable), object: nil)
} else if status == .reachable(.ethernetOrWiFi) || status == .reachable(.wwan) {
//NotificationCenter.default.post(name: Notification.Name(rawValue: networkReachable), object: nil)
}
}
}
class NYTAPIManager: SessionManager {
/// Creating the singleton instance of the APIManager class.
static let manager: NYTAPIManager = {
let configuration = Reqres.defaultSessionConfiguration()
configuration.timeoutIntervalForRequest = 120
configuration.httpMaximumConnectionsPerHost = 1
let manager = NYTAPIManager(configuration: configuration)
return manager
}()
// MARK: API Request
func request(withRouter router: NYTBaseRouter, isUserInteractionEnabled userInteractionEnabled: Bool = true, shouldShowLoader loaderEnabled: Bool = false, shouldShowToast toastEnabled: Bool = true, withSuccess success:@escaping (_ decryptedJSONString: JSON) -> Void, andFailure failure:@escaping (_ error: Error?) -> Void) {
guard isReachable() else {
let error = APIError(errorCode: -200, errorDetails: noNetworkText)
failure(error)
return
}
loaderEnabled ? NYTHelper.helper.showLoader() : debugPrint("Loader not enabled")
!userInteractionEnabled ? NYTHelper.helper.showClearView() : debugPrint("User interaction enabled")
NYTAPIManager.manager.request(router).validate().responseJSON { (response) in
if loaderEnabled {
DispatchQueue.main.async {
NYTHelper.helper.hideLoader()
}
}
!userInteractionEnabled ? NYTHelper.helper.hideClearView() : debugPrint("User interaction was enabled")
switch response.result {
case .success(let value):
let json = JSON(value)
guard json["status"].stringValue == successResponseStatus else {
let error = APIError(errorCode: 700, errorDetails: noData)
failure(error)
return
}
success(json)
case .failure(let error):
toastEnabled ? NYTToast.show(withText: error.localizedDescription, position: .middle) : debugPrint("Toast not enabled")
failure(error)
}
}
}
}
| true
|
47db57201cc22bd56521b9c7da3077ea562f8d0d
|
Swift
|
dictav/onsha-heisha-swift
|
/howto.playground/Sources/Fibonacci.swift
|
UTF-8
| 338
| 3.1875
| 3
|
[] |
no_license
|
import Foundation
public func simpleFib(n: Int) -> Int {
return n < 2 ? n : simpleFib(n - 1) + simpleFib(n - 2)
}
// http://qiita.com/satoshia/items/d39860e54daada5c0693
public func fix(f: (Int -> Int, Int) -> Int) -> (Int -> Int) {
var fix_f: (Int -> Int)!
fix_f = {(n: Int) -> Int in return f(fix_f, n)}
return fix_f
}
| true
|
6c41bc56f7509cd72a492e9c605c811b72d730c3
|
Swift
|
tomaskraina/AirBankCodeChallenge
|
/AirBank/Networking/NetworkingError.swift
|
UTF-8
| 951
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
//
// NetworkingError.swift
// AirBank
//
// Created by Tom Kraina on 22/10/2018.
// Copyright ยฉ 2018 Tom Kraina. All rights reserved.
//
import Foundation
enum NetworkingError: LocalizedError {
case network(Error, response: HTTPURLResponse?)
case notFound(Error, response: HTTPURLResponse?)
var errorDescription: String? {
switch self {
case .network(let error, _):
return error.localizedDescription
case .notFound:
return L10n.Networking.Error.notFound
}
}
}
extension NetworkingError {
enum HTTPStatusCode: Int {
case notFound = 404
}
init(error: Error, httpUrlResponse: HTTPURLResponse?) {
if httpUrlResponse?.statusCode == HTTPStatusCode.notFound.rawValue {
self = .notFound(error, response: httpUrlResponse)
} else {
self = .network(error, response: httpUrlResponse)
}
}
}
| true
|
0409f1b5ad8756c2624d254bd5810a079356135d
|
Swift
|
jdangerslater/rkchallenge
|
/R.generated.swift
|
UTF-8
| 30,422
| 2.671875
| 3
|
[] |
no_license
|
//
// This is a generated file, do not edit!
// Generated by R.swift, see https://github.com/mac-cain13/R.swift
//
import Foundation
import Rswift
import UIKit
/// This `R` struct is generated and contains references to static resources.
struct R: Rswift.Validatable {
fileprivate static let applicationLocale = hostingBundle.preferredLocalizations.first.flatMap(Locale.init) ?? Locale.current
fileprivate static let hostingBundle = Bundle(for: R.Class.self)
/// Find first language and bundle for which the table exists
fileprivate static func localeBundle(tableName: String, preferredLanguages: [String]) -> (Foundation.Locale, Foundation.Bundle)? {
// Filter preferredLanguages to localizations, use first locale
var languages = preferredLanguages
.map(Locale.init)
.prefix(1)
.flatMap { locale -> [String] in
if hostingBundle.localizations.contains(locale.identifier) {
if let language = locale.languageCode, hostingBundle.localizations.contains(language) {
return [locale.identifier, language]
} else {
return [locale.identifier]
}
} else if let language = locale.languageCode, hostingBundle.localizations.contains(language) {
return [language]
} else {
return []
}
}
// If there's no languages, use development language as backstop
if languages.isEmpty {
if let developmentLocalization = hostingBundle.developmentLocalization {
languages = [developmentLocalization]
}
} else {
// Insert Base as second item (between locale identifier and languageCode)
languages.insert("Base", at: 1)
// Add development language as backstop
if let developmentLocalization = hostingBundle.developmentLocalization {
languages.append(developmentLocalization)
}
}
// Find first language for which table exists
// Note: key might not exist in chosen language (in that case, key will be shown)
for language in languages {
if let lproj = hostingBundle.url(forResource: language, withExtension: "lproj"),
let lbundle = Bundle(url: lproj)
{
let strings = lbundle.url(forResource: tableName, withExtension: "strings")
let stringsdict = lbundle.url(forResource: tableName, withExtension: "stringsdict")
if strings != nil || stringsdict != nil {
return (Locale(identifier: language), lbundle)
}
}
}
// If table is available in main bundle, don't look for localized resources
let strings = hostingBundle.url(forResource: tableName, withExtension: "strings", subdirectory: nil, localization: nil)
let stringsdict = hostingBundle.url(forResource: tableName, withExtension: "stringsdict", subdirectory: nil, localization: nil)
if strings != nil || stringsdict != nil {
return (applicationLocale, hostingBundle)
}
// If table is not found for requested languages, key will be shown
return nil
}
/// Load string from Info.plist file
fileprivate static func infoPlistString(path: [String], key: String) -> String? {
var dict = hostingBundle.infoDictionary
for step in path {
guard let obj = dict?[step] as? [String: Any] else { return nil }
dict = obj
}
return dict?[key] as? String
}
static func validate() throws {
try intern.validate()
}
#if os(iOS) || os(tvOS)
/// This `R.storyboard` struct is generated, and contains static references to 2 storyboards.
struct storyboard {
/// Storyboard `LaunchScreen`.
static let launchScreen = _R.storyboard.launchScreen()
/// Storyboard `Main`.
static let main = _R.storyboard.main()
#if os(iOS) || os(tvOS)
/// `UIStoryboard(name: "LaunchScreen", bundle: ...)`
static func launchScreen(_: Void = ()) -> UIKit.UIStoryboard {
return UIKit.UIStoryboard(resource: R.storyboard.launchScreen)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIStoryboard(name: "Main", bundle: ...)`
static func main(_: Void = ()) -> UIKit.UIStoryboard {
return UIKit.UIStoryboard(resource: R.storyboard.main)
}
#endif
fileprivate init() {}
}
#endif
/// This `R.color` struct is generated, and contains static references to 3 colors.
struct color {
/// Color `DividerColour`.
static let dividerColour = Rswift.ColorResource(bundle: R.hostingBundle, name: "DividerColour")
/// Color `NavBarColour`.
static let navBarColour = Rswift.ColorResource(bundle: R.hostingBundle, name: "NavBarColour")
/// Color `TextColour`.
static let textColour = Rswift.ColorResource(bundle: R.hostingBundle, name: "TextColour")
#if os(iOS) || os(tvOS)
/// `UIColor(named: "DividerColour", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func dividerColour(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.dividerColour, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIColor(named: "NavBarColour", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func navBarColour(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.navBarColour, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIColor(named: "TextColour", bundle: ..., traitCollection: ...)`
@available(tvOS 11.0, *)
@available(iOS 11.0, *)
static func textColour(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIColor? {
return UIKit.UIColor(resource: R.color.textColour, compatibleWith: traitCollection)
}
#endif
fileprivate init() {}
}
/// This `R.file` struct is generated, and contains static references to 1 files.
struct file {
/// Resource file `trophies.json`.
static let trophiesJson = Rswift.FileResource(bundle: R.hostingBundle, name: "trophies", pathExtension: "json")
/// `bundle.url(forResource: "trophies", withExtension: "json")`
static func trophiesJson(_: Void = ()) -> Foundation.URL? {
let fileResource = R.file.trophiesJson
return fileResource.bundle.url(forResource: fileResource)
}
fileprivate init() {}
}
/// This `R.image` struct is generated, and contains static references to 15 images.
struct image {
/// Image `Icon_launchscreen`.
static let icon_launchscreen = Rswift.ImageResource(bundle: R.hostingBundle, name: "Icon_launchscreen")
/// Image `back_button`.
static let back_button = Rswift.ImageResource(bundle: R.hostingBundle, name: "back_button")
/// Image `ellipsis_button`.
static let ellipsis_button = Rswift.ImageResource(bundle: R.hostingBundle, name: "ellipsis_button")
/// Image `fast_10k`.
static let fast_10k = Rswift.ImageResource(bundle: R.hostingBundle, name: "fast_10k")
/// Image `fast_5k`.
static let fast_5k = Rswift.ImageResource(bundle: R.hostingBundle, name: "fast_5k")
/// Image `hakone_ekiden`.
static let hakone_ekiden = Rswift.ImageResource(bundle: R.hostingBundle, name: "hakone_ekiden")
/// Image `half_marathon`.
static let half_marathon = Rswift.ImageResource(bundle: R.hostingBundle, name: "half_marathon")
/// Image `highest_elevation`.
static let highest_elevation = Rswift.ImageResource(bundle: R.hostingBundle, name: "highest_elevation")
/// Image `longest_run`.
static let longest_run = Rswift.ImageResource(bundle: R.hostingBundle, name: "longest_run")
/// Image `marathon`.
static let marathon = Rswift.ImageResource(bundle: R.hostingBundle, name: "marathon")
/// Image `singapore_ekiden`.
static let singapore_ekiden = Rswift.ImageResource(bundle: R.hostingBundle, name: "singapore_ekiden")
/// Image `tokyo_hakone`.
static let tokyo_hakone = Rswift.ImageResource(bundle: R.hostingBundle, name: "tokyo_hakone")
/// Image `virtual_10k`.
static let virtual_10k = Rswift.ImageResource(bundle: R.hostingBundle, name: "virtual_10k")
/// Image `virtual_5k`.
static let virtual_5k = Rswift.ImageResource(bundle: R.hostingBundle, name: "virtual_5k")
/// Image `virtual_half_marathon`.
static let virtual_half_marathon = Rswift.ImageResource(bundle: R.hostingBundle, name: "virtual_half_marathon")
#if os(iOS) || os(tvOS)
/// `UIImage(named: "Icon_launchscreen", bundle: ..., traitCollection: ...)`
static func icon_launchscreen(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.icon_launchscreen, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "back_button", bundle: ..., traitCollection: ...)`
static func back_button(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.back_button, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "ellipsis_button", bundle: ..., traitCollection: ...)`
static func ellipsis_button(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.ellipsis_button, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "fast_10k", bundle: ..., traitCollection: ...)`
static func fast_10k(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.fast_10k, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "fast_5k", bundle: ..., traitCollection: ...)`
static func fast_5k(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.fast_5k, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "hakone_ekiden", bundle: ..., traitCollection: ...)`
static func hakone_ekiden(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.hakone_ekiden, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "half_marathon", bundle: ..., traitCollection: ...)`
static func half_marathon(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.half_marathon, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "highest_elevation", bundle: ..., traitCollection: ...)`
static func highest_elevation(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.highest_elevation, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "longest_run", bundle: ..., traitCollection: ...)`
static func longest_run(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.longest_run, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "marathon", bundle: ..., traitCollection: ...)`
static func marathon(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.marathon, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "singapore_ekiden", bundle: ..., traitCollection: ...)`
static func singapore_ekiden(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.singapore_ekiden, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "tokyo_hakone", bundle: ..., traitCollection: ...)`
static func tokyo_hakone(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.tokyo_hakone, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "virtual_10k", bundle: ..., traitCollection: ...)`
static func virtual_10k(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.virtual_10k, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "virtual_5k", bundle: ..., traitCollection: ...)`
static func virtual_5k(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.virtual_5k, compatibleWith: traitCollection)
}
#endif
#if os(iOS) || os(tvOS)
/// `UIImage(named: "virtual_half_marathon", bundle: ..., traitCollection: ...)`
static func virtual_half_marathon(compatibleWith traitCollection: UIKit.UITraitCollection? = nil) -> UIKit.UIImage? {
return UIKit.UIImage(resource: R.image.virtual_half_marathon, compatibleWith: traitCollection)
}
#endif
fileprivate init() {}
}
/// This `R.nib` struct is generated, and contains static references to 2 nibs.
struct nib {
/// Nib `TrophyCaseHeaderView`.
static let trophyCaseHeaderView = _R.nib._TrophyCaseHeaderView()
/// Nib `TrophyCell`.
static let trophyCell = _R.nib._TrophyCell()
#if os(iOS) || os(tvOS)
/// `UINib(name: "TrophyCaseHeaderView", in: bundle)`
@available(*, deprecated, message: "Use UINib(resource: R.nib.trophyCaseHeaderView) instead")
static func trophyCaseHeaderView(_: Void = ()) -> UIKit.UINib {
return UIKit.UINib(resource: R.nib.trophyCaseHeaderView)
}
#endif
#if os(iOS) || os(tvOS)
/// `UINib(name: "TrophyCell", in: bundle)`
@available(*, deprecated, message: "Use UINib(resource: R.nib.trophyCell) instead")
static func trophyCell(_: Void = ()) -> UIKit.UINib {
return UIKit.UINib(resource: R.nib.trophyCell)
}
#endif
static func trophyCaseHeaderView(owner ownerOrNil: AnyObject?, options optionsOrNil: [UINib.OptionsKey : Any]? = nil) -> TrophyCaseHeaderView? {
return R.nib.trophyCaseHeaderView.instantiate(withOwner: ownerOrNil, options: optionsOrNil)[0] as? TrophyCaseHeaderView
}
static func trophyCell(owner ownerOrNil: AnyObject?, options optionsOrNil: [UINib.OptionsKey : Any]? = nil) -> TrophyCell? {
return R.nib.trophyCell.instantiate(withOwner: ownerOrNil, options: optionsOrNil)[0] as? TrophyCell
}
fileprivate init() {}
}
/// This `R.string` struct is generated, and contains static references to 1 localization tables.
struct string {
/// This `R.string.localizable` struct is generated, and contains static references to 16 localization keys.
struct localizable {
/// Value: Couldn't load the trophy data.
static let couldnt_load = Rswift.StringResource(key: "couldnt_load", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Fastest 10K
static let fast_10k = Rswift.StringResource(key: "fast_10k", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Fastest 5K
static let fast_5k = Rswift.StringResource(key: "fast_5k", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Hakone Ekiden
static let hakone_ekiden = Rswift.StringResource(key: "hakone_ekiden", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Half Marathon
static let half_marathon = Rswift.StringResource(key: "half_marathon", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Highest Elevation
static let highest_elevation = Rswift.StringResource(key: "highest_elevation", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Longest Run
static let longest_run = Rswift.StringResource(key: "longest_run", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Marathon
static let marathon = Rswift.StringResource(key: "marathon", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Mizuno Singapore Ekiden 2020
static let singapore_ekiden = Rswift.StringResource(key: "singapore_ekiden", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: OK
static let ok = Rswift.StringResource(key: "ok", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Personal Records
static let personal_records = Rswift.StringResource(key: "personal_records", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Tokyo-Hakone Ekiden 2020
static let tokyo_hakone = Rswift.StringResource(key: "tokyo_hakone", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Virtual 10K Race
static let virtual_10k = Rswift.StringResource(key: "virtual_10k", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Virtual 5K Race
static let virtual_5k = Rswift.StringResource(key: "virtual_5k", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Virtual Half Marathon Race
static let virtual_half_marathon = Rswift.StringResource(key: "virtual_half_marathon", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Virtual Races
static let virtual_races = Rswift.StringResource(key: "virtual_races", tableName: "Localizable", bundle: R.hostingBundle, locales: [], comment: nil)
/// Value: Couldn't load the trophy data.
static func couldnt_load(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("couldnt_load", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "couldnt_load"
}
return NSLocalizedString("couldnt_load", bundle: bundle, comment: "")
}
/// Value: Fastest 10K
static func fast_10k(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("fast_10k", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "fast_10k"
}
return NSLocalizedString("fast_10k", bundle: bundle, comment: "")
}
/// Value: Fastest 5K
static func fast_5k(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("fast_5k", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "fast_5k"
}
return NSLocalizedString("fast_5k", bundle: bundle, comment: "")
}
/// Value: Hakone Ekiden
static func hakone_ekiden(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("hakone_ekiden", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "hakone_ekiden"
}
return NSLocalizedString("hakone_ekiden", bundle: bundle, comment: "")
}
/// Value: Half Marathon
static func half_marathon(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("half_marathon", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "half_marathon"
}
return NSLocalizedString("half_marathon", bundle: bundle, comment: "")
}
/// Value: Highest Elevation
static func highest_elevation(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("highest_elevation", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "highest_elevation"
}
return NSLocalizedString("highest_elevation", bundle: bundle, comment: "")
}
/// Value: Longest Run
static func longest_run(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("longest_run", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "longest_run"
}
return NSLocalizedString("longest_run", bundle: bundle, comment: "")
}
/// Value: Marathon
static func marathon(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("marathon", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "marathon"
}
return NSLocalizedString("marathon", bundle: bundle, comment: "")
}
/// Value: Mizuno Singapore Ekiden 2020
static func singapore_ekiden(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("singapore_ekiden", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "singapore_ekiden"
}
return NSLocalizedString("singapore_ekiden", bundle: bundle, comment: "")
}
/// Value: OK
static func ok(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("ok", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "ok"
}
return NSLocalizedString("ok", bundle: bundle, comment: "")
}
/// Value: Personal Records
static func personal_records(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("personal_records", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "personal_records"
}
return NSLocalizedString("personal_records", bundle: bundle, comment: "")
}
/// Value: Tokyo-Hakone Ekiden 2020
static func tokyo_hakone(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("tokyo_hakone", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "tokyo_hakone"
}
return NSLocalizedString("tokyo_hakone", bundle: bundle, comment: "")
}
/// Value: Virtual 10K Race
static func virtual_10k(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("virtual_10k", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "virtual_10k"
}
return NSLocalizedString("virtual_10k", bundle: bundle, comment: "")
}
/// Value: Virtual 5K Race
static func virtual_5k(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("virtual_5k", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "virtual_5k"
}
return NSLocalizedString("virtual_5k", bundle: bundle, comment: "")
}
/// Value: Virtual Half Marathon Race
static func virtual_half_marathon(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("virtual_half_marathon", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "virtual_half_marathon"
}
return NSLocalizedString("virtual_half_marathon", bundle: bundle, comment: "")
}
/// Value: Virtual Races
static func virtual_races(preferredLanguages: [String]? = nil) -> String {
guard let preferredLanguages = preferredLanguages else {
return NSLocalizedString("virtual_races", bundle: hostingBundle, comment: "")
}
guard let (_, bundle) = localeBundle(tableName: "Localizable", preferredLanguages: preferredLanguages) else {
return "virtual_races"
}
return NSLocalizedString("virtual_races", bundle: bundle, comment: "")
}
fileprivate init() {}
}
fileprivate init() {}
}
fileprivate struct intern: Rswift.Validatable {
fileprivate static func validate() throws {
try _R.validate()
}
fileprivate init() {}
}
fileprivate class Class {}
fileprivate init() {}
}
struct _R: Rswift.Validatable {
static func validate() throws {
#if os(iOS) || os(tvOS)
try nib.validate()
#endif
#if os(iOS) || os(tvOS)
try storyboard.validate()
#endif
}
#if os(iOS) || os(tvOS)
struct nib: Rswift.Validatable {
static func validate() throws {
try _TrophyCell.validate()
}
struct _TrophyCaseHeaderView: Rswift.NibResourceType {
let bundle = R.hostingBundle
let name = "TrophyCaseHeaderView"
func firstView(owner ownerOrNil: AnyObject?, options optionsOrNil: [UINib.OptionsKey : Any]? = nil) -> TrophyCaseHeaderView? {
return instantiate(withOwner: ownerOrNil, options: optionsOrNil)[0] as? TrophyCaseHeaderView
}
fileprivate init() {}
}
struct _TrophyCell: Rswift.NibResourceType, Rswift.Validatable {
let bundle = R.hostingBundle
let name = "TrophyCell"
func firstView(owner ownerOrNil: AnyObject?, options optionsOrNil: [UINib.OptionsKey : Any]? = nil) -> TrophyCell? {
return instantiate(withOwner: ownerOrNil, options: optionsOrNil)[0] as? TrophyCell
}
static func validate() throws {
if UIKit.UIImage(named: "fast_10k", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'fast_10k' is used in nib 'TrophyCell', but couldn't be loaded.") }
if #available(iOS 11.0, tvOS 11.0, *) {
if UIKit.UIColor(named: "TextColour", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Color named 'TextColour' is used in storyboard 'TrophyCell', but couldn't be loaded.") }
}
}
fileprivate init() {}
}
fileprivate init() {}
}
#endif
#if os(iOS) || os(tvOS)
struct storyboard: Rswift.Validatable {
static func validate() throws {
#if os(iOS) || os(tvOS)
try launchScreen.validate()
#endif
#if os(iOS) || os(tvOS)
try main.validate()
#endif
}
#if os(iOS) || os(tvOS)
struct launchScreen: Rswift.StoryboardResourceWithInitialControllerType, Rswift.Validatable {
typealias InitialController = UIKit.UIViewController
let bundle = R.hostingBundle
let name = "LaunchScreen"
static func validate() throws {
if UIKit.UIImage(named: "Icon_launchscreen", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Image named 'Icon_launchscreen' is used in storyboard 'LaunchScreen', but couldn't be loaded.") }
if #available(iOS 11.0, tvOS 11.0, *) {
if UIKit.UIColor(named: "NavBarColour", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Color named 'NavBarColour' is used in storyboard 'LaunchScreen', but couldn't be loaded.") }
}
}
fileprivate init() {}
}
#endif
#if os(iOS) || os(tvOS)
struct main: Rswift.StoryboardResourceWithInitialControllerType, Rswift.Validatable {
typealias InitialController = NavigationController
let bundle = R.hostingBundle
let name = "Main"
static func validate() throws {
if #available(iOS 11.0, tvOS 11.0, *) {
if UIKit.UIColor(named: "NavBarColour", in: R.hostingBundle, compatibleWith: nil) == nil { throw Rswift.ValidationError(description: "[R.swift] Color named 'NavBarColour' is used in storyboard 'Main', but couldn't be loaded.") }
}
}
fileprivate init() {}
}
#endif
fileprivate init() {}
}
#endif
fileprivate init() {}
}
| true
|
58f9d79d6a1dedeb6ca561b6c22f290caf008396
|
Swift
|
Alex-Zhou99/Connection-App
|
/Connection/LoginView.swift
|
UTF-8
| 1,585
| 2.65625
| 3
|
[] |
no_license
|
//
// LoginView.swift
// exmaple
//
// Created by Edward on 7/13/16.
// Copyright ยฉ 2016 Edward. All rights reserved.
//
import UIKit
import Firebase
class LoginView: UIViewController {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
func dismissKeyboard(tap: UITapGestureRecognizer){
view.endEditing(true)
}
@IBAction func logInDidTapped(sender: AnyObject)
{
let email = emailField.text!
let password = passwordField.text!
if email != "" && password != ""
{
FIRAuth.auth()?.signInWithEmail(email, password: password, completion: {(user, error) in
if error != nil {
self.showErrorAlert("Alert", msg: "Check your username and password.")
}else{
NSUserDefaults.standardUserDefaults().setValue(user!.uid, forKey: "uid")
self.performSegueWithIdentifier("loggedIn", sender: nil)
}
}
)
}else {
showErrorAlert("Alert", msg: "Don't forget to enter your email and password.")
}
}
func showErrorAlert(title: String, msg: String) {
let alert = UIAlertController(title: title, message: msg, preferredStyle: .Alert)
let action = UIAlertAction(title: "Ok", style: .Default, handler: nil)
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
}
}
| true
|
279ab47120b053e0738fa7c717a1cffa144c6fea
|
Swift
|
arinakt/sunnyDay
|
/sunnyDay/Models/CurrentWeather.swift
|
UTF-8
| 1,809
| 3.203125
| 3
|
[] |
no_license
|
//
// CurrentWeather.swift
// sunnyDay
//
// Created by ะัะธะฝะฐ on 28.05.2020.
// Copyright ยฉ 2020 ะัะธะฝะฐ. All rights reserved.
//
import Foundation
struct CurrentWeather {
let cityName: String
let temperature: Double
var temperatureString: String {
return String(format: "%.0f", temperature)
}
let pressure: Int
var pressureString: String {
return "\(pressure)"
}
let humidity: Int
var humidityString: String {
return "\(humidity)"
}
let tempMin: Double
var tempMinString: String {
return String(format: "%.0f", tempMin)
}
let tempMax: Double
var tempMaxString: String {
return String(format: "%.0f", tempMax)
}
let speed: Double
var speedString: String {
return String(format: "%.0f", speed)
}
let main: String
/*let conditionCode: Int
var systemIconString: String {
switch conditionCode {
case 200...232: return "cloud.rain.fill"
case 300...321: return "cloud.drizzle"
case 500...531: return "cloud.rain"
case 600...622: return "cloud.snow"
case 701...781: return "smoke"
case 800: return "sun"
case 801...804: return "cloud"
default:
return "nosign"
}
}*/
init?(currentWeatherData: CurrentWeatherData) {
cityName = currentWeatherData.name
temperature = currentWeatherData.main.temp
pressure = currentWeatherData.main.pressure
humidity = currentWeatherData.main.humidity
tempMin = currentWeatherData.main.tempMin
tempMax = currentWeatherData.main.tempMax
speed = currentWeatherData.wind.speed
main = currentWeatherData.weather.first!.main
}
}
| true
|
bb677ba7689e5201a745db029a77dde94edef022
|
Swift
|
iikuznetsov/ConPro
|
/ConPro/Models/User.swift
|
UTF-8
| 303
| 2.765625
| 3
|
[] |
no_license
|
import UIKit
class User: NSObject {
var id: Int?
var name: String?
var image: UIImage?
var eventsVisited = [Event]()
var eventsOrganized = [Event]()
init(id: Int, name: String, image: UIImage) {
self.id = id
self.name = name
self.image = image
}
}
| true
|
dc1fced3a4d749f5ad02cad0bd80c76bbaced9e9
|
Swift
|
bheuju/Cooking-App-iOS
|
/Recipe/ViewControllers/RecipeDetails/RecipeDetailsViewController.swift
|
UTF-8
| 2,193
| 2.65625
| 3
|
[] |
no_license
|
//
// RecipeDetailsViewController.swift
// Recipe
//
// Created by Bishal Heuju on 3/6/17.
// Copyright ยฉ 2017 Bishal Heuju. All rights reserved.
//
import UIKit
class RecipeDetailsViewController: UIViewController {
@IBOutlet weak var recipeTitle: UILabel!
@IBOutlet weak var recipeImage: UIImageView!
@IBOutlet weak var recipeFavourited: UIButton!
@IBOutlet weak var recipeReview: UILabel!
var recipe: Recipe?
override func viewDidLoad() {
super.viewDidLoad()
if UserData.shared.getUser() != nil {
//TODO: Add edit bar button
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(RecipeDetailsViewController.onEditRecipe))
}
guard let _ = recipe else {
let _ = self.navigationController?.popViewController(animated: true)
return
}
setRecipe(myRecipe: recipe!)
}
func onEditRecipe() {
//Alerter.shared.createDefaultAlert(controller: self, alertTitle: "Edit", alertMessage: "Do you want to edit te recipe?")
if let editRecipeVC = self.storyboard?.instantiateViewController(withIdentifier: "EditRecipeViewController") as? EditRecipeViewController {
self.navigationController?.pushViewController(editRecipeVC, animated: true)
editRecipeVC.recipe = recipe
}
}
func setRecipe(myRecipe:Recipe) {
//print(myRecipe.recipeTitle!)
recipeTitle.text = myRecipe.recipeTitle!
recipeImage.image = UIImage(named: myRecipe.recipeImage!)
if myRecipe.recipeFavourited! {
recipeFavourited.setImage(UIImage(named: "heart-selected"), for: .normal)
} else {
recipeFavourited.setImage(UIImage(named: "heart-unselected"), for: .normal)
}
recipeReview.text = myRecipe.recipeReview!
}
@IBAction func favouriteButtonClicked(_ sender: UIButton) {
//toggle favourite button
print("favourite clicked")
}
}
| true
|
49a20bb5c66d6ea8c593c0547fa13128c4117c2f
|
Swift
|
Erozone/myApp
|
/myResturentApp/OrdersViewController.swift
|
UTF-8
| 4,230
| 2.609375
| 3
|
[] |
no_license
|
//
// OrdersViewController.swift
// myResturentApp
//
// Created by Mohit Kumar on 19/05/17.
// Copyright ยฉ 2017 Mohit Kumar. All rights reserved.
//
import UIKit
import FirebaseAuth
import FirebaseDatabase
import Firebase
class OrdersViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
//MARK: - OUTLETS
@IBOutlet weak var collectionView: UICollectionView!
//MARK: - Properties
var customerOrders = [String:[CustomerDetails]]()
var customers = [Customers]()
{
didSet{
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
if let restaurentId = UserDefaults.standard.value(forKey: restaurentIDKey) as? String{
loadOrdersFromDatabase(restaurentId: restaurentId)
}
collectionView.dataSource = self
collectionView.delegate = self
print(customerOrders)
}
func loadOrdersFromDatabase(restaurentId:String){
let databaseRef = FIRDatabase.database().reference()
let ordersRef = databaseRef.child("Orders").child(restaurentId)
ordersRef.observe(.childAdded, with: { (snapshot) in
let userRef = databaseRef.child("Customers").child(snapshot.key)
userRef.observeSingleEvent(of: .value, with: { (snap) in // This will retrieve users from Database
if let userDictionary = snap.value as? [String:String]{
let customer = Customers()
customer.setValuesForKeys(userDictionary)
self.customers.append(customer)
}
}, withCancel: nil)
}, withCancel: nil)
}
//MARK:- Collection View DataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return customers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "orderCell", for: indexPath) as! mainOrdersCollectionViewCell
let customer = customers[indexPath.row]
if let name = customer.CustomerName{
cell.gotAnOrderMsg.text = "You Got An Order From \(String(describing: name))"
}else{
cell.gotAnOrderMsg.text = "You Got An Order"
}
return cell
}
//MARK:- Actions
@IBAction func logoutBtn(_sender:UIButton){
do{
try FIRAuth.auth()?.signOut()
print("Logout the User")
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SelectionVC")
self.present(vc, animated: true, completion: nil)
}catch let err as NSError{
print(err.localizedDescription)
}
}
//MARK:- My Functions
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toDetailOrder",let destination = segue.destination as? OrderDetailViewController{
if let cell = sender as? mainOrdersCollectionViewCell{
if let indexPath = self.collectionView?.indexPath(for: cell){
let selectedRow = customers[indexPath.row]
destination.customer = selectedRow
}
}
}
}
//MARK:- Actions
@IBAction func cancelBtnPressed(segue: UIStoryboardSegue){
}
@IBAction func doneBtnPressed(segue: UIStoryboardSegue){
if let orderDetailVC = segue.source as? OrderDetailViewController{
print("Sucessfully Get back")
}
}
}
class mainOrdersCollectionViewCell: UICollectionViewCell{
@IBOutlet weak var gotAnOrderMsg: UILabel!
}
| true
|
31e2285490ff3f35a8831150dd432a27fc2f99da
|
Swift
|
omaralbeik/HomebrUI
|
/HomebrUI/Homebrew/HomebrewCommand.swift
|
UTF-8
| 1,180
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
enum HomebrewCommand {
case list
case info([HomebrewID])
case search(String)
case update
case upgrade(HomebrewUpgradeStrategy)
case install([HomebrewID])
case uninstall([HomebrewID])
}
enum HomebrewUpgradeStrategy {
case only([HomebrewID])
case all
}
extension HomebrewCommand {
var isBlocking: Bool {
switch self {
case .list, .info, .search: return false
case .update, .upgrade, .install, .uninstall: return true
}
}
var arguments: [String] {
switch self {
case .list:
return ["info", "--json=v2", "--installed"]
case .info(let formulae):
return ["info", "--json=v2"] + formulae
case .search(let query):
return ["search", query]
case .update:
return ["update"]
case .upgrade(.all):
return ["upgrade"]
case .upgrade(.only(let formulae)):
return ["upgrade"] + formulae
case .install(let formulae):
return ["install"] + formulae
case .uninstall(let formulae):
return ["uninstall"] + formulae
}
}
}
private func +(_ arguments: [String], ids: [HomebrewID]) -> [String] {
ids.reduce(into: arguments) { $0.append($1.rawValue) }
}
| true
|
bcb788b029543ec52c60b4a2600fb946851b6611
|
Swift
|
sara1142/iOS.Nanodegree.Projects
|
/TheMap/TheMap/Model/Account.swift
|
UTF-8
| 626
| 2.671875
| 3
|
[] |
no_license
|
//
// Account.swift
// TheMap
//
// Created by Sarah Alasadi on 28/09/1440 AH.
// Copyright ยฉ 1440 Sarah Alasadi. All rights reserved.
//
import Foundation
struct Account {
let registered: Bool
let key: String
init?(data: [String: AnyObject]) {
guard let registered = data[UdacityAPIClient.JSONResponseKeys.AccountRegistered] as? Bool else {
return nil
}
guard let key = data[UdacityAPIClient.JSONResponseKeys.AccountKey] as? String else {
return nil
}
self.registered = registered
self.key = key
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.