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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a3b7fe4f0c2efa88a22a316f4dc22a05dd719420
|
Swift
|
melbrng/ConcurrencyDemo
|
/ConcurrencyDemo/ConcurrencyDemo/ViewController.swift
|
UTF-8
| 8,957
| 3.015625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ConcurrencyDemo
//
// Created by Hossam Ghareeb on 11/15/15.
// Copyright © 2015 Hossam Ghareeb. All rights reserved.
//
import UIKit
public enum NSOperationQueuePriority : Int {
case VeryLow
case Low
case Normal
case High
case VeryHigh
}
let imageURLs = ["http://www.planetware.com/photos-large/F/france-paris-eiffel-tower.jpg", "http://adriatic-lines.com/wp-content/uploads/2015/04/canal-of-Venice.jpg", "http://algoos.com/wp-content/uploads/2015/08/ireland-02.jpg", "http://bdo.se/wp-content/uploads/2014/01/Stockholm1.jpg"]
class Downloader {
class func downloadImageWithURL(url:String) -> UIImage! {
let data = NSData(contentsOfURL: NSURL(string: url)!)
return UIImage(data: data!)
}
}
class ViewController: UIViewController {
@IBOutlet weak var imageView1: UIImageView!
@IBOutlet weak var imageView2: UIImageView!
@IBOutlet weak var imageView3: UIImageView!
@IBOutlet weak var imageView4: UIImageView!
@IBOutlet weak var sliderValueLabel: UILabel!
var queue = NSOperationQueue()
var operation1 = NSBlockOperation()
var operation2 = NSBlockOperation()
var operation3 = NSBlockOperation()
var operation4 = NSBlockOperation()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didClickOnStart(sender: AnyObject) {
//dependencies for calling nsBlockOperation
operation2.addDependency(operation1)
operation3.addDependency(operation2)
}
@IBAction func didClickOnCancel(sender: AnyObject) {
self.queue.cancelAllOperations()
}
@IBAction func sliderValueChanged(sender: UISlider) {
self.sliderValueLabel.text = "\(sender.value * 100.0)"
}
//MARK: Dispatch Queues
//Downloads are submitted as concurrent tasks to the default queue
func concurrentOnDefaultQueue() {
//submit image downloads as concurrent tasks to the default queue
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
//download on background
dispatch_async(queue){ () -> Void in
let img1 = Downloader.downloadImageWithURL(imageURLs[0])
//execute UI related tasks on main queue
dispatch_async(dispatch_get_main_queue(), {
self.imageView1.image = img1
})
}
dispatch_async(queue) { () -> Void in
let img2 = Downloader.downloadImageWithURL(imageURLs[1])
dispatch_async(dispatch_get_main_queue(), {
self.imageView2.image = img2
})
}
dispatch_async(queue) { () -> Void in
let img3 = Downloader.downloadImageWithURL(imageURLs[2])
dispatch_async(dispatch_get_main_queue(), {
self.imageView3.image = img3
})
}
dispatch_async(queue) { () -> Void in
let img4 = Downloader.downloadImageWithURL(imageURLs[3])
dispatch_async(dispatch_get_main_queue(), {
self.imageView4.image = img4
})
}
}
//Default serial queue is the main queue for the UI , so you have to create a new serialQueue
//Serial so images load one after the other (waits for previous task to finish before execution)
func serialQueue(){
let serialQueue = dispatch_queue_create("com.appcoda.imagesQueue", DISPATCH_QUEUE_SERIAL)
dispatch_async(serialQueue) { () -> Void in
let img1 = Downloader .downloadImageWithURL(imageURLs[0])
//same as before, pop back onto the main queue for UI related stuff
dispatch_async(dispatch_get_main_queue(), {
self.imageView1.image = img1
})
}
dispatch_async(serialQueue) { () -> Void in
let img2 = Downloader.downloadImageWithURL(imageURLs[1])
dispatch_async(dispatch_get_main_queue(), {
self.imageView2.image = img2
})
}
dispatch_async(serialQueue) { () -> Void in
let img3 = Downloader.downloadImageWithURL(imageURLs[2])
dispatch_async(dispatch_get_main_queue(), {
self.imageView3.image = img3
})
}
dispatch_async(serialQueue) { () -> Void in
let img4 = Downloader.downloadImageWithURL(imageURLs[3])
dispatch_async(dispatch_get_main_queue(), {
self.imageView4.image = img4
})
}
}
//MARK: Operation Queues
//High level abstraction of the queue model build on top of GCD
//Can execute tasks concurrently but in an object oriented fashion
//Op queues don't conform to FIFO (like dispatch queues) you can set a priority for operations and add dependencies
//Operate concurrently by default (cannot change to serial) but can use dependencies between for a workaround
//Tasks are encapsulated in instances of NSOperation (not blocks) - a single unit of work
//allows downloading of images in the background
func nsAddOperationBlockQueue(){
queue = NSOperationQueue()
queue.addOperationWithBlock { () -> Void in
let img1 = Downloader.downloadImageWithURL(imageURLs[0])
//pop back on main thread
NSOperationQueue.mainQueue().addOperationWithBlock({
self.imageView1.image = img1
})
}
queue.addOperationWithBlock { () -> Void in
let img2 = Downloader.downloadImageWithURL(imageURLs[1])
NSOperationQueue.mainQueue().addOperationWithBlock({
self.imageView2.image = img2
})
}
queue.addOperationWithBlock { () -> Void in
let img3 = Downloader.downloadImageWithURL(imageURLs[2])
NSOperationQueue.mainQueue().addOperationWithBlock({
self.imageView3.image = img3
})
}
queue.addOperationWithBlock { () -> Void in
let img4 = Downloader.downloadImageWithURL(imageURLs[3])
NSOperationQueue.mainQueue().addOperationWithBlock({
self.imageView4.image = img4
})
}
}
//Encapsulate the operation in a block and when done, completion handler is called
//BlockOperation allows management of operations and more functionality
func nsBlockOperation(){
queue = NSOperationQueue()
operation1 = NSBlockOperation(block: {
let img1 = Downloader.downloadImageWithURL(imageURLs[0])
NSOperationQueue.mainQueue().addOperationWithBlock({
self.imageView1.image = img1
})
})
operation1.completionBlock = {
print("Operation 1 completed, cancelled:\(self.operation1.cancelled) ")
}
queue.addOperation(operation1)
operation2 = NSBlockOperation(block: {
let img2 = Downloader.downloadImageWithURL(imageURLs[1])
NSOperationQueue.mainQueue().addOperationWithBlock({
self.imageView2.image = img2
})
})
operation2.completionBlock = {
print("Operation 2 completed")
}
queue.addOperation(operation2)
operation3 = NSBlockOperation(block: {
let img3 = Downloader.downloadImageWithURL(imageURLs[2])
NSOperationQueue.mainQueue().addOperationWithBlock({
self.imageView3.image = img3
})
})
operation3.completionBlock = {
print("Operation 3 completed")
}
queue.addOperation(operation3)
operation4 = NSBlockOperation(block: {
let img4 = Downloader.downloadImageWithURL(imageURLs[3])
NSOperationQueue.mainQueue().addOperationWithBlock({
self.imageView4.image = img4
})
})
operation4.completionBlock = {
print("Operation 4 completed")
}
queue.addOperation(operation4)
}
}
| true
|
ebe3735adddb46f90487a30d60675a4f8bf42e32
|
Swift
|
ranggasenatama/iOS-Mobile-Task
|
/Tugas 2/Upload Image/Upload Image/Controller/ViewController.swift
|
UTF-8
| 7,627
| 2.671875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Upload Image
//
// Created by Rangga Senatama Putra on 07/09/18.
// Copyright © 2018 Rangga Senatama Putra. All rights reserved.
//
import UIKit
import Alamofire
import Photos
import RappleProgressHUD
class ViewController: UIViewController {
@IBOutlet weak var imageViewPhoto: UIImageView!
@IBOutlet weak var timer: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
checkPermission()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func cameraIconPressed(_ sender: UIBarButtonItem) {
CameraHandler.shared.camera(vc: self)
CameraHandler.shared.imagePickedBlock = { (image) in
self.imageViewPhoto.image = image
}
}
@IBAction func uploadImageButtonPressed(_ sender: UIButton) {
guard var image = imageViewPhoto.image else { fatalError("photo is nill") }
image = image.resize(withWidth: 200)!
uploadImage(image: image)
}
func uploadImage(image: UIImage) {
let apiLink = "http://mobile.if.its.ac.id/kirimgambar"
let nrp = "5115100076"
let base64String = "data:image/png;base64,"+convertImageToBase64(image: image)
let parameters = [
"nrp": nrp,
"image": base64String
]
let start = Date()
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
}, to: apiLink)
{ (result) in
switch result {
case .success(let upload, _, _):
let attributes = RappleActivityIndicatorView.attribute(style: RappleStyle.circle)
RappleActivityIndicatorView.startAnimatingWithLabel("Uploading..." ,attributes: attributes)
upload.uploadProgress(closure: { (progress) in
self.progressHUD(current: progress.fractionCompleted)
})
upload.responseJSON { response in
RappleActivityIndicatorView.stopAnimation(completionIndicator: .success, completionLabel: "Completed.", completionTimeout: 1.0)
let end = Date()
self.timer.text = "Time needed :\(start.elapsedTime(to: end))"
}
case .failure(let encodingError):
print(encodingError)
}
}
}
func progressHUD(current: Double) {
RappleActivityIndicatorView.setProgress(CGFloat(current), textValue: "\(Int(current*100))%")
}
func checkPermission() {
let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
switch photoAuthorizationStatus {
case .authorized:
print("Access is granted by user")
case .notDetermined:
PHPhotoLibrary.requestAuthorization({
(newStatus) in
print("status is \(newStatus)")
if newStatus == PHAuthorizationStatus.authorized {
print("success")
}
})
print("It is not determined until now")
case .restricted:
print("User do not have access to photo album.")
case .denied:
print("User has denied the permission.")
}
}
//
// Convert String to base64
//
func convertImageToBase64(image: UIImage) -> String {
let imageData = UIImagePNGRepresentation(image)!
return imageData.base64EncodedString(options: Data.Base64EncodingOptions.lineLength64Characters)
}
//
// Convert base64 to String
//
func convertBase64ToImage(imageString: String) -> UIImage {
let imageData = Data(base64Encoded: imageString, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
return UIImage(data: imageData)!
}
}
extension UIImage {
func resize(withWidth newWidth: CGFloat) -> UIImage? {
let scale = newWidth / self.size.width
let newHeight = self.size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
@IBDesignable extension UIButton {
@IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
@IBInspectable var borderColor: UIColor? {
set {
guard let uiColor = newValue else { return }
layer.borderColor = uiColor.cgColor
}
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
}
}
extension Date {
func elapsedTime(to date: Date) -> String {
let attoseconds100 = date.timeIntervalSince(self) * 10000000000000
switch attoseconds100 {
case 6048000000000000000...:
let weeks : Int = Int(attoseconds100 / 6048000000000000000)
return "\(weeks)w" + " " + "\(Int(attoseconds100 / 864000000000000000) - (weeks * 7))d"
case 864000000000000000...:
let days : Int = Int(attoseconds100 / 864000000000000000)
return "\(days)d" + " " + "\(Int(attoseconds100 / 36000000000000000) - (days * 24))h"
case 36000000000000000...:
let hours : Int = Int(attoseconds100 / 36000000000000000)
return "\(hours)h" + " " + "\(Int(attoseconds100 / 600000000000000) - (hours * 60))m"
case 600000000000000...:
let mins : Int = Int(attoseconds100 / 600000000000000)
return "\(mins)m" + " " + "\(Int(attoseconds100 / 10000000000000) - (mins * 60))s"
case 10000000000000...:
let secs : Int = Int(attoseconds100 / 10000000000000)
return "\(secs)s" + " " + "\(Int(attoseconds100 / 10000000000) - (secs * 1000))ms"
case 10000000000...:
let millisecs : Int = Int(attoseconds100 / 10000000000)
return "\(millisecs)ms" + " " + "\(Int(attoseconds100 / 10000000) - (millisecs * 1000))μs"
case 10000000...:
let microsecs : Int = Int(attoseconds100 / 10000000)
return "\(microsecs)μs" + " " + "\(Int(attoseconds100 / 10000) - (microsecs * 1000))ns"
case 10000...:
let nanosecs : Int = Int(attoseconds100 / 10000)
return "\(nanosecs)ns" + " " + "\(Int(attoseconds100 / 10) - (nanosecs * 1000))ps"
case 10...:
let picosecs : Int = Int(attoseconds100 / 10)
return "\(picosecs)ps" + " " + "\(Int(attoseconds100 / 0.01) - (picosecs * 1000))fs"
case 0.01...:
let femtosecs : Int = Int(attoseconds100 * 100)
return "\(femtosecs)fs" + " " + "\((Int(attoseconds100 / 0.001) - (femtosecs * 10)) * 100)as"
case 0.001...:
return "\(Int(attoseconds100 * 100000))as"
default:
return "Less than 100 attoseconds"
}
}
}
| true
|
62a6e3bc580d4163dcd98053b5244a615535be65
|
Swift
|
randerson112358/Pocket-Change
|
/Lincoln Laws/Data Types/Party.swift
|
UTF-8
| 216
| 2.640625
| 3
|
[] |
no_license
|
//
// Party.swift
// Lincoln Laws
//
// Created by Christopher Perkins on 3/2/19.
// Copyright © 2019 Christopher Perkins. All rights reserved.
//
public enum Party: String, Codable {
case democrat = "D"
case republican = "R"
}
| true
|
944793d0fee1835df55fa573650fccc9a5f5e50e
|
Swift
|
Gavin888888/learn
|
/LearnSwift/LearnSwift/Person.swift
|
UTF-8
| 709
| 3.046875
| 3
|
[] |
no_license
|
//
// Person.swift
// LearnSwift
//
// Created by lei li on 2018/6/7.
// Copyright © 2018年 lei li. All rights reserved.
//
import UIKit
/* kvc赋值
1.继承 NSObject
2.初始化方法调用 super.init()
3.实现 setValuesForKeys(info)
4.重写 setValue forUndefinedKey
*/
class Person: NSObject {
@objc var name: String = ""
@objc var age: Int = 0
weak var book: Book?
init(name: String, age: Int) {
self.name = name
self.age = age
}
deinit {
print("Person销毁")
}
init(info:[String: Any]) {
super.init()
setValuesForKeys(info)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
| true
|
738865b0f6bd73a53ff0148f7126d4f3946c0e08
|
Swift
|
hemmlj/aural-player
|
/Source/UI/Effects/EQ/EQSubview.swift
|
UTF-8
| 2,782
| 2.734375
| 3
|
[] |
no_license
|
import Cocoa
class EQSubview: NSView {
@IBOutlet weak var globalGainSlider: EffectsUnitSlider!
var bandSliders: [EffectsUnitSlider] = []
var allSliders: [EffectsUnitSlider] = []
override func awakeFromNib() {
for subView in self.subviews {
if let slider = subView as? EffectsUnitSlider {
if slider.tag >= 0 {bandSliders.append(slider)}
allSliders.append(slider)
}
}
}
func initialize(_ stateFunction: @escaping EffectsUnitStateFunction, _ sliderAction: Selector?, _ sliderActionTarget: AnyObject?) {
allSliders.forEach({$0.stateFunction = stateFunction})
bandSliders.forEach({
$0.action = sliderAction
$0.target = sliderActionTarget
})
}
func stateChanged() {
allSliders.forEach({$0.updateState()})
}
func changeSliderColor() {
allSliders.forEach({$0.redraw()})
}
func changeActiveUnitStateColor(_ color: NSColor) {
allSliders.forEach({$0.redraw()})
}
func changeBypassedUnitStateColor(_ color: NSColor) {
allSliders.forEach({$0.redraw()})
}
func changeSuppressedUnitStateColor(_ color: NSColor) {
allSliders.forEach({$0.redraw()})
}
func setState(_ state: EffectsUnitState) {
allSliders.forEach({$0.setUnitState(state)})
}
func updateBands(_ bands: [Float], _ globalGain: Float) {
// If number of bands doesn't match, need to perform a mapping
if bands.count != bandSliders.count {
let mappedBands = bands.count == 10 ? EQMapper.map10BandsTo15Bands(bands, AppConstants.Sound.eq15BandFrequencies) : EQMapper.map15BandsTo10Bands(bands, AppConstants.Sound.eq10BandFrequencies)
self.updateBands(mappedBands, globalGain)
return
}
// Slider tag = index. Default gain value, if bands array doesn't contain gain for index, is 0
bandSliders.forEach({
$0.floatValue = $0.tag < bands.count ? bands[$0.tag] : AppDefaults.eqBandGain
})
globalGainSlider.floatValue = globalGain
}
func updateBands(_ bands: [Float: Float], _ globalGain: Float) {
var sortedBands: [Float] = []
let sortedBandsMap = bands.sorted(by: {r1, r2 -> Bool in r1.key < r2.key})
var index = 0
for (_, gain) in sortedBandsMap {
sortedBands.append(gain)
index += 1
}
updateBands(sortedBands, globalGain)
}
func changeColorScheme() {
allSliders.forEach({$0.redraw()})
}
}
| true
|
3570810770790e99596fbd536ea19225fc9adcd9
|
Swift
|
geoff-hom-gmail-com/Hanabi-Ai
|
/Hanabi Ai/Views/AboutView.swift
|
UTF-8
| 1,912
| 3.125
| 3
|
[] |
no_license
|
//
// AboutView.swift
// Hanabi Ai
//
// Created by Geoff Hom on 8/31/19.
// Copyright © 2019 Geoff Hom. All rights reserved.
//
import SwiftUI
/// A view that shows info about this app.
///
/// If a newbie runs this app, this view should bring them up to speed. Set appropriate expectations of what the app can/can't do. (Don't promise upcoming features because my track record is poor.) Also provides app version/build, for debugging.
struct AboutView: View {
var body: some View {
// Using Form until Text.lineLimit(nil) starts working robustly. (A grouped List makes more sense that Form.)
Form {
Section {
Text("Hanabi Ai is a simulator for the card game Hanabi.")
}
VStack(alignment: .leading) {
Text("Use Hanabi Ai to:")
Text("• Auto-play many games in a row.")
Text("• Auto-play a specific game (i.e., deck setup).")
}
VStack(alignment: .leading) {
Text("Notes:")
Text("• Only 2-player games for now.")
Text("• Only 1 AI personality offered:")
Text(" • Superman: Has X-ray vision, so knows all cards, including the deck.")
// TODO: this is the % wins for the AI
// add average score
Text(" • Win %: TBD (1 in X)")
// TODO: move elsewhere?
Text("• Losing-deck example: TBD")
}
Section {
Text("Version \(AppInfo.version) (build \(AppInfo.build))")
}
}
.navigationBarTitle(Text("About"), displayMode: .inline)
}
}
// MARK: Previews
struct AboutView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
AboutView()
}
}
}
| true
|
946b821707c677f04215e5888ad7fb7fa6340752
|
Swift
|
younatics/MediaBrowser
|
/MediaBrowser/MediaTapDetectingView.swift
|
UTF-8
| 1,671
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// MediaTapDetectingView.swift
// MediaBrowser
//
// Created by Seungyoun Yi on 2017. 9. 6..
// Copyright © 2017년 Seungyoun Yi. All rights reserved.
//
//
import Foundation
class MediaTapDetectingView: UIView {
weak var tapDelegate: TapDetectingViewDelegate?
init() {
super.init(frame: .zero)
isUserInteractionEnabled = true
}
override init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let tapCount = touch.tapCount
switch tapCount {
case 1: handleSingleTap(touch: touch)
case 2: handleDoubleTap(touch: touch)
case 3: handleTripleTap(touch: touch)
default: break
}
}
next?.touchesEnded(touches, with: event)
}
private func handleSingleTap(touch: UITouch) {
tapDelegate?.singleTapDetectedInView(view: self, touch: touch)
}
private func handleDoubleTap(touch: UITouch) {
tapDelegate?.doubleTapDetectedInView(view: self, touch: touch)
}
private func handleTripleTap(touch: UITouch) {
tapDelegate?.tripleTapDetectedInView(view: self, touch: touch)
}
}
protocol TapDetectingViewDelegate: class {
func singleTapDetectedInView(view: UIView, touch: UITouch)
func doubleTapDetectedInView(view: UIView, touch: UITouch)
func tripleTapDetectedInView(view: UIView, touch: UITouch)
}
| true
|
588fee69636f9d35c379128b5b1f43256a7990c8
|
Swift
|
willds40/MusicForThought
|
/MusicForThought/API.swift
|
UTF-8
| 612
| 2.921875
| 3
|
[] |
no_license
|
import Alamofire
import Foundation
import SwiftyJSON
class API{
func uploadData(){
let paramters = MockData().getParamters()
Alamofire.request("http://10.27.10.57:2525/imposters/", method: .post, parameters: paramters, encoding: JSONEncoding.default).responseJSON{ response in
}
}
func retrieveData(forPath path: String, completion : @escaping (JSON) -> ()){
Alamofire.request("http://10.27.10.57:4545/" + "\(path)").responseJSON { response in
let jsonData = JSON(data: response.data!)
completion(jsonData)
}
}
}
| true
|
3b82d90133b8aa211cd00bd73bd55ce38e4018d5
|
Swift
|
skiny-n/SwiftyScraper
|
/SwiftyScraper/SwiftyScraper/Protocols/RequestBuilderType.swift
|
UTF-8
| 478
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// RequestBuilderType.swift
// SwiftyScraper
//
// Created by Stanislav Novacek on 13/11/2018.
// Copyright © 2018 Stanislav Novacek. All rights reserved.
//
import Foundation
/** Describes a request builder. */
public protocol RequestBuilderType {
/** Creates an HTTP request with given method, URL, parameters, body and headers. */
func buildRequest(method: HTTPMethod, url: String, parameters: JSON?, body: RequestBodyType?, headers: [String: String]) -> URLRequest?
}
| true
|
2cacd4e8bed204e79d5642599b91422eb08ae77b
|
Swift
|
southfox/JFAlgo
|
/Example/JFAlgo/FrogJmpViewController.swift
|
UTF-8
| 2,574
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
//
// FrogJmpViewController.swift
// JFAlgo
//
// Created by Javier Fuchs on 9/8/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import JFAlgo
/// A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.
/// Count the minimal number of jumps that the small frog must perform to reach its target.
///
/// Write a function:
///
/// public func solution(X : Int, _ Y : Int, _ D : Int) -> Int
/// that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
///
/// For example, given:
///
/// X = 10
/// Y = 85
/// D = 30
/// the function should return 3, because the frog will be positioned as follows:
///
/// after the first jump, at position 10 + 30 = 40
/// after the second jump, at position 10 + 30 + 30 = 70
/// after the third jump, at position 10 + 30 + 30 + 30 = 100
/// Assume that:
///
/// X, Y and D are integers within the range [1..1,000,000,000];
/// X ≤ Y.
/// Complexity:
///
/// expected worst-case time complexity is O(1);
/// expected worst-case space complexity is O(1).
class FrogJmpViewController : BaseViewController {
@IBOutlet weak var xField: UITextField!
@IBOutlet weak var yField: UITextField!
@IBOutlet weak var jumpField: UITextField!
@IBOutlet weak var runButton: UIButton!
let frogJmp = FrogJmp()
@IBAction func runAction() {
guard let xText = xField.text,
x = Int(xText),
yText = yField.text,
y = Int(yText),
jumpText = jumpField.text,
jump = Int(jumpText) else {
return
}
runButton.enabled = false
for field in [xField, yField, jumpField] {
field.resignFirstResponder()
}
for v in [x, y, jump] {
if frogJmp.checkDomainGenerator(v) == false {
self.showAlert(frogJmp.domainErrorMessage()) { [weak self] in
if let strong = self {
strong.runButton.enabled = true
}
}
return
}
}
let solution = frogJmp.solution(x, y, jump)
self.showAlert("x = \(x), y = \(y), jump = \(jump): Solution = \(solution)") { [weak self] in
if let strong = self {
strong.runButton.enabled = true
}
}
}
}
| true
|
2eaf7c03a5eac6fcb562a85b417afd65619d3342
|
Swift
|
ulkoart/NewsApiClient
|
/NewsApiClient/Model/News.swift
|
UTF-8
| 2,540
| 3.265625
| 3
|
[] |
no_license
|
//
// News.swift
// NewsApiClient
//
// Created by user on 18.06.2021.
// Copyright © 2021 Artem Ulko. All rights reserved.
//
import Foundation
import UIKit
enum NewsCategory: Int, Codable, CaseIterable {
case general
case business
case entertainment
case health
case science
case sports
case technology
}
extension NewsCategory {
var isDefault: Bool {
switch self {
case .general:
return true
case _:
return false
}
}
var stringValue: String {
switch self {
case .business:
return "business"
case .entertainment:
return "entertainment"
case .general:
return "general"
case .health:
return "health"
case .science:
return "science"
case .sports:
return "sports"
case .technology:
return "technology"
}
}
var titleValue: String {
switch self {
case .business:
return "Бизнес"
case .entertainment:
return "Досуг"
case .general:
return "Главное"
case .health:
return "Здоровье"
case .science:
return "Наука"
case .sports:
return "Спорт"
case .technology:
return "Технологии"
}
}
var image: UIImage? {
switch self {
case .business:
return UIImage(named: self.stringValue)
case .entertainment:
return UIImage(named: self.stringValue)
case .general:
return UIImage(named: self.stringValue)
case .health:
return UIImage(named: self.stringValue)
case .science:
return UIImage(named: self.stringValue)
case .sports:
return UIImage(named: self.stringValue)
case .technology:
return UIImage(named: self.stringValue)
}
}
var emojiValue: String {
switch self {
case .general:
return "🚩"
case .business:
return "👔"
case .entertainment:
return "🎪"
case .health:
return "🏥"
case .science:
return "👨🔬"
case .sports:
return "🏈"
case .technology:
return "🖥"
}
}
}
| true
|
9d10f396e4eaf22cb2336026786c7c1c7274e3df
|
Swift
|
gringoireDM/MERLin
|
/MERLinSample/RestaurantDetailModule/ViewModel/RestaurantDetailViewModel.swift
|
UTF-8
| 2,034
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// RestaurantDetailVMProtocol.swift
// RestaurantDetailModule
//
// Created by Giuseppe Lanza on 15/08/2018.
// Copyright © 2018 Giuseppe Lanza. All rights reserved.
//
import Foundation
protocol RestaurantDetailVMInput {
var viewWillAppear: Driver<Void> { get }
var bookButtonTapped: Driver<RestaurantProtocol> { get }
}
protocol RestaurantDetailVMOutput {
var restaurantDetailFetched: Driver<RestaurantProtocol> { get }
var error: Driver<Error> { get }
}
protocol RestaurantDetailViewModelProtcol {
init(events: PublishSubject<RestaurantDetailEvent>, restaurantId: String)
func transform(input: RestaurantDetailVMInput) -> RestaurantDetailVMOutput
}
class RestaurantDetailViewModel: RestaurantDetailViewModelProtcol {
struct Output: RestaurantDetailVMOutput {
var restaurantDetailFetched: Driver<RestaurantProtocol>
var error: Driver<Error>
}
let disposeBag = DisposeBag()
private let repositories: [RestaurantRepository] = [
MockRepository()
]
private let events: PublishSubject<RestaurantDetailEvent>
private let id: String
required init(events: PublishSubject<RestaurantDetailEvent>, restaurantId: String) {
self.events = events
id = restaurantId
}
func transform(input: RestaurantDetailVMInput) -> RestaurantDetailVMOutput {
input.bookButtonTapped
.map(RestaurantDetailEvent.bookButtonTapped)
.drive(events)
.disposed(by: disposeBag)
let errors = PublishSubject<Error>()
let getDetail = repositories.getDetail(for: id)
let restaurantDetailFetched = input.viewWillAppear
.flatMap { _ in
getDetail
.asDriver(onErrorRecover: {
errors.onNext($0)
return .empty()
})
}
return Output(restaurantDetailFetched: restaurantDetailFetched, error: errors.asDriverIgnoreError())
}
}
| true
|
2a967d445f8a9c50277a869d3f46dc2efac934d3
|
Swift
|
marbleinteractivespain/SwiftUIMarvelStudiosApp
|
/Shared/Views/Loading/LoadingView.swift
|
UTF-8
| 1,212
| 3.125
| 3
|
[] |
no_license
|
//
// LoadingView.swift
// AvengersAppSwiftUI (iOS)
//
// Created by David dela Puente on 20/9/21.
//
import SwiftUI
struct LoadingView: View {
@State private var isLoading = false
var body: some View {
ZStack{
Color.black
.ignoresSafeArea()
Image("logo")
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 150, height: 150, alignment: .center)
Circle()
.stroke(Color(.systemGray5), lineWidth: 14)
.frame(width: 150, height: 150)
Circle()
.trim(from: 0, to: 0.2)
.stroke(Color("RedMarvel"), lineWidth: 7)
.frame(width: 200, height: 200)
.rotationEffect(Angle(degrees: isLoading ? 360 : 0)) .animation(Animation.linear(duration: 1).repeatForever(autoreverses: false))
.onAppear(){
self.isLoading = true
}
.onDisappear{
self.isLoading = false
}
}
}
}
struct LoadingView_Previews: PreviewProvider {
static var previews: some View {
LoadingView()
}
}
| true
|
dc925184d1b1b5f88595452c00c4990bde5a44b1
|
Swift
|
lizthebiz/carousel-demo
|
/carousel/TutorialViewController.swift
|
UTF-8
| 1,961
| 2.5625
| 3
|
[] |
no_license
|
//
// TutorialViewController.swift
// carousel
//
// Created by Liz Dalay on 10/14/15.
// Copyright © 2015 Liz Dalay. All rights reserved.
//
import UIKit
class TutorialViewController: UIViewController, UIScrollViewDelegate {
@IBOutlet weak var tutorialScrollView: UIScrollView!
@IBOutlet weak var tutorialImageView: UIImageView!
@IBOutlet weak var tutorialPageControl: UIPageControl!
@IBOutlet weak var carouselSpinView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tutorialScrollView.contentSize = tutorialImageView.image!.size
tutorialScrollView.delegate = self
carouselSpinView.alpha = 0
}
func scrollViewDidEndDecelerating(ScrollView: UIScrollView) {
// Get the current page based on the scroll offset
let page : Int = Int(round(tutorialScrollView.contentOffset.x / 320))
// Set the current page, so the dots will update
tutorialPageControl.currentPage = page
if page == 3 {
tutorialPageControl.hidden = true
UIView.animateWithDuration(0.5, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: {
self.carouselSpinView.alpha = 1
}, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
3e077055b0987f8244af884dccb88404687092bc
|
Swift
|
Trevdawg347/TheRealIsh
|
/The Real Ish/Components/SearchBar.swift
|
UTF-8
| 1,166
| 2.9375
| 3
|
[] |
no_license
|
//
// SearchBar.swift
// The Real Ish
//
// Created by Wendy Buhler on 9/11/21.
//
import SwiftUI
struct SearchBar: View {
@Binding var textFieldText: String
var body: some View {
HStack {
Image(systemName: "magnifyingglass")
TextField("Search...", text: $textFieldText)
}
.padding(.horizontal)
.frame(maxWidth: .infinity)
.frame(height: 45)
.background(Color.theme.secondaryText)
.foregroundColor(Color.theme.accent)
.padding()
.overlay(
Image(systemName: "xmark.circle.fill")
.padding()
.offset(x: -20)
.foregroundColor(Color.theme.accent)
.opacity(textFieldText.isEmpty ? 0.0 : 1.0)
.onTapGesture {
UIApplication.shared.endEditing()
textFieldText = ""
}
, alignment: .trailing
)
}
}
struct SearchBar_Previews: PreviewProvider {
static var previews: some View {
SearchBar(textFieldText: .constant("yo"))
.preferredColorScheme(.dark)
}
}
| true
|
dadcfbc7183904977dfb42c3a91af048cd5e87d7
|
Swift
|
engjasonp/LoveWar
|
/LoveWar/GameViewController.swift
|
UTF-8
| 1,339
| 3.109375
| 3
|
[] |
no_license
|
//
// GameViewController.swift
// LoveWar
//
// Created by Jason Eng on 6/28/16.
// Copyright © 2016 EngJason. All rights reserved.
//
import UIKit
class GameViewController: UIViewController {
@IBOutlet weak var playerCard1: UIButton!
@IBOutlet weak var playerCard2: UIButton!
@IBOutlet weak var statusLabel: UILabel!
var numberOfPlayers: Int?
var game = Game()
override func viewDidLoad() {
super.viewDidLoad()
if (numberOfPlayers == 2) {
view.backgroundColor = UIColor.blue
}
if (numberOfPlayers == 3) {
view.backgroundColor = UIColor.red
}
if (numberOfPlayers == 4) {
view.backgroundColor = UIColor.green
}
print("\(numberOfPlayers!) players")
game.setUpGameLogic()
// adds number of players up to playerCount and deals each one a new card from deck
game.addPlayers(playerCount: numberOfPlayers!)
//let playerCardImage1 = UIImage(named: game.players[game.currentTurn!].currentCards[0].image!)
//let playerCardImage2 = UIImage(named: game.players[0].cardStringArray[1])
//playerCard1.setImage(playerCardImage1, for: .normal)
//playerCard2.setImage(playerCardImage2, for: .normal)
}
}
| true
|
fb210cced51f796a5a561b1ff12e6b032382a4f9
|
Swift
|
sharafa839/Allied-SwiftUI-
|
/AlliedProject/Modules/Views/CustomCell.swift
|
UTF-8
| 806
| 2.890625
| 3
|
[] |
no_license
|
//
// AppetizerCell.swift
// SwiftUI-MVVM
//
// Created by Sean Allen on 5/24/21.
//
import SwiftUI
struct CustomCell: View {
let model: payload?
var body: some View {
HStack {
DownloadRemoteImage(urlString: model?.image ?? "")
.aspectRatio(contentMode: .fit)
.frame(width: 120, height: 90)
.cornerRadius(8)
VStack(alignment: .leading, spacing: 5) {
Text(model?.name ?? "")
.font(.title2)
.fontWeight(.medium)
}
.padding(.leading)
}
}
}
struct AppetizerCell_Previews: PreviewProvider {
static var previews: some View {
CustomCell(model: MockData.sampleUser)
}
}
| true
|
3410415771209cb5cff28771941aca115cec1ace
|
Swift
|
MiraEs/AC3.2-LibraryOfCongress
|
/LibraryOfCongress/APIManager.swift
|
UTF-8
| 997
| 2.578125
| 3
|
[] |
no_license
|
//
// CongressManager.swift
// LibraryOfCongress
//
// Created by Ilmira Estil on 10/30/16.
// Copyright © 2016 C4Q. All rights reserved.
//
import Foundation
internal class APIRequestManager {
internal static let manager: APIRequestManager = APIRequestManager()
private init() {}
func getCongressJdata(endpoint: String, callback: @escaping ((Data) -> Void)){
guard let url = URL(string: endpoint) else { return }
//let session: URLSession = URLSession(configuration: .default)
let session = URLSession.init(configuration: .default)
session.dataTask(with: url) { (data: Data?, response: URLResponse?, error: Error?) in
//Error handling
if error != nil {
print("Encountered an error: \(error)")
}
//get data
guard let validData = data else { return }
callback(validData)
}.resume()
}
}
| true
|
f4b37c23f4fdd1478e4794bbe85a86a756962e50
|
Swift
|
farrasdoko/nbs-test
|
/nbs-test/Model/Detail/CDDetail.swift
|
UTF-8
| 1,157
| 2.75
| 3
|
[] |
no_license
|
//
// CDDetail.swift
// nbs-test
//
// Created by Farras Doko on 24/02/21.
//
import UIKit
struct CDDetail {
var title: String
var genre: String
var year: String
var image: UIImage?
var banner: UIImage?
var body: String
var movieID: String
init(_ favorite: Detail) {
self.title = favorite.title ?? ""
self.genre = Utils.getGenres(favorite.genres)
self.year = favorite.releaseDate ?? ""
self.body = favorite.overview ?? ""
self.movieID = String(favorite.id ?? 0)
}
init(_ favorite: Favorite) {
self.title = favorite.title ?? ""
self.genre = favorite.genre ?? ""
self.year = favorite.year ?? ""
self.body = favorite.body ?? ""
self.movieID = favorite.movieID ?? ""
if let data = favorite.image {
self.image = UIImage(data: data)
}
if let data = favorite.banner {
self.banner = UIImage(data: data)
}
}
mutating func addBanner(image: UIImage?) {
self.banner = image
}
mutating func addPoster(image: UIImage?) {
self.image = image
}
}
| true
|
a762e5d98d51a4961f60e017b7fa51d4a0858d60
|
Swift
|
FCZLumpy/RedditApp
|
/RedditTest/Screens/ViewController/ViewControllerModels.swift
|
UTF-8
| 3,579
| 3
| 3
|
[] |
no_license
|
// Single Post
struct SinglePost {
let authorName: String
let title: String
let thumbnailURL: String
let created: Int
let commentsCount: Int
let name: String
let imageURL: String
}
extension SinglePost: Decodable {
enum SinglePostKeys: String, CodingKey {
case authorName = "author"
case title
case thumbnailURL = "thumbnail"
case created
case commentsCount = "num_comments"
case name
case imageURL = "url"
case preview
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: SinglePostKeys.self)
authorName = try container.decode(String.self, forKey: .authorName)
title = try container.decode(String.self, forKey: .title)
thumbnailURL = try container.decode(String.self, forKey: .thumbnailURL)
created = try container.decode(Int.self, forKey: .created)
commentsCount = try container.decode(Int.self, forKey: .commentsCount)
name = try container.decode(String.self, forKey: .name)
imageURL = try container.decode(String.self, forKey: .thumbnailURL)
//Here should be imageURL from preview, but I dont know why I receive 403 in app and in Safary
/* let image = try container.decode(Preview.self, forKey: .preview)
imageURL = image.images.first?.source.url ?? "" */
}
}
// Decode preview
struct Preview {
let images : [Source]
}
extension Preview: Decodable {
enum PreviewKeys: String, CodingKey {
case images
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PreviewKeys.self)
images = try container.decode([Source].self, forKey: .images)
}
}
// Decode preview
struct Source {
let source : PreviewUrl
}
extension Source: Decodable {
enum SourceKeys: String, CodingKey {
case source
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: SourceKeys.self)
source = try container.decode(PreviewUrl.self, forKey: .source)
}
}
// Decode url
struct PreviewUrl {
let url : String
}
extension PreviewUrl: Decodable {
enum PreviewUrlKeys: String, CodingKey {
case url
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PreviewUrlKeys.self)
url = try container.decode(String.self, forKey: .url)
}
}
// Single Post from Data
struct PostData {
let data: SinglePost
}
extension PostData: Decodable {
enum PostDataKeys: String, CodingKey {
case data
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: PostDataKeys.self)
data = try container.decode(SinglePost.self, forKey: .data)
}
}
// Posts List
struct Children {
let children: [PostData]
}
extension Children: Decodable {
enum ChildrenKeys: String, CodingKey {
case children
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ChildrenKeys.self)
children = try container.decode([PostData].self, forKey: .children)
}
}
// All data
struct TopData {
let topData: Children
}
extension TopData: Decodable {
enum TopDataKeys: String, CodingKey {
case topData = "data"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: TopDataKeys.self)
topData = try container.decode(Children.self, forKey: .topData)
}
}
| true
|
912471e5ad4c3bd788379b96b16a02c4410898e5
|
Swift
|
MuhammadBilal164/DelegatesPractice
|
/DelegatesPractice-master/Task3/Cell/tableCell.swift
|
UTF-8
| 1,905
| 2.828125
| 3
|
[] |
no_license
|
//
// tableCell.swift
// Task3
//
// Created by Umer Farooq on 22/09/2020.
// Copyright © 2020 Umer Farooq. All rights reserved.
//
import UIKit
protocol TableViewCellDelegate: AnyObject {
func tableViewCellIndex(cell: tableCell, collectionViewCellIndexNumber: Int)
}
class tableCell: UITableViewCell {
//MARK: - IBOutlet
@IBOutlet weak var collectionView: UICollectionView!
//MARK: - Variables
let cellIdentifier = "cell"
weak var delegate: TableViewCellDelegate?
//MARK: - Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
setupView()
}
//MARK: - SetupView
func setupView() {
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(UINib(nibName: "collectionCell", bundle: nil), forCellWithReuseIdentifier: "cell")
}
//MARK: - Actions
//MARK: - Helper Methods
}
//MARK: - UICollectionViewDelegate & DataSource
extension tableCell:UICollectionViewDelegate,UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! collectionCell
cell.delegate = self
return cell
}
}
//MARK: - CollectionViewCellDelegate
extension tableCell: CollectionViewCellDelegate {
func collectionViewCellIndex(cell: collectionCell) {
guard let indexPath = collectionView.indexPath(for: cell) else { return }
delegate?.tableViewCellIndex(cell: self, collectionViewCellIndexNumber: indexPath.row)
}
}
| true
|
26781732f2ba878ee82abe238d3c4a6463c5bba8
|
Swift
|
design-ops/stylable-uikit
|
/StylableUIKit/Classes/Components/StylableTextView.swift
|
UTF-8
| 1,279
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
//
// StylableTextView.swift
// StylableUIKit
//
import Foundation
import UIKit
public final class StylableTextView: UITextView {
private var textStyle: BasicTextStyle?
override public var text: String? {
didSet {
guard let textStyle = self.textStyle else { return }
self.applyTextStyle(textStyle)
}
}
override public var attributedText: NSAttributedString? {
set { super.attributedText = newValue.map { self.applyTextStyleTo(attributedText: $0) } }
get { return super.attributedText }
}
public func setTextStyle(_ textStyle: BasicTextStyle) {
self.textStyle = textStyle
self.applyTextStyle(textStyle)
}
private func applyTextStyle(_ textStyle: BasicTextStyle) {
self.attributedText = self.attributedText.map { self.applyTextStyleTo(attributedText: $0) }
}
private func applyTextStyleTo(attributedText: NSAttributedString) -> NSAttributedString {
guard let textStyle = self.textStyle else { return attributedText }
return textStyle.apply(attributedText)
.applyingAttributes([.backgroundColor: textStyle.backgroundColor ?? self.backgroundColor ?? .clear],
preservingCurrent: false)
}
}
| true
|
43ebdd54406669de73a66678ccd495db1c2ea7c8
|
Swift
|
bengottlieb/Serif
|
/Serif/Framework Code/TrueTypeDescriptor/TrueTypeDescriptor+Header.swift
|
UTF-8
| 1,918
| 2.578125
| 3
|
[] |
no_license
|
//
// TrueTypeFont+Header.swift
// FontExplorer
//
// Created by Ben Gottlieb on 5/26/17.
// Copyright © 2017 Stand Alone, Inc. All rights reserved.
//
import Foundation
extension TrueTypeDescriptor {
public struct Header {
let version: CGFloat
let fontRevision: CGFloat
let checksumAdjustment: UInt32
let magicNumber: UInt32
let flags: UInt16
let unitsPerEm: UInt16
let created: Int64
let modified: Int64
let xMin: Int16
let yMin: Int16
let xMax: Int16
let yMax: Int16
let macStyle: UInt16
let lowestRectPPEM: UInt16
let fontDirectionHint: Int16
let indexToLocFormat: Int16
let glyphDataFormat: Int16
let numberOfGlyphs: UInt16
public var size: CGSize { return CGSize(width: CGFloat(self.xMax - self.xMin), height: CGFloat(self.yMax - self.yMin)) }
public var origin: CGPoint { return CGPoint(x: CGFloat(self.xMin), y: CGFloat(self.yMin)) }
public var bbox: CGRect { return CGRect(origin: self.origin, size: self.size) }
init(header: Table, maxProfile: Table) throws {
var bytes = header.parser
self.version = CGFloat(try bytes.nextFixed())
self.fontRevision = CGFloat(try bytes.nextFixed())
self.checksumAdjustment = try bytes.nextUInt32()
self.magicNumber = try bytes.nextUInt32()
self.flags = try bytes.nextUInt16()
self.unitsPerEm = try bytes.nextUInt16()
self.created = try bytes.nextInt64()
self.modified = try bytes.nextInt64()
self.xMin = try bytes.nextInt16()
self.yMin = try bytes.nextInt16()
self.xMax = try bytes.nextInt16()
self.yMax = try bytes.nextInt16()
self.macStyle = try bytes.nextUInt16()
self.lowestRectPPEM = try bytes.nextUInt16()
self.fontDirectionHint = try bytes.nextInt16()
self.indexToLocFormat = try bytes.nextInt16()
self.glyphDataFormat = try bytes.nextInt16()
bytes = maxProfile.parser
bytes.skip(4)
self.numberOfGlyphs = try bytes.nextUInt16()
}
}
}
| true
|
5f1afc8dd5c0de8374873f693ede5fb48fd37581
|
Swift
|
getGuaka/guaka-cli
|
/Sources/GuakaClILib/FileWriteOperation.swift
|
UTF-8
| 2,952
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// FileWriteOperation.swift
// guaka-cli
//
// Created by Omar Abdelhafith on 27/11/2016.
//
//
public struct FileOperations {
let operations: [FileOperation]
public static func newProjectOperations(paths: Paths) -> FileOperations {
let operations = [
FileWriteOperation(
fileContent: GeneratorParts.packageFile(forCommandName: paths.projectName),
filePath: paths.packagesFile,
errorString: "package"),
FileWriteOperation(
fileContent: GeneratorParts.mainSwiftFileContent(),
filePath: paths.mainSwiftFile,
errorString: "main swift"),
FileWriteOperation(
fileContent: GeneratorParts.commandFile(forVarName: "root", commandName: paths.projectName),
filePath: paths.path(forSwiftFile: "root"),
errorString: "root swift"),
FileWriteOperation(
fileContent: GeneratorParts.setupFileContent(),
filePath: paths.setupSwiftFile,
errorString: "setup swift"),
]
return FileOperations(operations: operations)
}
public static func addCommandOperations(paths: Paths,
commandName name: String,
parent: String?) -> FileOperations {
let setupUpdateBlock = { content in
try GeneratorParts.updateSetupFile(
withContent: content,
byAddingCommand: "\(name)Command",
withParent: parent)
}
let operations: [FileOperation] = [
FileUpdateOperation(
filePath: paths.setupSwiftFile,
operation: setupUpdateBlock,
errorString: "setup swift"),
FileWriteOperation(
fileContent: GeneratorParts.commandFile(forVarName: name, commandName: name),
filePath: paths.path(forSwiftFile: name),
errorString: "\(name) swift"),
]
return FileOperations(operations: operations)
}
public func perform() throws {
try operations.forEach { try $0.perform() }
}
}
public protocol FileOperation {
var filePath: String { get }
var errorString: String { get }
func perform() throws
}
public struct FileWriteOperation: FileOperation {
let fileContent: String
public let filePath: String
public let errorString: String
public func perform() throws {
if GuakaCliConfig.file.write(string: fileContent, toFile: filePath) == false {
throw GuakaError.cannotCreateFile(errorString)
}
}
}
public struct FileUpdateOperation: FileOperation {
public let filePath: String
let operation: (String) throws -> (String)
public let errorString: String
public func perform() throws {
guard let fileContent = GuakaCliConfig.file.read(fromFile: filePath) else {
throw GuakaError.cannotReadFile(filePath)
}
let newFileContent = try operation(fileContent)
if GuakaCliConfig.file.write(string: newFileContent, toFile: filePath) == false {
throw GuakaError.cannotCreateFile(errorString)
}
}
}
| true
|
1ea12e2bd0e0ccff601677fb4822ef08856eefe0
|
Swift
|
chengyunfei/structureAlgorithm
|
/StructAndArithmetic/StructAndArithmetic/13-并查集/UnionFind_QU_Rank.swift
|
UTF-8
| 887
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
//
// UnionFind_QU_Rank.swift
// StructAndArithmetic
//
// Created by zl on 2021/7/20.
//
import Cocoa
/*
* Quick Union - 基于rank的优化
* 矮的树嫁接到高的树
*/
class UnionFind_QU_Rank: UnionFind_QU {
/// 存储集合的树的高度
fileprivate var rankArr = [Int]()
override init(capacity: Int) {
super.init(capacity: capacity)
rankArr = Array(repeating: 1, count: capacity)
}
/// 将v1的根节点嫁接到v2的根节点上
override func union(v1: Int, v2: Int) {
let p1 = find(v: v1)
let p2 = find(v: v2)
if p1 == p2 { return }
if rankArr[p1] < rankArr[p2] {
parents[p1] = p2
} else if rankArr[p2] < rankArr[p1] {
parents[p2] = p1
} else {
parents[p1] = p2
rankArr[p2] += 1
}
}
}
| true
|
6049d42370e32e94af86d38f3eeec02bde51301f
|
Swift
|
Abdulrahman-Alharbi/ViewData
|
/ViewData/ViewController.swift
|
UTF-8
| 2,835
| 2.890625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ViewData
//
// Created by Abdualrahman Alharbi on 28/06/1442 AH.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
// Edit Text
@IBOutlet weak var TFFirstName: UITextField!
@IBOutlet weak var TFMiddleName: UITextField!
@IBOutlet weak var TFLastName: UITextField!
var selectedDate = ""
var actionSheetController : UIAlertController?
@IBOutlet var datePicker: UIDatePicker!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
// Get Date from datePicker
func getDateFromDatepicker(){
datePicker.datePickerMode = UIDatePicker.Mode.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MMMM yyyy"
// save Date as String
selectedDate = dateFormatter.string(from: datePicker.date)
print(selectedDate)
}
// On click Show Data
@IBAction func showData(_ sender: Any) {
// Check if one or more of TF are empty.
if TFFirstName.text!.isEmpty || TFMiddleName.text!.isEmpty || TFLastName.text!.isEmpty {
// Show Dialog
showDialog()
}else {
let vcShowData = storyboard?.instantiateViewController(identifier: "ShowData") as! ViewControllerShowData
// Get Birhday date
getDateFromDatepicker()
// send values to another view
vcShowData.firstName = TFFirstName.text!
vcShowData.middleName = TFMiddleName.text!
vcShowData.lastName = TFLastName.text!
vcShowData.birthDay = selectedDate
vcShowData.modalPresentationStyle = .fullScreen
present(vcShowData, animated: true)
}
}
func showDialog(){
actionSheetController = UIAlertController(title: "تنبيه!", message: "يرجى تعبئة جميع الحقول قبل الإنتقال للصفحة التالية", preferredStyle: .alert)
let okAction = UIAlertAction(title: "حسناً", style: .default) { action -> Void in
//
}
actionSheetController?.addAction(okAction)
self.present(actionSheetController!, animated: true, completion: nil)
}
// dismiss keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// close keyboard when click enter
textField.resignFirstResponder()
return true
}
// close keyboard when click anywhere on viewController
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
}
| true
|
9c58abe5cfaf12359fcc7e3a0cfdf8b52f556c34
|
Swift
|
techThrive/DataStructure
|
/LinkedList.playground/Sources/LinkedList/LinkedList.swift
|
UTF-8
| 9,441
| 3.65625
| 4
|
[] |
no_license
|
import Foundation
public struct LinkedList<Value: Comparable> {
public var head: Node<Value>?
public var tail: Node<Value>?
public init() {
}
public var count: Int {
return getNodes()
}
public var isEmpty: Bool {
return head == nil
}
public mutating func push(_ value: Value) {
head = Node(value: value, next: head)
if tail == nil {
tail = head
}
}
public mutating func append(_ value: Value) {
guard !isEmpty else {
push(value)
return
}
tail!.next = Node(value: value)
tail = tail!.next
}
public mutating func append(_ node: Node<Value>) {
guard !isEmpty else {
head = node
tail = node
return
}
tail!.next = node
tail = node
}
public func node(at index: Int, fromBack: Bool = false) -> Node<Value>? {
var currentNode = head
var currentIndex = 0
var index = index
if fromBack {
index = self.count - index
}
while currentNode != nil && currentIndex < index {
currentNode = currentNode!.next
currentIndex += 1
}
return currentNode
}
@discardableResult
public mutating func insert(_ value: Value, after node: Node<Value>) -> Node<Value> {
guard tail !== node else {
append(value)
return tail!
}
node.next = Node(value: value, next: node.next)
return node.next!
}
@discardableResult
public mutating func pop() -> Value? {
defer {
head = head?.next
if isEmpty {
tail = nil
}
}
return head?.value
}
@discardableResult
public mutating func removeLast() -> Value? {
guard let head = head else {
return nil
}
guard head.next != nil else {
return pop()
}
var prev = head
var current = head
while let next = current.next {
prev = current
current = next
}
prev.next = nil
tail = prev
return current.value
}
@discardableResult
public mutating func remove(after node: Node<Value>) -> Value? {
defer {
if node.next === tail {
tail = node
}
node.next = node.next?.next
}
return node.next?.value
}
public mutating func remove(node: Node<Value>) {
while let head = head, head === node {
self.head = head.next
}
var prev = head
var current = head?.next
while let currentNode = current {
guard currentNode !== node else {
prev?.next = currentNode.next
current = prev?.next
continue
}
prev = current
current = current?.next
}
}
func getNodes() -> Int {
var count = 0
var temp = head
repeat {
count += 1
temp = temp?.next
} while temp != nil
return count
}
}
extension LinkedList: CustomStringConvertible {
public var description: String {
guard let head = head else {
return "Empty list"
}
return String(describing: head)
}
}
extension LinkedList {
public mutating func reverse() {
var prev = head
var current = head?.next
prev?.next = nil
while current != nil {
let next = current?.next
current?.next = prev
prev = current
current = next
}
head = prev
}
public mutating func remove(value: Value) {
while let head = head, head.value == value {
self.head = head.next
}
var prev = head
var current = head?.next
while let currentNode = current {
guard currentNode.value != value else {
prev?.next = currentNode.next
current = prev?.next
continue
}
prev = current
current = current?.next
}
}
}
extension LinkedList {
static public func +=( lhs: inout LinkedList<Value>, rhs: LinkedList<Value>) {
var current = rhs.head
while let c = current {
lhs.append(c.value)
current = current?.next
}
}
public static func +(lhs: LinkedList<Value>, rhs: LinkedList<Value>) -> LinkedList<Value> {
var joined = LinkedList()
var current = lhs.head
while let c = current {
joined.append(c.value)
current = current?.next
}
current = rhs.head
while let c = current {
joined.append(c.value)
current = current?.next
}
return joined
}
public static func sortedMerge(first: LinkedList<Value>, second: LinkedList<Value>) -> LinkedList<Value> {
var mergedList = LinkedList<Value>()
var cFirst = first.head
var cSecond = second.head
while cFirst != nil || cSecond != nil {
if cFirst == nil {
mergedList.append(cSecond!.value)
cSecond = cSecond?.next
} else if cSecond == nil {
mergedList.append(cFirst!.value)
cFirst = cFirst?.next
} else if cFirst!.value < cSecond!.value {
mergedList.append(cFirst!.value)
cFirst = cFirst?.next
} else {
mergedList.append(cSecond!.value)
cSecond = cSecond?.next
}
}
return mergedList
}
}
extension LinkedList {
public static func intersect(first: LinkedList<Value>, second: LinkedList<Value>) -> Node<Value>? {
let firstLength = first.count
let secondLength = second.count
print(firstLength)
print(secondLength)
var diff = 0
if firstLength > secondLength {
diff = firstLength - secondLength
print(diff)
return getIntersectNode(first: first, second: second, diff: diff)
} else {
diff = secondLength - firstLength
return getIntersectNode(first: second, second: first, diff: diff)
}
}
private static func getIntersectNode(first: LinkedList<Value>, second: LinkedList<Value>, diff: Int) -> Node<Value>? {
var head1 = first.head
var head2 = second.head
for _ in 0..<diff {
head1 = head1?.next
}
while head1 != nil && head2 != nil {
if head1 === head2 {
return head1
}
head1 = head1?.next
head2 = head2?.next
}
return nil
}
}
infix operator ⊕
extension LinkedList {
public mutating func removeDuplicates() {
var current = head
var arr = [Node<Value>]()
while current != nil {
if arr.contains(current!) {
remove(node: current!)
} else {
arr.append(current!)
}
current = current!.next
}
}
public mutating func deleteMiddleElement() {
var current = head
var current2 = head
var currentPrevious = current2
while current2 != nil {
currentPrevious = current
current = current?.next
current2 = current2?.next?.next
}
currentPrevious?.next = current?.next
}
public mutating func partition(at: Value) {
var list1 = LinkedList<Value>()
var current = head
while current != nil {
if current!.value < at {
list1.push(current!.value)
} else {
list1.append(current!.value)
}
current = current?.next
}
self.head = list1.head
}
public static func sum(lhs: LinkedList<Int>, rhs: LinkedList<Int>) -> LinkedList<Int> {
var result = LinkedList<Int>()
var carryForward = 0
var current1 = lhs.head
var current2 = rhs.head
while current1 != nil && current2 != nil {
let tempResult = current1!.value + current2!.value + carryForward
let resultNode = tempResult % 10
carryForward = (tempResult - resultNode) / 10
result.append(resultNode)
current1 = current1?.next
current2 = current2?.next
}
if carryForward > 0 {
result.append(carryForward)
}
return result
}
public var isPalindrome: Bool {
var reverse = LinkedList<Value>()
var current = head
while current != nil {
reverse.push(current!.value)
current = current!.next
}
var current1 = head
var current2 = reverse.head
while current1 != nil && current2 != nil {
if current1!.value != current2!.value {
return false
}
current1 = current1!.next
current2 = current2!.next
}
return true
}
}
| true
|
c70630cbeb02a41e697c18ee2bfa94b6d417602a
|
Swift
|
cup27551/QuarkAuthenticator-ios
|
/QuarkAuthenticator/QuarkAuthenticator/LFeatures/DisplayTime.swift
|
UTF-8
| 514
| 3.140625
| 3
|
[] |
no_license
|
//
// DisplayTime.swift
// QuarkAuthenticator
//
// Created by quark on 2019/7/12.
// Copyright © 2019 lsw. All rights reserved.
//
import Foundation
/// A simple value representing a moment in time, stored as the number of seconds since the epoch.
struct DisplayTime {
let timeIntervalSince1970: TimeInterval
init(date: Date) {
timeIntervalSince1970 = date.timeIntervalSince1970
}
var date: Date {
return Date(timeIntervalSince1970: timeIntervalSince1970)
}
}
| true
|
8fdf9e4ee2e34d72a9c6a6d01be83e4f07b0c2a0
|
Swift
|
megknoll/ga-mob-nyc-2
|
/07/Lesson07/Lesson07/FifthViewController.swift
|
UTF-8
| 1,199
| 2.75
| 3
|
[] |
no_license
|
//
// FifthViewController.swift
// Lesson07
//
// Created by Rudd Taylor on 9/30/14.
// Copyright (c) 2014 General Assembly. All rights reserved.
//
import UIKit
class FifthViewController: UIViewController {
var todoFive = [String]()
@IBOutlet weak var textView: UITextView!
var pathToFile : NSURL? {
get {
let fileName = "todoFive.plist"
let docDirectory = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as! NSURL
let url = docDirectory.URLByAppendingPathComponent(fileName)
return url
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
todoFive = split(textView.text) {$0 == " "}
if segue.identifier == "saveSegueTwo" {
println("starting save")
if self.pathToFile != nil {
(self.todoFive as NSArray).writeToURL(self.pathToFile!, atomically: true)
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
| true
|
9bba7fcd4b4419ad9d4df4c336d4e2c78dc21a71
|
Swift
|
Pypy233/DrawingTaggingPad
|
/DrawingTaggingPad/DrawingTaggingPad/AppDelegate.swift
|
UTF-8
| 5,240
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// AppDelegate.swift
// SwiftOneStroke
//
// Created by py on 2018/9/8.
// Copyright © 2018年 Yu Pan. All rights reserved.
//
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
//后台任务
var backgroundTask : UIBackgroundTaskIdentifier! = nil
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .badge, .sound]) { (resulet, error) in
if resulet {
print("register notification success")
}
else {
print("register notification fail error.localizedDescription:\(String(describing: error?.localizedDescription))")
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
//如果已存在后台任务,先将其设为完成
if self.backgroundTask != nil {
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
}
//注册后台任务
self.backgroundTask = application.beginBackgroundTask(expirationHandler: {
() -> Void in
//如果没有调用endBackgroundTask,时间耗尽时应用程序将被终止
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
})
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
print("shortcutItem.type: \(shortcutItem.type)")
}
// The method will be called on the delegate only if the application is in the foreground. If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user.
// app在前台运行时,收到通知会唤起该方法,但是前提是得 实现该方法 及 实现completionHandler
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void){
print("categoryIdentifier: \(notification.request.content.categoryIdentifier)")
completionHandler(.alert)
}
// The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:.
// 用户收到通知点击进入app的时候唤起,
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void) {
let catogoryIdentifier = response.notification.request.content.categoryIdentifier
if catogoryIdentifier == "local_notification" {
if response.actionIdentifier == "sure_action" {
print("response.actionIdentifier: sure_action")
}
}
completionHandler()
}
}
| true
|
ad239ed34c8831062e29e978d2c57f8be9dc5a0c
|
Swift
|
notkevinvu/SpacedRepetition
|
/Spaced Repetition/Services/MemoryDecksStore.swift
|
UTF-8
| 6,419
| 3.140625
| 3
|
[] |
no_license
|
//
// DecksMemStore.swift
// Spaced Repetition
//
// Created by Kevin Vu on 4/1/20.
// Copyright © 2020 An Nguyen. All rights reserved.
//
import Foundation
import CoreData
protocol DecksStoreFactory {
func makeDecksStore() -> DecksStoreProtocol
}
protocol CoreDataManagedContextFactory {
func makeManagedContext() -> NSManagedObjectContext
}
protocol DecksStoreProtocol {
var managedContext: NSManagedObjectContext! { get set }
func fetchDecks(completion: @escaping ([Deck]) -> () )
func createDeck() -> Deck?
}
// MARK: - TestDecksStore
final class TestDecksStore: DecksStoreProtocol {
typealias Factory = CoreDataManagedContextFactory
var managedContext: NSManagedObjectContext!
init(factory: Factory) {
self.managedContext = factory.makeManagedContext()
}
// MARK: - Core Data methods
static var decks: [Deck] = []
// MARK: Fetch decks
func fetchDecks(completion: @escaping ([Deck]) -> ()) {
let deckFetchReq = Deck.deckFetchRequest()
/*
a sort descriptor for sorting by "index" - as we add decks, we set the added
deck's deckIndex to the count of the current store (i.e. if there are currently
0 decks fetched, when we add the first deck, its index will be 0 - the
second deck will check the fetched decks array and find 1 deck, thus the
index of the second deck will become 1)
*/
let deckIndexSortDescriptor = NSSortDescriptor(key: #keyPath(Deck.deckIndex), ascending: true)
deckFetchReq.sortDescriptors = [deckIndexSortDescriptor]
deckFetchReq.fetchBatchSize = 10
let asyncFetchReq = NSAsynchronousFetchRequest<Deck>(fetchRequest: deckFetchReq) { (result: NSAsynchronousFetchResult) in
guard let decks = result.finalResult else { return }
TestDecksStore.decks = decks
completion(TestDecksStore.decks)
}
do {
try managedContext.execute(asyncFetchReq)
} catch let error as NSError {
assertionFailure("Failed to fetch decks \(#line), \(#file) - error: \(error) with desc \(error.userInfo)")
return
}
}
// MARK: Create deck
// create deck for test store makes a pre-populated deck
func createDeck() -> Deck? {
let card1 = Card(context: managedContext)
card1.initializeCardWith(frontSideText: "Test front 1 CD", backSideText: "Test back 1 CD", cardID: UUID(), dateCreated: Date())
let card2 = Card(context: managedContext)
card2.initializeCardWith(frontSideText: "Test front 2 CORE DATA", backSideText: "Test back 2 CORE DATA", cardID: UUID(), dateCreated: Date())
let card3 = Card(context: managedContext)
card3.initializeCardWith(frontSideText: "Lorem ipsum", backSideText: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", cardID: UUID(), dateCreated: Date())
let newDeck = Deck(context: managedContext)
newDeck.initializeDeckWithValues(name: "Untitled Deck", deckID: UUID(), dateCreated: Date(), deckIndex: TestDecksStore.decks.count, cards: [card1, card2, card3])
TestDecksStore.decks.append(newDeck)
do {
guard managedContext.hasChanges else { return nil }
try managedContext.save()
} catch let error as NSError {
assertionFailure("Error saving new deck \(#line), \(#file) - error: \(error) with desc: \(error.userInfo)")
return nil
}
return newDeck
}
}
// MARK: - MemoryDecksStore
final class MemoryDecksStore: DecksStoreProtocol {
typealias Factory = CoreDataManagedContextFactory
var managedContext: NSManagedObjectContext!
init(factory: Factory) {
self.managedContext = factory.makeManagedContext()
}
static var decks: [Deck] = []
// MARK: Fetch decks
func fetchDecks(completion: @escaping ([Deck]) -> () ) {
let deckFetchReq = Deck.deckFetchRequest()
/*
a sort descriptor for sorting by "index" - as we add decks, we set the added
deck's deckIndex to the count of the current store (i.e. if there are currently
0 decks fetched, when we add the first deck, its index will be 0 - the
second deck will check the fetched decks array and find 1 deck, thus the
index of the second deck will become 1)
*/
let deckIndexSortDescriptor = NSSortDescriptor(key: #keyPath(Deck.deckIndex), ascending: true)
deckFetchReq.sortDescriptors = [deckIndexSortDescriptor]
deckFetchReq.fetchBatchSize = 10
let asyncFetchReq = NSAsynchronousFetchRequest<Deck>(fetchRequest: deckFetchReq) { (result: NSAsynchronousFetchResult) in
guard let decks = result.finalResult else { return }
MemoryDecksStore.decks = decks
completion(MemoryDecksStore.decks)
}
do {
try managedContext.execute(asyncFetchReq)
} catch let error as NSError {
assertionFailure("Failed to fetch decks \(#line), \(#file) - error: \(error) with desc \(error.userInfo)")
return
}
}
// MARK: Create deck
func createDeck() -> Deck? {
let deck = Deck(context: managedContext)
deck.initializeDeckWithValues(name: "Untitled Deck", deckID: UUID(), dateCreated: Date(), deckIndex: MemoryDecksStore.decks.count, cards: [])
MemoryDecksStore.decks.append(deck)
do {
guard managedContext.hasChanges else { return nil }
try managedContext.save()
} catch let error as NSError {
assertionFailure("Error saving new deck \(#line), \(#file) - error: \(error) with desc: \(error.userInfo)")
return nil
}
return deck
}
}
| true
|
14330cad71d9186dfaf9aba72c60397fdc90d064
|
Swift
|
haduong825/WatchFaces
|
/WatchFaces/Extensions/UIView+AutoLayout.swift
|
UTF-8
| 4,495
| 2.6875
| 3
|
[] |
no_license
|
//
// UIView+AutoLayout.swift
// Prayer Times Reminder
//
// Created by Hussein Al-Ryalat on 8/6/18.
// Copyright © 2018 SketchMe. All rights reserved.
//
import UIKit
extension UIView {
func pinToSafeArea(top: CGFloat? = 0, left: CGFloat? = 0, bottom: CGFloat? = 0, right: CGFloat? = 0){
guard let superview = self.superview else { return }
prepareForAutoLayout()
var guide: UILayoutGuide
if #available(iOS 11.0, *) {
guide = superview.safeAreaLayoutGuide
} else {
guide = superview.layoutMarginsGuide
}
if let top = top {
self.topAnchor.constraint(equalTo: guide.topAnchor, constant: top).isActive = true
}
if let bottom = bottom {
self.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: bottom).isActive = true
}
if let left = left {
self.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: left).isActive = true
}
if let right = right {
self.trailingAnchor.constraint(equalTo: guide.trailingAnchor, constant: right).isActive = true
}
}
func pinToSuperView(top: CGFloat? = 0, left: CGFloat? = 0, bottom: CGFloat? = 0, right: CGFloat? = 0){
guard let superview = self.superview else { return }
prepareForAutoLayout()
if let top = top {
self.topAnchor.constraint(equalTo: superview.topAnchor, constant: top).isActive = true
}
if let bottom = bottom {
self.bottomAnchor.constraint(equalTo: superview.bottomAnchor, constant: bottom).isActive = true
}
if let left = left {
self.leadingAnchor.constraint(equalTo: superview.leadingAnchor, constant: left).isActive = true
}
if let right = right {
self.trailingAnchor.constraint(equalTo: superview.trailingAnchor, constant: right).isActive = true
}
}
func centerInSuperView(){
guard let superview = self.superview else { return }
prepareForAutoLayout()
self.centerXAnchor.constraint(equalTo: superview.centerXAnchor).isActive = true
self.centerYAnchor.constraint(equalTo: superview.centerYAnchor).isActive = true
}
func constraint(width: CGFloat){
prepareForAutoLayout()
self.widthAnchor.constraint(equalToConstant: width).isActive = true
}
func constraint(height: CGFloat){
prepareForAutoLayout()
self.heightAnchor.constraint(equalToConstant: height).isActive = true
}
func makeWidthEqualHeight(){
prepareForAutoLayout()
self.widthAnchor.constraint(equalTo: self.heightAnchor).isActive = true
}
func prepareForAutoLayout(){
translatesAutoresizingMaskIntoConstraints = false
}
}
@IBDesignable
class GradientView: UIView {
@IBInspectable var startColor: UIColor = .black { didSet { updateColors() }}
@IBInspectable var endColor: UIColor = .white { didSet { updateColors() }}
@IBInspectable var startLocation: Double = 0.05 { didSet { updateLocations() }}
@IBInspectable var endLocation: Double = 0.95 { didSet { updateLocations() }}
@IBInspectable var horizontalMode: Bool = false { didSet { updatePoints() }}
@IBInspectable var diagonalMode: Bool = false { didSet { updatePoints() }}
override public class var layerClass: AnyClass { CAGradientLayer.self }
var gradientLayer: CAGradientLayer { layer as! CAGradientLayer }
func updatePoints() {
if horizontalMode {
gradientLayer.startPoint = diagonalMode ? .init(x: 1, y: 0) : .init(x: 0, y: 0.5)
gradientLayer.endPoint = diagonalMode ? .init(x: 0, y: 1) : .init(x: 1, y: 0.5)
} else {
gradientLayer.startPoint = diagonalMode ? .init(x: 0, y: 0) : .init(x: 0.5, y: 0)
gradientLayer.endPoint = diagonalMode ? .init(x: 1, y: 1) : .init(x: 0.5, y: 1)
}
}
func updateLocations() {
gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
}
func updateColors() {
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
}
override public func layoutSubviews() {
super.layoutSubviews()
updatePoints()
updateLocations()
updateColors()
}
}
| true
|
4c42f0baf5b24d8dd8b002115c1cd3dd333891b5
|
Swift
|
TeaganBriggs/BitTrader
|
/BitTraderTests/NumberPadStateTests.swift
|
UTF-8
| 14,053
| 2.9375
| 3
|
[] |
no_license
|
//
// NumberPadStateTests.swift
// BitTrader
//
// Created by chako on 2016/10/15.
// Copyright © 2016年 Bit Trader. All rights reserved.
//
import XCTest
@testable import BitTrader
class NumberPadStateTests: XCTestCase {
func test初期値入力() {
let initialState = NumberPadState.CLEAR_STATE
// 初期値確認
XCTAssertEqual(initialState.inScreen, "", "initial state failure")
// addDot
XCTAssertEqual(initialState.tranformState(NumberPadAction.addDot).inScreen, "0.", "addDot failure")
// backspace
XCTAssertEqual(initialState.tranformState(NumberPadAction.backspace).inScreen, "", "backspace failure")
// clear
XCTAssertEqual(initialState.tranformState(NumberPadAction.clear).inScreen, "", "clear failure")
// number 0
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("0")).inScreen, "0", "number input 0 failure")
// number 1
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("1")).inScreen, "1", "number input 1 failure")
// number 2
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("2")).inScreen, "2", "number input 2 failure")
// number 3
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("3")).inScreen, "3", "number input 3 failure")
// number 4
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("4")).inScreen, "4", "number input 4 failure")
// number 5
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("5")).inScreen, "5", "number input 5 failure")
// number 6
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("6")).inScreen, "6", "number input 6 failure")
// number 7
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("7")).inScreen, "7", "number input 7 failure")
// number 8
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("8")).inScreen, "8", "number input 8 failure")
// number 9
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("9")).inScreen, "9", "number input 9 failure")
// number 000
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("000")).inScreen, "0", "number input 000 failure")
}
func test初期値0から入力() {
var initialState = NumberPadState.CLEAR_STATE
initialState = initialState.tranformState(NumberPadAction.addNumber("0"))
// 初期値確認
XCTAssertEqual(initialState.inScreen, "0", "initial state failure")
// addDot
XCTAssertEqual(initialState.tranformState(NumberPadAction.addDot).inScreen, "0.", "addDot failure")
// backspace
XCTAssertEqual(initialState.tranformState(NumberPadAction.backspace).inScreen, "", "backspace failure")
// clear
XCTAssertEqual(initialState.tranformState(NumberPadAction.clear).inScreen, "", "clear failure")
// number 0
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("0")).inScreen, "0", "number input 0 failure")
// number 1
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("1")).inScreen, "1", "number input 1 failure")
// number 2
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("2")).inScreen, "2", "number input 2 failure")
// number 3
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("3")).inScreen, "3", "number input 3 failure")
// number 4
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("4")).inScreen, "4", "number input 4 failure")
// number 5
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("5")).inScreen, "5", "number input 5 failure")
// number 6
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("6")).inScreen, "6", "number input 6 failure")
// number 7
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("7")).inScreen, "7", "number input 7 failure")
// number 8
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("8")).inScreen, "8", "number input 8 failure")
// number 9
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("9")).inScreen, "9", "number input 9 failure")
// number 000
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("000")).inScreen, "0", "number input 000 failure")
}
func test初期値数値から入力() {
var initialState = NumberPadState.CLEAR_STATE
initialState = initialState.tranformState(NumberPadAction.addNumber("1"))
// 初期値確認
XCTAssertEqual(initialState.inScreen, "1", "initial state failure")
// addDot
XCTAssertEqual(initialState.tranformState(NumberPadAction.addDot).inScreen, "1.", "addDot failure")
// backspace
XCTAssertEqual(initialState.tranformState(NumberPadAction.backspace).inScreen, "", "backspace failure")
// clear
XCTAssertEqual(initialState.tranformState(NumberPadAction.clear).inScreen, "", "clear failure")
// number 0
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("0")).inScreen, "10", "number input 0 failure")
// number 1
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("1")).inScreen, "11", "number input 1 failure")
// number 2
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("2")).inScreen, "12", "number input 2 failure")
// number 3
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("3")).inScreen, "13", "number input 3 failure")
// number 4
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("4")).inScreen, "14", "number input 4 failure")
// number 5
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("5")).inScreen, "15", "number input 5 failure")
// number 6
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("6")).inScreen, "16", "number input 6 failure")
// number 7
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("7")).inScreen, "17", "number input 7 failure")
// number 8
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("8")).inScreen, "18", "number input 8 failure")
// number 9
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("9")).inScreen, "19", "number input 9 failure")
// number 000
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("000")).inScreen, "1000", "number input 000 failure")
}
func test初期値整数部複数桁から入力() {
var initialState = NumberPadState.CLEAR_STATE
initialState = initialState.tranformState(NumberPadAction.addNumber("1"))
initialState = initialState.tranformState(NumberPadAction.addNumber("2"))
// 初期値確認
XCTAssertEqual(initialState.inScreen, "12", "initial state failure")
// addDot
XCTAssertEqual(initialState.tranformState(NumberPadAction.addDot).inScreen, "12.", "addDot failure")
// backspace
XCTAssertEqual(initialState.tranformState(NumberPadAction.backspace).inScreen, "1", "backspace failure")
// clear
XCTAssertEqual(initialState.tranformState(NumberPadAction.clear).inScreen, "", "clear failure")
// number 0
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("0")).inScreen, "120", "number input 0 failure")
// number 1
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("1")).inScreen, "121", "number input 1 failure")
// number 2
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("2")).inScreen, "122", "number input 2 failure")
// number 3
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("3")).inScreen, "123", "number input 3 failure")
// number 4
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("4")).inScreen, "124", "number input 4 failure")
// number 5
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("5")).inScreen, "125", "number input 5 failure")
// number 6
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("6")).inScreen, "126", "number input 6 failure")
// number 7
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("7")).inScreen, "127", "number input 7 failure")
// number 8
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("8")).inScreen, "128", "number input 8 failure")
// number 9
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("9")).inScreen, "129", "number input 9 failure")
// number 000
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("000")).inScreen, "12000", "number input 000 failure")
}
func test初期値小数点ありから入力() {
var initialState = NumberPadState.CLEAR_STATE
initialState = initialState.tranformState(NumberPadAction.addDot)
// 初期値確認
XCTAssertEqual(initialState.inScreen, "0.", "initial state failure")
// addDot
XCTAssertEqual(initialState.tranformState(NumberPadAction.addDot).inScreen, "0.", "addDot failure")
// backspace
XCTAssertEqual(initialState.tranformState(NumberPadAction.backspace).inScreen, "0", "backspace failure")
// clear
XCTAssertEqual(initialState.tranformState(NumberPadAction.clear).inScreen, "", "clear failure")
// number 0
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("0")).inScreen, "0.0", "number input 0 failure")
// number 1
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("1")).inScreen, "0.1", "number input 1 failure")
// number 2
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("2")).inScreen, "0.2", "number input 2 failure")
// number 3
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("3")).inScreen, "0.3", "number input 3 failure")
// number 4
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("4")).inScreen, "0.4", "number input 4 failure")
// number 5
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("5")).inScreen, "0.5", "number input 5 failure")
// number 6
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("6")).inScreen, "0.6", "number input 6 failure")
// number 7
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("7")).inScreen, "0.7", "number input 7 failure")
// number 8
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("8")).inScreen, "0.8", "number input 8 failure")
// number 9
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("9")).inScreen, "0.9", "number input 9 failure")
// number 000
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("000")).inScreen, "0.000", "number input 000 failure")
}
func test初期値小数点ありの小数部複数桁から入力() {
var initialState = NumberPadState.CLEAR_STATE
initialState = initialState.tranformState(NumberPadAction.addDot)
initialState = initialState.tranformState(NumberPadAction.addNumber("3"))
// 初期値確認
XCTAssertEqual(initialState.inScreen, "0.3", "initial state failure")
// addDot
XCTAssertEqual(initialState.tranformState(NumberPadAction.addDot).inScreen, "0.3", "addDot failure")
// backspace
XCTAssertEqual(initialState.tranformState(NumberPadAction.backspace).inScreen, "0.", "backspace failure")
// clear
XCTAssertEqual(initialState.tranformState(NumberPadAction.clear).inScreen, "", "clear failure")
// number 0
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("0")).inScreen, "0.30", "number input 0 failure")
// number 1
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("1")).inScreen, "0.31", "number input 1 failure")
// number 2
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("2")).inScreen, "0.32", "number input 2 failure")
// number 3
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("3")).inScreen, "0.33", "number input 3 failure")
// number 4
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("4")).inScreen, "0.34", "number input 4 failure")
// number 5
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("5")).inScreen, "0.35", "number input 5 failure")
// number 6
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("6")).inScreen, "0.36", "number input 6 failure")
// number 7
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("7")).inScreen, "0.37", "number input 7 failure")
// number 8
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("8")).inScreen, "0.38", "number input 8 failure")
// number 9
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("9")).inScreen, "0.39", "number input 9 failure")
// number 000
XCTAssertEqual(initialState.tranformState(NumberPadAction.addNumber("000")).inScreen, "0.3000", "number input 000 failure")
}
}
| true
|
6eb39bec896160582ffc63c6e665b9fec87cf2a4
|
Swift
|
organicmaps/organicmaps
|
/iphone/Maps/Bookmarks/Categories/BMCViewModel/BMCDefaultViewModel.swift
|
UTF-8
| 4,739
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
protocol BMCView: AnyObject {
func update(sections: [BMCSection])
func delete(at indexPaths: [IndexPath])
func insert(at indexPaths: [IndexPath])
func conversionFinished(success: Bool)
}
enum BMCShareCategoryStatus {
case success(URL)
case error(title: String, text: String)
}
final class BMCDefaultViewModel: NSObject {
private let manager = BookmarksManager.shared()
weak var view: BMCView?
private var sections: [BMCSection] = []
private var categories: [BookmarkGroup] = []
private var actions: [BMCAction] = []
private var notifications: [BMCNotification] = []
private(set) var isPendingPermission = false
private var isAuthenticated = false
private var filesPrepared = false
typealias OnPreparedToShareHandler = (BMCShareCategoryStatus) -> Void
private var onPreparedToShareCategory: OnPreparedToShareHandler?
let minCategoryNameLength: UInt = 0
let maxCategoryNameLength: UInt = 60
override init() {
super.init()
reloadData()
}
private func setCategories() {
categories = manager.userCategories()
}
private func setActions() {
actions = [.create]
}
private func setNotifications() {
notifications = [.load]
}
func reloadData() {
sections = []
if manager.areBookmarksLoaded() {
sections.append(.categories)
setCategories()
sections.append(.actions)
setActions()
} else {
sections.append(.notifications)
setNotifications()
}
view?.update(sections: [])
}
}
extension BMCDefaultViewModel {
func numberOfSections() -> Int {
return sections.count
}
func sectionType(section: Int) -> BMCSection {
return sections[section]
}
func sectionIndex(section: BMCSection) -> Int {
return sections.firstIndex(of: section)!
}
func numberOfRows(section: Int) -> Int {
return numberOfRows(section: sectionType(section: section))
}
func numberOfRows(section: BMCSection) -> Int {
switch section {
case .categories: return categories.count
case .actions: return actions.count
case .notifications: return notifications.count
}
}
func category(at index: Int) -> BookmarkGroup {
return categories[index]
}
func action(at index: Int) -> BMCAction {
return actions[index]
}
func notification(at index: Int) -> BMCNotification {
return notifications[index]
}
func areAllCategoriesHidden() -> Bool {
var result = true
categories.forEach { if $0.isVisible { result = false } }
return result
}
func updateAllCategoriesVisibility(isShowAll: Bool) {
manager.setUserCategoriesVisible(isShowAll)
}
func addCategory(name: String) {
guard let section = sections.firstIndex(of: .categories) else {
assertionFailure()
return
}
categories.append(manager.category(withId: manager.createCategory(withName: name)))
view?.insert(at: [IndexPath(row: categories.count - 1, section: section)])
}
func deleteCategory(at index: Int) {
guard let section = sections.firstIndex(of: .categories) else {
assertionFailure()
return
}
let category = categories[index]
categories.remove(at: index)
manager.deleteCategory(category.categoryId)
view?.delete(at: [IndexPath(row: index, section: section)])
}
func checkCategory(name: String) -> Bool {
return manager.checkCategoryName(name)
}
func shareCategoryFile(at index: Int, handler: @escaping OnPreparedToShareHandler) {
let category = categories[index]
onPreparedToShareCategory = handler
manager.shareCategory(category.categoryId)
}
func finishShareCategory() {
manager.finishShareCategory()
onPreparedToShareCategory = nil
}
func addToObserverList() {
manager.add(self)
}
func removeFromObserverList() {
manager.remove(self)
}
func setNotificationsEnabled(_ enabled: Bool) {
manager.setNotificationsEnabled(enabled)
}
func areNotificationsEnabled() -> Bool {
return manager.areNotificationsEnabled()
}
}
extension BMCDefaultViewModel: BookmarksObserver {
func onBookmarksLoadFinished() {
reloadData()
}
func onBookmarkDeleted(_: MWMMarkID) {
reloadData()
}
func onBookmarksCategoryFilePrepared(_ status: BookmarksShareStatus) {
switch status {
case .success:
onPreparedToShareCategory?(.success(manager.shareCategoryURL()))
case .emptyCategory:
onPreparedToShareCategory?(.error(title: L("bookmarks_error_title_share_empty"), text: L("bookmarks_error_message_share_empty")))
case .archiveError: fallthrough
case .fileError:
onPreparedToShareCategory?(.error(title: L("dialog_routing_system_error"), text: L("bookmarks_error_message_share_general")))
}
}
}
| true
|
b553dcab989c0e112badbfcb5e9530a6de18315b
|
Swift
|
kill60673/LaviLogiOS-TeamProject-
|
/LaviLog/JheJhen/Model/FirebaseWorks.swift
|
UTF-8
| 5,261
| 2.890625
| 3
|
[] |
no_license
|
//
// FirebaseWorks.swift
// SignInExample
//
// Created by JerryWang on 2017/2/22.
// Copyright © 2017年 Jerrywang. All rights reserved.
//
import Foundation
import Firebase
import FacebookLogin
import FacebookCore
import GoogleSignIn
var userAccount:String!
//import GoogleSignIn
let firebaseWorks = FirebaseWorks()
enum Result{
case success
case fail
case fail_changePW
}
class FirebaseWorks{
func signInFireBaseWithFB(completion: @escaping (_ result: Result) -> ()){
let fbAccessToken = AccessToken.current
guard let fbAccessTokenString = fbAccessToken?.tokenString else { return }
let fbCredentials = FacebookAuthProvider.credential(withAccessToken: fbAccessTokenString)
firebaseSignInWithCredential(credential: fbCredentials, completion: completion)
}
func signInFireBaseWithGoogle(user: GIDGoogleUser,completion: @escaping (_ result: Result) -> ()){
print("google1")
guard let authentication = user.authentication else { return }
let googleCredential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
print("google2")
firebaseSignInWithCredential(credential: googleCredential, completion: completion)
}
func firebaseSignInWithCredential(credential: AuthCredential,completion: @escaping (_ result: Result) -> ()){
print("google3")
Auth.auth().signIn(with: credential, completion: { (profile, error) in
if error != nil {
//登入失敗 請重新登入
completion(Result.fail_changePW)
print("Something went wrong with our FB user: ", error ?? "")
return
}else{
completion(Result.success)
let user = profile?.user
print(profile?.credential!)
print("Successfully logged in with our user: ", user ?? "")
let request = GraphRequest(graphPath: "me", parameters: ["fields": "id, email, name, picture.type(large)"])
request.start { (response, result, error) in
var imagePathString = "no_image.jpg"
if let result = result as? [String : Any] {
print("account",result["email"] as! String)
userAccount = result["email"] as! String
var data = Data()
// 若沒有照片檔案可以讀取,就讓要傳的data為空值
if let imageURLString = ((result["picture"] as? [String: Any])?["data"] as? [String: Any])?["url"] as? String {
if let imageURL = URL(string: imageURLString),let imageData = try? Data(contentsOf: imageURL) {
imagePathString = "/images_users/\(userAccount!).jpg"
data = imageData
}
}
print("看userAccount",userAccount!)
let db = Firestore.firestore()
let reference = db.collection("users").document()
let id = reference.documentID
let dicFirebase = ["account":userAccount,"birthDay":"未填","gender":"未填","id":id,"imagePath":imagePathString,"name":user?.displayName,"password":"FB","phone":"未填","status":"0","verificationCode":"","verificationId":""]
db.collection("users").whereField("account", isEqualTo: userAccount!).getDocuments { (querySnapshot, error) in
if let querySnapshot = querySnapshot {
let document = querySnapshot.documents.first
if document != nil{
print("不用再存 ",document)
}else{
let imagePath = Storage.storage().reference().child("images_users/\(userAccount!).jpg")
let metaData = StorageMetadata()
metaData.contentType = "image/jpg"
imagePath.putData(data, metadata: metaData) { (data, error) in
guard error == nil else { return }
print("照片放成功")
imagePath.downloadURL { (url, error) in
print("\(url!)")
}
}
db.collection("users").document(id).setData(dicFirebase) { (error) in
if error != nil {
print(error?.localizedDescription)
} else {
print("資料有存成功")
}
}
}
}
}
}
}
}
})
}
}
| true
|
3a8ad78d8c991934a1cf641f6dacf7ba99030bbf
|
Swift
|
gengwang/ARCompass
|
/ARCompass/ViewController.swift
|
UTF-8
| 4,272
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// testLazyAnimation
//
// Created by Geng Wang on 12/28/18.
// Copyright © 2018 Geng Wang. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSCNViewDelegate {
@IBOutlet var sceneView: ARSCNView!
var animations = [String: CAAnimation]()
var isOpening = false
fileprivate func setupScene() {
guard let dataURL = Bundle.main.url(forResource: "compass", withExtension: "dae", subdirectory: "art.scnassets/compass") else { return }
guard let data = SCNSceneSource(url: dataURL, options: [SCNSceneSource.LoadingOption.animationImportPolicy: SCNSceneSource.AnimationImportPolicy.doNotPlay]),
let compassNode = data.entryWithIdentifier("Dice", withClass: SCNNode.self),
let lightNode = data.entryWithIdentifier("Light", withClass: SCNNode.self)
else { return }
sceneView.scene.rootNode.addChildNode(lightNode)
sceneView.scene.rootNode.addChildNode(compassNode)
// Load animations
if let animationObj = data.entryWithIdentifier("open_cover", withClass: CAAnimation.self) {
animationObj.fillMode = .forwards
animationObj.isRemovedOnCompletion = false
animations["open"] = animationObj
}
// Placement animation
let delay = SCNAction.wait(duration: 1)
let rotation = SCNAction.rotateBy(x: 0, y: 180 * .pi/180, z: 0, duration: 1)
let moveIn = SCNAction.move(to: SCNVector3(0, -0.1, -0.2), duration: 1)
let inAction = SCNAction.group([rotation, moveIn])
compassNode.runAction(SCNAction.sequence([delay, inAction]))
}
private func setupGestureRecognizers() {
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.handleTap(recognizer:)))
sceneView.addGestureRecognizer(tapRecognizer)
}
// TODO: to get animation events, use SCNAnimation and maybe also SCNAnimationPlayer
@objc private func handleTap(recognizer: UITapGestureRecognizer) {
guard let openAnimation = animations["open"] else { return }
if (!isOpening) {
sceneView.scene.rootNode.removeAnimation(forKey: "close")
animations["open"]?.speed = 1
sceneView.scene.rootNode.addAnimation(openAnimation, forKey: "open")
isOpening = true
} else {
sceneView.scene.rootNode.removeAnimation(forKey: "open")
animations["open"]?.speed = -1
sceneView.scene.rootNode.addAnimation(openAnimation, forKey: "close")
isOpening = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Set the view's delegate
sceneView.delegate = self
// Show statistics such as fps and timing information
sceneView.showsStatistics = true
setupScene()
setupGestureRecognizers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Create a session configuration
let configuration = ARWorldTrackingConfiguration()
// Run the view's session
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Pause the view's session
sceneView.session.pause()
}
// MARK: - ARSCNViewDelegate
/*
// Override to create and configure nodes for anchors added to the view's session.
func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
let node = SCNNode()
return node
}
*/
func session(_ session: ARSession, didFailWithError error: Error) {
// Present an error message to the user
}
func sessionWasInterrupted(_ session: ARSession) {
// Inform the user that the session has been interrupted, for example, by presenting an overlay
}
func sessionInterruptionEnded(_ session: ARSession) {
// Reset tracking and/or remove existing anchors if consistent tracking is required
}
}
| true
|
2aea48c87b874ff7bcf889ba3284f034e7393398
|
Swift
|
rjmendus/Infinity-Workshop-iOS
|
/Bootcamp/Controller/LoginViewController.swift
|
UTF-8
| 3,433
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
// LoginViewController.swift
// Bootcamp
//
// Created by Rajat Jaic Mendus on 11/2/18.
// Copyright © 2018 IODevelopers. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class LoginViewController: UIViewController {
@IBOutlet weak var LoginContainer: UIView!
@IBOutlet weak var admissionTextField: UITextField!
@IBAction func submitLoginButton(_ sender: Any) {
print("Login Pressed")
guard let admissionNumber = admissionTextField.text, !admissionNumber.isEmpty else {
showAlert(alertTitle: "Null entry", alertMessage: "Please enter your admission number", alertAction: "Ok")
return
}
checkForValidUser(userAdmissionNumber: admissionNumber)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setContainerShadowAndRoundedEdges(container: LoginContainer)
admissionTextField.borderStyle = UITextField.BorderStyle.none
}
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: animated)
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: animated)
super.viewWillDisappear(animated)
}
func setContainerShadowAndRoundedEdges(container: UIView) {
// Set rounded corners at top right and bottom right
container.layer.cornerRadius = 20
container.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMaxXMinYCorner]
// Set container shadow
container.layer.shadowColor = UIColor.black.cgColor
container.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
container.layer.shadowRadius = 4.0
container.layer.shadowOpacity = 0.2
}
func checkForValidUser(userAdmissionNumber: String) {
let parameters: Parameters = ["Idno": userAdmissionNumber]
let url = Constants.loginAPI
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).validate().responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
print("LoginAPIJSON: \(json)")
if (json["statusCode"] == 200) {
print("Login Successfull")
UserDefaults.standard.set(userAdmissionNumber, forKey: "UserAdmissionNumber")
self.performSegue(withIdentifier: "loginToHomeSegue", sender: self)
}
else {
print("Invalid credentials")
self.showAlert(alertTitle: "Invalid credentials", alertMessage: "Invalid admission number", alertAction: "Ok")
}
case .failure(let error):
print(error)
}
}
}
func showAlert(alertTitle: String, alertMessage: String, alertAction: String) {
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: alertAction, style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
| true
|
aaad360e8801a08ae81c48ed7f6147fdd1db1cc9
|
Swift
|
annachiuu/tictactoe
|
/TTT/references.swift
|
UTF-8
| 876
| 2.609375
| 3
|
[] |
no_license
|
/*
Learning the MiniMax algorithm
https://www.youtube.com/watch?v=cGN6LfnOPeo
http://www.flyingmachinestudios.com/programming/minimax/
How to create a tree structure in Swift: https://www.raywenderlich.com/138190/swift-algorithm-club-swift-tree-data-structure
- didin't end up using
Copied code for passing NSObject classes by VALUE: https://www.hackingwithswift.com/example-code/system/how-to-copy-objects-in-swift-using-copy
- didn't end up using
Swift command line tutorial: https://www.raywenderlich.com/163134/command-line-programs-macos-tutorial-2
alpha - beta pruning:
http://inst.eecs.berkeley.edu/~cs61b/fa14/ta-materials/apps/ab_tree_practice/
https://www.youtube.com/watch?v=xBXHtz4Gbdo
Loop breaking in swift: https://stackoverflow.com/questions/24049629/how-to-break-outer-loops-from-inner-structures-that-respond-break-loops-switch
*/
| true
|
a65bc1e264ef20853319b574dd4345e9759369c3
|
Swift
|
NeuralSilicon/FuelPricePrediction
|
/FuelRate/Model/Client/PasswordEncryption.swift
|
UTF-8
| 643
| 2.96875
| 3
|
[] |
no_license
|
//Ian cooper
import UIKit
import CryptoSwift
class Encryption{
func aesEncrypt(KEY:String, IV:String, password:String) throws -> String {
let encrypted = try AES(key: KEY, iv: IV, padding: .pkcs7).encrypt([UInt8](password.data(using: .utf8)!))
return Data(encrypted).base64EncodedString()
}
func aesDecrypt(KEY:String, IV:String, password:String) throws -> String {
guard let data = Data(base64Encoded: password) else { return "" }
let decrypted = try AES(key: KEY, iv: IV, padding: .pkcs7).decrypt([UInt8](data))
return String(bytes: decrypted, encoding: .utf8) ?? password
}
}
| true
|
7cd581306359e7642451d963c00cd53368076de0
|
Swift
|
ebrahim2910/realmTask
|
/Task/Players.swift
|
UTF-8
| 547
| 2.96875
| 3
|
[] |
no_license
|
//
// Players.swift
// Bundesliga App
//
// Created by Admin on 11/25/17.
// Copyright © 2017 ITI. All rights reserved.
//
import Foundation
class Players {
var playerName : String
var playerPosition :String
init(playerName :String, playerPosition :String ){
self.playerName = playerName
self.playerPosition = playerPosition
}
var titleFirstLetter: String {
return String(self.playerName[self.playerName.startIndex]).uppercased()
}
}
| true
|
0bd416c643412a6dc689d58299f1cade836ebce1
|
Swift
|
fran2711/HackerBooksLite
|
/HackerBooks/Book.swift
|
UTF-8
| 4,515
| 3.015625
| 3
|
[] |
no_license
|
//
// Book.swift
// HackerBooks
//
// Created by Fran Lucena on 1/2/17.
// Copyright © 2017 Fran Lucena. All rights reserved.
//
import Foundation
import UIKit
typealias Title = String
typealias Author = String
typealias Authors = [Author]
typealias PDF = AsyncData
typealias Cover = AsyncData
class Book {
//MARK: - Attributes
let _authors: Authors
let _title: Title
var _tags: Tags
let _pdf: PDF
let _cover: Cover
weak var delegate: BookDelegate?
var tags: Tags{
return _tags
}
var title: Title {
return _title
}
init(title: Title, authors: Authors, tags: Tags, pdf: PDF, cover: Cover) {
(_title, _authors, _tags, _pdf, _cover) = (title, authors, tags, pdf, cover)
// Set Delegate
_cover.delegate = self
_pdf.delegate = self
}
func formattedListOfAuthors() -> String {
return _authors.sorted().joined(separator: ", ").capitalized
}
func formattedListOfTags() -> String {
return _tags.sorted().map{$0._name}.joined(separator: ", ").capitalized
}
}
// MARK: - Favorites
extension Book{
private func hasFavoriteTag()-> Bool {
return _tags.contains(Tag.favoriteTag())
}
private func addFavoriteTag(){
_tags.insert(Tag.favoriteTag())
}
private func removeFavoriteTag() {
_tags.remove(Tag.favoriteTag())
}
var isFavorite: Bool {
get{
return hasFavoriteTag()
}
set {
if newValue == true {
addFavoriteTag()
sendNotification(name: BookDidChange)
}else{
removeFavoriteTag()
sendNotification(name: BookDidChange)
}
}
}
}
// MARK: - Protocols
extension Book: Hashable {
var proxyForHasing: String {
return "\(_title)\(_authors)"
}
var hashValue: Int {
return proxyForHasing.hashValue
}
}
extension Book: Equatable {
var proxyForComparision: String {
return "\(isFavorite ? "A" : "Z")\(_title)\(formattedListOfAuthors())"
}
static func == (lhs: Book, rhs: Book) -> Bool {
return lhs.proxyForComparision == rhs.proxyForComparision
}
}
extension Book: Comparable {
static func < (lhs: Book, rhs: Book) -> Bool {
return lhs.proxyForComparision < rhs.proxyForComparision
}
}
// MARK: - Comunication - Delegate
protocol BookDelegate: class {
func bookDidChange(sender: Book)
func bookCoverImageDidDownload(sender: Book)
func bookPDFDidDownload(sender: Book)
}
extension BookDelegate{
func bookDidChange(sender: Book){}
func bookCoverImageDidDownload(sender: Book){}
func bookPDFDidDownload(sender: Book){}
}
let BookDidChange = Notification.Name(rawValue: "com.franlucenadejuan.BookDidChange")
let BookKey = "com.franlucenadejuan.BookKey"
let BookCoverImageDidDownload = Notification.Name(rawValue: "com.franlucenadejuan.BookCoverImageDidDownload")
let BookPDFDidDownload = Notification.Name(rawValue: "com.franlucenadejuan.BookPDFDidDownload")
extension Book {
func sendNotification(name: Notification.Name) {
let notification = Notification(name: name, object: self, userInfo: [BookKey: self])
let notificationCenter = NotificationCenter.default
notificationCenter.post(notification)
}
}
// MARK: - AsyncDataDelegate
extension Book: AsyncDataDelegate {
func asyncData(_ sender: AsyncData, didEndLoadingFrom url: URL) {
let notificationName: Notification.Name
switch sender {
case _cover:
notificationName = BookCoverImageDidDownload
delegate?.bookCoverImageDidDownload(sender: self)
case _pdf:
notificationName = BookPDFDidDownload
delegate?.bookPDFDidDownload(sender: self)
default:
fatalError("Fatal Error")
}
sendNotification(name: notificationName)
}
func asyncData(_ sender: AsyncData, shouldStartLoadingFrom url: URL) -> Bool {
return true
}
func asyncData(_ sender: AsyncData, willStartLoadingFrom url: URL) {
print("Loading from \(url)")
}
func asyncData(_ sender: AsyncData, didFailLoadingFrom url: URL, error: NSError) {
print("Error loading from \(url)")
}
}
| true
|
e8720e2aeff8bff42b06c5b18181e30926a43e57
|
Swift
|
skasriel/Sapristi-iOS
|
/ConfigManager.swift
|
UTF-8
| 3,065
| 2.609375
| 3
|
[] |
no_license
|
//
// ConfigManager.swift
// Sapristi
//
// Created by Stephane Kasriel on 10/8/14.
// Copyright (c) 2014 Stephane Kasriel. All rights reserved.
//
import Foundation
import UIKit
let CONFIG_TIMESLOT = "timeslotEnabled"
let CONFIG_CALENDAR = "calendarEnabled"
let CONFIG_CAR_MOTION = "carMotionEnabled"
let CONFIG_USERNAME = "username"
let CONFIG_PWD = "authToken"
let CONFIG_SELECTED_TAB = "selectedTab"
class ConfigManager {
class func getIntConfigValue(key: String, defaultValue: Int) -> Int {
let userDefaults = NSUserDefaults.standardUserDefaults();
let value = userDefaults.objectForKey(key) as Int?
if (value == nil) {
return defaultValue
}
return value! as Int
}
class func setIntConfigValue(key: String, newValue: Int) {
let userDefaults = NSUserDefaults.standardUserDefaults();
userDefaults.setObject(newValue, forKey: key)
userDefaults.synchronize()
}
class func getBoolConfigValue(key: String) -> Bool {
let userDefaults = NSUserDefaults.standardUserDefaults();
let value = userDefaults.objectForKey(key) as Bool?
if (value == nil) {
return false
}
return value! as Bool
}
class func setBoolConfigValue(key: String, newValue: Bool) {
let userDefaults = NSUserDefaults.standardUserDefaults();
userDefaults.setObject(newValue, forKey: key)
userDefaults.synchronize()
}
class func showButton(button: UIButton, isChecked: Bool) {
if (isChecked) {
button.setImage(UIImage(named: "Checkbox_checked"), forState: UIControlState.Normal)
} else {
button.setImage(UIImage(named: "Checkbox_unchecked"), forState: UIControlState.Normal)
}
}
class func doLogout() {
let userDefaults = NSUserDefaults.standardUserDefaults();
userDefaults.removeObjectForKey(CONFIG_USERNAME)
userDefaults.removeObjectForKey(CONFIG_PWD)
userDefaults.synchronize()
// TODO: Other values to delete here? Clear CoreData?
}
}
func colorWithHexString (hex:String) -> UIColor {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (countElements(cString) != 6) {
return UIColor.grayColor()
}
var rString = (cString as NSString).substringToIndex(2)
var gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
var bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
| true
|
a2f25195b74f60ea6430451c473ab388f71545c4
|
Swift
|
ddropx/HomeworkRepo
|
/swift_24.playground/Contents.swift
|
UTF-8
| 1,917
| 4.21875
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
// Задание - Создайте расширение для Int со свойствами isNegative, isPositive, которые должны возвращать Bool. Добавьте свойство, которое возвращает количество символов в числе. Добавьте метод, который возвращает символ числа по индексу. Добавить стрингу метод truncate, чтобы отрезал лишние символы и, если таковые были, заменял их на троеточие.
extension Int {
var isPositive: Bool {
return self > 0
}
var isNegative: Bool {
return !isPositive
}
var checkForValid: Bool {
return self != 0
}
var symbolCount: Int {
return String(self).count
}
subscript(symbolForIndex: Int) -> Int {
var symbol = 1
for _ in 0..<symbolForIndex {
symbol *= 10
}
return(self / symbol) % 10
}
}
let a = 20
a.checkForValid
a.isNegative
let b = -555
b.isPositive
a.symbolCount
b.symbolCount
print(a[1])
extension String {
subscript(value: Range<Int>) -> String {
let startIndex = self.index(self.startIndex, offsetBy: value.lowerBound)
let endIndex = self.index(self.startIndex, offsetBy: value.upperBound - value.lowerBound)
return String(self[Range(startIndex..<endIndex)])
}
func truncate(index: Int) -> String {
var string = " "
for (i, j) in self.enumerated() {
switch i {
case index: string.append("...")
case _ where i < index: string.append(j)
default: break
}
}
return string
}
}
let testString = "Skutarenko"
testString[0..<8]
testString.truncate(index: 7)
| true
|
ea563865631b54146bb4779e46738b02d0649602
|
Swift
|
Xecca/LeetCodeProblems
|
/821.Shortest_Distance_to_a_Character.swift
|
UTF-8
| 2,503
| 4.0625
| 4
|
[] |
no_license
|
// Solved by Xecca
//821. Shortest Distance to a Character
//Сomplexity: Easy
//https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/
//----------------------------------------------------
//Runtime: 12 ms, faster than 92.86% of Swift online submissions for Shortest Distance to a Character.
//Memory Usage: 14.2 MB, less than 92.86% of Swift online submissions for Shortest Distance to a Character.
//----------------------------------------------------
//Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.
//
//Note:
//
//S string length is in [1, 10000].
//C is a single character, and guaranteed to be in string S.
//All letters in S and C are lowercase.
//----------------------------------------------------
func shortestToChar(_ S: String, _ C: Character) -> [Int] {
var arr = Array(repeating: 0, count: S.count)
var arrWithCharIndexes = [Int]()
var start = 0
var end = 0
for (i, char) in S.enumerated() {
if char == C {
arrWithCharIndexes.append(i)
}
}
let charCount = arrWithCharIndexes.count
var i = 0
var num = arrWithCharIndexes[i]
if arrWithCharIndexes[0] > 0 {
while start < arrWithCharIndexes[i] {
arr[start] = num
num -= 1
start += 1
}
}
while i < charCount {
num = 0
if i + 1 < charCount && arrWithCharIndexes[i + 1] - arrWithCharIndexes[i] > 1 {
start = arrWithCharIndexes[i]
end = arrWithCharIndexes[i + 1]
while start <= end {
arr[start] = num
arr[end] = num
num += 1
start += 1
end -= 1
}
}
i += 1
}
if arrWithCharIndexes[charCount - 1] < S.count - 1 {
num = 0
i = arrWithCharIndexes[charCount - 1]
while i < S.count {
arr[i] = num
i += 1
num += 1
}
}
return arr
}
//Example 1:
//
//Input: S = "loveleetcode", C = 'e'
//Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
//Test cases:
//
if shortestToChar("loveleetcode", "e") == [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] { print("Correct!") } else { print("Error! Expected: \([3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0])") }
if shortestToChar("aaba", "b") == [2,1,0,1] { print("Correct!") } else { print("Error! Expected: \([2,1,0,1])") }
| true
|
3e9708aa67a602806a4905294e183607b5572f48
|
Swift
|
yukuifang/ios-swift
|
/Base/Base/Classes/BezierPath.swift
|
UTF-8
| 1,153
| 2.703125
| 3
|
[] |
no_license
|
//
// BezierPath.swift
// Base
//
// Created by fangyukui on 2018/5/10.
// Copyright © 2018年 fangyukui. All rights reserved.
//
import UIKit
class BezierView: UIView {
override func draw(_ rect: CGRect) {
// let react = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: 10, height: bounds.size.height)
//
// let pathRect = UIEdgeInsetsInsetRect(react, UIEdgeInsetsMake(1, 1, 1, 1))
//
// let path = UIBezierPath(roundedRect: pathRect, cornerRadius: 10)
//
//
// path.lineWidth = 1
//
// UIColor.green.setFill()
//
// UIColor.black.setStroke()
//
// path.fill()
//
// path.stroke()
let react = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: 10, height: bounds.size.height)
let pathRect = UIEdgeInsetsInsetRect(react, UIEdgeInsetsMake(4,4,4, 4))
let path = UIBezierPath(roundedRect: pathRect, cornerRadius: 10)
let sLayer = CAShapeLayer()
sLayer.path = path.cgPath
sLayer.fillColor = UIColor.red.cgColor
layer.addSublayer(sLayer)
}
}
| true
|
bb729726326a58bc17f8fb258a9ad840800361de
|
Swift
|
sphericalwave/SQLSpeaks
|
/SQLSpeaks/main.swift
|
UTF-8
| 784
| 2.90625
| 3
|
[] |
no_license
|
//
// main.swift
// SQLSpeaks
//
// Created by Aaron Anthony on 2020-01-06.
// Copyright © 2020 SphericalWaveSoftware. All rights reserved.
//
import Foundation
let db = SQLiteDatabase()
//let posts = Posts(database: db)
//
//do {
// let post = try posts.add(title: "Keeg!")
// print("Just added post # \(post.id), \(post.title())")
//}
//catch { print(error) }
//print("Post count: \(posts.count())")
//for post in posts { print("Post #: \(post.id), title: \(post.title())") }
//
//let users = Users(database: db)
let governers = Governers(database: db)
//let addGoverner = "INSERT INTO Governers(GID, Name, Address, TermBegin) values(110, 'Bob', '123 Any St', '1-Jan-2009');"
try! governers.add(id: 112, name: "Arnold", address: "California", termBegin: "1-Jan-2009")
| true
|
616397db6710aa38f693124e334b7a0c96408b0d
|
Swift
|
blkbrds/intern14-practice
|
/BaiTap10/DuongNT/AutoLayout/AutoLayout/Controllers/Ex6/Ex6ViewController.swift
|
UTF-8
| 1,688
| 2.515625
| 3
|
[] |
no_license
|
//
// Ex6ViewController.swift
// PracticeTemplate
//
// Created by Tien Le P. on 6/22/18.
// Copyright © 2018 Tien Le P. All rights reserved.
//
import UIKit
class Ex6ViewController: BaseViewController {
// MARK: - Outlets
@IBOutlet var buttons: [UIButton]!
// MARK: - Properties
var exercise: Exercise?
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Config
override func setupUI() {
super.setupUI()
self.title = exercise?.name
buttons.forEach { button in
button.layer.cornerRadius = 5
}
}
override func setupData() {
super.setupData()
}
// MARK: - Actions
@IBAction func buttonsActionTouchUpInside(_ button: UIButton) {
switch button.tag {
case 1:
let baiTap6 = BaiTap6ViewController()
navigationController?.pushViewController(baiTap6, animated: true)
case 2:
let baiTap62 = BaiTap62ViewController()
navigationController?.pushViewController(baiTap62, animated: true)
case 3:
let baiTap63 = BaiTap63ViewController()
navigationController?.pushViewController(baiTap63, animated: true)
case 4:
let baiTap64 = BaiTap64ViewController()
navigationController?.pushViewController(baiTap64, animated: true)
case 5:
let baiTap65 = BaiTap65ViewController()
navigationController?.pushViewController(baiTap65, animated: true)
default:
break
}
}
}
| true
|
b46267c42159d669c1a7bf4dd042108a2b2ec3f0
|
Swift
|
nanurai/ios
|
/Nanurai/Controllers/Onboarding/ConfirmMnemonicViewController.swift
|
UTF-8
| 6,064
| 2.515625
| 3
|
[] |
no_license
|
//
// ConfirmMnemonicViewController.swift
// Nanurai
//
// Created by Elliott Minns on 26/08/2018.
// Copyright © 2018 Nanurai. All rights reserved.
//
import UIKit
import Stevia
class ConfirmMnemonicViewController: NanuraiViewController {
let mnemonic: Mnemonic
static let challengeCount = 4
let challenges: [Int]
let scrollView = UIScrollView()
let input = NanuraiTextField()
let nextButton = NanuraiButton(withType: .standard)
var currentChallenge: Int = 0 {
didSet {
let width = scrollView.frame.width
let offset = CGPoint(
x: scrollView.contentOffset.x + width, y: scrollView.contentOffset.y
)
scrollView.setContentOffset(offset, animated: true)
input.text = nil
if currentChallenge + 1 == challenges.count {
nextButton.setAttributedTitle("Done")
}
nextButton.isEnabled = false
}
}
var expected: String {
return mnemonic.words[challenges[currentChallenge]]
}
init(mnemonic: Mnemonic) {
self.mnemonic = mnemonic
self.challenges = ConfirmMnemonicViewController.setupChallenges(for: mnemonic)
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func render() {
super.render()
view.sv(scrollView, input, nextButton)
scrollView.top(0).left(0).right(0).height(120)
nextButton.isEnabled = false
let margin = StyleGuide.Size.margin
nextButton.bottom(margin).left(margin).right(margin)
nextButton.defaultHeight()
nextButton.setAttributedTitle("Next")
nextButton.addTarget(
self, action: #selector(nextButtonPressed(sender:)), for: .touchUpInside
)
let views = challenges.map { (object) -> UIView in
return generateLabel(for: object)
}
scrollView.pageAlign(views: views)
input.left(margin).right(margin).height(44)
input.backgroundColor = UIColor.white
input.layer.cornerRadius = StyleGuide.Size.Button.radius
input.Top == scrollView.Bottom + margin
input.textAlignment = .center
input.font = UIFont.systemFont(ofSize: 24)
input.autocapitalizationType = .none
input.autocorrectionType = .no
input.addTarget(
self,
action: #selector(onTextFieldUpdate(sender:)),
for: UIControlEvents.editingChanged
)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil
)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
input.becomeFirstResponder()
}
static func setupChallenges(for mnemonic: Mnemonic) -> [Int] {
var chosen = Set<Int>()
var values: [Int] = []
while chosen.count < challengeCount {
let challenge = Int(arc4random_uniform(UInt32(mnemonic.words.count)))
if !chosen.contains(challenge) {
chosen.insert(challenge)
values.append(challenge)
}
}
return values
}
func generateLabel(for challenge: Int) -> UIView {
let view = UIView()
let descriptionLabel = UILabel()
let width = UIScreen.main.bounds.width
let margin = StyleGuide.Size.margin
view.sv(descriptionLabel)
descriptionLabel.numberOfLines = 0
descriptionLabel.left(margin).right(margin)
descriptionLabel.centerVertically()
descriptionLabel.textAlignment = .center
descriptionLabel.textColor = .white
descriptionLabel.font = UIFont.systemFont(ofSize: 28, weight: .light)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
let i = NSNumber(integerLiteral: challenge + 1)
guard let num = numberFormatter.string(from: i) else { return view }
descriptionLabel.text = "Please enter the \(num) word"
view.height(120)
view.width(width)
return view
}
@objc
func onTextFieldUpdate(sender: UITextField) {
let word = mnemonic.words[challenges[currentChallenge]]
nextButton.isEnabled = word.lowercased() == sender.text?.lowercased()
}
@objc
func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
let curveValue = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
let durationValue = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber
let duration = durationValue?.doubleValue ?? 0.5
let animationCurveRaw = curveValue?.uintValue ?? UIViewAnimationOptions.curveEaseInOut.rawValue
let animationCurve: UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
nextButton.bottomConstraint?.constant = -(StyleGuide.Size.margin + keyboardHeight)
self.view.setNeedsLayout()
UIView.animate(
withDuration: duration,
delay: 0,
options: animationCurve,
animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
}
@objc
func nextButtonPressed(sender: NanuraiButton) {
guard expected == input.text?.lowercased() else { return }
if currentChallenge < challenges.count - 1 {
currentChallenge += 1
} else {
nextButton.isEnabled = false
KeyManager.shared.store(mnemonic: mnemonic)
sender.isLoading = true
AccountManager.shared.initial(loadFrom: mnemonic) {
self.input.resignFirstResponder()
self.navigationController?.dismiss(animated: true, completion: nil)
}
}
}
}
| true
|
eaef24a99163eb50873be57e15ac62a3ceddfe20
|
Swift
|
gitter-badger/ramda.swift
|
/Ramda/Extensions/difference.swift
|
UTF-8
| 1,313
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
//
// Created by Justin Guedes on 2016/09/13.
//
import Foundation
// swiftlint:disable line_length
extension R {
/**
Finds the set (i.e. no duplicates) of all elements in the first list not contained in
the second list.
- parameter collection: The first list.
- parameter collection2: The second list.
- returns: An array of the difference between the two lists.
*/
public class func difference<A: CollectionType, B: CollectionType where A.Generator.Element: Comparable, A.Generator.Element == B.Generator.Element>(collection: A, from collection2: B) -> [A.Generator.Element] {
let check: (A.Generator.Element, B) -> Bool = R.complement(R.contains)
return collection.filter { (element: A.Generator.Element) -> Bool in check(element, collection2) }
}
/**
Finds the set (i.e. no duplicates) of all elements in the first list not contained in
the second list.
- parameter array: The first array.
- returns: A curried function that accepts the second array and returns an array of
the difference between the two lists.
*/
public class func difference<T: Comparable>(array: [T]) -> (from: [T]) -> [T] {
return curry(difference)(array)
}
}
// swiftlint:enable line_length
| true
|
683d6ba5dc0d2619f88ede0d8a160d50d0b3145c
|
Swift
|
carabina/SFStaticNavigationBarController
|
/SFStaticNavigationBarController/Classes/Views/StaticNavigationBar.swift
|
UTF-8
| 2,209
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
//
// StaticNavigationBar.swift
// StaticNavigationController
//
// Created by Seth Folley on 12/25/17.
// Copyright © 2017 Seth Folley. All rights reserved.
//
import UIKit
public class StaticNavigationBar: UINavigationBar {
// MARK: Slider vars
/// The length of the slider. Default value is 44.0
public var sliderLength: CGFloat = 44.0 {
didSet {
slider.frame.size.width = sliderLength
}
}
/// The thickness of the slider. Default value is 1.0
public var sliderWidth: CGFloat = 1.0 {
didSet {
slider.frame.size.height = sliderWidth
}
}
/// Defines if the slider is hidden. Default is false
public var isSliderHidden: Bool = false {
didSet {
slider.alpha = isSliderHidden ? 0.0 : 1.0
}
}
/// The color of the slider. Default is Dark Gray
public var sliderColor: UIColor = .darkGray {
didSet {
slider.backgroundColor = sliderColor
}
}
/// The corner radius for the slider. Default is 1.0
public var sliderCornerRadius: CGFloat = 1.0 {
didSet {
slider.layer.cornerRadius = sliderCornerRadius
}
}
/// The slider will come this close to the screens edge. Can be negative. Default is 0.0
public var sliderMarginToEdge: CGFloat = 0.0
lazy var slider: UIView = {
let view = UIView()
view.frame.size.width = self.sliderLength
view.frame.size.height = self.sliderWidth
view.frame.origin.x = (self.frame.width - view.frame.width) / 2.0
view.frame.origin.y = self.frame.height - view.frame.height
view.layer.cornerRadius = self.sliderCornerRadius
view.layer.masksToBounds = true
view.backgroundColor = self.sliderColor
return view
}()
// MARK: Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
tintColor = .black
barTintColor = .white
isTranslucent = false
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: UI
func addSubviews() {
self.addSubview(slider)
}
}
| true
|
20e0ba801ffa395dbd1b8f954c9fb345c5768945
|
Swift
|
thetealpickle/marvel-pickle-ios
|
/marvel/Models/Comic/ComicImage.swift
|
UTF-8
| 897
| 3.25
| 3
|
[] |
no_license
|
//
// ComicImage.swift
// marvel
//
// Created by Jessica Joseph on 3/26/20.
// Copyright © 2020 JESSICA JEAN JOSEPH. All rights reserved.
//
import Foundation
struct ComicImage: Codable {
var path: String?
var ext: String?
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: ComicImageCodingKeys.self)
self.path = try container.decodeIfPresent(String.self, forKey: .path)
self.ext = try container.decodeIfPresent(String.self, forKey: .ext)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: ComicImageCodingKeys.self)
try container.encodeIfPresent(self.path, forKey: .path)
try container.encodeIfPresent(self.ext, forKey: .ext)
}
enum ComicImageCodingKeys: String, CodingKey{
case path
case ext = "extension"
}
}
| true
|
0c1fef38a4b32ddf4d5e23ec9678ffbb0679a268
|
Swift
|
ftp5500/chart
|
/ViewController.swift
|
UTF-8
| 2,077
| 2.765625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// SwiftyStats
//
// Created by Brian Advent on 19.03.18.
// Copyright © 2018 Brian Advent. All rights reserved.
//
import UIKit
import Charts // جلب مكتبة المؤشرات بعد تحميلها من cocoapods
class ViewController: UIViewController {
@IBOutlet weak var pieChart: PieChartView!
@IBOutlet weak var iosStepper: UIStepper!
@IBOutlet weak var macStepper: UIStepper!
var iosDataEntry = PieChartDataEntry(value: 0)
var macDataEntry = PieChartDataEntry(value: 0)
var numberOfDownloadsDataEntries = [PieChartDataEntry]()
override func viewDidLoad() {
super.viewDidLoad()
//الارقام والبيانات التي تظهر على المؤشر
pieChart.chartDescription?.text = ""
iosDataEntry.value = iosStepper.value
iosDataEntry.label = "mac"
macDataEntry.value = iosStepper.value
macDataEntry.label = "macOS"
numberOfDownloadsDataEntries = [macDataEntry,iosDataEntry]
updateChartData()
}
//عند استخدام ازار للزيادة او النقص في المؤشر
@IBAction func changeiOS(_ sender: UIStepper) {
iosDataEntry.value = sender.value
updateChartData()
}
@IBAction func changeMac(_ sender: UIStepper) {
macDataEntry.value = sender.value
updateChartData()
}
// اضافة وظيفة تحديث المؤشر والبيانات
func updateChartData() {
let chartDataSet = PieChartDataSet(values: numberOfDownloadsDataEntries, label: nil)
let chartData = PieChartData(dataSet: chartDataSet)
let color = [UIColor(named: "iosColor") , UIColor(named: "macColor")]
chartDataSet.colors = color as! [NSUIColor]
pieChart.data = chartData
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
602d85c1ba19f2b4f2322802792f0fabc4a9042a
|
Swift
|
johnmalatras/sharefish
|
/ShareFish/NearMeCell.swift
|
UTF-8
| 1,747
| 2.703125
| 3
|
[] |
no_license
|
//
// NearMeCell.swift
// ShareFish
//
// Created by John Malatras on 2/6/16.
// Copyright © 2016 ShareFish LLC. All rights reserved.
//
import Foundation
import ParseUI
class NearMeCell : UITableViewCell{
@IBOutlet weak var NameLabel: UILabel!
@IBOutlet weak var DistanceLabel: UILabel!
@IBOutlet var ImageViewV: PFImageView!
@IBOutlet weak var AgeImageView: UIImageView!
@IBOutlet weak var AgeLabel: UILabel!
@IBOutlet weak var GenderImageView: UIImageView!
func setAgeLbl(info: String){
self.AgeLabel.text = info
}
func setAgeImgView(pic: UIImage){
AgeImageView.image = pic
}
func setGenderImgView(pic: UIImage){
GenderImageView.image = pic
}
func setNameLbl(name: String){
self.NameLabel.text = name
}
func setDistanceLbl(distance: Double){
let distanceString = "\(round(distance * 10)/10) mi away"
self.DistanceLabel.text = distanceString
}
func setImgView(image: PFFile, open: Bool){
self.ImageViewV.layer.borderWidth = 2.2
if open {
self.ImageViewV.layer.borderColor = UIColor(red: 37.0/255.0, green: 182.0/255.0, blue: 71.0/255.0, alpha: 1.0).CGColor
}
else {
self.ImageViewV.layer.borderColor = UIColor(red: 220.0/255.0, green: 26.0/255.0, blue: 26.0/255.0, alpha: 1.0).CGColor
}
self.ImageViewV.layer.cornerRadius = self.ImageViewV.frame.height/2.033
self.ImageViewV.contentMode = UIViewContentMode.ScaleAspectFill
self.ImageViewV.clipsToBounds = true
self.ImageViewV.file = image
self.ImageViewV.loadInBackground()
self.ImageViewV.sizeToFit()
}
}
| true
|
49e5e92ac8cc25c9494ee602807254027acc7b22
|
Swift
|
neena9940/MovieAlbum
|
/MovieAlbum/Model/Movie/DTOCountry.swift
|
UTF-8
| 736
| 2.8125
| 3
|
[] |
no_license
|
//
// DTOCountry.swift
// MovieAlbum
//
// Created by Nina Yousefi on 10/24/17.
// Copyright © 2017 Nina Yousefi. All rights reserved.
//
import Foundation
import SwiftyJSON
class DTOCountry {
var name: String?
var code: String?
var timezone: String?
init(jsonDictionary: [String : JSON]?) {
//super.init()
guard let dictionary = jsonDictionary else {
return
}
mapping(jsonDictionary: dictionary)
}
func mapping(jsonDictionary : [String : JSON]) {
name = jsonDictionary["name"]?.stringValue
code = jsonDictionary["code"]?.stringValue
timezone = jsonDictionary["timezone"]?.stringValue
}
}
| true
|
ae441e436bc6bfc08c094a9ac30cee35c08a9809
|
Swift
|
UglyBlueCat/IGTDevTask
|
/IGTDevTask/NetworkManager.swift
|
UTF-8
| 2,779
| 3
| 3
|
[] |
no_license
|
//
// NetworkManager.swift
// IGTDevTask
//
// Created by Robin Spinks on 07/09/2016.
// Copyright © 2016 UglyBlueCat. All rights reserved.
//
import Foundation
class NetworkManager {
let defaultSession : NSURLSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
/*
* Create a shared instance to initialise class as a singleton
* originally taken from: http://krakendev.io/blog/the-right-way-to-write-a-singleton
*/
static let sharedInstance = NetworkManager()
private init() {}
/*
* fetchJackpotList
*
* Downloads a list of games and their jackpots
*/
func fetchJackpotList () {
guard let jackpotURL : NSURL = NSURL(string: jackpotURLString) else {
DLog("Cannot initialise jackpot URL: \(jackpotURLString)")
return
}
let jackPotURLRequest : NSURLRequest = NSURLRequest(URL: jackpotURL)
downloadData(jackPotURLRequest)
}
/*
* downloadData
*
* Downloads data from a given URL request
*
* It would make more sense for the completion method to be passed to this method as it handles the data
* in a way that is specific to parsing jackpot data, but that would leave this method empty.
* I want this method to show the distinction of having a method specifically for download requests
* There could be other methods for other types of requests; we just don't need them in this case
*
* @param: request: NSURLRequest - The URL request to download data from
*/
func downloadData (request: NSURLRequest) {
handleRequest(request, completion: { (data, urlResponse, error) in
guard error == nil else {
DLog("Download error: \(error!.description)")
return
}
if data != nil {
FileHandler.sharedInstance.writeDataToFile(data!)
} else {
DLog("Null data")
}
})
}
/*
* handleRequest
*
* Handles an NSURLRequest of whatever type
*
* This gives me the ability to expand the class to handle different request methods
* e.g. For RESTful API interaction
*
* @param: request: NSURLRequest - The URL request
* @param: completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void)
* - A method to handle the returned data
*/
func handleRequest (request: NSURLRequest, completion: (NSData?, NSURLResponse?, NSError?) -> Void) {
let task : NSURLSessionDataTask = defaultSession.dataTaskWithRequest(request, completionHandler: completion)
task.resume()
}
}
| true
|
1c4bcc71c19bd067d3d59eb0d6e218ac9f7a0b11
|
Swift
|
1Dante/FootballScore
|
/FootballScore/StandingsViewController/StandingsViewController.swift
|
UTF-8
| 3,548
| 2.53125
| 3
|
[] |
no_license
|
//
// StandingsTableViewController.swift
// FootballScore
//
// Created by MacBook on 30.12.2020.
//
import UIKit
class StandingsViewController: UIViewController {
@IBOutlet var standingsBattons: [UIButton]!
@IBOutlet weak var tableViewStandings: TableViewStandings!
@IBOutlet weak var tableViewFixtures: TableViewFixtures!
@IBOutlet weak var tableViewResults: TableViewResults!
let tableViewStandingsReference = TableViewStandings()
let tableViewFixturesReference = TableViewFixtures()
let tableViewResultsReference = TableViewResults()
override func viewDidLoad() {
super.viewDidLoad()
setupButtonsStyle()
tableViewStandings.delegate = tableViewStandingsReference
tableViewStandings.dataSource = tableViewStandingsReference
tableViewFixtures.delegate = tableViewFixturesReference
tableViewFixtures.dataSource = tableViewFixturesReference
tableViewResults.delegate = tableViewResultsReference
tableViewResults.dataSource = tableViewResultsReference
tableViewStandingsReference.standingsProvider.fetchJson { (json) in
_ = json?.response?.compactMap({ (league) -> [Standings]? in
league.standings.flatMap { (groupes) -> [Standings] in
groupes.flatMap { (standings) -> [Standings] in
self.tableViewStandingsReference.standingsArray = standings
DispatchQueue.main.async {
self.tableViewStandings.reloadData()
}
return standings
}
}
})
}
}
// use three button with tag: stadings = 0, results = 1, fixtures = 2
@IBAction private func tapButtons(_ sender: UIButton){
switch (sender.tag) {
case 0:
tableViewStandings.isHidden = false
tableViewFixtures.isHidden = true
tableViewResults.isHidden = true
case 1:
tableViewResults.isHidden = false
tableViewStandings.isHidden = true
tableViewFixtures.isHidden = true
tableViewResultsReference.resultsProvider.fetchJson { (json) in
_ = json.flatMap { (fixture) in
if let fixture = fixture.response{
self.tableViewResultsReference.resultsArray = fixture
DispatchQueue.main.async {
self.tableViewResults.reloadData()
}
}
}
}
case 2:
tableViewStandings.isHidden = true
tableViewResults.isHidden = true
tableViewFixtures.isHidden = false
tableViewFixturesReference.fixturesProvider.fetchJson { (json) in
_ = json.flatMap { (fixture) in
if let fixture = fixture.response{
self.tableViewFixturesReference.fixturesArray = fixture
DispatchQueue.main.async {
self.tableViewFixtures.reloadData()
}
}
}
}
default:
break
}
}
//add to button some additional design
func setupButtonsStyle(){
standingsBattons.forEach { (button) in
button.layer.borderColor = UIColor(red: 0.14, green: 0.33, blue: 0.23, alpha: 0.8).cgColor
button.layer.borderWidth = 0.7
button.layer.cornerRadius = button.bounds.size.height / 3
}
}
}
| true
|
2a38fb9cf527ffd36b294def49f8703d835c78c1
|
Swift
|
MirandaChar/PrototipoCursoiOS
|
/WebServices/Tools/Tools.swift
|
UTF-8
| 5,124
| 3.203125
| 3
|
[] |
no_license
|
//
// Tools.swift
// WebServices
//
// Created by Carlos on 09/11/21.
//
import Foundation
import UIKit
//Escribimos nuestra clase de Servicios y realizamos un Singleton de ella misma para gestionar nuestros servicios Web.
class Service: NSObject {
static let shared = Service()
func getJokes(completion: @escaping(Result<QuoteData, Error>) -> ()) {
let typeAux = "twopart"
guard let url = URL(string: "https://v2.jokeapi.dev/joke/Any?type=\(typeAux)") else {
return
}
let urlSession = URLSession.shared.dataTask(with: url, completionHandler:{
data, response, error in
//Nos aseguramos que no exista algún error de lo contrario retornar.
if let error = error {
print("Error: ", error)
return
}
//Si se pudo almacenar la informacion la guardamos, en caso contrario retornar
guard let data = data else {
return
}
print(String(data: data, encoding: .utf8) ?? "")
//Ahora decodificar los Datos, sabemos que vienen en un formato Json así que podemos usar el decodificador JSONDecoder
do {
let decodedData = try JSONDecoder().decode(QuoteData.self, from: data)
completion(.success(decodedData))
}
catch {
//Muestro mensaje de error en caso de un error de decodificacion
print("Error en la descarga. ", error)
completion(.failure(error))
}
})
urlSession.resume()
}
func createActividad(key: String, name: String, description: String, completion: @escaping(Result<[NewActivity],Error>) -> ()) {
guard let url = URL(string: "http://3.238.21.227:8080/activities") else {
return
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let newActivity = NewActivity(key: key, name: name, description: description)
guard let newActivityJson = try? JSONEncoder().encode(newActivity) else {
return
}
print(String(data: newActivityJson, encoding: .utf8) ?? "")
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
//urlRequest.addValue("multipart/form-data; boundary=---BOUNDARY", forHTTPHeaderField: "Content-Type")
urlRequest.httpBody = newActivityJson
/*"""
-----BOUNDARY
Content-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"
Content-Type: image/jpeg
Base64DeLaImagen
-----BOUNDARY
Content-Disposition: form-data; name=\"Curos iOS\"
Content-Type: text/plain
Encabezado de la noticia
-----BOUNDARY
Content-Disposition: form-data; name=\"summary\"
Content-Type: text/plain
Resumen de la noticia
-----BOUNDARY
Content-Disposition: form-data; name=\"body\"
Content-Type: text/plain
Cuerpo de la noticia
-----BOUNDARY
""".data(using: .utf8)*/
/*urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.addValue("c28684740cf2156cee9541eb47d061f4570593110fc72f021686caba29dc6f72", forHTTPHeaderField: "Authorization")*/
URLSession.shared.dataTask(with: urlRequest, completionHandler: {
data, res, err in
if let err = err {
completion(.failure(err))
return
}
guard let data = data else {
return
}
print(String(data: data, encoding: .utf8)!)
DispatchQueue.main.async {
do {
let decodedData = try JSONDecoder().decode([NewActivity].self, from: data)
completion(.success(decodedData))
}
catch {
//Muestro mensaje de error en caso de un error de decodificacion
print("Error en la descarga. ", error)
completion(.failure(error))
}
}
}).resume()
}
}
class UnderlinedLabel: UILabel {
override var text: String? {
didSet {
guard let text = text else { return }
let textRange = NSRange(location: 0, length: text.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(.underlineStyle,
value: NSUnderlineStyle.single.rawValue,
range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
}
| true
|
acbe809dfaf6ca308c0f90fb4e9a10d7a5874a0c
|
Swift
|
Murat116/secretProject
|
/Wins/StatisticVC/StatisticsInteractor.swift
|
UTF-8
| 423
| 2.515625
| 3
|
[] |
no_license
|
//
// StatisticsInteractor.swift
// Wins
//
// Created by Мурат Камалов on 20.04.2020.
// Copyright © 2020 Hope To. All rights reserved.
//
import Foundation
class StatisticInteractor{
weak var output: StatInteractorOutput!
func getTricks(){
let tricks = DataManager._shared.skateTricks
let arrOfTricks = Array(tricks)
self.output.configure(with: arrOfTricks)
}
}
| true
|
eb92a783dd4ef5b3807a2c835fa22b378d1c78a0
|
Swift
|
doc22940/CommonMark-1
|
/Sources/CommonMark/Nodes/Node.swift
|
UTF-8
| 6,710
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
import cmark
/// A CommonMark node.
public class Node: Codable {
class var cmark_node_type: cmark_node_type { return CMARK_NODE_NONE }
/// A pointer to the underlying `cmark_node` for the node.
final let cmark_node: OpaquePointer
/// Whether the underlying `cmark_node` should be freed upon deallocation.
var managed: Bool = false
/**
Creates a node from a `cmark_node` pointer.
- Parameter cmark_node: A `cmark_node` pointer.
*/
required init(_ cmark_node: OpaquePointer) {
self.cmark_node = cmark_node
assert(type(of: self) != Node.self)
assert(cmark_node_get_type(cmark_node) == type(of: self).cmark_node_type)
}
convenience init(nonrecursively: Void) {
self.init()
}
convenience init() {
self.init(cmark_node_new(type(of: self).cmark_node_type))
self.managed = true
}
deinit {
guard managed else { return }
cmark_node_free(cmark_node)
}
/**
Creates and returns the `Node` subclass corresponding to
the type of a `cmark_node` pointer.
- Parameter cmark_node: A `cmark_node` pointer.
- Returns: An instance of a `Node` subclass.
*/
static func create(for cmark_node: OpaquePointer!) -> Node? {
guard let cmark_node = cmark_node else { return nil }
switch cmark_node_get_type(cmark_node) {
case CMARK_NODE_BLOCK_QUOTE:
return BlockQuote(cmark_node)
case CMARK_NODE_LIST:
switch cmark_node_get_list_type(cmark_node) {
case CMARK_BULLET_LIST:
return List(cmark_node)
case CMARK_ORDERED_LIST:
return List(cmark_node)
default:
return nil
}
case CMARK_NODE_ITEM:
return List.Item(cmark_node)
case CMARK_NODE_CODE_BLOCK:
return CodeBlock(cmark_node)
case CMARK_NODE_HTML_BLOCK:
return HTMLBlock(cmark_node)
case CMARK_NODE_PARAGRAPH:
return Paragraph(cmark_node)
case CMARK_NODE_HEADING:
return Heading(cmark_node)
case CMARK_NODE_THEMATIC_BREAK:
return ThematicBreak(cmark_node)
case CMARK_NODE_TEXT:
return Text(cmark_node)
case CMARK_NODE_SOFTBREAK:
return SoftLineBreak(cmark_node)
case CMARK_NODE_LINEBREAK:
return HardLineBreak(cmark_node)
case CMARK_NODE_CODE:
return Code(cmark_node)
case CMARK_NODE_HTML_INLINE:
return RawHTML(cmark_node)
case CMARK_NODE_EMPH:
return Emphasis(cmark_node)
case CMARK_NODE_STRONG:
return Strong(cmark_node)
case CMARK_NODE_LINK:
return Link(cmark_node)
case CMARK_NODE_IMAGE:
return Image(cmark_node)
default:
return nil
}
}
/// The line and column range of the element in the document.
public var range: ClosedRange<Document.Position> {
let start = Document.Position(line: numericCast(cmark_node_get_start_line(cmark_node)), column: numericCast(cmark_node_get_start_column(cmark_node)))
let end = Document.Position(line: max(start.line, numericCast(cmark_node_get_end_line(cmark_node))), column: max(start.column, numericCast(cmark_node_get_end_column(cmark_node))))
return start...end
}
/// The parent of the element, if any.
public var parent: Node? {
return Node.create(for: cmark_node_parent(cmark_node))
}
// MARK: - Codable
public required convenience init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let commonmark = try container.decode(String.self)
switch Self.cmark_node_type {
case CMARK_NODE_DOCUMENT:
let document = try Document(commonmark, options: [])
self.init(document.cmark_node)
case CMARK_NODE_DOCUMENT,
CMARK_NODE_BLOCK_QUOTE,
CMARK_NODE_LIST,
CMARK_NODE_ITEM,
CMARK_NODE_CODE_BLOCK,
CMARK_NODE_HTML_BLOCK,
CMARK_NODE_CUSTOM_BLOCK,
CMARK_NODE_PARAGRAPH,
CMARK_NODE_HEADING,
CMARK_NODE_THEMATIC_BREAK:
let document = try Document(commonmark, options: [])
let documentChildren = document.children
guard let block = documentChildren.first as? Self,
documentChildren.count == 1
else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "expected single block node")
}
self.init(block.cmark_node)
case CMARK_NODE_TEXT,
CMARK_NODE_SOFTBREAK,
CMARK_NODE_LINEBREAK,
CMARK_NODE_CODE,
CMARK_NODE_HTML_INLINE,
CMARK_NODE_CUSTOM_INLINE,
CMARK_NODE_EMPH,
CMARK_NODE_STRONG,
CMARK_NODE_LINK,
CMARK_NODE_IMAGE:
let document = try Document(commonmark, options: [])
let documentChildren = document.children
guard let paragraph = documentChildren.first as? Paragraph,
documentChildren.count == 1
else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "expected single paragraph node")
}
let paragraphChildren = paragraph.children
guard let inline = paragraphChildren.first as? Self,
paragraphChildren.count == 1
else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "expected single inline node")
}
self.init(inline.cmark_node)
default:
throw DecodingError.dataCorruptedError(in: container, debugDescription: "unsupported node type")
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(description)
}
}
// MARK: - Equatable
extension Node: Equatable {
public static func == (lhs: Node, rhs: Node) -> Bool {
return lhs.cmark_node == rhs.cmark_node
}
}
// MARK: - Hashable
extension Node: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(cmark_node_get_type(cmark_node).rawValue)
hasher.combine(cmark_render_commonmark(cmark_node, 0, 0))
}
}
// MARK: - CustomStringConvertible
extension Node: CustomStringConvertible {
public var description: String {
return String(cString: cmark_render_commonmark(cmark_node, 0, 0))
}
}
| true
|
e83395a77993df6b6b0a2d7f2ad9e80a0f0c3679
|
Swift
|
abin0992/PingSDK
|
/Sources/PingSDK/APIEndpoints.swift
|
UTF-8
| 567
| 2.546875
| 3
|
[] |
no_license
|
//
// APIEndpoints.swift
// PinkSDK
//
// Created by Abin Baby on 07/03/21.
//
import Foundation
struct APIEndpoint {
let path: String
var queryItems: [URLQueryItem]?
var url: URL? {
var components: URLComponents = URLComponents()
components.scheme = "https"
components.host = Constants.hostName
components.path = path
components.queryItems = queryItems
return components.url
}
static func log() -> APIEndpoint {
APIEndpoint(
path: "/post", queryItems: nil
)
}
}
| true
|
8c14bfaa2856f8b9e260cebb61cd288e5f534890
|
Swift
|
lucberar910/training
|
/Training/Training/Architecture/DataSources/NetworkManager.swift
|
UTF-8
| 2,887
| 3
| 3
|
[] |
no_license
|
//
// NetworkManager.swift
// Training
//
// Created by Luca Berardinelli on 23/06/21.
//
import Foundation
import Alamofire
import UIKit
import Combine
protocol NetworkManagerProtocol {
// --- combine
func search(_ text : String) -> AnyPublisher<[Beer],Error>
// --- closure
// func search(_ text : String, completion : @escaping (Result<[Beer],Error>) -> Void)
}
class NetworkManager : NetworkManagerProtocol {
// static let shared = NetworkManager()
var currentRequest : DataRequest?
// --- COMBINE
func search(_ text : String) -> AnyPublisher<[Beer],Error> {
currentRequest?.cancel()
let request : String = "https://api.punkapi.com/v2/beers?page=1&per_page=80&beer_name=\(text.replacingOccurrences(of: " ", with: "_"))"
currentRequest = AF.request(request)
return Future<[Beer], Error> { promise in
self.currentRequest!
.validate(statusCode: 200..<300)
.response {
response in
guard let data = response.data, response.error == nil else {
promise(.failure(response.error!))
return
}
do {
var response : [Beer]?
let decoder = JSONDecoder()
response = try decoder.decode([Beer].self, from: data)
promise(.success(response!))
} catch let error {
promise(.failure(error))
}
}
}.eraseToAnyPublisher()
}
// --- CLOSURE
// func search(_ text : String, completion : @escaping (Result<[Beer],Error>) -> Void) {
// currentRequest?.cancel()
// let request : String = "https://api.punkapi.com/v2/beers?page=1&per_page=80&beer_name=\(text.replacingOccurrences(of: " ", with: "_"))"
//
// currentRequest = AF.request(request)
// .validate(statusCode: 200..<300)
// .response {
// response in
// guard let data = response.data, response.error == nil else {
// completion(Result.failure(response.error!))
// return
// }
// do {
// var response : [Beer]?
// let decoder = JSONDecoder()
// response = try decoder.decode([Beer].self, from: data)
// completion(Result.success(response!))
//// completion(Result.failure(URLError(URLError.badServerResponse)))
// } catch let error {
// completion(Result.failure(error))
// }
// }
// }
}
| true
|
f3e3086fac2c99e44800af292443760a3ced2249
|
Swift
|
wiencheck/Odtwarzacz-Muzyczny
|
/Odtwarzacz Muzyczny/Extensions/Foundation/TimeInterval.swift
|
UTF-8
| 790
| 3.625
| 4
|
[] |
no_license
|
//
// TimeInterval.swift
// Musico
//
// Created by adam.wienconek on 11.09.2018.
// Copyright © 2018 adam.wienconek. All rights reserved.
//
import Foundation
extension TimeInterval{
func calculateFromTimeInterval() ->(minute: String, second: String){
let minute_ = abs(Int((self/60).truncatingRemainder(dividingBy: 60)))
let second_ = abs(Int(self.truncatingRemainder(dividingBy: 60)))
let minute = minute_ > 9 ? "\(minute_)" : "\(minute_)"
let second = second_ > 9 ? "\(second_)" : "0\(second_)"
return (minute,second)
}
/// Returns time in minutes and seconds like this: 3:45
var asString: String {
let tuple = calculateFromTimeInterval()
return "\(tuple.minute):\(tuple.second)"
}
}
| true
|
3d4b006d0b510527071801c2c7c5a2213a3d7876
|
Swift
|
stefangeorgescu970/university-assignments
|
/Anul_3/Semestrul_1/MobileDev/swift/DoIT/DoIT/Classes/UI/ProjectList/ProjectListTableViewController.swift
|
UTF-8
| 2,155
| 2.59375
| 3
|
[] |
no_license
|
//
// ProjectListTableViewController.swift
// DoIT
//
// Created by Georgescu Stefan on 26/10/2018.
// Copyright © 2018 stefan. All rights reserved.
//
import UIKit
protocol ProjectListTableViewControllerDelegate: class {
func didSelectProject(project: Project)
}
class ProjectListTableViewController: UITableViewController {
var delegate: ProjectListTableViewControllerDelegate?
var projects: [Project] = []
func syncData() {
GlobalData.sharedInstance.getProjectService().getAllProjects { [unowned self] (projects: [Project]?, error: NSError?) in
if let projects = projects {
self.projects = projects
self.tableView.reloadData()
} else {
// handle some error
}
}
}
init(frame: CGRect) {
super.init(nibName: nil, bundle: nil)
self.tableView = UITableView(frame: frame)
self.tableView.register(ProjectListTableViewCell.self, forCellReuseIdentifier: "cell-id")
self.tableView.backgroundColor = AppColors.lightGray
self.tableView.separatorStyle = .none
syncData()
}
func updateForProject(_ project: Project) {
self.projects.append(project)
self.tableView.reloadData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return projects.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell-id", for: indexPath) as! ProjectListTableViewCell
cell.syncView(project: projects[indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.delegate?.didSelectProject(project: projects[indexPath.row])
}
}
| true
|
1239a2f6decf45855aa6669bbfd0e96d27a25942
|
Swift
|
CYBAVO/ios_wallet_sdk_sample
|
/WalletSDKDemo/View/ToastView.swift
|
UTF-8
| 3,619
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//Copyright (c) 2019 Cybavo. All rights reserved.
import Foundation
import UIKit
class ToastView : NSObject{
static var instance : ToastView = ToastView()
var windows = UIApplication.shared.windows
let rv = (UIApplication.shared.keyWindow?.subviews.first)!
func showLoadingView() {
clear()
let frame = CGRect(x: 0, y: 0, width: 78, height: 78)
let loadingContainerView = UIView()
loadingContainerView.layer.cornerRadius = 12
loadingContainerView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.8)
let indicatorWidthHeight :CGFloat = 36
let loadingIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.whiteLarge)
loadingIndicatorView.frame = CGRect(x: frame.width/2 - indicatorWidthHeight/2, y: frame.height/2 - indicatorWidthHeight/2, width: indicatorWidthHeight, height: indicatorWidthHeight)
loadingIndicatorView.startAnimating()
loadingContainerView.addSubview(loadingIndicatorView)
let window = UIWindow()
window.backgroundColor = UIColor.clear
window.frame = frame
loadingContainerView.frame = frame
window.windowLevel = UIWindow.Level.alert
window.center = CGPoint(x: rv.center.x, y: rv.center.y)
window.isHidden = false
window.addSubview(loadingContainerView)
windows.append(window)
}
func showToast(content:String , imageName:String="icon_cool", duration:CFTimeInterval=1.5) {
print("show toast")
clear()
let frame = CGRect(x: 0, y: 0, width: 130, height: 60)
let toastContainerView = UIView()
toastContainerView.layer.cornerRadius = 10
toastContainerView.backgroundColor = UIColor(red:0, green:0, blue:0, alpha: 0.7)
if let image = UIImage(named: imageName) {
let iconWidthHeight :CGFloat = 36
let toastIconView = UIImageView(image: image)
toastIconView.frame = CGRect(x: (frame.width - iconWidthHeight)/2, y: 15, width: iconWidthHeight, height: iconWidthHeight)
toastContainerView.addSubview(toastIconView)
}
let toastContentView = UILabel(frame: CGRect(x: 0, y: 0, width: 130, height: 60))
toastContentView.font = UIFont.systemFont(ofSize: 14)
toastContentView.textColor = UIColor.white
toastContentView.text = content
toastContentView.lineBreakMode = .byWordWrapping
toastContentView.numberOfLines = 2
toastContentView.textAlignment = NSTextAlignment.center
toastContainerView.addSubview(toastContentView)
let window = UIWindow()
window.backgroundColor = UIColor.clear
window.frame = frame
toastContainerView.frame = frame
window.windowLevel = UIWindow.Level.alert
window.center = CGPoint(x: rv.center.x, y: rv.center.y * 16/10)
window.isHidden = false
window.addSubview(toastContainerView)
windows.append(window)
DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: {
self.removeToast(window)
})
}
func removeToast(_ window: UIWindow) {
if let index = windows.index(of: window) {
// print("find the window and remove it at index \(index)")
windows.remove(at: index)
}
}
func clear() {
NSObject.cancelPreviousPerformRequests(withTarget: self)
windows.removeAll(keepingCapacity: false)
}
}
| true
|
379361c4e63bcf5569acdc25441a50f581e6be7e
|
Swift
|
Kyome22/KyomeUtils
|
/Sources/KyomeUtils/CGPoint+Extension.swift
|
UTF-8
| 1,899
| 3.59375
| 4
|
[
"MIT"
] |
permissive
|
//
// CGPoint+Extension.swift
//
//
// Created by Takuto Nakamura on 2021/04/14.
//
import CoreGraphics
public func + (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x + right.x, y: left.y + right.y)
}
public func += (left: inout CGPoint, right: CGPoint) {
left = left + right
}
public func - (left: CGPoint, right: CGPoint) -> CGPoint {
return CGPoint(x: left.x - right.x, y: left.y - right.y)
}
public func -= (left: inout CGPoint, right: CGPoint) {
left = left - right
}
public func * (left: CGFloat, right: CGPoint) -> CGPoint {
return CGPoint(x: left * right.x, y: left * right.y)
}
public func * (left: CGPoint, right: CGFloat) -> CGPoint {
return CGPoint(x: right * left.x, y: right * left.y)
}
public func *= (left: inout CGPoint, right: CGFloat) {
left = left * right
}
public func / (left: CGPoint, right: CGFloat) -> CGPoint {
precondition(right != 0, "divide by zero")
return CGPoint(x: left.x / right, y: left.y / right)
}
public func /= (left: inout CGPoint, right: CGFloat) {
precondition(right != 0, "divide by zero")
left = left / right
}
public extension CGPoint {
// xとyが同じ時の初期化
init(_ scalar: CGFloat) {
self.init(x: scalar, y: scalar)
}
// Intにキャスト
var intPoint: CGPoint {
return CGPoint(x: Int(self.x), y: Int(self.y))
}
// 二点間の距離を返す
func length(from: CGPoint) -> CGFloat {
return sqrt(pow(self.x - from.x, 2.0) + pow(self.y - from.y, 2.0))
}
// 二点を結んだ線分の角度(ラジアン)を返す
func radian(from: CGPoint) -> CGFloat {
return atan2(self.y - from.y, self.x - from.x)
}
// 二点を結んだ線分の角度(度)を返す
func degree(from: CGPoint) -> CGFloat {
return atan2(self.y - from.y, self.x - from.x) * 180 / CGFloat.pi
}
}
| true
|
4f299746ef4b9805148fb5509583b243ff5e92a7
|
Swift
|
AndreyNovikov2000/TwitterCloneMod
|
/TwitterClone/View/ActionSheetCell.swift
|
UTF-8
| 2,413
| 2.703125
| 3
|
[] |
no_license
|
//
// ActionSheetCell.swift
// TwitterClone
//
// Created by Andrey Novikov on 7/23/20.
// Copyright © 2020 Andrey Novikov. All rights reserved.
//
import UIKit
class ActionSheetCell: UITableViewCell {
static let reuseId = "ActionSheetCell"
// MARK: - Public properties
var option: ActionSheetOption? {
didSet {
configure()
}
}
// MARK: - Private properties
private let optionImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
imageView.clipsToBounds = true
imageView.image = UIImage(named: "twitter_logo_blue")
return imageView
}()
private let titleLabele: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = .systemFont(ofSize: 18)
label.text = "Test"
return label
}()
// MARK: - Live cycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupCell()
setupConstraintsForActionSheetCell()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private methods
private func setupCell() {
backgroundColor = .white
selectionStyle = .none
}
private func configure() {
titleLabele.text = option?.description
}
private func setupConstraintsForActionSheetCell() {
addSubview(optionImageView)
addSubview(titleLabele)
optionImageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16).isActive = true
optionImageView.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
optionImageView.heightAnchor.constraint(equalToConstant: 36).isActive = true
optionImageView.widthAnchor.constraint(equalToConstant: 36).isActive = true
titleLabele.leadingAnchor.constraint(equalTo: optionImageView.trailingAnchor, constant: 12).isActive = true
titleLabele.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16).isActive = true
titleLabele.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
}
}
| true
|
45b91bf4ece094269bb0a888ebc8379fe40c9a64
|
Swift
|
2NU71AN9/MyLib
|
/QTRadio-master/QTRadio/QTRadio/Classes/Home/Model/RecommendModel/RecommendDataModel.swift
|
UTF-8
| 1,397
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
//
// RecommendDataModel.swift
// 多层嵌套JSON
//
// Created by Enrica on 2017/11/14.
// Copyright © 2017年 Enrica. All rights reserved.
//
import UIKit
@objcMembers
class RecommendDataModel: NSObject {
// MARK: - 自定义的模型数组
/// 用于将转换完成的模型数据存储起来
lazy var recommendDataDataModelArray: [RecommendDataDataModel] = [RecommendDataDataModel]()
// MARK: - 服务器返回的模型属性
/// 标题
var title: String = ""
/// 数组数据
var data: [[String: Any]]? {
didSet {
// 首先校验数组data是否有值
guard let data = data else { return }
// 遍历数组中的字典
for dict in data {
// 将字典转为模型
let item = RecommendDataDataModel(dict: dict)
// 将转换完成的模型数据存储到数组中
recommendDataDataModelArray.append(item)
}
}
}
// MARK: - 自定义构造函数
/// 将字典转为模型
init(dict: [String: Any]) {
super.init()
// 利用KVC将字典转为模型
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) { }
}
| true
|
f15f5e24cb08e59a346581b74290daef2b9c8c5e
|
Swift
|
lubowiczmichal/Kursy-walut
|
/Kursy walut/ViewModel/CurrencyDetailsViewModel.swift
|
UTF-8
| 2,359
| 2.703125
| 3
|
[] |
no_license
|
//
// CurrencyDetailsViewModel.swift
// Kursy walut
//
// Created by Michał Lubowicz on 30/06/2021.
//
import Foundation
class CurrencyDetailsViewModel{
var nbpData: NBPDataElement?
var code: String?
var table: String?
var startDate: Date = Calendar.current.date(byAdding: .day, value: -10, to: Date())!
var endDate: Date = Date()
var currencyDetailsViewController: CurrencyDetailsViewController?
func spinnerAndLoad(){
currencyDetailsViewController?.spinner.startAnimating()
DispatchQueue.main.async {
self.load()
}
}
func load() {
let dataToParse = Api.request(url: "https://api.nbp.pl/api/exchangerates/rates/" + self.table! + "/" + self.code! + "/" + self.formatDate(date: self.startDate) + "/" + self.formatDate(date: self.endDate) + "/")
self.parse(json: dataToParse)
}
func parse(json: Data) {
let group = DispatchGroup()
group.enter()
DispatchQueue.global(qos: .background).async {
let decoder = JSONDecoder()
do {
self.nbpData = try decoder.decode(NBPDataElement.self, from: json)
} catch {
print(error.localizedDescription)
}
group.leave()
}
group.wait()
DispatchQueue.main.async { self.currencyDetailsViewController?.spinner.stopAnimating()
self.currencyDetailsViewController?.tableView.reloadData()
let top = IndexPath(row: 0, section: 0)
self.currencyDetailsViewController?.tableView.scrollToRow(at: top, at: .bottom, animated: true)
}
var sum: Double = 0.0
for rate in nbpData!.rates{
sum += rate.mid ?? (rate.ask! + rate.bid!)/2
}
let average: Double = sum/Double(nbpData!.rates.count)
currencyDetailsViewController?.textLabel.text = "Średnia cena waluty " + (nbpData?.currency)! + " w dniach " + formatDate(date: startDate) + " - " + formatDate(date: endDate) + " to " + String(format: "%.4f", average) + " PLN"
}
func formatDate(date: Date) -> String{
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: date)
}
}
| true
|
66c84a2ad4b315ff0faf7cabc0bb44a66beab4c9
|
Swift
|
KuoPingL/Swift-Samples
|
/ExperimentalCodes/Swift 4/BLE/BLE_ChatRoom/BLE_ChatRoom/Scenes/ChatRoom/ChatRoomTableViewCell.swift
|
UTF-8
| 1,363
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// ChatRoomTableViewCell.swift
// BLE_ChatRoom
//
// Created by Jimmy on 2019/8/11.
// Copyright © 2019 Jimmy. All rights reserved.
//
import Foundation
import UIKit
class ChatRoomTableViewCell: UITableViewCell, ChatRoomCellDelegate {
static let cellID = "chatRoomTableViewCell"
public var bleData: String = "" {
didSet {
user.bleData = bleData
imageView?.image = user.avatar
textLabel?.text = user.name
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd"
detailTextLabel?.text = "Last Seen : \(formatter.string(from: date))"
}
}
private var user = UserModel.defaultUser()
override func prepareForReuse() {
super.prepareForReuse()
imageView?.image = nil
textLabel?.text = nil
detailTextLabel?.text = nil
user = UserModel.defaultUser()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
textLabel?.font = UIFont.systemFont(ofSize: 20, weight: .heavy)
detailTextLabel?.font = UIFont.systemFont(ofSize: 15)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not implement")
}
}
| true
|
451689e47ac715c5789f354648bd9100aa6aa880
|
Swift
|
GRGBISHOW/Network-Manager
|
/NetworkCaller/NetworkManger/NetworkCaller.swift
|
UTF-8
| 3,611
| 2.796875
| 3
|
[] |
no_license
|
//
// NetworkCaller.swift
// NetworkCaller
//
// Created by Gurung Bishow on 6/7/18.
// Copyright © 2018 Gurung Bishow. All rights reserved.
//
import Foundation
import RxSwift
import Alamofire
import RxCocoa
import RxAlamofire
extension Encodable {
var dictionary: [String: Any]? {
guard let data = try? JSONEncoder().encode(self) else { return nil }
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] }
}
}
typealias NetworkClient = (manager: SessionManager, endpoint: Endpoint)
protocol ClientCreatable {
func createClient(withPath path:String, method:Method) -> Observable<NetworkClient>
}
class NetWorkManager: ClientCreatable {
private var manager: Alamofire.SessionManager
#if DEBUG
private let url = NetWorkManager.devURL
#elseif RELEASE
private let url = NetWorkManager.uatURL
#endif
init(withSessionType type: SessionType = .defaultConfig) {
manager = SessionConfiguration.getSessionManager(fromSessionType: type)
}
func createClient(withPath path: String, method: Method) -> Observable<NetworkClient> {
return Observable.create({(observer) -> Disposable in
//guard let slf = self else {return Disposables.create()}
if let url = URL(string: self.url) {
observer.on(.next((self.manager,Endpoint(method: method, url: self.getUrl(fromUrl: url, path: path)))))
observer.on(.completed)
}else {
observer.on(.error(NetworkError.invalidURL))
}
return Disposables.create()
})
}
private func appendPath(toBaseUrl url:URL, path: String) -> URL {
return url.appendingPathComponent(path)
}
private func getUrl(fromUrl url: URL, path: String) -> URL{
return path.contains("http") ? URL(string:path)! : appendPath(toBaseUrl: url, path: path)
}
}
extension NetWorkManager {
fileprivate static var devURL = ""
fileprivate static var uatURL = ""
enum BaseUrl {
static func set(devURl url: String) {
devURL = url
}
static func set(uatURl url: String) {
uatURL = url
}
}
}
enum SessionType {
case defaultConfig
case ephemeral
case background(String)
}
final class SessionConfiguration {
private static let sharedDefaultInstance: Alamofire.SessionManager = {
return Alamofire.SessionManager.default
}()
private static let sharedEphemeralInstance: Alamofire.SessionManager = {
return Alamofire.SessionManager(configuration: URLSessionConfiguration.ephemeral)
}()
static func getSessionManager(fromSessionType type: SessionType) -> Alamofire.SessionManager {
switch type {
case .defaultConfig:
return sharedDefaultInstance
case .ephemeral:
return sharedEphemeralInstance
case .background(let identifier):
return Alamofire.SessionManager(configuration: URLSessionConfiguration.background(withIdentifier: identifier))
}
}
}
typealias Parameters = [String: Any]
typealias Method = HTTPMethod
// MARK: Endpoint
class Endpoint {
let method: Method
let url: URL
init(method: Method, url: URL) {
self.method = method
self.url = url
}
}
extension HTTPMethod{
var encodingType:ParameterEncoding{
switch self{
case .get:
return URLEncoding.default
default:
return JSONEncoding.default
}
}
}
| true
|
5f3c9fb3fc916c9fef7c7144c4214453541cde0c
|
Swift
|
felipekpetersen/ChallengeAcessibilidade
|
/Acessibilidade/Acessibilidade/ViewControllers/Near Restaurant/NearRestaurantViewModel.swift
|
UTF-8
| 750
| 2.703125
| 3
|
[] |
no_license
|
//
// NearRestaurantViewModel.swift
// Acessibilidade
//
// Created by Pedro Henrique Guedes Silveira on 30/08/19.
// Copyright © 2019 Felipe Petersen. All rights reserved.
// swiftlint:disable trailing_whitespace
import Foundation
class NearRestaurantViewModel{
var restaurants: [RestaurantCodable] = []
var categoryName: String?
func getRestaurants(index: Int) -> RestaurantCodable {
return restaurants[index]
}
func getMenu(restaurant: RestaurantCodable, row: Int) -> MenuCodable{
return restaurant.menus?[row] ?? MenuCodable()
}
func getRestaurantsCategory(index: Int) -> String {
return categoryName ?? ""
}
func numberOfRows() -> Int {
return restaurants.count
}
}
| true
|
54c7fb5e9f01c34331d9d9cf6a9782b1914cde33
|
Swift
|
Rmurthy1/sellBook
|
/buyBooks/CustomViewIBDesignable.swift
|
UTF-8
| 3,503
| 2.921875
| 3
|
[] |
no_license
|
import UIKit
@IBDesignable class DesignableImageView: UIImageView{}
@IBDesignable class DesignableButton: UIButton{}
@IBDesignable class DesignableTextView: UITextField{
@IBInspectable
var placeholderTextColor: UIColor = UIColor.lightGrayColor(){
didSet{
guard let placeholder = placeholder else{
return
}
attributedPlaceholder = NSAttributedString(string: placeholder, attributes:
[NSForegroundColorAttributeName : placeholderTextColor])
}
}
}
class UnderlinedLabel: UILabel {
override var text: String! {
didSet {
// swift < 2. : let textRange = NSMakeRange(0, count(text))
let textRange = NSMakeRange(0, text.characters.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSUnderlineStyleAttributeName , value:NSUnderlineStyle.StyleSingle.rawValue, range: textRange)
// Add other attributes if needed
self.attributedText = attributedText
}
}
}
extension UIView {
@IBInspectable
var borderWidth: CGFloat{
get {
return layer.borderWidth
}
set(newBoarderWidth){
layer.borderWidth = newBoarderWidth
}
}
@IBInspectable
var borderColor: UIColor?{
get {
return layer.borderColor != nil ? UIColor(CGColor: layer.borderColor!) : nil
}
set {
layer.borderColor = newValue?.CGColor
}
}
@IBInspectable
var cornerRadius: CGFloat{
get{
return layer.cornerRadius
}
set{
layer.cornerRadius = newValue
layer.masksToBounds = newValue != 0
}
}
@IBInspectable
var shadowColor: UIColor?{
get{
return layer.shadowColor != nil ? UIColor(CGColor: layer.shadowColor!) : nil
}
set{
layer.backgroundColor = newValue?.CGColor
}
}
@IBInspectable
var makeCircular: Bool?{
get {
return nil
}
set {
if let makeCircular = newValue where makeCircular{
cornerRadius = min(bounds.width, bounds.height)/2.0
}
}
}
}
// added some uicolor to hex thing from https://gist.github.com/arshad/de147c42d7b3063ef7bc
extension UIColor {
// Creates a UIColor from a Hex string.
convenience init(hexString: String) {
var cString: String = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substringFromIndex(1)
}
if (cString.characters.count != 6) {
self.init(white: 0.5, alpha: 1.0)
} else {
let rString: String = (cString as NSString).substringToIndex(2)
let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)
var r: CUnsignedInt = 0, g: CUnsignedInt = 0, b: CUnsignedInt = 0;
NSScanner(string: rString).scanHexInt(&r)
NSScanner(string: gString).scanHexInt(&g)
NSScanner(string: bString).scanHexInt(&b)
self.init(red: CGFloat(r) / CGFloat(255.0), green: CGFloat(g) / CGFloat(255.0), blue: CGFloat(b) / CGFloat(255.0), alpha: CGFloat(1))
}
}
}
extension UILabel {
var substituteFontName : String {
get { return self.font.fontName }
set { self.font = UIFont(name: newValue, size: self.font.pointSize) }
}
}
| true
|
676122bce97a56c2532c62043518c95788063732
|
Swift
|
deepakchoudhary7/Components
|
/DesignLabel.swift
|
UTF-8
| 707
| 2.8125
| 3
|
[] |
no_license
|
//
// DesignLabel.swift
// Ride Share
//
// Created by Saurabh on 12/12/17.
// Copyright © 2017 Aryavrat. All rights reserved.
//
import UIKit
class DesignLabel: UILabel {
override func draw(_ rect: CGRect) {
// Drawing code
let path = UIBezierPath()
path.move(to: CGPoint(x: self.bounds.origin.x, y: self.bounds.height
- 0.5))
path.addLine(to: CGPoint(x: self.bounds.size.width, y: self.bounds.height
- 0.5))
path.lineWidth = 0.5
self.bottomColor.setStroke()
path.stroke()
}
@IBInspectable var bottomColor:UIColor = UIColor.clear {
didSet {
self.setNeedsDisplay()
}
}
}
| true
|
54ad6c44e15417362ae7f4ceae77292aa04a08ea
|
Swift
|
Daniel-zww/ZMusicPlayerSwift
|
/ZMusicPlayerSwift/UI/View/ZLyricLabel.swift
|
UTF-8
| 674
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// ZLyricLabel.swift
// ZMusicPlayerSwiftDemo
//
// Created by Daniel on 23/05/2017.
// Copyright © 2017 Z. All rights reserved.
//
import UIKit
class ZLyricLabel: UILabel {
/// 播放进度
var progress: CGFloat = 0 {
didSet {
self.setNeedsDisplay()
}
}
/// 设置颜色
override func draw(_ rect: CGRect) {
super.draw(rect)
UIColor.green.set()
let fillRect = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width * progress, height: rect.size.height)
textColor = .white
UIRectFillUsingBlendMode(fillRect, .sourceIn)
}
}
| true
|
f4652db34edd4445fa7d15b7ff9c01ef7773d6d0
|
Swift
|
rafattouqir/MyMovieApp-Rx-MVVMC
|
/MyMovieApp/Commons/Extensions/UIViewVFLExtension.swift
|
UTF-8
| 1,379
| 2.75
| 3
|
[] |
no_license
|
//
// UIViewVFLExtension.swift
// MyMovieApp
//
// Created by RAFAT TOUQIR RAFSUN on 7/7/19.
// Copyright © 2019 RAFAT TOUQIR RAFSUN. All rights reserved.
//
import UIKit
//MARK:- VFL Extensions
extension UIView {
func addConstraintsWithFormat(format: String, views: UIView... , options: NSLayoutConstraint.FormatOptions = NSLayoutConstraint.FormatOptions()) {
var viewsDictionary = [String: UIView]()
for (index, view) in views.enumerated() {
let key = "v\(index)"
viewsDictionary[key] = view
view.translatesAutoresizingMaskIntoConstraints = false
}
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: options, metrics: nil, views: viewsDictionary))
}
func boundInside(superView: UIView,inset:UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)){
self.translatesAutoresizingMaskIntoConstraints = false
superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(inset.left)-[subview]-\(inset.right)-|", options: NSLayoutConstraint.FormatOptions.directionLeadingToTrailing, metrics:nil, views:["subview":self]))
superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(inset.top)-[subview]-\(inset.bottom)-|", options: NSLayoutConstraint.FormatOptions.directionLeadingToTrailing, metrics:nil, views:["subview":self]))
}
}
| true
|
212f66fa10630400cd04c5c67c8f16b44b7d249f
|
Swift
|
carabina/Pippin
|
/Sources/Pippin/Extensions/UIKit/FormController.swift
|
UTF-8
| 4,085
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
//
// FormController.swift
// Pippin
//
// Created by Andrew McKnight on 1/11/17.
// Copyright © 2017 Two Ring Software. All rights reserved.
//
import Anchorage
import UIKit
public class FormController: NSObject {
fileprivate var textFields: [UITextField]!
fileprivate var oldTextFieldDelegates: [UITextField: UITextFieldDelegate?] = [:]
fileprivate var currentTextField: UITextField?
public init(textFields: [UITextField]) {
super.init()
self.textFields = textFields
for textField in textFields {
oldTextFieldDelegates[textField] = textField.delegate
textField.delegate = self
textField.inputAccessoryView = accessoryViewForTextField(textField: textField)
if textFields.index(of: textField)! < textFields.count - 1 {
textField.returnKeyType = .next
} else {
textField.returnKeyType = .done
}
}
}
}
// MARK: Public
public extension FormController {
func resignResponders() {
for responder in textFields {
responder.resignFirstResponder()
}
}
func accessoryViewForTextField(textField: UITextField) -> UIView {
let previousButton = UIBarButtonItem(title: "Prev", style: .plain, target: self, action: #selector(previousTextField))
if let idx = textFields.index(of: textField) {
previousButton.isEnabled = idx > 0
} else {
previousButton.isEnabled = false
}
let nextButton = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(nextTextField))
if let idx = textFields.index(of: textField) {
nextButton.isEnabled = idx < textFields.count - 1
} else {
nextButton.isEnabled = false
}
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(donePressed))
let space = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
space.width = 12
let toolbar = UIToolbar(frame: .zero)
toolbar.items = [
space,
previousButton,
space,
nextButton,
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
doneButton,
space,
]
let view = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: UIScreen.main.bounds.width, height: 44)))
view.backgroundColor = .lightGray
view.addSubview(toolbar)
toolbar.edgeAnchors == view.edgeAnchors
return view
}
}
extension FormController: UITextFieldDelegate {
// MARK: UITextField traversal
public func textFieldDidBeginEditing(_ textField: UITextField) {
currentTextField = textField
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let delegate = oldTextFieldDelegates[textField], let unwrappedDelegate = delegate {
if unwrappedDelegate.responds(to: #selector(UITextFieldDelegate.textField(_:shouldChangeCharactersIn:replacementString:))) {
return unwrappedDelegate.textField!(textField, shouldChangeCharactersIn: range, replacementString: string)
}
}
return true
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let idx = textFields.index(of: textField)!
if idx == textFields.count - 1 {
resignResponders()
} else {
nextTextField()
}
return true
}
}
@objc extension FormController {
func donePressed() {
resignResponders()
}
func nextTextField() {
let nextIdx = textFields.index(of: currentTextField!)! + 1
textFields[nextIdx].becomeFirstResponder()
}
func previousTextField() {
let previousIdx = textFields.index(of: currentTextField!)! - 1
textFields[previousIdx].becomeFirstResponder()
}
}
| true
|
cf25cccdb0d4c54fe469a189c7ceb5b7846bc64b
|
Swift
|
Dchahar/News-App
|
/News/Protocol/NewsRepositoryProtocol.swift
|
UTF-8
| 586
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// NewsRepositoryProtocol.swift
// News
//
// Created by Dheeraj Chahar on 01/02/21.
//
import UIKit
/// Protocol for news repository
protocol NewsRepositoryProtocol {
/// All available news
var news: [News] { get set }
/// To get top news from the service
func getNews()
/// To get more news from the service
func loadMoreNews()
/// Available number of news to show
func numberOfRows() -> Int
/// To show news in each cell
func cellForRowAt(indexPath: IndexPath, for cell: NewsTableViewCell) -> NewsTableViewCell
}
| true
|
e74ff74ae3dbacc6074da92ad44f12970683da09
|
Swift
|
TuckerMogren/Trigger-Tracker
|
/Trigger Tracker/View/CustomShapeButton.swift
|
UTF-8
| 1,375
| 2.75
| 3
|
[] |
no_license
|
/*
* Name: CustomShape Button Class
* Description: Allows for the welcome screen buttons to be custom.
* Author/Date: Tucker J. Mogren/ 1/18/2019
*/
import UIKit
@IBDesignable
class CustomShapeButton: UIButton
{
/*
* Function Name: customView()
* Changes button color and corner radius, adds border
* Tucker Mogren; 1/23/19
*/
func CustomView ()
{
layer.cornerRadius = 15.0
layer.borderWidth = 2.0
layer.borderColor = #colorLiteral(red: 0.6431372549, green: 0.04705882353, blue: 0.9098039216, alpha: 1)
backgroundColor = #colorLiteral(red: 0.1960784314, green: 0.3215686275, blue: 1, alpha: 1)
setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
}
/*
* Function Name: prepareForInterfaceBuilder()
* Loads the customView after the objects have been updated - Guaranteed that all the outlets and actions are connected
* Tucker Mogren; 1/23/19
*/
override func prepareForInterfaceBuilder()
{
CustomView()
}
/*
* Function Name: awakeFromNib()
* Loads the customizeView after the objects have been updated - Guaranteed that all the outlets and actions are connected
* Tucker Mogren; 1/23/19
*/
override func awakeFromNib() {
super.awakeFromNib()
CustomView()
}
}
| true
|
dd1482289a2239291091952ed1fab962c30ac7bc
|
Swift
|
greadvx/tistic-chat
|
/tistic.co/tistic.co/MessageTableViewCell.swift
|
UTF-8
| 1,473
| 2.671875
| 3
|
[] |
no_license
|
//
// MessageTableViewCell.swift
// tistic.co
//
// Created by Yan Khamutouski on 4/29/18.
// Copyright © 2018 Yan Khamutouski. All rights reserved.
//
import UIKit
class MessageTableViewCell: UITableViewCell {
//
@IBOutlet weak var profilePhoto: UIImageView!
@IBOutlet weak var nameAndSurnameLabel: UILabel!
@IBOutlet weak var lastMessagePrevLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.profilePhoto.contentMode = .scaleAspectFill
self.profilePhoto.layer.cornerRadius = 33
self.profilePhoto.layer.masksToBounds = true
}
func updateMessageCell(nameAndSurname: String, lastMessagePrev: String, profilePhoto: String, timeStamp: NSNumber?) {
self.nameAndSurnameLabel.text = nameAndSurname
self.lastMessagePrevLabel.text = lastMessagePrev
self.profilePhoto.loadImageUsingCacheWithUrlString(urlString: profilePhoto)
if let seconds = timeStamp?.doubleValue {
let timestampDate = NSDate(timeIntervalSince1970: seconds)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
self.timeLabel.text = dateFormatter.string(from: timestampDate as Date)
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| true
|
c3e73ef8f98c7033c7e105328e3ecd3e65bc9e32
|
Swift
|
peslopes/NotesCollection
|
/NotesCollection/NotesCollection/Extensions/UIViewExtension.swift
|
UTF-8
| 1,062
| 2.609375
| 3
|
[] |
no_license
|
//
// UIViewExtension.swift
// NotesCollection
//
// Created by Luiz Pedro Franciscatto Guerra on 08/06/19.
// Copyright © 2019 Pedro. All rights reserved.
//
import UIKit
extension UIView {
func addButtonTypeShaddow () {
clipsToBounds = false
layer.shadowOpacity = 0.25
layer.shadowColor = UIColor.black.cgColor
layer.shadowRadius = 4
layer.shadowOffset = CGSize(width: 0, height: 4)
}
func addNoteTypeShaddow () {
clipsToBounds = false
layer.shadowOpacity = 0.25
layer.shadowColor = UIColor.black.cgColor
layer.shadowRadius = 2
layer.shadowOffset = CGSize(width: 0, height: 2)
}
func roundTop () {
self.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]
self.layer.cornerRadius = 15
self.layer.masksToBounds = true
}
func roundBottom () {
self.layer.maskedCorners = [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]
self.layer.cornerRadius = 15
self.layer.masksToBounds = true
}
}
| true
|
a12f77cd08e04a3a373cb3fb17f7dbe3ff80f149
|
Swift
|
Syro4444/MedicaLife
|
/MedicaLife/scenes/AddTreatmentViewController.swift
|
UTF-8
| 3,479
| 2.734375
| 3
|
[] |
no_license
|
//
// AddTreatmentViewController.swift
// MedicaLife
//
// Created by Norman on 23/02/2020.
// Copyright © 2020 raphael. All rights reserved.
//
import UIKit
class AddTreatmentViewController: UIViewController,UIPickerViewDelegate, UIPickerViewDataSource
{
override var prefersStatusBarHidden: Bool {
return true
}
let traitmentWebService: TreatmentWebService = TreatmentWebService()
var keyboardVisible = false
let dose = ["1","2","3","4","5","6","7","8","9"]
//@IBOutlet weak var medicsTextField: UITextField!
//@IBOutlet weak var pickerView: UIPickerView!
//@IBOutlet weak var datePicker: UIDatePicker!
//@IBOutlet weak var hourPicker: UIDatePicker!
@IBOutlet weak var medicsTextField: UITextField!
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var hourPicker: UIDatePicker!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var commentTextField: UITextField!
@IBAction func addButton(_ sender: Any) {
let inscription = MainViewController()
self.navigationController?.pushViewController(inscription, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.medicsTextField.delegate = self
pickerView.delegate = self
pickerView.dataSource = self
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return dose.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return dose[row]
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if self.keyboardVisible == true {
self.view.endEditing(true) // close all user interaction
self.keyboardVisible = false
}
}
/**
@IBAction func submitTreatment(_ sender: UIButton) {
guard let medics = self.medicsTextField.text,
let day = self.pickerView.delegate,
let hour = self.datePicker,
let startTreatment = self.hourPicker,
let dose = self.pickerView,
let comment = self.commentTextField.text else {
return
}
let treatment = Treatment(medics: medics, day: day, hour: hour, startTreatment: startTreatment, doseByDay: dose, comment: comment)
self.traitmentWebService.addTreatment(treatment: treatment) { (success) in
print("\(success)")
}
}
*/
}
extension AddTreatmentViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
self.keyboardVisible = true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
if textField == self.medicsTextField {
return self.pickerView.becomeFirstResponder() // ouverture du clavier
}
if textField == self.pickerView {
return self.datePicker.becomeFirstResponder() // ouverture du clavier
}
if textField == self.datePicker {
return self.hourPicker.becomeFirstResponder() // ouverture du clavier
}
self.keyboardVisible = false
return false
}
}
| true
|
96de445f09c762281085338b50bddefc72f7178a
|
Swift
|
aydenp/StockKit
|
/Sources/StockKit/Model/StockPhotoResults.swift
|
UTF-8
| 661
| 2.71875
| 3
|
[] |
no_license
|
//
// StockPhotoResults.swift
// StockKit
//
// Created by Ayden Panhuyzen on 2020-01-04.
// Copyright © 2020 Ayden Panhuyzen. All rights reserved.
//
import Foundation
public struct StockPhotoResults {
/// The photos retrieved as part of this request.
public let photos: [StockPhoto]
/**
A token that can be used to provide information required to retrieve the next page, such as the last photo's ID or the offset from the previous request.
If not provided, pagination cannot be performed, such as if a service does not perform pagination or has reached the end of the returnable photos.
*/
public let paginationToken: String?
}
| true
|
950760d63668465ee22b9cc3740096106fb9eacd
|
Swift
|
HanweeeeLee/algorithm-study
|
/2021/Old/0307/Hanwe/20210307Programmers_lv2_1/20210307Programmers_lv2_1/ViewController.swift
|
UTF-8
| 2,797
| 3.3125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// 20210307Programmers_lv2_1
//
// Created by hanwe on 2021/03/07.
//
//https://programmers.co.kr/learn/courses/30/lessons/60057
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("result:\(solution("aabbaccc"))") //7
// print("result:\(solution("ababcdcdababcdcd"))") //9
// print("result:\(solution("abcabcdede"))") //8
// print("result:\(solution("abcabcabcabcdededededede"))") //14
// print("result:\(solution("xababcdcdababcdcd"))") //17
}
func solution(_ s:String) -> Int {
var shortestCnt: Int = s.count
let firstIndex = s.index(s.startIndex, offsetBy: 0)
for i in 0..<s.count { //몇개씩 끊어쓸껀지
for j in 0..<s.count { //현재 index
let start = s.index(s.startIndex, offsetBy: j)
let end = s.index(s.startIndex, offsetBy: j+i)
print("test:\(String(s[start..<end]))")
}
print("------")
}
return shortestCnt
}
// func solution(_ s:String) -> Int {
//
// var shortestCnt: Int = s.count
//
// var convertStr: String = ""
// for i in 0..<s.count {
// var copyS = s
// for j in i..<s.count {
// let startIndex = s.index(s.startIndex, offsetBy: i)
// let endIndx = s.index(s.startIndex, offsetBy: j)
// convertStr = String(s[startIndex..<endIndx])
// print("convertStr:\(convertStr)")
// copyS = s.replacingOccurrences(of: "\(convertStr)", with:"#").removeOverlap().convertOriginStrCnt(originConvertStr: convertStr)
// print("copyS:\(copyS)")
// if shortestCnt > copyS.count {
// shortestCnt = copyS.count
// print("shortestChanged!")
// }
// }
// }
//
// return shortestCnt
// }
}
extension String {
func removeOverlap() -> String {
var returnValue = self
while true {
if returnValue.contains("##") {
returnValue = returnValue.replacingOccurrences(of: "##", with:"#")
}
else {
break
}
}
return returnValue
}
func convertOriginStrCnt(originConvertStr: String) -> String {
var returnValue = self
returnValue = returnValue.replacingOccurrences(of: "#", with:"N\(originConvertStr)")
return returnValue
}
}
//let firstIndex = returnValue.index(returnValue.startIndex, offsetBy: 0)
//let lastIndex = returnValue.index(returnValue.startIndex, offsetBy: 15)
//returnValue = String(returnValue[firstIndex..<lastIndex])
| true
|
15581c2060a840462887e902ad4e38f23274b0b9
|
Swift
|
dodikk/NMessenger
|
/nMessenger/Source/Messenger/Components/CameraViewDelegate.swift
|
UTF-8
| 971
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
//
// CameraViewDelegate.swift
// nMessenger
//
// Created by Oleksandr Dodatko on 17/07/2017.
// Copyright © 2017 Ebay Inc. All rights reserved.
//
import Foundation
import UIKit
import Photos
//MARK: CameraViewController
/**
CameraViewDelegate protocol for NMessenger.
Defines methods to be implemented inorder to use the CameraViewController
*/
public protocol CameraViewDelegate : class
{
/**
Should define behavior when a photo is selected.
Is called together with `pickedImageAssets()`.
Provides UIImage objects to update the GUI.
*/
func pickedImages(_ image: [UIImage])
/**
Should define behavior when a photo is selected.
Is called together with `pickedImages()`.
Provides low level details and metadata to use with business logic.
*/
func pickedImageAssets(_ assets: [PHAsset])
/**
Should define behavior cancel button is tapped
*/
func cameraCancelSelection()
}
| true
|
e5d86faad1523c14073f9f5367be90a253ef54e7
|
Swift
|
jojjesv/fuzz-ios
|
/Fuzz/Dialog.swift
|
UTF-8
| 2,705
| 2.765625
| 3
|
[] |
no_license
|
//
// Dialog.swift
// Fuzz
//
// Created by Johan Svensson on 2017-11-19.
// Copyright © 2017 Fuzz. All rights reserved.
//
import Foundation
import UIKit
public class Dialog: NSObject {
// Retrieves the entire view.
internal func baseView() -> UIView! {
return nil
}
// Retrieves the dialog content.
internal func content() -> UIView! {
return nil
}
// Whether this dialog is cancelable by touching outside of the content view.
public var isCancelable: Bool! = true
var gesture: UITapGestureRecognizer?
public func show(parent: UIView){
let view: UIView! = self.baseView()
let content: UIView! = self.content()
view.frame.size = parent.frame.size
view.frame.origin = CGPoint(x: 0.0, y: 0.0)
parent.addSubview(view)
if let bg = view as? DialogBackgroundView {
bg.dialog = self
}
view.alpha = 0
content.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
UIView.setAnimationCurve(UIViewAnimationCurve.easeOut)
UIView.animate(withDuration: 0.3) {
view.alpha = 1
content.transform = CGAffineTransform(scaleX: 1, y: 1)
}
}
@objc public func dismiss(){
let view: UIView! = self.baseView()
let content: UIView! = self.content()
view.alpha = 1
UIView.setAnimationCurve(UIViewAnimationCurve.easeIn)
UIView.animate(withDuration: 0.3, animations: {
view.alpha = 0
content.transform = CGAffineTransform(scaleX: 0.8, y: 0.8)
}, completion: {
(finished) in
view.removeFromSuperview()
})
}
}
internal class DialogBackgroundView: UIView {
public var dialog: Dialog?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addGestureRecognizer(
UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
)
}
@objc private func handleTap(_ gesture: UIGestureRecognizer){
guard (dialog?.isCancelable)! else { return }
if subviews[0].frame.contains(gesture.location(in: self)) {
// Touched subview
return
}
dialog?.dismiss()
}
}
extension UIView {
public func absoluteSuperview() -> UIView? {
var nextParent: UIView? = superview
while true {
if nextParent?.superview == nil {
return nextParent
}
nextParent = nextParent?.superview
}
}
}
| true
|
2398269b7f5bdfdda46fc8133d86e0adbfa654d4
|
Swift
|
LIFX/rxrouter
|
/Sources/RxRouter/Helpers/UIViewController+dismissed.swift
|
UTF-8
| 1,243
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
//
// UIViewController+dismissed.swift
//
//
// Created by Alexander Stonehouse on 10/6/21.
//
import UIKit
import RxSwift
import RxCocoa
extension UIViewController {
/// If VC is embedded in a parent ViewController then we need to check whether parent is being dismissed.
fileprivate var isParentBeingDismissed: Bool {
return checkParent(self)
}
/// Recursively check the hierarchy for a VC that is being dismissed
private func checkParent(_ vc: UIViewController) -> Bool {
if let parent = vc.parent {
return parent.isBeingDismissed || checkParent(parent)
} else {
return false
}
}
}
extension Reactive where Base: UIViewController {
/// Rx observable, triggered when the view is being dismissed
public var dismissed: Completable {
Observable<[Any]>.merge(
self.sentMessage(#selector(Base.viewDidDisappear))
.filter { [unowned base] _ in base.isBeingDismissed || base.isParentBeingDismissed },
// Called when removing childVC
self.sentMessage(#selector(Base.removeFromParent))
)
.take(1)
.ignoreElements()
.asCompletable()
}
}
| true
|
7deee5473272bdc716a397be1fd312555a453253
|
Swift
|
davbeck/aws-lambda-swift-hook
|
/Sources/Lambda/Connection.swift
|
UTF-8
| 3,309
| 2.796875
| 3
|
[] |
no_license
|
import Foundation
import Socket
public class Connection {
public enum Error: Swift.Error {
case endOfStream
}
public enum ResultType: UInt8 {
case success = 1
case error = 2
}
private let socket: Socket
private var buffer = Data()
public let decoder = JSONDecoder()
public let encoder = JSONEncoder()
public init() throws {
socket = try Socket.create(family: .unix, type: .stream, proto: .unix)
}
private func connect() throws {
try socket.connect(to: "/tmp/swift.sock")
}
private func read(count: Int) throws -> Data {
while buffer.count < count {
var newData = Data()
let newCount = try socket.read(into: &newData)
buffer.append(newData)
if newCount <= 0 {
break
}
}
if buffer.count < count {
throw Error.endOfStream
}
let chunk = buffer.prefix(count)
buffer.removeFirst(count)
return chunk
}
private func readUInt32() throws -> UInt32 {
let data = try self.read(count: 4)
return data.withUnsafeBytes({ UInt32(bigEndian: $0.pointee) })
}
private func readJSON() throws -> Data {
let count = try self.readUInt32()
let data = try self.read(count: Int(count))
return data
}
private func write(_ data: Data) throws {
try self.socket.write(from: data)
}
private func write<T: FixedWidthInteger>(_ value: T) throws {
var value = value.bigEndian
let bufSize = value.bitWidth / UInt8.bitWidth
_ = try withUnsafeBytes(of: &value) { (pointer) in
try self.socket.write(from: pointer.baseAddress!, bufSize: bufSize)
}
}
private func write(json: Data) throws {
try self.write(UInt32(json.count))
try self.write(json)
}
public func start(_ handler: (Context, Data, @escaping (Result<Data>) -> Void) throws -> Void) throws {
try connect()
while true {
do {
let contextData = try self.readJSON()
let context = try decoder.decode(Context.self, from: contextData)
let payloadData = try self.readJSON()
try handler(context, payloadData) { result in
switch result {
case .success(let output):
try! self.write(Connection.ResultType.success.rawValue)
try! self.write(json: output)
case .error(let error):
console.error(error)
try! self.write(Connection.ResultType.error.rawValue)
try! self.write(json: error.jsonData())
}
}
} catch {
console.error(error)
try! self.write(Connection.ResultType.error.rawValue)
}
}
}
public func start<Input: Decodable, Output: Encodable>(_ handler: (Context, Input, @escaping (Result<Output>) -> Void) throws -> Void) throws {
try self.start { (context, inputData: Data, completion: @escaping (Result<Data>) -> Void) in
let input = try decoder.decode(Input.self, from: inputData)
try handler(context, input) { result in
switch result {
case .success(let output):
let outputData = try! self.encoder.encode(output)
completion(.success(outputData))
case .error(let error):
completion(.error(error))
}
}
}
}
}
public func start<Input: Decodable, Output: Encodable>(_ handler: (Context, Input, @escaping (Result<Output>) -> Void) throws -> Void) {
do {
let server = try Connection()
try server.start(handler)
} catch {
console.error(error)
fatalError("failed to setup connection")
}
}
| true
|
10ddd6f73b5718de459508cdc3fd2517f9ee26db
|
Swift
|
arthurfjadecastro/aapp
|
/AAPP/GPSUpdatesHandler.swift
|
UTF-8
| 784
| 2.546875
| 3
|
[] |
no_license
|
//
// GPSUpdatesHandler.swift
// AAPP
//
// Created by Arthur Castro on 26/12/2018.
// Copyright © 2018 Arthur Castro. All rights reserved.
//
import Foundation
import GoogleMaps
struct GPSUpdatesHandler: GPSDelegate {
private weak var mapViewController: MapViewController?
init(mapViewController: MapViewController) {
self.mapViewController = mapViewController
}
func gps(_ gps: GPS, didUpdate location: Coordinate) {
let _location = CLLocationCoordinate2D(coordinate: location)
let _camera = GMSCameraPosition.camera(withTarget: _location , zoom: 15)
self.mapViewController?.mapView?.camera = _camera
//print(self.mapViewController?.mapView?.myLocation?.coordinate)
//print("aeae\(_location)")
}
}
| true
|
2965217817e036cc16279af36664e47510854f0b
|
Swift
|
vmsavka/CmrUI
|
/CmrUI/Helpers/Color+Random.swift
|
UTF-8
| 360
| 2.625
| 3
|
[] |
no_license
|
//
// Color+Random.swift
// CmrUI
//
import Foundation
import UIKit
extension UIColor {
static func random() -> UIColor {
return UIColor(
red: CGFloat(arc4random_uniform(255))/255.0,
green: CGFloat(arc4random_uniform(255))/255.0,
blue: CGFloat(arc4random_uniform(255))/255.0,
alpha: 1.0)
}
}
| true
|
61c4d1fd8277c88075899184e753af06d4c7b256
|
Swift
|
carabina/ThemeColor
|
/ThemeColor/UIImageExtension.swift
|
UTF-8
| 663
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// UIImageExtension.swift
// ThemeColor
//
// Created by KyleRuan on 2018/1/7.
// Copyright © 2018年 KyleRuan. All rights reserved.
//
import UIKit
extension UIImage {
public convenience init?(themeName:String?) {
guard let imageName = themeName else {
return nil
}
var themedName = imageName
do {
themedName = try ThemeManager.sharedManager.getImageName(imageName: imageName)
} catch let ThemeChangeError.ImagePrefixConfig(state) {
print(state)
}catch {
print("unexpected error")
}
self.init(named: themedName)
}
}
| true
|
7683c35cfb6065659d3c9edec231ef2fe756d860
|
Swift
|
Mindinventory/MIFieldValidator
|
/ValidationsDemo/Helper/MIValidations.swift
|
UTF-8
| 20,908
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
//
// MIValidations.swift
// ValidationsDemo
//
// Created by mac-0008 on 05/10/19.
// Copyright © 2019 Mac-0008. All rights reserved.
//
import Foundation
import UIKit
//MARK:- Validation Enums -
enum ValidationOptions {
case notEmpty, email, password, gender, dateOfBirth, mobileNumber, msgRange
}
//MARK:- Validation Messages -
private let charLimitForName = 15
private let minAge = 1
// Email
let CBlankEmail = "Please enter your email address."
let CBlankInvalidEmail = "Please enter a valid email address."
// MobileNumber
let CBlankPhoneNumber = "Please enter your phone number."
let CInvalidPhoneNumber = "Please enter a valid phone number."
// ChangePassword
private let CBlankOldPswd = "Please enter your old password."
let CBlankPswd = "Please enter your password."
private let CBlankNewPswd = "Please enter a new password."
private let CInvalidNewPswd = "Password must be a minimum of 8 characters alphanumeric and must contain at least one special character."
private let CMismatchNewConfirmPswd = "New password and confirm password doesn’t match."
private let CSameOldNewPswd = "New Password can not be same as Old password."
private let CSameCurrentOldPswd = "Old Password must be same as Current Password"
// Message or note
private let CBlankMessage = "Please enter a message"
// Sign up
let CBlankGender = "Please select gender"
let CBlankDateOfBirth = "Please select date of birth"
private let CMinAge = "Age should be greater than required"
let CBlankFullName = "Please enter your name"
private let CBlankConfirmPswd = "Please enter confirm password."
private let CExceedNameCharacterCount = "Name should not be more than 15 characters"
let CMale = "Male"
let CFemale = "Female"
let COther = "Other"
// Constants
let COk = "Ok"
let CshadowColor = "shadowColor"
let CCurrentPassword = "mind@123"
let CPasswordChangeAlert = "Password Changed Succesfully"
let logOutTitle = "Settings"
let dateFormat = "dd MMM yyyy"
let CSharedApplication = UIApplication.shared
let appDelegate = CSharedApplication.delegate as! AppDelegate
// Get Top Most View Controller
var CTopMostViewController: UIViewController {
get { return CSharedApplication.topMostViewControllerMIV }
set {}
}
let CMainScreen = UIScreen.main
let CBounds = CMainScreen.bounds
let CScreenSize = CBounds.size
let CScreenWidth = CScreenSize.width
//MARK:- Validation methods -
struct ValidationModel {
let validation: ValidationOptions?
let value: Any?
let message: String?
}
class MIValidation {
/// This Method Check to text is Blank or Not
///
/// - Parameters:
/// - text: here we need to pass the text which you want to check for blank validatin
/// - message: here we need to pass message that you want to show in alert when that field is empty
/// - Returns: check the validation successful
private static func isNotBlank(_ text: String?, _ message: String) -> Bool {
if let strText = text {
if strText.isBlank {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: message, btnOneTitle: COk, btnOneTapped: nil)
return false
}
return true
}
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: message, btnOneTitle: COk, btnOneTapped: nil)
return false
}
/// This Method Check to Validation of Email(Blank and Valid)
///
/// - Parameter text: here we need to pass the text which you want to check for email validatin
/// - Returns: check the validation successful
static func isValidEmail(_ text: String?) -> Bool {
if let strEmail = text {
if strEmail.isBlank {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankEmail, btnOneTitle: COk, btnOneTapped: nil)
return false
}
if !strEmail.isValidEmail {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankInvalidEmail, btnOneTitle: COk, btnOneTapped: nil)
return false
}
return true
}
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankEmail, btnOneTitle: COk, btnOneTapped: nil)
return false
}
/// This Method Check to Validation of Mobile Number(Blank and Valid)
///
/// - Parameter text: here we need to pass the text which you want to check for email validatin
/// - Returns: check the validation successful
private static func isValidMobileNumber(_ text: String?) -> Bool {
if let strMobile = text {
if strMobile.isBlank {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankPhoneNumber, btnOneTitle: COk, btnOneTapped: nil)
return false
}
if !strMobile.isValidPhone {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CInvalidPhoneNumber, btnOneTitle: COk, btnOneTapped: nil)
return false
}
return true
}
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankPhoneNumber, btnOneTitle: COk, btnOneTapped: nil)
return false
}
/// This Method Check to Validation of Password
///
/// - Parameters:
/// - text: here we need to pass the text which you want to check for password validation
/// - message: This Message show on Alert
/// - Returns: check the validation successful
private static func isValidPassword(_ text: String?, _ message: String?) -> Bool {
if let strPassword = text {
if strPassword.isBlank {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: message, btnOneTitle: COk, btnOneTapped: nil)
return false
}
if !strPassword.isValidPassword {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CInvalidNewPswd, btnOneTitle: COk, btnOneTapped: nil)
return false
}
return true
}
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: message, btnOneTitle: COk, btnOneTapped: nil)
return false
}
/// This method is used to check the passwords matching and mismatching
///
/// - Parameters:
/// - password: here we need to pass the text which you want to check for password validation
/// - cPassword: here we need to pass the text which you want to check for Confiorm password validation
/// - Returns: check the validation successful
private static func isMatchedPasswords(_ password: String?, _ cPassword: String?) -> Bool {
if let strPassword = password {
if strPassword.isBlank {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankPswd, btnOneTitle: COk, btnOneTapped: nil)
return false
}
if !strPassword.isValidPassword {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CInvalidNewPswd, btnOneTitle: COk, btnOneTapped: nil)
return false
}
if strPassword != cPassword {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CMismatchNewConfirmPswd, btnOneTitle: COk, btnOneTapped: nil)
return false
}
return true
}
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankPswd, btnOneTitle: COk, btnOneTapped: nil)
return false
}
/// This method is used to check the passwords matching and mismatching
///
/// - Parameters:
/// - password1: here we need to pass the text which you want to check for password1
/// - password2: here we need to pass the text which you want to check for password2
/// - isOldAndCurrent: here we pass to boolean for which message show on Alert
/// - Returns: check the validation successful
private static func checkPasswordsSame(_ password1: String, _ password2: String, _ isOldAndCurrent: Bool) -> Bool {
if password1 != password2 {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: isOldAndCurrent ? CSameCurrentOldPswd : CMismatchNewConfirmPswd , btnOneTitle: COk, btnOneTapped: nil)
return false
}
return true
}
/// This Function use For Change Password Validation
///
/// - Parameters:
/// - currentPassword: here we need to pass the text which you want to check for current password validation
/// - oldPassword: here we need to pass the text which you want to check for old password validation
/// - newPassword: here we need to pass the text which you want to check for new password validation
/// - confirmPassword: here we need to pass the text which you want to check for confirm password validation
/// - Returns: check the validation successful
static func changePassword(currentPassword: String, _ oldPassword: String, _ newPassword: String, _ confirmPassword: String) -> Bool {
if oldPassword.isBlank {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankOldPswd, btnOneTitle: COk, btnOneTapped: nil)
return false
}
if !checkPasswordsSame(currentPassword, oldPassword, true) {
return false
}
if !isValidPassword(newPassword, CBlankNewPswd) {
return false
}
if oldPassword == newPassword {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CSameOldNewPswd, btnOneTitle: COk, btnOneTapped: nil)
return false
}
if confirmPassword.isBlank {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankConfirmPswd, btnOneTitle: COk, btnOneTapped: nil)
return false
}
if !checkPasswordsSame(newPassword, confirmPassword, false) {
return false
}
return true
}
/// This Method check to char limit of String
///
/// - Parameters:
/// - text: here we need to pass the text which you want to check the limit of string
/// - charMaxLimit: here we need to pass the value if there is any min character count
/// - message: here we need to pass the message that you want to show in alert
/// - Returns: check the validation successfull
private static func isMessageInRange(_ text: String?, _ charMaxLimit: Int, _ message: String) -> Bool {
if let strText = text {
if strText.isBlank {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: message, btnOneTitle: COk, btnOneTapped: nil)
return false
}
if strText.count > charMaxLimit {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CExceedNameCharacterCount, btnOneTitle: COk, btnOneTapped: nil)
return false
}
return true
}
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankMessage, btnOneTitle: COk, btnOneTapped: nil)
return false
}
/// This function get to age from birthDate
///
/// - Parameter birthDate: here we need to pass the text which you want to check the date
/// - Returns: check the validation successfull
private static func age(birthDate: Date?) -> Int {
let now = Date()
if let birthday = birthDate {
let calendar = Calendar.current
let ageComponents = calendar.dateComponents([.year], from: birthday, to: now)
let age = ageComponents.year!
return age
}
return 0
}
/// This method check to validation For Login
///
/// - Parameters:
/// - userName: here we need to pass username
/// - password: here we need to pass password
/// - isEmailLogin: if that is not any email login then we should pass false otherwise true
/// - Returns: check the Login successfull
static func isUserCanAbleToLogin(_ userName: String, _ password: String, _ isEmailLogin: Bool = true) -> Bool {
if userName.isBlank {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankEmail, btnOneTitle: COk, btnOneTapped: nil)
return false
}
if isEmailLogin {
if !userName.isValidEmail {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankInvalidEmail, btnOneTitle: COk, btnOneTapped: nil)
return false
}
}
if password.isBlank || !password.isValidPassword{
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankPswd, btnOneTitle: COk, btnOneTapped: nil)
return false
}
return true
}
/// This Function check to minAge
///
/// - Parameters:
/// - minAge: here we need to pass min age if there is any min age validation otherwise need pass 0
/// - text: here we need to pass dateOfbirth string value
/// - date: here we need to pass dateOfbirth date value
/// - Returns: check the Login successfull
private static func isDOB(_ minimumAge: Int = minAge, text: String?, date: Date?) -> Bool {
if let strText = text {
if strText.isBlank {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankDateOfBirth, btnOneTitle: COk, btnOneTapped: nil)
return false
}
let age = MIValidation.age(birthDate: date)
if age < minimumAge {
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CMinAge, btnOneTitle: COk, btnOneTapped: nil)
return false
}
return true
}
CTopMostViewController.presentAlertViewWithOneButtonMIV(alertTitle: nil, alertMessage: CBlankDateOfBirth, btnOneTitle: COk, btnOneTapped: nil)
return false
}
/// This Method is use for Form Validation Like SignUp
///
/// - Parameter validationModel: this parameter use for pass validation model like Message, Validation Option and Value
/// - Returns: check the Validation successfull
static func isValidData(_ validationModel: [ValidationModel]) -> Bool {
for validateModel in validationModel {
switch validateModel.validation {
case .notEmpty?:
if !isNotBlank(validateModel.value as? String, validateModel.message ?? "") {
return false
}
continue
case .msgRange?:
if !isMessageInRange(validateModel.value as? String, charLimitForName, validateModel.message ?? "") {
return false
}
continue
case .mobileNumber?:
if !isValidMobileNumber(validateModel.value as? String) {
return false
}
continue
case .email?:
if !isValidEmail(validateModel.value as? String) {
return false
}
continue
case .dateOfBirth?:
let date = DateFormatter.sharedMIV().dateMIV(fromString: validateModel.value as? String ?? "", dateFormat: "dd MM YYYY")
if !isDOB(text: validateModel.value as? String, date: date) {
return false
}
continue
case .password?:
if !isValidPassword(validateModel.value as? String, validateModel.message) {
return false
}
continue
default:
continue
}
}
return true
}
}
//MARK:- Extension - DateFormatter Singleton -
extension DateFormatter {
private static var sharedInstanceMIV: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone.system
return dateFormatter
}()
static func sharedMIV() -> DateFormatter {
return sharedInstanceMIV
}
func stringMIV(fromDate: Date, dateFormat: String) -> String {
self.dateFormat = dateFormat
return self.string(from: fromDate)
}
func dateMIV(fromString: String, dateFormat: String) -> Date? {
self.dateFormat = dateFormat
return self.date(from: fromString)
}
}
// MARK:- Extenstion UI ViewController -
extension UIViewController {
typealias alertActionHandler = ((UIAlertAction) -> ())?
/// This Method is used to show AlertView with one Button.
///
/// - Parameters:
/// - alertTitle: A String value that indicates the title of AlertView , it is Optional so you can pass nil if you don't want Alert Title.
/// - alertMessage: A String value that indicates the title of AlertView , it is Optional so you can pass nil if you don't want alert message.
/// - btnOneTitle: A String value - Title of button.
/// - btnOneTapped: Button Tapped Handler (Optional - you can pass nil if you don't want any action).
func presentAlertViewWithOneButtonMIV(alertTitle: String?, alertMessage: String?, btnOneTitle: String, btnOneTapped: alertActionHandler) {
let alertController = UIAlertController(title: alertTitle ?? "", message: alertMessage ?? "", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: btnOneTitle, style: .default, handler: btnOneTapped))
self.present(alertController, animated: true, completion: nil)
}
}
// MARK:- extension String -
extension String {
var trim: String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
var isBlank: Bool {
return self.trim.isEmpty
}
var isNotBlank: Bool {
return !self.isBlank
}
var isValidEmail: Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9-]+\\.[A-Za-z]{2,4}"
let predicate = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return predicate.evaluate(with:self)
}
var isValidPhoneNo: Bool {
let phoneCharacters = CharacterSet(charactersIn: "+0123456789").inverted
let arrCharacters = self.components(separatedBy: phoneCharacters)
return self == arrCharacters.joined(separator: "")
}
var isValidPassword: Bool {
let passwordRegex = "^(?=.*[a-z])(?=.*[@$!%*#?&])[0-9a-zA-Z@$!%*#?&]{8,}"
let predicate = NSPredicate(format:"SELF MATCHES %@", passwordRegex)
return predicate.evaluate(with:self)
}
var isValidPhone: Bool {
let phoneRegex = "^[0-9+]{0,1}+[0-9]{4,15}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneRegex)
return phoneTest.evaluate(with: self)
}
var isValidURL: Bool {
let urlRegEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
return NSPredicate(format: "SELF MATCHES %@", urlRegEx).evaluate(with: self)
}
}
// MARK:- Extension UI Application -
extension UIApplication {
var topMostViewControllerMIV: UIViewController {
var topViewController = self.keyWindow?.rootViewController
while topViewController?.presentedViewController != nil {
topViewController = topViewController?.presentedViewController
}
return topViewController!
}
}
| true
|
2c8b77c0ef3d24555781f06d5261d8911a18225b
|
Swift
|
mahmutmercan/Weather
|
/Weather/TVC/DailyWeatherCell/DailyWeatherTableViewCell.swift
|
UTF-8
| 3,298
| 2.859375
| 3
|
[] |
no_license
|
//
// DailyWeatherTableViewCell.swift
// Weather
//
// Created by Mahmut MERCAN on 1.12.2020.
//
import UIKit
class DailyWeatherTableViewCell: UITableViewCell {
@IBOutlet var dayLabel: UILabel!
@IBOutlet var highTempLabel: UILabel!
@IBOutlet var lowTempLabel: UILabel!
@IBOutlet var iconImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
static let identifier = "DailyWeatherTableViewCell"
static func nib() -> UINib {
return UINib(nibName: "DailyWeatherTableViewCell", bundle: nil)
}
func configure(with model: DailyWeatherEntry) {
self.highTempLabel.textAlignment = .center
self.lowTempLabel.textAlignment = .center
let temparatureLowResult = calculateCelsius(fahrenheit: model.temperatureLow)
let temparatureHighResult = calculateCelsius(fahrenheit: model.temperatureHigh)
self.lowTempLabel.text = "\(String(temparatureLowResult))°"
self.highTempLabel.text = "\(String(temparatureHighResult))°"
self.dayLabel.text = getDayForDate(Date(timeIntervalSince1970: Double(model.time)))
self.iconImageView.contentMode = .scaleAspectFill
let icon = model.icon.lowercased()
if icon.contains("clear-day") {
self.iconImageView.image = UIImage(named: "Sun")
} else if icon.contains("clear-night") {
self.iconImageView.image = UIImage(named: "Moon")
} else if icon.contains("rain"){
self.iconImageView.image = UIImage(named: "Cloud_angled_rain")
} else if icon.contains("clear"){
self.iconImageView.image = UIImage(named: "Sun")
} else if icon.contains("snow"){
self.iconImageView.image = UIImage(named: "Big snow")
} else if icon.contains("sleet"){
self.iconImageView.image = UIImage(named: "Cloud_little_snow")
} else if icon.contains("wind"){
self.iconImageView.image = UIImage(named: "Fast_winds")
} else if icon.contains("fog"){
self.iconImageView.image = UIImage(named: "fog")
} else if icon.contains("hail"){
self.iconImageView.image = UIImage(named: "Cloud_hailstone")
} else if icon.contains("cloudy"){
self.iconImageView.image = UIImage(named: "Cloud")
} else if icon.contains("partly-cloudy-day"){
self.iconImageView.image = UIImage(named: "sun_cloud")
} else {
self.iconImageView.image = UIImage(named: "Big_rain_drops")
}
}
func getDayForDate(_ date: Date?) -> String {
guard let inputDate = date else {
return ""
}
let formatter = DateFormatter()
formatter.dateFormat = "EEEE" // Monday
return formatter.string(from: inputDate)
}
func calculateCelsius(fahrenheit: Double) -> Double {
var celsius: Double
var roundedCelsius: Double
celsius = (fahrenheit - 32) / 1.8
roundedCelsius = Double(round(10*celsius)/10)
return roundedCelsius
}
}
| true
|
be5584168110a8710226eddadcacb1fbf8b553da
|
Swift
|
shahriarRahmanShaon/Mac-Pint.
|
/Mac Pint./Views/TabButton.swift
|
UTF-8
| 1,404
| 2.75
| 3
|
[] |
no_license
|
//
// TabButton.swift
// Mac Pint.
//
// Created by sergio shaon on 5/5/21.
//
import SwiftUI
struct TabButton: View {
var image: String
var text: String
@Binding var selected: String
var animation: Namespace.ID
var body: some View {
Button(action: {
withAnimation {
selected = text
}
}, label: {
HStack(spacing: 20){
Image(systemName:image)
.font(.title2)
.foregroundColor(selected == text ? Color.black : Color.black.opacity(0.4))
.frame(width: 25)
Text(text)
.font(.callout)
.fontWeight(selected == text ? .semibold : .none)
.foregroundColor(selected == text ? Color.black : Color.black.opacity(0.4))
}
Spacer()
// tab indicator
ZStack{
Capsule()
.fill(Color.clear)
.frame(width: 3, height: 20)
if selected == text{
Capsule()
.fill(Color.red)
.frame(width: 3, height: 25)
.matchedGeometryEffect(id: "tab", in: animation)
}
}
})
.padding(.horizontal)
.buttonStyle(PlainButtonStyle())
}
}
| true
|
8507693d866356b220c1cf9f03af7cc6143ed8b3
|
Swift
|
jeffyjkang/ios-tictactoe-unit-tests
|
/TicTacToeTests/GameAITests.swift
|
UTF-8
| 4,935
| 2.84375
| 3
|
[] |
no_license
|
//
// GameAITests.swift
// TicTacToeTests
//
// Created by Jeff Kang on 1/18/21.
// Copyright © 2021 Lambda School. All rights reserved.
//
import XCTest
@testable import TicTacToe
class GameAITests: XCTestCase {
// Horizontal 1 - 3
func testWinHorizontal1() {
var board = GameBoard()
try! board.place(mark: .x, on: (0, 0))
try! board.place(mark: .o, on: (0, 1))
try! board.place(mark: .x, on: (1, 0))
try! board.place(mark: .o, on: (1, 1))
try! board.place(mark: .x, on: (2, 0))
XCTAssertTrue(game(board: board, isWonBy: .x))
XCTAssertFalse(game(board: board, isWonBy: .o))
}
func testWinHorizontal2() {
var board = GameBoard()
try! board.place(mark: .x, on: (0, 1))
try! board.place(mark: .o, on: (0, 2))
try! board.place(mark: .x, on: (1, 1))
try! board.place(mark: .o, on: (1, 2))
try! board.place(mark: .x, on: (2, 1))
XCTAssertTrue(game(board: board, isWonBy: .x))
XCTAssertFalse(game(board: board, isWonBy: .o))
}
func testWinHorizontal3() {
var board = GameBoard()
try! board.place(mark: .x, on: (0, 2))
try! board.place(mark: .o, on: (0, 0))
try! board.place(mark: .x, on: (1, 2))
try! board.place(mark: .o, on: (1, 0))
try! board.place(mark: .x, on: (2, 2))
XCTAssertTrue(game(board: board, isWonBy: .x))
XCTAssertFalse(game(board: board, isWonBy: .o))
}
// Vertical 1 - 3
func testWinCheckingVertical1() {
var board = GameBoard()
try! board.place(mark: .x, on: (0, 0))
try! board.place(mark: .o, on: (1, 0))
try! board.place(mark: .x, on: (0, 1))
try! board.place(mark: .o, on: (1, 1))
try! board.place(mark: .x, on: (0, 2))
XCTAssertTrue(game(board: board, isWonBy: .x))
XCTAssertFalse(game(board: board, isWonBy: .o))
}
func testWinCheckingVertical2() {
var board = GameBoard()
try! board.place(mark: .x, on: (1, 0))
try! board.place(mark: .o, on: (2, 0))
try! board.place(mark: .x, on: (1, 1))
try! board.place(mark: .o, on: (2, 1))
try! board.place(mark: .x, on: (1, 2))
XCTAssertTrue(game(board: board, isWonBy: .x))
XCTAssertFalse(game(board: board, isWonBy: .o))
}
func testWinCheckingVertical3() {
var board = GameBoard()
try! board.place(mark: .x, on: (2, 0))
try! board.place(mark: .o, on: (0, 0))
try! board.place(mark: .x, on: (2, 1))
try! board.place(mark: .o, on: (0, 1))
try! board.place(mark: .x, on: (2, 2))
XCTAssertTrue(game(board: board, isWonBy: .x))
XCTAssertFalse(game(board: board, isWonBy: .o))
}
// Diagonal rtl, ltr
func testWinCheckingDiagonalrtl() {
var board = GameBoard()
try! board.place(mark: .x, on: (0, 1))
try! board.place(mark: .o, on: (0, 0))
try! board.place(mark: .x, on: (1, 2))
try! board.place(mark: .o, on: (1, 1))
try! board.place(mark: .x, on: (2, 1))
try! board.place(mark: .o, on: (2, 2))
XCTAssertTrue(game(board: board, isWonBy: .o))
XCTAssertFalse(game(board: board, isWonBy: .x))
}
func testWinCheckingDiagonalltr() {
var board = GameBoard()
try! board.place(mark: .x, on: (2, 1))
try! board.place(mark: .o, on: (2, 0))
try! board.place(mark: .x, on: (1, 0))
try! board.place(mark: .o, on: (1, 1))
try! board.place(mark: .x, on: (0, 1))
try! board.place(mark: .o, on: (0, 2))
XCTAssertTrue(game(board: board, isWonBy: .o))
XCTAssertFalse(game(board: board, isWonBy: .x))
}
// Incomplete game
func testIncompleteGame() {
var board = GameBoard()
try! board.place(mark: .x, on: (0, 0))
try! board.place(mark: .o, on: (0, 2))
try! board.place(mark: .x, on: (1, 1))
try! board.place(mark: .o, on: (1, 0))
try! board.place(mark: .x, on: (2, 0))
try! board.place(mark: .o, on: (2, 2))
XCTAssertFalse(game(board: board, isWonBy: .o))
XCTAssertFalse(game(board: board, isWonBy: .x))
}
// Cats game
func testCatsGame() {
var board = GameBoard()
try! board.place(mark: .x, on: (0, 0))
try! board.place(mark: .o, on: (1, 0))
try! board.place(mark: .x, on: (2, 0))
try! board.place(mark: .o, on: (1, 1))
try! board.place(mark: .x, on: (0, 1))
try! board.place(mark: .o, on: (0, 2))
try! board.place(mark: .x, on: (2, 1))
try! board.place(mark: .o, on: (2, 2))
try! board.place(mark: .x, on: (1, 2))
XCTAssertTrue(board.isFull)
XCTAssertFalse(game(board: board, isWonBy: .o))
XCTAssertFalse(game(board: board, isWonBy: .x))
}
}
| true
|
1a3310d91f58936cb2b66cf40983320aa520948f
|
Swift
|
zizlak/SBChat
|
/ChatSwiftBook/Screens/Cell/ActiveChatCell.swift
|
UTF-8
| 4,201
| 2.609375
| 3
|
[] |
no_license
|
//
// ActiveChatCell.swift
// ChatSwiftBook
//
// Created by Aleksandr Kurdiukov on 03.07.21.
//
import UIKit
class ActiveChatCell: UICollectionViewCell, SelfConfiguringCell {
//MARK: - Interface
let friendImageView = UIImageView()
let friendNameLabel = UILabel(text: "UserName", font: .laoSangmamMN20)
let lastMessageLabel = UILabel(text: "How R U?", font: .laoSangmamMN18)
let gradientView = GradientView(from: .topTrailing, to: .bottomLeading, start: #colorLiteral(red: 0.7882352941, green: 0.631372549, blue: 0.9411764706, alpha: 1), end: #colorLiteral(red: 0.4784313725, green: 0.6980392157, blue: 0.9215686275, alpha: 1))
//MARK: - Properties
static var reuseID: String = String(describing: ActiveChatCell.self)
//MARK: - LifeCycle Methods
override init(frame: CGRect) {
super.init(frame: frame)
setupCell()
setupConstraints()
friendImageView.contentMode = .scaleAspectFill
friendImageView.clipsToBounds = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Methods
func configureWith<U>(value: U) where U : Hashable {
guard let chat: MChat = value as? MChat else { return }
friendImageView.sd_setImage(with: URL(string: chat.friendAvatarStringURL))
friendNameLabel.text = chat.friendUsername
lastMessageLabel.text = chat.lastMessageContent
}
private func setupCell() {
backgroundColor = .white
layer.cornerRadius = 8
clipsToBounds = true
}
private func setupConstraints() {
self.addViews(friendImageView, friendNameLabel, lastMessageLabel, gradientView)
friendImageView.translatesAutoresizingMaskIntoConstraints = false
friendImageView.backgroundColor = .orange
friendNameLabel.translatesAutoresizingMaskIntoConstraints = false
lastMessageLabel.translatesAutoresizingMaskIntoConstraints = false
gradientView.translatesAutoresizingMaskIntoConstraints = false
gradientView.backgroundColor = .purple
NSLayoutConstraint.activate([
friendImageView.centerYAnchor.constraint(equalTo: centerYAnchor),
friendImageView.leadingAnchor.constraint(equalTo: leadingAnchor),
friendImageView.heightAnchor.constraint(equalToConstant: 78),
friendImageView.widthAnchor.constraint(equalTo: friendImageView.heightAnchor),
gradientView.centerYAnchor.constraint(equalTo: centerYAnchor),
gradientView.trailingAnchor.constraint(equalTo: trailingAnchor),
gradientView.heightAnchor.constraint(equalToConstant: 78),
gradientView.widthAnchor.constraint(equalToConstant: 8),
friendNameLabel.topAnchor.constraint(equalTo: topAnchor, constant: 16),
friendNameLabel.leadingAnchor.constraint(equalTo: friendImageView.trailingAnchor, constant: 8),
friendNameLabel.trailingAnchor.constraint(equalTo: gradientView.leadingAnchor, constant: -8),
lastMessageLabel.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8),
lastMessageLabel.leadingAnchor.constraint(equalTo: friendImageView.trailingAnchor, constant: 8),
lastMessageLabel.trailingAnchor.constraint(equalTo: gradientView.leadingAnchor, constant: -8)
])
}
}
//MARK: - PreviewProvider
import SwiftUI
struct ActiveChatCellProvider: PreviewProvider {
static var previews: some View {
ContainerView().edgesIgnoringSafeArea(/*@START_MENU_TOKEN@*/.all/*@END_MENU_TOKEN@*/)
}
struct ContainerView: UIViewControllerRepresentable {
let vc = MainTabBarController(user: MUser(username: "Stepan", avatarStringURL: "", id: "1", description: "HoHoHo", gender: "male"))
func makeUIViewController(context: Context) -> MainTabBarController {
return vc
}
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
}
}
}
| true
|
04ed24d65e1e2e5646e032b81801f8e1683e0dd8
|
Swift
|
ryanneilstroud/Heart-Rate-Tracker
|
/Heart Rate Tracker/Components/FloatingButton.swift
|
UTF-8
| 453
| 2.625
| 3
|
[] |
no_license
|
//
// FloatingButton.swift
// Heart Rate Tracker
//
// Created by Ryan Neil Stroud on 10/8/2021.
//
import UIKit
class FloatingButton: UIButton {
required init?(coder: NSCoder) {
super.init(coder: coder)
layer.cornerRadius = frame.height / 2
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 1, height: 1)
layer.shadowRadius = 5
layer.shadowOpacity = 0.2
}
}
| true
|
2d9a9cf1553d2a4d749408c7fb4a66731ebe1c2d
|
Swift
|
pingwinator/github
|
/GithubClient/GithubAPI/Common/RechabilityManager.swift
|
UTF-8
| 3,102
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// RechabilityManager.swift
// GithubAPI
//
// Created by Vasyl Liutikov on 06.02.2018.
// Copyright © 2018 pingwinator. All rights reserved.
//
import Alamofire
import Foundation
public enum VLNetworkReachabilityStatus: Int {
case unknown
case notReachable
case reachableViaWWAN
case reachableViaWiFi
public var isReachable: Bool {
switch self {
case .notReachable:
return false
default:
return true
}
}
}
final class VLReachabilityManager: NSObject {
static let shared = VLReachabilityManager()
fileprivate let manager = NetworkReachabilityManager()
/// The current network reachability status.
var networkReachabilityStatus: VLNetworkReachabilityStatus = .unknown
/// A callback to be executed when the network availability changes.
public var onReachabilityStatusChanged: ((VLNetworkReachabilityStatus) -> Void)?
/// Whether or not the network is currently reachable.
var isReachable: Bool {
guard let manager = self.manager else { return true }
return manager.isReachable || manager.networkReachabilityStatus == .unknown
}
fileprivate override init() {
super.init()
manager?.listener = { [unowned self] status in
self.networkReachabilityStatus = status.convertToVLReachabilityStatus()
self.onReachabilityStatusChanged?(self.networkReachabilityStatus)
DispatchQueue.main.async {
let notification = NotificationCenter.default
let userInfo: [String: VLNetworkReachabilityStatus] = [VLReachabilityNotificationStatusItem: self.networkReachabilityStatus]
notification.post(name: NSNotification.Name.VLNetworkingReachabilityDidChange, object: nil, userInfo: userInfo)
}
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/// Start monitoring network reachability
func startMonitoring() {
manager?.startListening()
}
/// Stop monitoring network reachability
func stopMonitoring() {
manager?.stopListening()
}
}
extension NetworkReachabilityManager.NetworkReachabilityStatus {
func convertToVLReachabilityStatus() -> VLNetworkReachabilityStatus {
switch self {
case .notReachable:
return VLNetworkReachabilityStatus.notReachable
case .reachable(.ethernetOrWiFi):
return VLNetworkReachabilityStatus.reachableViaWiFi
case .reachable(.wwan):
return VLNetworkReachabilityStatus.reachableViaWWAN
default:
return VLNetworkReachabilityStatus.unknown
}
}
}
extension NSNotification.Name {
/// Posted when network reachability changes.
public static let VLNetworkingReachabilityDidChange: NSNotification.Name = NSNotification.Name(rawValue: "com.pingwinator.VLNetworkingReachabilityDidChange")
}
public let VLReachabilityNotificationStatusItem: String = "com.pingwinator.VLNetworkingReachabilityDidChange"
| true
|
e3d10953847b9caa5cd7c8d1721cd926d32fcab3
|
Swift
|
robking91/DomesticCatCodingTest
|
/DomesticCatCodingTest/FavoritesList/Views/FavoritesListViewController.swift
|
UTF-8
| 2,867
| 2.625
| 3
|
[] |
no_license
|
//
// FavoritesListViewController.swift
// DomesticCatCodingTest
//
// Created by Robert King on 17/9/18.
// Copyright © 2018 Robert King. All rights reserved.
//
import UIKit
class FavoritesListViewController: UITableViewController {
var viewModel: FavoritesListViewModel!
override func viewDidLoad() {
super.viewDidLoad()
viewModel = FavoritesListViewModel()
registerCell()
configureViewModel()
tableView.tableFooterView = UIView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.fetchFavoriteRestaurants()
}
func configureViewModel() {
viewModel.stateChangedHandler = { [weak self] state in
guard let `self` = self else { return }
switch state {
case .initial: break
case .loading: break
case .loaded:
self.tableView.reloadData()
}
}
}
func registerCell() {
let cellName = String(describing: RestaurantCell.self)
let restaurantCellNib = UINib(nibName: cellName, bundle: nil)
tableView.register(restaurantCellNib, forCellReuseIdentifier: cellName)
}
}
extension FavoritesListViewController: FavoriteRestaurantProtocol {
func favoriteRestaurant(rest: Restaurant) {
viewModel.dataManager.setRestaurantFavoriteStatus(rest: rest, status: true, completion: {
self.viewModel.fetchFavoriteRestaurants()
})
}
func defavoriteRestaurant(rest: Restaurant) {
viewModel.dataManager.setRestaurantFavoriteStatus(rest: rest, status: false, completion: {
self.viewModel.fetchFavoriteRestaurants()
})
}
}
extension FavoritesListViewController {
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSections()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRows()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let restaurantCell = tableView.dequeueReusableCell(withIdentifier: String(describing: RestaurantCell.self), for: indexPath) as? RestaurantCell else {
return UITableViewCell.init()
}
restaurantCell.favoriteRestaurantsDelegate = self
let restaurant = viewModel.restaurants[indexPath.row]
DispatchQueue.main.async {
restaurantCell.configureCell(restaurant)
restaurantCell.configureFavoriteButton(isFavorite: restaurant.isFavorite)
}
return restaurantCell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return Constants.RestaurantList.restaurantCellHeight
}
}
| true
|
fdc90e09872cc2f9475ac419ad5f0a5fb910f644
|
Swift
|
ivanfavarin/Travels
|
/travels/Home/Controller/ViewController.swift
|
UTF-8
| 1,634
| 2.6875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// travels
//
// Created by ivan favarin on 20/10/19.
// Copyright © 2019 ivan favarin. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var travelTable: UITableView!
@IBOutlet weak var viewHotels: UIView!
@IBOutlet weak var viewPackages: UIView!
let travelList: Array<Travel> = TravelDAO().returnAllTravels()
override func viewDidLoad() {
super.viewDidLoad()
self.travelTable.dataSource = self
self.travelTable.delegate = self
self.viewPackages.layer.cornerRadius = 10
self.viewHotels.layer.cornerRadius = 10
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return travelList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
let travel = travelList[indexPath.row]
cell.labelTitle.text = travel.title
cell.labelNumberOfDays.text = "\(travel.numberOfDays) dias"
cell.labelPrice.text = "R$ \(travel.price)"
cell.travelImage.image = UIImage(named: travel.imagePath)
cell.travelImage.layer.cornerRadius = 10
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone ? 175 : 260
}
}
| true
|
2c903ad5f556b67158699f7d605c13e6fb7e3c29
|
Swift
|
kalpeshjethva18/Autolycus
|
/Demo/AutolycusDemo/ViewController.swift
|
UTF-8
| 1,101
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// AutolycusDemo
//
// Created by Harlan Kellaway on 11/3/17.
// Copyright © 2017 Harlan Kellaway. All rights reserved.
//
import Autolycus
import UIKit
class ViewController: UIViewController {
let myView = UIView()
let secondView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
myView.backgroundColor = .magenta
secondView.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
secondView.backgroundColor = .blue
secondView.center = view.center
view.addSubview(secondView)
secondView.addSubview(myView)
myView.constrain().widthToSuperview()
myView.constrain().heightToSuperview()
myView.constrain().centerInSuperview(offset: CGPoint(x: 50, y: 50))
}
private func manual() {
myView.constrain()
let constraints = [myView.leadingToTrailing(of: secondView)]
+ [myView.topToBottom(of: secondView)]
+ myView.size(CGSize(width: 50, height: 50))
NSLayoutConstraint.activate(constraints)
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.