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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
39f241f146b399c4790e29577148751e1f02a45e
|
Swift
|
chelwoong/Algorithm_Study
|
/DP/BOJ 2629 양팔저울/BOJ 2629 양팔저울.swift
|
UTF-8
| 710
| 2.609375
| 3
|
[] |
no_license
|
let n = Int(readLine()!)!
var scales = readLine()!.split(separator: " ").map { Int(String($0))! }
let k = Int(readLine()!)!
var marbles = readLine()!.split(separator: " ").map { Int(String($0))! }
var check = [[Bool]](repeating: [Bool](repeating: false, count: 15005), count: scales.count+1)
func addScale(_ idx: Int, _ weight: Int) {
guard !check[idx][weight] else { return }
check[idx][weight] = true
guard idx < scales.count else { return }
addScale(idx+1, weight + scales[idx])
addScale(idx+1, weight)
addScale(idx+1, abs(weight - scales[idx]))
}
addScale(0, 0)
print(marbles.map({ ($0 > 1500 || !check[scales.count][$0]) ? "N" : "Y" }).joined(separator: " "))
| true
|
d0a786bf4fc51854d213607acb167952ef24c63f
|
Swift
|
ymalinovsky/interactive_modal_menu_swift
|
/InteractiveModalTest/MainViewController.swift
|
UTF-8
| 3,151
| 2.75
| 3
|
[] |
no_license
|
//
// MainViewController.swift
// InteractiveModalTest
//
// Created by Yan Malinovsky on 28.12.16.
// Copyright © 2016 Yan Malinovsky. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
// Create interactor object
let interactor = Interactor()
@IBAction func openMenu(_ sender: UIBarButtonItem) {
performSegue(withIdentifier: "openMenu", sender: nil)
}
// All of this code is essentially trying to update the transition status each time a pan gesture event is fired.
@IBAction func edgePanGesture(sender: UIScreenEdgePanGestureRecognizer) {
// Get the pan gesture coordinates.
let translation = sender.translation(in: view)
// Using the MenuHelper‘s calculateProgress() method, you convert the coordinates into progress in a specific direction
let progress = MenuHelper.calculateProgress(translationInView: translation, viewBounds: view.bounds, direction: .Right)
// Pass all the information to the MenuHelper‘s mapGestureStateToInteractor() method. This does the hard work of syncing the gesture state with the interactive transition.
MenuHelper.mapGestureStateToInteractor(
gestureState: sender.state,
progress: progress,
interactor: interactor){
self.performSegue(withIdentifier: "openMenu", sender: nil)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationViewController = segue.destination as? MenuViewController {
destinationViewController.transitioningDelegate = self
// Pass the interactor object forward
destinationViewController.interactor = interactor
}
}
}
extension MainViewController: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return PresentMenuAnimator()
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return DismissMenuAnimator()
}
// You indicate that the dismiss transition is going to be interactive, but only if the user is panning. (Remember that hasStarted was set to true when the pan gesture began.)
func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactor.hasStarted ? interactor : nil
}
func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactor.hasStarted ? interactor : nil
}
}
| true
|
863ec6a47443261f541121b7cd6798c916303c4d
|
Swift
|
kentaka7/eMia-iOS
|
/Supporting files/Helpers/AppLifecycleMediator.swift
|
UTF-8
| 2,468
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// AppLifecycleMediator.swift
// eMia
//
// Created by Sergey Krotkih on 07/09/2018.
// Copyright © 2018 Sergey Krotkih. All rights reserved.
//
import Foundation
// MARK: - AppLifecycleListener
protocol AppLifecycleListener {
func onAppWillEnterForeground()
func onAppDidEnterBackground()
func onAppDidFinishLaunching()
}
// MARK: - Mediator
class AppLifecycleMediator: NSObject, AnyObservable {
var observers: [Any] = []
static var defaultInstance: AppLifecycleMediator!
static func makeDefaultMediator() {
let listener1 = DefaultAppLifeListener()
self.defaultInstance = AppLifecycleMediator(listeners: [listener1])
}
private let listeners: [AppLifecycleListener]
init(listeners: [AppLifecycleListener]) {
self.listeners = listeners
super.init()
registerObserver()
}
deinit {
unregisterObserver()
}
func registerObserver() {
let center = NotificationCenter.default
let queue = OperationQueue.main
observers.append(
_ = center.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: queue) { [weak self] notification in
guard let `self` = self else { return }
self.onAppWillEnterForeground()
}
)
observers.append(
_ = center.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: queue) { [weak self] notification in
guard let `self` = self else { return }
self.onAppDidEnterBackground()
}
)
observers.append(
_ = center.addObserver(forName: UIApplication.didFinishLaunchingNotification, object: nil, queue: queue) { [weak self] notification in
guard let `self` = self else { return }
self.onAppDidFinishLaunching()
}
)
}
private func onAppWillEnterForeground() {
listeners.forEach { $0.onAppWillEnterForeground() }
}
private func onAppDidEnterBackground() {
listeners.forEach { $0.onAppDidEnterBackground() }
}
private func onAppDidFinishLaunching() {
listeners.forEach { $0.onAppDidFinishLaunching() }
}
}
// MARK: - Default App Lifecycle listener
class DefaultAppLifeListener: AppLifecycleListener {
func onAppWillEnterForeground() {
Log()
}
func onAppDidEnterBackground() {
Log()
}
func onAppDidFinishLaunching() {
Log()
}
}
| true
|
e4993de64825a9da2467941a8b52c89c961cf171
|
Swift
|
nonsensery/advent-of-code-2019
|
/22. Slam Shuffle/SlamShuffle/Tests/SlamShuffleTests/SlamShuffleTests.swift
|
UTF-8
| 2,752
| 3
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
@testable import SlamShuffle
final class SlamShuffleTests: XCTestCase {
private func testShuffle(initial: Deck = "0 1 2 3 4 5 6 7 8 9", instructions: String, shuffled: Deck) {
var deck = initial
XCTAssertEqual(deck.description, initial.description)
deck.performAll(instructions)
XCTAssertEqual(deck.description, shuffled.description)
deck.reversePerformAll(instructions)
XCTAssertEqual(deck.description, initial.description)
}
func testDeck() {
let instructions = """
deal into new stack
"""
var deck: Deck = "0 1 2 3 4 5 6 7 8 9"
XCTAssertEqual(deck.description, "0 1 2 3 4 5 6 7 8 9")
deck.performAll(instructions)
XCTAssertEqual(deck.description, "9 8 7 6 5 4 3 2 1 0")
deck.reversePerformAll(instructions)
XCTAssertEqual(deck.description, "0 1 2 3 4 5 6 7 8 9")
}
func testExample1() {
testShuffle(
instructions: """
deal with increment 7
deal into new stack
deal into new stack
""",
shuffled: "0 3 6 9 2 5 8 1 4 7"
)
}
func testExample2() {
testShuffle(
instructions: """
cut 6
deal with increment 7
deal into new stack
""",
shuffled: "3 0 7 4 1 8 5 2 9 6"
)
}
func testExample3() {
testShuffle(
instructions: """
deal with increment 7
deal with increment 9
cut -2
""",
shuffled: "6 3 0 7 4 1 8 5 2 9"
)
}
func testExample4() {
testShuffle(
instructions: """
deal into new stack
cut -2
deal with increment 7
cut 8
cut -4
deal with increment 7
cut 3
deal with increment 9
deal with increment 3
cut -1
""",
shuffled: "9 2 5 8 1 4 7 0 3 6"
)
}
func testPart1() {
var card = Card(value: 2019)
card.performAll(inputData)
let result = card.position
XCTAssertEqual(result, 3377)
}
func testPart2() {
var card = Card(value: 2020, deckSize: 119315717514047)
let instructions = Instruction.all(inputData)
for _ in 1...101741582076661 {
card.reversePerformAll(instructions)
}
let result = card.position
XCTAssertEqual(result, -1)
}
static var allTests = [
("testExample1", testExample1),
]
}
| true
|
669f64a25577a60f82ad2304f24753b96964c1d9
|
Swift
|
OnePieceLv/NetService
|
/NetServiceTests/NetService/DataServiceTests.swift
|
UTF-8
| 5,609
| 2.65625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// RequestTests.swift
// Merlin-iOSTests
//
// Created by steven on 2021/1/5.
//
import XCTest
@testable import NetService
final class TestAPI: BaseAPIManager {
override var urlString: String {
return _urlString
}
override var httpMethod: NetServiceBuilder.Method {
return _method
}
private var _urlString: String
private var _method: NetServiceBuilder.Method = .GET
init(with url: String) {
_urlString = url
}
func setMethod(method: NetServiceBuilder.Method) -> Self {
_method = method
return self
}
}
class BaseDataServiceTests: BaseTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testAsync() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let urlString = "https://httpbin.org/get"
let api = TestAPI(with: urlString)
var response: DataResponse!
let exception = self.expectation(description: "\(api.urlString)")
api.async { (request) in
response = request.response
exception.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
XCTAssertNotNil(response)
if let response = response, let responseString = response.responseString {
print(responseString)
}
XCTAssertEqual(response.statusCode, 200)
XCTAssertTrue(response.result.isSuccess)
XCTAssertNotNil(response.result.success)
XCTAssertNotNil(response.value)
XCTAssertFalse(response.result.isFailure)
XCTAssertNil(response.error)
XCTAssertNil(response.result.failure)
XCTAssertNotNil(response.response)
XCTAssertNotNil(response.responseString)
}
func testSync() throws {
let urlString = "https://httpbin.org/get"
let api = TestAPI(with: urlString)
let res = api.sync()
XCTAssertNotNil(res.response)
XCTAssertEqual(res.response.statusCode, 200)
XCTAssertNotNil(res.response.responseString, "response string must be not nil")
if let response = res.response, let responseString = response.responseString {
print(responseString)
}
}
func testPublished() throws {
let urlString = "https://httpbin.org/get"
let api = TestAPI(with: urlString)
let request = URLRequest(url: URL.init(string: "\(api.urlString)")!)
let exception = self.expectation(description: "test \(api.urlString)")
var responseString: String? = nil
let dataTask: URLSessionDataTask = URLSession(configuration: .default).dataTask(with: request) { (data, response, error) in
responseString = String(data: data!, encoding: .utf8)
print(responseString ?? "null string")
exception.fulfill()
}
dataTask.resume()
waitForExpectations(timeout: 10, handler: nil)
XCTAssertTrue(true)
}
func testRetryPolicy() throws {
let urlString = "https://httpbin.org/status/503"
let api = TestAPI(with: urlString)
let exception = self.expectation(description: "test \(api.urlString)")
api.setMethod(method: .DELETE).async { (request) in
exception.fulfill()
}
waitForExpectations(timeout: 60, handler: nil)
// XCTAssertNotNil(api.response?.error)
XCTAssertEqual(api.response?.statusCode, 503)
let urlString2 = "https://httpbin.org/status/504"
var api2 = TestAPI(with: urlString2)
api2 = api2.setMethod(method: .DELETE).sync()
// XCTAssertNotNil(api2.response?.error)
XCTAssertEqual(api2.response?.statusCode, 504)
}
struct CustomMiddlewares: Middleware {
func prepare(_ builder: NetServiceBuilder) -> NetServiceBuilder {
XCTAssertEqual(builder.url?.absoluteString, "https://httpbin.org/get")
XCTAssertEqual(builder.httpMethod, .GET)
return builder
}
func afterReceive<Response>(_ result: Response) -> Response where Response : Responseable {
XCTAssertEqual(result.statusCode, 200)
XCTAssertNil(result.error)
return result
}
}
func testMiddlewares() throws {
let urlString = "https://httpbin.org/get"
let api = TestAPI(with: urlString)
api.middlewares = [CustomMiddlewares()]
let exception = self.expectation(description: "\(api.urlString)")
api.async { (request) in
exception.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
}
func testBecomeError() throws {
let urlString = "http://localhost:3000/"
let api = TestAPI(with: urlString)
let exception = self.expectation(description: "\(api.urlString)")
api.async { (request) in
exception.fulfill()
}
waitForExpectations(timeout: 30, handler: nil)
}
// func testPerformanceExample() throws {
// // This is an example of a performance test case.
// self.measure {
// // Put the code you want to measure the time of here.
// }
// }
}
| true
|
fad15a5ebbad710b73390e005ca5b4268cae4f2d
|
Swift
|
zjhabib/WagerMe
|
/WagerMe iOS Application/WagerMe/MenuViewController.swift
|
UTF-8
| 2,732
| 2.609375
| 3
|
[] |
no_license
|
//
// MenuViewController.swift
// WagerMe
//
// Created by chris calvert on 4/8/17.
// Copyright © 2017 Christopher calvert. All rights reserved.
//CODED BY CHRIS CALVERT
import UIKit
import GoogleMobileAds
class MenuViewController: UIViewController {
@IBOutlet weak var bannerView: GADBannerView!
@IBOutlet weak var userUsernameTextLabel: UILabel!
@IBOutlet weak var profilePhotoImageView: UIImageView!
@IBOutlet weak var currentBalance: UILabel!
override func viewWillAppear(_ animated: Bool) {
if(profilePhotoImageView.image == nil)
{
let userId = UserDefaults.standard.string(forKey: "id")
let imageUrl = URL(string:"https://cgi.soic.indiana.edu/~team10/profile-pictures/\(userId!)/user-profile.jpg")
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async {
let imageData = try? Data(contentsOf: imageUrl!)
if(imageData != nil)
{
DispatchQueue.main.async(execute: {
self.profilePhotoImageView.image = UIImage(data: imageData!)
})
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
let username = UserDefaults.standard.string(forKey: "userUsername")!
userUsernameTextLabel.text = username
let currentbalance = UserDefaults.standard.string(forKey: "balance")!
currentBalance.text = currentbalance
// Do any additional setup after loading the view.
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(MenuViewController.dismissKeyboard))
//Uncomment the line below if you want the tap not not interfere and cancel other interactions.
//tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
// Do any additional setup after loading the view, typically from a nib.
/// The banner view.
print("Google Mobile Ads SDK version: " + GADRequest.sdkVersion())
bannerView.adUnitID = "ca-app-pub-3940256099942544/2934735716"
bannerView.rootViewController = self
bannerView.load(GADRequest())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Calls this function when the tap is recognized.
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
}
| true
|
740ffcf57dbeb1497c0ec71ab5b1189f8a2f29e3
|
Swift
|
ojhad/MADLab
|
/MADLab/PostsTableViewController.swift
|
UTF-8
| 4,482
| 2.546875
| 3
|
[] |
no_license
|
//
// PostsTableViewController.swift
// MADLab
//
// Created by Dilip Ojha on 2015-08-05.
// Copyright (c) 2015 madlab. All rights reserved.
//
import UIKit
import Parse
class PostsTableViewController: UITableViewController, DatabaseDelegate {
var board: PFObject?
var posts: [PFObject]? = nil
var tappedPost: PFObject?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.updateData()
self.tableView.estimatedRowHeight = 80.0
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override func viewDidAppear(animated: Bool) {
self.updateData()
}
func updateData(){
Database.sharedInstance.delegate = self;
Database.sharedInstance.getAllPosts(board!)
}
// MARK: - Database Delegate
func pulledAllObjects(type: String, pulledObjects: [PFObject]?, error: String?) {
if type == "Post"{
if error == nil{
self.posts = pulledObjects
self.tableView.reloadData()
}
else{
println("Error Pulling Boards: \(error)")
}
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
if (posts?.count != nil){
return posts!.count
}
else{
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("post_cell", forIndexPath: indexPath) as! PostTableViewCell
var post: PFObject = self.posts![indexPath.row]
cell.lblTitle.text = post["title"] as? String
var postCount: Int = post["numberOfComments"] as! Int
cell.lblCommentCount.text = "\(postCount)"
var date: NSDate? = post.createdAt
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE MMM dd - hh:mm a"
var dateString: String = dateFormatter.stringFromDate(date!)
var user: PFUser? = PFUser.currentUser()
var name = user?.username
cell.lblAuthor.text = "Posted by \(name!)"
cell.lblDate.text = dateString
if post["image"] == nil{
cell.ivImage.image = UIImage(named: "Folder-50");
}
else{
var imageData: PFFile = post["image"] as! PFFile
imageData.getDataInBackgroundWithBlock({
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data:imageData)
cell.ivImage.image = image
}
}
})
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tappedPost = self.posts![indexPath.row]
self.performSegueWithIdentifier("post_detailed", sender: self)
}
// 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.
if segue.identifier == "new_post"{
var vc: NewPostViewController = segue.destinationViewController as! NewPostViewController
vc.board = self.board
}
if segue.identifier == "post_detailed"{
var vc: PostTableViewController = segue.destinationViewController as! PostTableViewController
vc.post = tappedPost
}
}
}
| true
|
c0a7381cddef83e45e267e5ba7c2ed30c2aa352e
|
Swift
|
RayPS/Link-Text-Selector
|
/Link Text Selector/Link Text Selector/ViewController.swift
|
UTF-8
| 2,869
| 2.515625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Link Text Selector
//
// Created by Ray on 2018/6/12.
// Copyright © 2018 Ray. All rights reserved.
//
import Cocoa
import SafariServices
class ViewController: NSViewController, NSWindowDelegate {
@IBOutlet weak var radioButton_shift: NSButton!
@IBOutlet weak var radioButton_control: NSButton!
@IBOutlet weak var radioButton_option: NSButton!
@IBOutlet weak var radioButton_command: NSButton!
@IBOutlet weak var enableIndicator: NSTextField!
@IBOutlet weak var infomationLabel: NSTextField!
@IBOutlet weak var enableButton: NSButton!
let extId = "com.rayps.Link-Text-Selector.Link-Text-Selector-Extension"
let keys = ["Shift", "Control", "Alt", "Meta"]
var userDefaults: UserDefaults?
var hotKey = String() {
didSet {
let radioButtons: [String: NSButton] = [
"Shift": radioButton_shift,
"Control": radioButton_control,
"Alt": radioButton_option,
"Meta": radioButton_command
]
radioButtons[hotKey]?.state = .on
userDefaults?.set(hotKey, forKey: "hotKey")
userDefaults?.synchronize()
}
}
override func viewDidLoad() {
super.viewDidLoad()
userDefaults = UserDefaults(suiteName: "group.Link-Text-Selector")
}
override func viewWillAppear() {
checkExtensionState()
}
override func viewDidAppear() {
view.window!.delegate = self
view.window!.styleMask.remove(.resizable)
hotKey = userDefaults?.string(forKey: "hotKey") ?? keys.first!
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.checkExtensionState), userInfo: nil, repeats: true)
}
func windowShouldClose(_ sender: NSWindow) -> Bool {
NSApplication.shared.terminate(self)
return true
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
@objc func checkExtensionState() {
SFSafariExtensionManager.getStateOfSafariExtension(withIdentifier: extId) { (state, error) in
DispatchQueue.main.async {
if let status = state?.isEnabled {
self.enableIndicator.textColor = status ? .systemGreen : .systemRed
self.infomationLabel.stringValue = status ? "Enabled" : "Extension is currently disabled, enable in Safari preferences"
self.enableButton.isHidden = status
}
}
}
}
@IBAction func enableButtonClicked(_ sender: Any) {
SFSafariApplication.showPreferencesForExtension(withIdentifier: extId)
}
@IBAction func hotKeyRadioButtonSelected(_ sender: NSMatrix) {
hotKey = keys[sender.selectedTag()]
}
}
| true
|
0f50f6cd4d7c57027183daf898a2fbdc034e1171
|
Swift
|
gelik31/wa_homework
|
/homework2/robot.pyramid.swift
|
UTF-8
| 1,297
| 3.15625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// iOS dev try
//
// Created by Samurai on 05.09.2021.
//
import UIKit
// All robot commands can be founded in GameViewController.h
class SwiftRobotControlCenter: RobotControlCenter {
// Level name setup
override func viewDidLoad() {
levelName = "L4H" // "L4H/L55H"
super.viewDidLoad()
}
override func run() {
descentFunc()
let a: Int = 5
fill(Argument: a)
}
func descentFunc() {
turnRight()
while frontIsClear {
move()
}
turnLeft()
}
func fill(Argument: Int) {
var secondArgument = Argument
for _ in 0..<Argument {
var thirdArgument = 0
while thirdArgument < secondArgument {
put()
move()
thirdArgument += 1
}
thirdArgument = 0
secondArgument -= 1
turnBack()
while frontIsClear {
move()
}
turnRight()
move()
turnRight()
}
}
func turnLeft() {
turnRight()
turnRight()
turnRight()
}
func turnBack() {
turnRight()
turnRight()
}
}
| true
|
7b37ffbf36bcd4360e8a03c5a111a8eb0013a6f6
|
Swift
|
Gunwoos/yanoljaProject
|
/yanolja/controller/LikeViewController.swift
|
UTF-8
| 1,677
| 2.796875
| 3
|
[] |
no_license
|
//
// LikeViewController.swift
// yanolja
//
// Created by 임건우 on 2018. 8. 22..
// Copyright © 2018년 seob. All rights reserved.
//
import UIKit
class LikeViewController: UIViewController {
@IBOutlet weak var likedPensionTableView: UITableView!
@IBOutlet weak var likedPensionView:UIView!
var likedPensionNum = 0
override func viewDidLoad() {
super.viewDidLoad()
setView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setView(){
let titleString = "가고싶어요"
let label = UILabel()
label.text = titleString
label.sizeToFit()
self.navigationItem.titleView = label
if likedPensionNum == 0{
print("no liked pension")
likedPensionView.isHidden = false
likedPensionTableView.isHidden = true
likedPensionView.backgroundColor = UIColor.lightGray
}
else{
print("one more than liked Pension")
likedPensionView.isHidden = true
likedPensionTableView.isHidden = false
}
}
}
extension LikeViewController: UITableViewDelegate{
}
extension LikeViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return likedPensionNum
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
return cell
}
}
| true
|
7b091e8dd916d4d70f872fccf95fb7b06841078b
|
Swift
|
bignerdranch/Deferred
|
/Sources/Deferred/Locking.swift
|
UTF-8
| 6,393
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
//
// Locking.swift
// Deferred
//
// Created by John Gallagher on 7/17/14.
// Copyright © 2014-2019 Big Nerd Ranch. Licensed under MIT.
//
import Dispatch
import Foundation
/// A type that mutually excludes execution of code such that only one unit of
/// code is running at any given time. An implementing type may choose to have
/// readers-writer semantics, such that many readers can read at once, or lock
/// around all reads and writes the same way.
public protocol Locking {
/// Call `body` with a reading lock.
///
/// If the implementing type models a readers-writer lock, this function may
/// behave differently to `withWriteLock(_:)`.
///
/// - parameter body: A function that reads a value while locked.
/// - returns: The value returned from the given function.
func withReadLock<Return>(_ body: () throws -> Return) rethrows -> Return
/// Attempt to call `body` with a reading lock.
///
/// If the lock cannot immediately be taken, return `nil` instead of
/// executing `body`.
///
/// - returns: The value returned from the given function, or `nil`.
/// - see: withReadLock(_:)
func withAttemptedReadLock<Return>(_ body: () throws -> Return) rethrows -> Return?
/// Call `body` with a writing lock.
///
/// If the implementing type models a readers-writer lock, this function may
/// behave differently to `withReadLock(_:)`.
///
/// - parameter body: A function that writes a value while locked, then returns some value.
/// - returns: The value returned from the given function.
func withWriteLock<Return>(_ body: () throws -> Return) rethrows -> Return
}
extension Locking {
public func withWriteLock<Return>(_ body: () throws -> Return) rethrows -> Return {
return try withReadLock(body)
}
}
/// A variant lock backed by a platform type that attempts to allow waiters to
/// block efficiently on contention. This locking type behaves the same for both
/// read and write locks.
///
/// - On Apple platforms (iOS, macOS, tvOS, watchOS, or better), this efficiency is a guarantee.
/// - On Linux, BSD, or Android, waiters perform comparably to a kernel lock
/// under contention.
public final class NativeLock: Locking {
#if canImport(os)
private let lock = UnsafeMutablePointer<os_unfair_lock>.allocate(capacity: 1)
#else
private let lock = UnsafeMutablePointer<pthread_mutex_t>.allocate(capacity: 1)
#endif
/// Creates a standard platform lock.
public init() {
#if canImport(os)
lock.initialize(to: os_unfair_lock())
#else
lock.initialize(to: pthread_mutex_t())
pthread_mutex_init(lock, nil)
#endif
}
deinit {
#if !canImport(os)
pthread_mutex_destroy(lock)
#endif
lock.deinitialize(count: 1)
lock.deallocate()
}
public func withReadLock<Return>(_ body: () throws -> Return) rethrows -> Return {
#if canImport(os)
os_unfair_lock_lock(lock)
defer {
os_unfair_lock_unlock(lock)
}
#else
pthread_mutex_lock(lock)
defer {
pthread_mutex_unlock(lock)
}
#endif
return try body()
}
public func withAttemptedReadLock<Return>(_ body: () throws -> Return) rethrows -> Return? {
#if canImport(os)
guard os_unfair_lock_trylock(lock) else { return nil }
defer {
os_unfair_lock_unlock(lock)
}
#else
guard pthread_mutex_trylock(lock) == 0 else { return nil }
defer {
pthread_mutex_unlock(lock)
}
#endif
return try body()
}
}
/// A readers-writer lock provided by the platform implementation of the
/// POSIX Threads standard. Read more: https://en.wikipedia.org/wiki/POSIX_Threads
public final class POSIXReadWriteLock: Locking {
private let lock: UnsafeMutablePointer<pthread_rwlock_t>
/// Create the standard platform lock.
public init() {
lock = UnsafeMutablePointer<pthread_rwlock_t>.allocate(capacity: 1)
lock.initialize(to: pthread_rwlock_t())
pthread_rwlock_init(lock, nil)
}
deinit {
pthread_rwlock_destroy(lock)
lock.deinitialize(count: 1)
lock.deallocate()
}
public func withReadLock<Return>(_ body: () throws -> Return) rethrows -> Return {
pthread_rwlock_rdlock(lock)
defer {
pthread_rwlock_unlock(lock)
}
return try body()
}
public func withAttemptedReadLock<Return>(_ body: () throws -> Return) rethrows -> Return? {
guard pthread_rwlock_tryrdlock(lock) == 0 else { return nil }
defer {
pthread_rwlock_unlock(lock)
}
return try body()
}
public func withWriteLock<Return>(_ body: () throws -> Return) rethrows -> Return {
pthread_rwlock_wrlock(lock)
defer {
pthread_rwlock_unlock(lock)
}
return try body()
}
}
/// A locking construct using a counting semaphore from Grand Central Dispatch.
/// This locking type behaves the same for both read and write locks.
///
/// The semaphore lock performs comparably to a spinlock under little lock
/// contention, and comparably to a platform lock under contention.
extension DispatchSemaphore: Locking {
public func withReadLock<Return>(_ body: () throws -> Return) rethrows -> Return {
_ = wait(timeout: .distantFuture)
defer {
signal()
}
return try body()
}
public func withAttemptedReadLock<Return>(_ body: () throws -> Return) rethrows -> Return? {
guard case .success = wait(timeout: .now()) else { return nil }
defer {
signal()
}
return try body()
}
}
/// A lock object from the Foundation Kit used to coordinate the operation of
/// multiple threads of execution within the same application.
extension NSLock: Locking {
public func withReadLock<Return>(_ body: () throws -> Return) rethrows -> Return {
lock()
defer {
unlock()
}
return try body()
}
public func withAttemptedReadLock<Return>(_ body: () throws -> Return) rethrows -> Return? {
guard `try`() else { return nil }
defer {
unlock()
}
return try body()
}
}
| true
|
2e162991e4810d1cc9ca966cbbf285233e091d56
|
Swift
|
moguonyanko/moglabo
|
/lang/swift/DesignPattern/DesignPattern/observer.swift
|
UTF-8
| 2,221
| 4.03125
| 4
|
[] |
no_license
|
//
// observer.swift
// DesignPattern
//
//
import Foundation
private protocol Watchable {
func register(watcher: Watcher)
}
private protocol Student: Watchable {
var name: String { get }
var talking: Bool { get }
var running: Bool { get }
func talk()
func run()
func apology()
}
private extension Student {
//extensionにdeinitを定義することはできない。
// deinit {
// print("\(name) is free")
// }
}
private protocol Watcher {
//weakはprotocolのプロパティ宣言に指定できない。
var targets: [Student] { get }
func watch(target: Student)
func patrol()
}
private class StrictManager: Watcher {
//lazyの有無はprotocolの要求を満たしているかどうかに影響を与えない。
lazy var targets: [Student] = [Student]()
func watch(target: Student) {
targets.append(target)
}
func patrol() {
targets.forEach { student in
if student.talking || student.running {
student.apology()
}
}
}
deinit {
print("Finished management")
}
}
private class JuniorStudent: Student {
var talking: Bool = false
var running: Bool = false
var name: String
init(name: String) {
self.name = name
}
func register(watcher: Watcher) {
watcher.watch(target: self)
}
func talk() {
self.talking = true
}
func run() {
self.running = true
}
func apology() {
print("I am \(name).")
if talking {
print("\(name) was talking...")
}
if running {
print("\(name) was running...")
}
print("I am sorry. Please don't hit me!")
self.talking = false
self.running = false
}
deinit {
print("\(name) is free")
}
}
private func runAllCases() {
let foo = JuniorStudent(name: "foo")
let bar = JuniorStudent(name: "bar")
let manager = StrictManager()
foo.register(watcher: manager)
bar.register(watcher: manager)
foo.run()
bar.talk()
bar.run()
manager.patrol()
}
struct Observer {
static func main() {
runAllCases()
}
}
| true
|
061ade0ecb8b46e6c1efa119539df58a9f310091
|
Swift
|
empty667One/TTKGManager
|
/TTKG_Merchant/TTKG_Merchant/Classes/HomeControler/View/HomeVCZeroCell.swift
|
UTF-8
| 2,272
| 2.515625
| 3
|
[] |
no_license
|
//
// HomeVCZeroCell.swift
// TTKG_Merchant
//
// Created by macmini on 16/8/2.
// Copyright © 2016年 yd. All rights reserved.
//
import UIKit
class HomeVCZeroCell: UICollectionViewCell {
let btn1 = UIButton()
let btn2 = UIButton()
let btn3 = UIButton()
override init(frame: CGRect) {
super.init(frame: frame)
btn1.backgroundColor = UIColor.yellowColor()
btn2.backgroundColor = UIColor.redColor()
btn3.backgroundColor = UIColor.blueColor()
self.addSubview(btn1)
btn1.snp_makeConstraints { (make) in
make.left.equalTo(0).offset(2)
make.width.equalTo((screenWith - 20) / 3)
make.top.equalTo(0).offset(5)
make.bottom.equalTo(0).offset(-5)
}
//点击满赠按钮
btn1.addTarget(self, action: #selector(self.btn1Click), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(btn3)
btn3.snp_makeConstraints { (make) in
make.right.equalTo(0).offset(-2)
make.width.equalTo((screenWith - 20) / 3)
make.top.equalTo(0).offset(5)
make.bottom.equalTo(0).offset(-5)
}
//点击供应商按钮
btn3.addTarget(self, action: #selector(self.btn3Click), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(btn2)
btn2.snp_makeConstraints { (make) in
make.left.equalTo(btn1.snp_right).offset(10)
make.right.equalTo(btn3.snp_left).offset(-10)
make.top.equalTo(0).offset(5)
make.bottom.equalTo(0).offset(-5)
}
//点击热卖按钮
btn2.addTarget(self, action: #selector(self.btn2Click), forControlEvents: UIControlEvents.TouchUpInside)
}
//按钮的点击事件
func btn1Click() {
print("点击了满赠")
}
func btn2Click() {
print("点击了热卖")
}
func btn3Click() {
print("点击了供应商")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
0adbe9e3fe9addc543487bd3ebbccd441ea3f6a6
|
Swift
|
bree-jeune/ios-sum-and-product-swift-challenge
|
/sumAndProduct.playground/Contents.swift
|
UTF-8
| 210
| 3.0625
| 3
|
[
"MIT"
] |
permissive
|
import UIKit
func sumAndProduct(_ sum: UInt, _ product: UInt) -> [UInt] {
for x in sum {
if x % 2 == 0, x <= y {
print()
}
}
}
var sum = 6
var product = 12
| true
|
045e06afd2522f7472125422895a446842c1d9a2
|
Swift
|
masakazukarasaki/op_ios
|
/ios-opdep/Extension/SkyFloatingLabelTextField.swift
|
UTF-8
| 2,335
| 2.703125
| 3
|
[] |
no_license
|
//
// SkyFloatingLabelTextField.swift
import SkyFloatingLabelTextField
extension SkyFloatingLabelTextField {
@discardableResult
func apply(_ title: String? = nil,
placeholder: String? = nil,
titleFont: UIFont = UIFont.primary(),
placeholderFont: UIFont = UIFont.font(style: .italic, size: 20),
titleColor: UIColor? = UIColor.Basic.black,
placeholderColor: UIColor = UIColor.Basic.black,
lineColor: UIColor = UIColor.Basic.black,
selectedLineColor: UIColor = UIColor.Basic.black,
isSecureTextEntry: Bool = false) -> Self {
self.title = title
self.placeholder = placeholder ?? title
self.textColor = titleColor
self.titleColor = titleColor ?? UIColor.Basic.black
self.placeholderColor = placeholderColor
self.font = titleFont
self.placeholderFont = placeholderFont
self.selectedTitleColor = .init(hexString: "f57224")
self.lineColor = lineColor
self.selectedLineColor = selectedLineColor
self.isSecureTextEntry = isSecureTextEntry
self.titleFormatter = { (text: String) -> String in return text }
return self
}
class func create(_ title: String? = nil,
placeholder: String? = nil,
titleFont: UIFont = .font(style: .regular, size: 14),
placeholderFont: UIFont = .font(style: .regular, size: 14),
titleColor: UIColor? = UIColor.Basic.black,
placeholderColor: UIColor = .init(hexString: "717171"),
isSecureTextEntry: Bool = false) -> SkyFloatingLabelTextField {
SkyFloatingLabelTextField().apply(title, placeholder: placeholder, titleFont: titleFont,
placeholderFont: placeholderFont, titleColor: titleColor,
placeholderColor: placeholderColor, isSecureTextEntry: isSecureTextEntry)
}
}
import ReactiveCocoa
import ReactiveSwift
extension Reactive where Base: SkyFloatingLabelTextField {
var errorMessage: BindingTarget<String?> {
makeBindingTarget(on: UIScheduler()) { base, value in
base.errorMessage = value
}
}
}
| true
|
e45da9c20291aa18d5a2c0e2c637f45d391841f3
|
Swift
|
Tetsukick/RxSwift-MVVM_base
|
/base/App/Extensions/Array+.swift
|
UTF-8
| 560
| 3.078125
| 3
|
[] |
no_license
|
extension Array where Element: Equatable {
typealias E = Element
func subtracting(_ other: [E]) -> [E] {
return self.compactMap { element in
if (other.filter { $0 == element }).count == 0 {
return element
} else {
return nil
}
}
}
mutating func subtract(_ other: [E]) {
self = subtracting(other)
}
mutating func remove(value: Element) {
if let i = self.index(of: value) {
self.remove(at: i)
}
}
}
| true
|
108cb16cb1bf41406a6cf94060706044b6ddcc1b
|
Swift
|
uwangyh/LeetCodeSummary
|
/LeetCodeSummary/TwoSum.swift
|
UTF-8
| 1,564
| 3.734375
| 4
|
[] |
no_license
|
//
// TwoSum.swift
// LeetCodeSummary
//
// Created by WangYonghe on 2020/5/8.
// Copyright © 2020 WangYonghe. All rights reserved.
// 1:两数之和
import UIKit
/*
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class TwoSum: NSObject {
func twoSumResult(nums: [Int], target: Int)->Array<Int>{
var dict = [Int:Int]()
for (i,num) in nums.enumerated() {
if let lastIndex = dict[target - num] {
return [lastIndex ,i]
}else{
dict[2] = 0
dict[num] = i
}
}
return []
}
//简化版本 只需判断是否存在两个数相加等于目标值
func twoSumSimple(nums: [Int], target: Int)->Bool{
var tmpArr:[Int] = []
for element:Int in nums{
if tmpArr.contains(target - element) {
return true
}else{
tmpArr.append(element)
}
}
return false
}
}
| true
|
1e13d9455efb686dd015c902ea0f057add228cf4
|
Swift
|
nixta/maps-app-ios-prerelease
|
/maps-app-ios/Map View/MapViewController+GPS/AGSLocationDisplay+MapView.swift
|
UTF-8
| 1,033
| 2.5625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
//
// AGSLocationDisplay+MapsApp.swift
// maps-app-ios
//
// Created by Nicholas Furness on 4/5/17.
// Copyright © 2017 Esri. All rights reserved.
//
import ArcGIS
private var autoPanSequence:[AGSLocationDisplayAutoPanMode] = [
.off,
.recenter,
.compassNavigation
]
extension AGSLocationDisplayAutoPanMode {
func next() -> AGSLocationDisplayAutoPanMode {
let newIndex = ((autoPanSequence.index(of: self) ?? -1) + 1) % autoPanSequence.count
return autoPanSequence[newIndex]
}
}
extension AGSLocationDisplay {
func getImage() -> UIImage {
switch self.autoPanMode {
case .off:
return self.started ? #imageLiteral(resourceName: "GPS NoFollow") : #imageLiteral(resourceName: "GPS Off")
case .recenter:
return #imageLiteral(resourceName: "GPS Follow")
case .navigation:
return #imageLiteral(resourceName: "GPS Follow")
case .compassNavigation:
return #imageLiteral(resourceName: "GPS Compass")
}
}
}
| true
|
1149cda29fde1701e86affc32d2765fb722855f5
|
Swift
|
beichenglangzi/MovieRecommendation
|
/MovieRecommendation/Models/User.swift
|
UTF-8
| 875
| 3.234375
| 3
|
[] |
no_license
|
//
// User.swift
// MovieRecommendation
//
// Created by Soren Nelson on 7/10/18.
// Copyright © 2018 SORN. All rights reserved.
//
import Foundation
class User: Hashable {
var id: Int
var ratings: [Double]
var theta: vector
// Number of movies rated by user
var mj: Int
init(id: Int, theta: vector) {
self.id = id
mj = 0
ratings = Array(repeating: 0, count: 164979)
self.theta = theta
}
public var description: String {
return String("ID: \(id) \nratings: \(ratings)")
}
func addRating(_ rating: Double, for movie: Int) {
mj += 1
ratings[movie - 1] = rating;
}
// MARK: Hashable Protocol
static func == (lhs: User, rhs: User) -> Bool {
return lhs.id == rhs.id
}
var hashValue: Int {
return id.hashValue
}
}
| true
|
e0f34b6b82f71705641508afbdb0843a04d5e6b7
|
Swift
|
IgorMuzyka/Tyler.Style
|
/Sources/Style/GenericStylist.swift
|
UTF-8
| 1,264
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
import Variable
import Tag
#if os(iOS) || os(tvOS) || os(macOS)
public protocol GenericStylist: Stylist {
associatedtype GenericStyle: Style
associatedtype Stylable
func style(stylable: Stylable, style: GenericStyle, tags: [Tag], pair: VariableResolutionPair) throws
}
extension GenericStylist {
public func style(anyStylable: Any, style: Style, tags: [Tag], pair: VariableResolutionPair) throws {
guard let genericStyle = style as? GenericStyle else {
throw StylistError.doesNotHandleStyle(style)
}
if let keyPath = Self.keyPath {
guard let value = anyStylable[keyPath: keyPath] else {
throw StylistError.failedToExtractStylableByKeyPath(keyPath)
}
guard let stylable = value as? Stylable else {
throw StylistError.stylableTypeMismatched(value)
}
try self.style(stylable: stylable, style: genericStyle, tags: tags, pair: pair)
} else {
guard let stylable = anyStylable as? Stylable else {
throw StylistError.stylableTypeMismatched(anyStylable)
}
try self.style(stylable: stylable, style: genericStyle, tags: tags, pair: pair)
}
}
}
#endif
| true
|
a68fe4a199783b832885240d7af33769933154b3
|
Swift
|
tantan39/CustomCollectionViewLayout
|
/CollectionViewFlowLayout/CollectionViewLayout/CollectionViewController.swift
|
UTF-8
| 1,216
| 2.515625
| 3
|
[] |
no_license
|
//
// CollectionViewController.swift
// CollectionViewFlowLayout
//
// Created by Tan Tan on 3/29/20.
// Copyright © 2020 Tan Tan. All rights reserved.
//
import Foundation
import UIKit
class CollectionViewController: UIViewController, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let layout = AlbumCollectionViewLayout()
collectionView.setCollectionViewLayout(layout, animated: true)
collectionView.register(UINib(nibName: "CollectionViewCell", bundle: .main), forCellWithReuseIdentifier: "cellId")
collectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 61
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as? CollectionViewCell else { return UICollectionViewCell() }
cell.label.text = "\(indexPath.row)"
return cell
}
}
| true
|
1259c6d4cd42c428f8ad81aaf9ec186699319a41
|
Swift
|
MUECKE446/CyberSolitaire
|
/CyberSolitaire/GamesPListHelpers.swift
|
UTF-8
| 2,458
| 2.890625
| 3
|
[] |
no_license
|
//
// GamesPListHelpers.swift
// CyberSolitaire
//
// Created by Christian Muth on 16.10.18.
// Copyright © 2018 Christian Muth. All rights reserved.
//
import Foundation
import SwiftyPlistManager
struct GamePList {
let name:String
var sourcePath:String? {
guard let path = Bundle.main.path(forResource: name, ofType: "plist") else { return .none }
return path
}
}
// liefert ein Array mit allen URLs der Spiele
func getAllGamePListURLs() -> [URL] {
let mainBundle = Bundle.main
let urls = mainBundle.urls(forResourcesWithExtension: "plist", subdirectory: nil)
var gameUrls : [URL] = []
for url in urls! {
let strUrl = url.relativeString
if strUrl.hasPrefix("game(") {
gameUrls.append(url)
}
}
return gameUrls
}
// liefert ein Array mit allen plist Namen der Spiele
func getAllGamePListNames() -> [String] {
let gameUrls = getAllGamePListURLs()
var gamePListNames : [String] = []
for url in gameUrls {
let strUrl = url.relativeString
var strComponents = strUrl.split(separator: ".")
strComponents.removeLast()
let str = String(strComponents[0])
let replaced = str.replacingOccurrences(of: "%20", with: " ")
gamePListNames.append(replaced)
}
return gamePListNames
}
// liefert ein Array mit allen Namen der Spiele
func getAllGameNames() -> [String] {
let gamePListNames = getAllGamePListNames()
var gameNames : [String] = []
for plist in gamePListNames {
let game = SwiftyPlistManager.shared.fetchValue(for: "game", fromPlistWithName: plist) as! Dictionary<String,Any>
let gameName = game["gameName"] as! String
gameNames.append(gameName)
}
return gameNames
}
func getGameName(plistName:String) -> String {
let game = SwiftyPlistManager.shared.fetchValue(for: "game", fromPlistWithName: plistName) as! Dictionary<String,Any>
let gameName = game["gameName"] as! String
return gameName
}
func getAllGames() -> [Dictionary<String,Dictionary<String,Any>>] {
let gamePListNames = getAllGamePListNames()
var games : [Dictionary<String,Dictionary<String,Any>>] = []
for plist in gamePListNames {
let game = SwiftyPlistManager.shared.fetchValue(for: "game", fromPlistWithName: plist) as! Dictionary<String,Any>
let dictItem = [getGameName(plistName: plist):game]
games.append(dictItem)
}
return games
}
| true
|
24b2de6d744e644b9e5bebd602228d6f23a12395
|
Swift
|
nallick/Reflection
|
/Sources/Reflection/Reflection.swift
|
UTF-8
| 3,244
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// Reflection.swift
//
// Copyright © 2018-2020 Purgatory Design. All rights reserved.
//
import Runtime
public enum Reflection {
public static func kind(of type: Any.Type) -> Kind? {
guard let info = try? typeInfo(of: type) else { return nil }
return info.kind
}
public static func name(of type: Any.Type) -> String {
return String(describing: type)
}
// This doesn't appear to be mangled.
//
// public static func mangledName(of type: Any.Type) -> String? {
// guard let info = try? typeInfo(of: type) else { return nil }
// return info.mangledName
// }
public static func enumCases(of type: Any.Type) -> [String] {
guard let info = try? typeInfo(of: type) else { return [] }
return info.cases.map { $0.name }
}
public static func properties(of type: Any.Type) -> [PropertyInfo] {
guard let info = try? typeInfo(of: type) else { return [] }
return info.properties
}
public static func genericTypes(of type: Any.Type) -> [Any.Type] {
guard let info = try? typeInfo(of: type) else { return [] }
return info.genericTypes
}
public static func superClass(of aClass: AnyClass) -> AnyClass? {
guard let info = try? typeInfo(of: aClass) else { return nil }
return info.superClass as? AnyClass
}
public static func allSuperClasses(of aClass: AnyClass) -> [AnyClass] {
guard let info = try? typeInfo(of: aClass) else { return [] }
return info.inheritance.compactMap { $0 as? AnyClass }
}
}
#if canImport(ObjectiveC)
import Foundation
extension Reflection {
/// A list of all available classes that exist at the first time this is called.
///
/// - Note: Any classes added dynamically after that first call won't be reflected here.
///
public static let allClasses: [AnyClass] = {
Reflection.allExistingClasses
}()
/// A list of all available classes at the current time.
///
public static var allExistingClasses: [AnyClass] {
var count: UInt32 = 0
guard let classList = objc_copyClassList(&count) else { return [] }
let classListBuffer = UnsafeBufferPointer(start: classList, count: Int(count))
defer { classListBuffer.deallocate() }
return classListBuffer.map { $0 }
}
@inlinable public static func `class`(_ aClass: AnyClass, conformsTo objcProtocol: Protocol) -> Bool {
class_conformsToProtocol(aClass, objcProtocol)
}
@inlinable public static func mangledName(of aClass: AnyClass) -> String {
String(cString: class_getName(aClass))
}
/// Get a list of all Obj-C methods of a class.
///
/// - Parameter type: The class type.
/// - Returns: The method name list.
///
public static func methodNames(of aClass: AnyClass) -> [String] {
var methodNames = [String]()
var count: CUnsignedInt = 0
var list: UnsafeMutablePointer<Method>? = class_copyMethodList(aClass, &count)
for _ in 0 ..< count {
methodNames.append(String(describing: method_getName((list?.pointee)!)))
list = list?.successor()
}
return methodNames
}
}
#endif
| true
|
808b3160805b6a1cd20fe1bfe7ac17245436548a
|
Swift
|
kieferyap/budget-bunny
|
/BudgetBunny/Classes/Models/Items/AttributeModel.swift
|
UTF-8
| 541
| 2.6875
| 3
|
[] |
no_license
|
//
// AttributeModel.swift
// BudgetBunny
//
// Created by Kiefer Yap on 5/20/16.
// Copyright © 2016 Kiefer Yap. All rights reserved.
//
import UIKit
import CoreData
class AttributeModel: NSObject {
var tableName: String
var format: String
var value: NSObject
init(tableName: String, key: String, value: NSObject) {
self.tableName = tableName
let formattedString = String.init(format: "%@ == ", key)
self.format = formattedString.stringByAppendingString("%@")
self.value = value
}
}
| true
|
5fbb45977b2ef32ba09c9f5b211015743bd887eb
|
Swift
|
TigerWolf/ipc_categories_app
|
/IPSearcher/HospitalModel.swift
|
UTF-8
| 236
| 2.984375
| 3
|
[] |
no_license
|
final class Hospital {
let location_name: String
let location_id: String
init(location_name: String, location_id: String){
self.location_name = location_name
self.location_id = location_id
}
}
| true
|
7be1f6e696cbf49c5bfc31dcb583af06a00a114e
|
Swift
|
BobbyRenTech/DocPronto
|
/DocPronto/LoginViewController.swift
|
UTF-8
| 4,788
| 2.609375
| 3
|
[] |
no_license
|
//
// LoginViewController.swift
// DocPronto
//
// Created by Bobby Ren on 8/2/15.
// Copyright (c) 2015 Bobby Ren. All rights reserved.
//
import UIKit
import Parse
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var inputLogin: UITextField!
@IBOutlet var inputPassword: UITextField!
@IBOutlet var buttonLogin: UIButton!
@IBOutlet var buttonSignup: UIButton!
let appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
self.reset()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func reset() {
self.inputPassword.text = nil;
self.inputLogin.superview!.layer.borderWidth = 1;
self.inputLogin.superview!.layer.borderColor = UIColor.lightGrayColor().CGColor;
self.inputPassword.superview!.layer.borderWidth = 1;
self.inputPassword.superview!.layer.borderColor = UIColor.lightGrayColor().CGColor;
}
@IBAction func didClickLogin(sender: UIButton) {
if count(self.inputLogin.text) == 0 {
self.simpleAlert("Please enter a login email", message: nil)
return
}
if count(self.inputPassword.text) == 0 {
self.simpleAlert("Please enter a password", message: nil)
return
}
let username = self.inputLogin.text
let password = self.inputPassword.text
PFUser.logInWithUsernameInBackground(username, password: password) { (user, error) -> Void in
println("logged in")
if user != nil {
self.loggedIn()
}
else {
let title = "Login error"
var message: String?
if error?.code == 100 {
message = "Please check your internet connection"
}
else if error?.code == 101 {
message = "Invalid email or password"
}
self.simpleAlert(title, message: message)
}
}
}
@IBAction func didClickSignup(sender: UIButton) {
if count(self.inputLogin.text) == 0 {
self.simpleAlert("Please enter an email address", message: nil)
return
}
if count(self.inputPassword.text) == 0 {
self.simpleAlert("Please enter a password", message: nil)
return
}
let email:NSString = self.inputLogin.text as NSString
if !email.isValidEmail() {
self.simpleAlert("Please enter a valid email address", message: nil)
return
}
let username = self.inputLogin.text
let password = self.inputPassword.text
let user = PFUser()
user.username = username
user.password = password
if email.isValidEmail() {
user.email = username
}
user.signUpInBackgroundWithBlock { (success, error) -> Void in
if success {
println("signup succeeded")
self.loggedIn()
}
else {
let title = "Signup error"
var message: String?
if error?.code == 100 {
message = "Please check your internet connection"
}
else if error?.code == 202 {
message = "Username already taken"
}
self.simpleAlert(title, message: message)
}
}
}
func loggedIn() {
appDelegate.didLogin()
}
// MARK: - TextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func simpleAlert(title: String?, message: String?) {
var alert: UIAlertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
/*
// 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
|
39df038bb4dc78a6a16c9559dfc3bc1e950c9164
|
Swift
|
bchewy/chewy_mad2
|
/practicals/Telefgramme-MapView/Telegramme/Friend.swift
|
UTF-8
| 349
| 2.609375
| 3
|
[] |
no_license
|
//
// Friend.swift
// Telegramme
//
// Created by MAD2_P03 on 22/11/19.
// Copyright © 2019 MAD2_P03. All rights reserved.
//
import Foundation
class Friend {
var Name:String
var ProfileImageName:String
init(name:String, profileImageName:String) {
Name = name
ProfileImageName = profileImageName
}
}
| true
|
b8b5957aada1bbf62a06880b46b6bab87c5f81a3
|
Swift
|
m-yamada04/TwitterClient
|
/TwitterClient/View/CustomView/TweetCell.swift
|
UTF-8
| 1,176
| 2.828125
| 3
|
[] |
no_license
|
//
// TweetCell.swift
// TwitterClient
//
// Created by Maika Yamada on 2018/04/28.
// Copyright © 2018年 Maika Yamada. All rights reserved.
//
import UIKit
protocol TweetCellDelegate {
func useIconDidTap(user: User)
}
class TweetCell: UITableViewCell {
@IBOutlet weak var _userIcon: CircleImageView!
@IBOutlet weak var _displayName: UILabel!
@IBOutlet weak var _userName: UILabel!
@IBOutlet weak var _tweetText: UITextView!
var delegate: TweetCellDelegate?
var tweet: Tweet? {
didSet {
_userIcon.image = UIImage(data: try! Data(contentsOf: URL(string: tweet!.owner!.profileImageUrl)!))
_displayName.text = tweet!.owner!.name
_userName.text = "@" + tweet!.owner!.screenName
_tweetText.text = tweet!.text
_userIcon.addGestureRecognizer(
UITapGestureRecognizer(target: self,
action: #selector(TweetCell.userIconDidTap(_:)))
)
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
@objc func userIconDidTap(_ sender: Any) {
delegate?.useIconDidTap(user: self.tweet!.owner!)
}
}
| true
|
fbae9082bc1126a764ae628e7ff3839a35fb193e
|
Swift
|
yuriypashkov/LenOblBridge
|
/LenOblBridge/models/Bridge.swift
|
UTF-8
| 1,428
| 2.5625
| 3
|
[] |
no_license
|
import Foundation
import MapKit
import Contacts
struct Bridge: Decodable {
var id: Int?
var title: String?
var river: String?
var year: String?
var length: String?
var width: String?
var architect: String?
var about: String?
var road: String?
var mainImageURL: String?
var previewImageURL: String?
var latitude: Double?
var longtitude: Double?
var shortText: String?
}
class BridgeAnnotation: NSObject, MKAnnotation {
let title: String?
let river: String?
let coordinate: CLLocationCoordinate2D
let bridgeObject: Bridge? // странное свойство для вызова нового VC по тапу на вьюаннотейшн из MapViewController
var mapItem: MKMapItem? {
guard let location = river else { return nil }
let addressDict = [CNPostalAddressStreetKey: location]
let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = title
return mapItem
}
var subtitle: String? {
return river
}
init(title: String?, river: String?, coordinate: CLLocationCoordinate2D, bridgeObject: Bridge) {
self.title = title
self.river = river
self.coordinate = coordinate
self.bridgeObject = bridgeObject
}
}
| true
|
0c4d72834acbd414ee96a3bde9c3a61a7edef88f
|
Swift
|
tiden0614/simplecalculator
|
/Calculator/Parser.swift
|
UTF-8
| 5,937
| 2.9375
| 3
|
[] |
no_license
|
//
// Parser.swift
// Calculator
//
// Created by tiden on 11/11/15.
// Copyright (c) 2015 Daryl Zhang. All rights reserved.
//
import Foundation
public class Parser {
var tokens = [String]()
var nextIndex = 0
var _err = ""
var error: String {
set {
if debug {
println(newValue)
}
_err = newValue
}
get {
return _err
}
}
var debug = true
private func next() -> String {
if nextIndex >= tokens.count {
return "$"
}
return tokens[nextIndex]
}
private func consume() {
nextIndex += 1
}
private func expect(expectation: String) -> Bool {
if expectation == next() {
consume()
return true
} else {
error = "line(\(__LINE__)) Error: expecting \(expectation) but receive \(next())"
return false
}
}
func parse(tokenStack: [String]) -> Expression? {
tokens = tokenStack
nextIndex = 0
return _expression()
}
// expression -> [ "+" | "-" ] term { "+" | "-" term }
func _expression() -> Expression? {
var children = [Expression]()
var operators = [String]()
func nextIsPlusOrMinu() -> Bool {
return next() == GlobalConstants.Operators.PLUS || next() == GlobalConstants.Operators.MINU
}
if nextIsPlusOrMinu() {
operators.append(next())
consume()
}
if let t = _term() {
children.append(t)
} else {
return nil
}
while nextIsPlusOrMinu() {
operators.append(next())
consume()
if let t = _term() {
children.append(t)
} else {
return nil
}
}
return expression(children: children, operators: operators)
}
// term -> factor { "*" | "/" factor }
func _term() -> Expression? {
var children = [Expression]()
var operators = [String]()
if let f = _factor() {
children.append(f)
} else {
return nil
}
while next() == GlobalConstants.Operators.MULT || next() == GlobalConstants.Operators.DIVI {
operators.append(next())
consume()
if let f = _factor() {
children.append(f)
} else {
return nil
}
}
return term(children: children, operators: operators)
}
// factor -> number | "(" expression ")" | function
func _factor() -> Expression? {
var result: Expression
if Utils.isNumber(next()) {
result = factor(child: number(value: NSNumberFormatter().numberFromString(next())!.doubleValue))
consume()
} else if next() == GlobalConstants.Operators.LPRE {
consume()
if let e = _expression() {
result = factor(child: e)
} else {
return nil
}
if !expect(GlobalConstants.Operators.RPRE) {
return nil
}
} else {
if let f = _function() {
result = factor(child: f)
} else {
return nil
}
}
return result
}
// function -> identifier "(" expression { "," expression } ")"
func _function() -> Expression? {
var children = [Expression]()
var identifier = ""
// find the identifier
if Utils.isIDentifier(next()) {
identifier = next()
consume()
} else {
// parse error
error = "line(\(__LINE__)) Error: expecting [identifier] but receive \(next())"
return nil
}
if !expect(GlobalConstants.Operators.LPRE) {
return nil
}
if let e = _expression() {
children.append(e)
} else {
return nil
}
while next() == GlobalConstants.Operators.COMM {
consume()
if let e = _expression() {
children.append(e)
} else {
return nil
}
}
if !expect(GlobalConstants.Operators.RPRE) {
return nil
}
var opr: [Expression] -> Double?
switch identifier {
case GlobalConstants.Operators.SQRT:
if children.count < 1 {
error = "line(\(__LINE__)) Error: \(identifier) function expects 1 arguments, but only got \(children.count)"
return nil
}
opr = { sqrt($0[0].evaluate()!) }
case GlobalConstants.Operators.SIN:
if children.count < 1 {
error = "line(\(__LINE__)) Error: \(identifier) function expects 1 arguments, but only got \(children.count)"
return nil
}
opr = { sin($0[0].evaluate()!) }
case GlobalConstants.Operators.COS:
if children.count < 1 {
error = "line(\(__LINE__)) Error: \(identifier) function expects 1 arguments, but only got \(children.count)"
return nil
}
opr = { cos($0[0].evaluate()!) }
case GlobalConstants.Operators.POW:
if children.count < 2 {
error = "line(\(__LINE__)) Error: \(identifier) function expects 2 arguments, but only got \(children.count)"
return nil
}
opr = { pow($0[0].evaluate()!, $0[1].evaluate()!) }
default:
opr = { $0[0].evaluate() }
}
return function(children: children, opr)
}
}
| true
|
bb09eaf6900c6ef7a20d8bb5736a0ccce1dd4c8d
|
Swift
|
SuguruSasaki/reactor-sample
|
/ReactorSample/Classes/Data/Login/LoginEntity.swift
|
UTF-8
| 530
| 3.125
| 3
|
[] |
no_license
|
//
// LoginEntity.swift
// ReactorSample
//
// Created by sugurusasaki on 2018/12/04.
// Copyright © 2018 sugurusasaki. All rights reserved.
//
import Foundation
protocol LoginModelType {
func getName() -> String
func getFullname() -> String
}
struct LoginEntity {
let name: String
let name2: String
}
extension LoginEntity: LoginModelType{
func getName() -> String {
return self.name
}
func getFullname() -> String {
return self.name + "." + self.name2
}
}
| true
|
a604f32f238c44c98e5b543d5585593478213d4b
|
Swift
|
SwiftMeetupBudapest/Compiler-Design-and-Implementation
|
/TypeAnn.swift
|
UTF-8
| 4,046
| 3.265625
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain"
] |
permissive
|
//
// TypeAnn.swift
//
// SwiSwi - a tiny Swift-like language
//
// Created for the Budapest Swift Meetup
// by Árpád Goretity (H2CO3)
// on 15/12/2015
//
// There's no warranty whatsoever.
//
class TypeAnn {
init() {}
func toString() -> String {
return "Type"
}
func equals(rhs: TypeAnn) -> Bool {
return false
}
func isNumeric() -> Bool {
return false
}
// For code generation.
// Returns the LLVM representation of the type.
func llvmType() -> LLVMTypeRef {
assert(false, "cannot represent generic TypeAnn in LLVM")
return nil
}
}
final class VoidType : TypeAnn {
override func toString() -> String {
return "Void"
}
override func equals(rhs: TypeAnn) -> Bool {
return rhs is VoidType // assumes final
}
override func llvmType() -> LLVMTypeRef {
return LLVMVoidType()
}
}
final class BoolType : TypeAnn {
override func toString() -> String {
return "Bool"
}
override func equals(rhs: TypeAnn) -> Bool {
return rhs is BoolType // assumes final
}
override func llvmType() -> LLVMTypeRef {
return LLVMInt1Type()
}
}
final class IntType : TypeAnn {
override func toString() -> String {
return "Int";
}
override func equals(rhs: TypeAnn) -> Bool {
return rhs is IntType // assumes final
}
override func isNumeric() -> Bool {
return true
}
override func llvmType() -> LLVMTypeRef {
return LLVMInt64Type()
}
}
final class DoubleType : TypeAnn {
override func toString() -> String {
return "Double";
}
override func equals(rhs: TypeAnn) -> Bool {
return rhs is DoubleType // assumes final
}
override func isNumeric() -> Bool {
return true
}
override func llvmType() -> LLVMTypeRef {
return LLVMDoubleType()
}
}
final class StringType : TypeAnn {
static var storedLlvmType: LLVMTypeRef? = nil
override func toString() -> String {
return "String";
}
override func equals(rhs: TypeAnn) -> Bool {
return rhs is StringType // assumes final
}
// Strings are represented by:
// struct string {
// char *begin;
// uint64_t length;
// }
override func llvmType() -> LLVMTypeRef {
if let storedLlvmType = StringType.storedLlvmType {
return storedLlvmType
}
var elems = [
LLVMPointerType(LLVMInt8Type(), 0), // char * in addr. space #0
LLVMInt64Type()
]
// 0: not packed
StringType.storedLlvmType = LLVMStructType(&elems, UInt32(elems.count), 0)
print("Generating String type \(StringType.storedLlvmType!)")
return StringType.storedLlvmType!
}
}
class FunctionType : TypeAnn {
let argType: TypeAnn
let retType: TypeAnn
init(_ argType: TypeAnn, _ retType: TypeAnn) {
self.argType = argType
self.retType = retType
super.init()
}
override func toString() -> String {
// TODO: may need parentheses in the future (precedence!)
return "\(self.argType.toString()) -> \(self.retType.toString())";
}
override func equals(rhs: TypeAnn) -> Bool {
guard let rt = rhs as? FunctionType else {
return false
}
return argType.equals(rt.argType) && retType.equals(rt.retType)
}
override func llvmType() -> LLVMTypeRef {
// a function with a 'Void' argument is a
// special case: it means '0 arguments'.
var args: [LLVMTypeRef] = []
if self.argType != VoidType() {
args.append(self.argType.llvmType())
}
return LLVMFunctionType(
self.retType.llvmType(),
&args,
UInt32(args.count),
0 // 0: not variadic
)
}
}
// Convenience equality operators
func ==(lhs: TypeAnn, rhs: TypeAnn) -> Bool {
return lhs.equals(rhs)
}
func !=(lhs: TypeAnn, rhs: TypeAnn) -> Bool {
return !(lhs == rhs)
}
func TypeFromTypeName(oname: String?) -> TypeAnn {
guard let name = oname else {
return VoidType()
}
switch name {
case "Void": return VoidType()
case "Bool": return BoolType()
case "Int": return IntType()
case "Double": return DoubleType()
case "String": return StringType()
default:
assert(false, "unknown type name: \(name)")
return VoidType()
}
}
| true
|
97f7a2fb96375fc4544ba30abace01bbb279cce6
|
Swift
|
prikshitsoni/Urban_Services
|
/UrbanServicesFB/Controller/SPForgorPasswordVC.swift
|
UTF-8
| 1,345
| 2.875
| 3
|
[] |
no_license
|
//
// SPForgorPasswordVC.swift
// UrbanServicesFB
//
// Created by prikshit soni on 08/04/21.
//
import UIKit
import Firebase
class SPForgorPasswordVC: UIViewController {
@IBOutlet weak var EmailET: UITextField!
@IBOutlet weak var ErrorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
ErrorLabel.alpha = 0
}
func valicateFields() -> String?{
//check if all fields are filled
if EmailET.text?.trimmingCharacters(in: .whitespacesAndNewlines) == ""{
return "Please fill in all fields"
}
return nil
}
//Send Button
@IBAction func SendBTN(_ sender: UIButton) {
//validate text Fields
let error = valicateFields()
if error != nil{ showErrorMessage(error!) }
else{
let auth = Auth.auth()
auth.sendPasswordReset(withEmail:EmailET.text!) {(error) in
if error != nil {
self.showErrorMessage("error")
//self.showErrorMessage(error!.localizedDescription)
}
else{
self.showErrorMessage("Reset Email Sent")
}
}
}
}
func showErrorMessage(_ messege: String){
ErrorLabel.text = messege
ErrorLabel.alpha = 1
}
}
| true
|
729fb489420a9e5f1d8a0ef5b5f07620ee8e3c6c
|
Swift
|
JianTing-Li/FellowBloggerV2
|
/FellowBloggerV2/Controller/Login Controllers/RegisterController.swift
|
UTF-8
| 1,954
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
//
// RegisterController.swift
// FellowBloggerV2
//
// Created by Jian Ting Li on 3/14/19.
// Copyright © 2019 Jian Ting Li. All rights reserved.
//
import UIKit
class RegisterController: UIViewController {
@IBOutlet weak var usernameTextfield: UITextField!
@IBOutlet weak var emailTextfield: UITextField!
@IBOutlet weak var passwordTextfield: UITextField!
private var authservice = AppDelegate.authservice
override func viewDidLoad() {
super.viewDidLoad()
authservice.authserviceCreateNewAccountDelegate = self
}
@IBAction func registerButtonPressed(_ sender: UIButton) {
guard let username = usernameTextfield.text, !username.isEmpty,
let email = emailTextfield.text, !email.isEmpty,
let password = passwordTextfield.text, !password.isEmpty else {
return
}
authservice.createNewAccount(username: username, email: email, password: password)
}
@IBAction func alreadyHaveAccountButtonPressed(_ sender: UIButton) {
navigationController?.popViewController(animated: true)
}
}
extension RegisterController: AuthServiceCreateNewAccountDelegate {
func didRecieveErrorCreatingAccount(_ authservice: AuthService, error: Error) {
showAlert(title: "Account Creation Error", message: error.localizedDescription)
}
func didCreateNewAccount(_ authservice: AuthService, blogger: Blogger) {
print("Account Created")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let fellowBloggerTabBarController = storyboard.instantiateViewController(withIdentifier: "FellowBloggerTabBarController") as! UITabBarController
fellowBloggerTabBarController.modalTransitionStyle = .crossDissolve
fellowBloggerTabBarController.modalPresentationStyle = .overFullScreen
present(fellowBloggerTabBarController, animated: true)
// TODO: Remove VC
}
}
| true
|
8b1392198c509d7e7bc23f47f7e420552e0a39dc
|
Swift
|
dmitry-davydov/mypath
|
/MyPath/App/Flow/TrackingList/TrackingListFlowPresenter.swift
|
UTF-8
| 1,110
| 2.578125
| 3
|
[] |
no_license
|
//
// TrackingListFlowPresenter.swift
// MyPath
//
// Created by Дима Давыдов on 21.08.2021.
//
import UIKit
protocol TrackingListFlowPresenterProtocol {
func present(_ response: TrackingListModel.MoveEntries.Response)
func present(_ response: TrackingListModel.Track.ResponseHistory)
func present(_ response: TrackingListModel.Track.ResponseNewTrack)
}
class TrackingListFlowPresenter: TrackingListFlowPresenterProtocol {
weak var viewController: TrackingListFlowDisplayLogic?
func present(_ response: TrackingListModel.MoveEntries.Response) {
viewController?.display(TrackingListModel.MoveEntries.Response(items: response.items))
}
func present(_ response: TrackingListModel.Track.ResponseHistory) {
viewController?.display(TrackingListModel.ViewModel.ViewModelHistory(item: MainViewController.State.view(response.item)))
}
func present(_ response: TrackingListModel.Track.ResponseNewTrack) {
viewController?.display(TrackingListModel.ViewModel.ViewModelNewTrack(item: MainViewController.State.tracking(response.item)))
}
}
| true
|
4e47eead66e7cfcc23d5d9d007548025bbe8d391
|
Swift
|
cnoon/swift-compiler-crashes
|
/unique-crash-locations/std_1_basic_string_char_std_1_char_traits_char_std_1_allocator_char_rfind_char_const_unsigned_long_const_47.swift
|
UTF-8
| 57
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
../crashes-fuzzing/23974-swift-declname-printpretty.swift
| true
|
f3cf369cacf9bbfbf0db93836e480ccfa39f794b
|
Swift
|
scottiedog45/SwiftUIScratchpad
|
/Overview/Form/FormViewLogic.swift
|
UTF-8
| 2,404
| 3.015625
| 3
|
[] |
no_license
|
//
// CombineLogic.swift
// Overview
//
// Created by Scott OToole on 6/25/19.
// Copyright © 2019 Scott OToole. All rights reserved.
//
import Foundation
import SwiftUI
import Combine
//bindable object here that fetches data and publishes it
struct Basic : Codable {
let userID, id: Int
let title: String
let completed: Bool
enum CodingKeys: String, CodingKey {
case userID = "userId"
case id, title, completed
}
}
struct SomeErrors: Error {
var code : Int
}
class FormViewLogic : BindableObject {
var willChange : PassthroughSubject<Void, Never> = PassthroughSubject()
var stuff : PassthroughSubject<Basic, Never> = PassthroughSubject()
var stuff2 : PassthroughSubject<Basic, Never> = PassthroughSubject()
public var score = 0 { willSet { willChange.send() } }
public var num = [1,2,3,4,5] { didSet { willChange.send() } }
private(set) var basic : Basic? = nil { didSet { willChange.send() } }
func getData() {
let urla = URLRequest(url: URL(string: "https://jsonplaceholder.typicode.com/todos/1")!)
let urlb = URLRequest(url: URL(string: "https://jsonplaceholder.typicode.com/todos/12")!)
let fra = URLSession.shared.dataTaskPublisher(for: urla)
.map {$0.data}
.decode(type: Basic.self, decoder: JSONDecoder())
let sha = URLSession.shared.dataTaskPublisher(for: urlb)
.map {$0.data}
.decode(type: Basic.self, decoder: JSONDecoder())
Publishers.Zip(sha, fra)
.receive(on: RunLoop.main)
.sink(receiveCompletion: { (completion) in
switch completion {
case .failure(let nev):
print(nev)
default:
print("complete")
}
}, receiveValue: { (response) in
print(response)
})
// precondition("" == "5")
let url = URLRequest(url: URL(string: "https://jsonplaceholder.typicode.com/todos/1")!)
_ = URLSession.shared.dataTaskPublisher(for: url)
.tryMap { data, response in
if let r = response as? HTTPURLResponse {
switch r.statusCode {
case 200...201:
return data
default:
fatalError()
}
}
return data
}
.decode(type: Basic.self, decoder: JSONDecoder())
.receive(on : RunLoop.main)
.sink(receiveCompletion: { (response) in
switch response {
case .failure(let error):
print("error: \(error)")
case .finished:
break
}
}, receiveValue: { print($0) })
}
}
| true
|
8cf12cc048a3b2e7190d418a426199e53ead273e
|
Swift
|
khymychd/MVP-LevelOne
|
/MVP-LevelOne/DetailModule/Presenter/DetailPresenter.swift
|
UTF-8
| 1,038
| 2.921875
| 3
|
[] |
no_license
|
//
// DetailPresenter.swift
// MVP-LevelOne
//
// Created by Dima Khymych on 29.09.2020.
//
import Foundation
protocol DetailViewProtocol:class {
func setComment(comment:Comment?)
}
protocol DetailViewPresenterProtocol:class {
init(view:DetailViewProtocol, networkService:NetworkServiceProtocol,
router:RouterProtocol,
comment:Comment?)
func setComment()
func tap()
}
class DetailPresenter:DetailViewPresenterProtocol {
weak var view:DetailViewProtocol?
let networkService:NetworkServiceProtocol!
var comment:Comment?
var router:RouterProtocol?
required init(view: DetailViewProtocol, networkService: NetworkServiceProtocol, router: RouterProtocol, comment: Comment?) {
self.networkService = networkService
self.view = view
self.comment = comment
self.router = router
}
public func setComment() {
self.view?.setComment(comment: comment)
}
func tap() {
router?.popToRoot()
}
}
| true
|
5bea4660c9021c796534bf6aba80034947a89154
|
Swift
|
KirthikaChinnaswamy/iOSAutomationWikipedia
|
/wikipedia-ios-main/WikipediaUITestAssignment/Screens/ResultScreen.swift
|
UTF-8
| 4,612
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// ResultScreen.swift
// wikipediaUITestsAssignment
//
// Created by Kirthika Chinnaswamy on 08/20/21.
//
import Foundation
public class ResultScreen: CommonUtility {
let applogo = app.navigationBars.buttons[AccessibilityIdentifiers.Result.applogo]
let backSearch = app.navigationBars.firstMatch.buttons[AccessibilityIdentifiers.Result.backSearch]
let safariBack = springboardApp.buttons[AccessibilityIdentifiers.Result.safariBack]
let cancel = app.buttons[AccessibilityIdentifiers.Home.cancel].firstMatch
let backHistory = app.navigationBars.firstMatch.buttons[AccessibilityIdentifiers.Result.backHistory]
func verifyWikiPageLogo() -> ResultScreen {
checkForElement(applogo, seconds: 5, action: .exists, description: "appLogo in wikiPage/verifyWikiPageLogo")
return self
}
func verifyWikiPage(wikiPageElements: [String]) -> ResultScreen {
wikiPageElements.forEach {(element) in
let wikiElement = app.staticTexts[element].firstMatch
checkForElement(wikiElement, description: "\(element) in wikiPage/verifyWikiPage")
}
return self
}
func verifySafariLink(heading: String, links: [String]) -> ResultScreen {
let heading = app.staticTexts[heading].firstMatch
tapOn(heading, action: .exists, description: "expand \(heading)/verifySafariLink")
let link = app.links[links[0]]
let linkTitle = safariApp.otherElements[links[1]]
tapOn(link, action: .exists, description: "link - \(link) from \(heading)/verifySafariLink")
checkForElement(linkTitle, seconds: 10, action: .exists, description: "safari Page Title/verifySafariLink")
tapOn(safariBack, seconds: 5, action: .exists, description: "Back to Wikipedia/verifySafariLink")
tapOn(heading, action: .exists, description: "collapse \(heading)/verifySafariLink")
return self
}
func backToHomeScreen() -> HomeScreen{
tapOn(backSearch, action: .exists, description: "backButton in wikiPage/gotoHomeScreen")
tapOn(cancel,seconds: 5, action: .exists, description: "cancelbutton from SearchField/gotoHomeScreen")
return HomeScreen()
}
func backToHistory() -> HistoryScreen {
tapOn(backHistory, action: .exists, description: "backButton in wikiPage/tapOnBack")
return HistoryScreen()
}
// func checkResultsScreen(wikiPageElements: [String]) -> HomeScreen {
// wikiPageElements.forEach {(wikiElement) in
// let wikiPageElement = app.staticTexts[wikiElement].firstMatch
// checkForElement(wikiPageElement, description: "\(wikiElement) in ResultScreen/checkFor\(wikiElement)")
// }
//
// verifylogo()
//
// verifyTitle()
// verifyHeadings()
// expandandCollapse()
// verifyExternalLinks()
// gotoHomeScreen()
// return HomeScreen()
// }
// func verifyTitle() {
// checkForElement(title, seconds: 5, action: .exists, description: "searchResult Title/checkForResultTitle")
// checkForElement(subTitle, seconds: 5, action: .exists, description: "SearchResult subTitle/checkForResultSubTitle")
// }
//
// func verifyHeadings() {
// checkForElement(quicFacts, seconds: 0, action: .exists, description: "quickFacts Heading/checkForQuickFacts")
// checkForElement(history, seconds: 0, action: .exists, description: "history Heading/checkForHistory")
// checkForElement(references, seconds: 0, action: .exists, description: "references Heading/checkForReferences")
// checkForElement(externalLinks, seconds: 0, action: .exists, description: "externalLinks Heading/checkForExternalLinks")
// }
//
// func expandandCollapse() {
// tapOn(quicFacts, action: .exists, description: "expand QuickFacts/tapOnQuickFacts")
// tapOn(quicFacts, action: .exists, description: "expand QuickFacts/tapOnQuickFacts")
// }
//
// func verifyExternalLinks() {
// tapOn(references, action: .exists, description: "expand References/tapOnReferences")
// tapOn(link, action: .exists, description: "link from References/tapOnlinktoSafari")
// checkForElement(linkTitle, seconds: 5, action: .exists, description: "safari Page Title/checkForPageTitle")
// tapOn(safariBack, seconds: 5, action: .exists, description: "Back to Wikipedia/tapOnBacktoWikipedia")
// }
}
| true
|
8bb41161af93e25988b8271bf3adb15e77b13a0f
|
Swift
|
alihand/DGSyeNeKadarKaldi
|
/Timer/GeometryTableViewController.swift
|
UTF-8
| 865
| 2.8125
| 3
|
[] |
no_license
|
//
// GeometryTableViewController.swift
// Timer
//
// Created by Alihan Demir on 11.02.2019.
// Copyright © 2019 Alihan Demir. All rights reserved.
//
import UIKit
class GeometryTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
let GeometryQuestions = ["Açılar ve Üçgenler","Çokgenler","Çember ve Daire","Katı Cisimler","Analitik Geometri"]
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return GeometryQuestions.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "GeometryList", for: indexPath)
cell.textLabel?.text = GeometryQuestions[indexPath.row]
return cell
}
}
| true
|
f6a4ce041d2b10ded6bf8eacab3bb6319eaca945
|
Swift
|
ituacm/ITU-ACM-18-19-iOS-Programming-Study-Group
|
/Weeks/Week 2/Answers/Answer1.playground/Contents.swift
|
UTF-8
| 925
| 3.890625
| 4
|
[
"MIT"
] |
permissive
|
protocol QueueProtocol {
associatedtype T
var isEmpty: Bool { get }
var container: [T] { get }
var count: Int { get }
}
class Queue<T>: QueueProtocol {
internal var container: [T]
var count: Int {
return container.count
}
var isEmpty: Bool {
return container.count == 0
}
init() {
container = []
}
func enqueue(item: T) {
container.insert(item, at: 0)
}
func dequeue() -> T? {
return container.popLast()
}
func getItems() -> [T] {
return container
}
func showItems() {
for item in container {
print(item, terminator: " ")
}
print("")
}
}
let myQueue = Queue<Int>()
for item in 0...10 {
myQueue.enqueue(item: item)
}
print("Myqueue contains \(myQueue.count) elements.")
myQueue.showItems()
while !myQueue.isEmpty {
print(myQueue.dequeue()!)
}
print("Myqueue contains \(myQueue.count) elements after dequeueing.")
| true
|
323403dd5329fa4606aba522f1c5003a2cc09aa3
|
Swift
|
hendriku/Sejima
|
/Sejima/Sources/MUNavigationBar/MUNavigationBar.swift
|
UTF-8
| 9,636
| 2.859375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// MUNavigationBar.swift
// Sejima
//
// Created by Loïc GRIFFIE on 31/10/2018.
// Copyright © 2018 Loïc GRIFFIE. All rights reserved.
//
import UIKit
import Neumann
/// Delegate protocol for MUNavigationBar.
@objc public protocol MUNavigationBarDelegate: class {
/// Will trigger on cancel / back button tap.
func leftDidTap(navigationBar: MUNavigationBar)
/// Will trigger on main / validate button tap.
func mainDidTap(navigationBar: MUNavigationBar)
/// Will trigger on more option button tap.
func rightDidTap(navigationBar: MUNavigationBar)
}
/// Class that act like UINavigationBar with more customizable options.
@IBDesignable
open class MUNavigationBar: MUNibView {
@IBOutlet private var leftButton: UIButton!
@IBOutlet private var leftButtonWidthConstraint: NSLayoutConstraint!
@IBOutlet private var leftSeparatorView: UIView!
@IBOutlet private var leftSeparatorWidthConstraint: NSLayoutConstraint!
@IBOutlet private var leftSeparatorHeightConstraint: NSLayoutConstraint!
@IBOutlet private var mainButton: MUButton!
@IBOutlet private var rightSeparatorView: UIView!
@IBOutlet private var rightSeparatorWidthConstraint: NSLayoutConstraint!
@IBOutlet private var rightSeparatorHeightConstraint: NSLayoutConstraint!
@IBOutlet private var rightButton: UIButton!
@IBOutlet private var rightButtonWidthConstraint: NSLayoutConstraint!
/// The object that acts as the delegate of the navigation bar.
@IBOutlet public weak var delegate: MUNavigationBarDelegate? // swiftlint:disable:this private_outlet strong_iboutlet line_length
// MARK: - Left button
/// A UIImage for the left button.
@IBInspectable open dynamic var leftButtonImage: UIImage? = nil {
didSet {
leftButton.setImage(leftButtonImage, for: .normal)
leftSeparatorView.isHidden = !(leftButton.image(for: .normal) != nil)
}
}
/// Specifies the let button's proportional width. Default is 70:375
@IBInspectable open dynamic var leftButtonWidthMultiplier: CGFloat = 70 / 375 {
didSet {
leftButtonWidthConstraint = NSLayoutConstraint.change(multiplier: leftButtonWidthMultiplier,
for: leftButtonWidthConstraint)
}
}
// MARK: - Right button
/// A UIImage for the left button.
@IBInspectable open dynamic var rightButtonImage: UIImage? = nil {
didSet {
rightButton.setImage(rightButtonImage, for: .normal)
rightSeparatorView.isHidden = !(rightButton.image(for: .normal) != nil)
}
}
/// Specifies the let button's proportional width. Default is 70:375
@IBInspectable open dynamic var rightButtonWidthMultiplier: CGFloat = 70 / 375 {
didSet {
rightButtonWidthConstraint = NSLayoutConstraint.change(multiplier: rightButtonWidthMultiplier,
for: rightButtonWidthConstraint)
}
}
// MARK: - Separator
/// The separator’s color.
@IBInspectable open dynamic var separatorColor: UIColor = .white {
didSet {
leftSeparatorView.backgroundColor = separatorColor
rightSeparatorView.backgroundColor = separatorColor
}
}
/// The separator’s width.
@IBInspectable open dynamic var separatorWidth: CGFloat = 1.0 {
didSet {
leftSeparatorWidthConstraint.constant = separatorWidth
rightSeparatorWidthConstraint.constant = separatorWidth
}
}
/// The separator’s height multiplier (should be between 0.0 and 1.0).
@IBInspectable open dynamic var separatorHeightMultiplier: CGFloat = 0.3 {
didSet {
leftSeparatorHeightConstraint = NSLayoutConstraint.change(multiplier: separatorHeightMultiplier,
for: leftSeparatorHeightConstraint)
rightSeparatorHeightConstraint = NSLayoutConstraint.change(multiplier: separatorHeightMultiplier,
for: rightSeparatorHeightConstraint)
}
}
// MARK: - Main button
/// The current title that is displayed by the main button.
@IBInspectable open var mainButtonTitle: String {
get {
return mainButton.title
}
set {
mainButton.title = newValue
}
}
/// The main button’s font.
@objc public dynamic var mainButtonTitleFont: UIFont {
get {
return mainButton.titleFont
}
set {
mainButton.titleFont = newValue
}
}
/// The main button’s horizontal alignment.
@objc public dynamic var mainButtonTitleAlignment: UIControl.ContentHorizontalAlignment {
get {
return mainButton.titleAlignment
}
set {
mainButton.titleAlignment = newValue
}
}
/// Optional: The IBInspectable version of the main button’s horizontal alignment.
@IBInspectable open var mainButtonTitleAlignmentInt: Int {
get {
return mainButton.titleAlignmentInt
}
set {
mainButton.titleAlignmentInt = newValue
}
}
/// The main button’s title color.
@IBInspectable open dynamic var mainButtonTitleColor: UIColor {
get {
return mainButton.titleColor
}
set {
mainButton.titleColor = newValue
}
}
/// The main button’s highlighted title color.
@IBInspectable open dynamic var mainButtonTitleHighlightedColor: UIColor {
get {
return mainButton.titleHighlightedColor
}
set {
mainButton.titleHighlightedColor = newValue
}
}
/// The activity indicator’s color of the main button.
@IBInspectable open dynamic var mainButtonProgressColor: UIColor {
get {
return mainButton.progressColor
}
set {
mainButton.progressColor = newValue
}
}
/// Show or hide the progress indicator of the main button.
@IBInspectable open dynamic var mainButtonIsLoading: Bool {
get {
return mainButton.isLoading
}
set {
mainButton.isLoading = newValue
}
}
/// The main button’s state. (Won’t work with application’s state and reserved state).
@objc public dynamic var mainButtonState: UIControl.State {
get {
return mainButton.state
}
set {
mainButton.state = newValue
}
}
/// The main button’s alpha value for disabled state.
@IBInspectable open dynamic var mainButtonDisabledAlphaValue: CGFloat {
get {
return mainButton.disabledAlphaValue
}
set {
mainButton.disabledAlphaValue = newValue
}
}
/// The main button’s background color.
@IBInspectable open dynamic var mainButtonBackgroundColor: UIColor {
get {
return mainButton.buttonBackgroundColor
}
set {
mainButton.buttonBackgroundColor = newValue
}
}
/// The main button’s border color.
@IBInspectable open dynamic var mainButtonBorderColor: UIColor {
get {
return mainButton.borderColor
}
set {
mainButton.borderColor = newValue
}
}
/// The main button’s border width.
@IBInspectable open dynamic var mainButtonBorderWidth: CGFloat {
get {
return mainButton.borderWidth
}
set {
mainButton.borderWidth = newValue
}
}
/// The main button’s corner radius.
@IBInspectable open dynamic var mainButtonCornerRadius: CGFloat {
get {
return mainButton.cornerRadius
}
set {
mainButton.cornerRadius = newValue
}
}
/// The main button’s vertical padding.
@IBInspectable open dynamic var mainButtonVerticalPadding: CGFloat {
get {
return mainButton.verticalPadding
}
set {
mainButton.verticalPadding = newValue
}
}
/// The main button’s horizontal padding.
@IBInspectable open dynamic var mainButtonHorizontalPadding: CGFloat {
get {
return mainButton.horizontalPadding
}
set {
mainButton.horizontalPadding = newValue
}
}
// MARK: - Private IBAction functions
@IBAction private func leftButtonDidTap(_ sender: Any?) {
delegate?.leftDidTap(navigationBar: self)
}
@IBAction private func rightButtonDidTap(_ sender: Any?) {
delegate?.rightDidTap(navigationBar: self)
}
// MARK: - Life cycle functions
/// Default setup to load the view from a xib file.
override open func xibSetup() {
super.xibSetup()
mainButton.delegate = self
leftSeparatorView.isHidden = true
rightSeparatorView.isHidden = true
}
/// The natural size for the receiving view, considering only properties of the view itself.
override open var intrinsicContentSize: CGSize {
return CGSize(width: 375, height: 44) // To act like a UINavigationBar with a default size
}
}
extension MUNavigationBar: MUButtonDelegate {
/// Will trigger each time the main button is tapped.
public func didTap(button: MUButton) {
delegate?.mainDidTap(navigationBar: self)
}
}
| true
|
24a0a5cce6effea9cd2676b36b8a3c0dd925e6a1
|
Swift
|
mariusjcb/swiftui-topmovies
|
/Top Movies/Api/BaseApi/BaseApiUrlBuilder.swift
|
UTF-8
| 521
| 2.78125
| 3
|
[] |
no_license
|
//
// BaseApiUrlBuilder.swift
// Top Movies
//
// Created by Marius Ilie on 02/10/2019.
// Copyright © 2019 Marius Ilie. All rights reserved.
//
import Foundation
class BaseApiUrlBuilder {
let baseUrl: String
init(baseUrl: String) {
self.baseUrl = baseUrl
}
func url(for resource: String, queryItems: [URLQueryItem] = []) -> URL {
var urlComponents = URLComponents(string: baseUrl + resource)!
urlComponents.queryItems = queryItems
return urlComponents.url!
}
}
| true
|
6d57faf9becb7b4181da7ebbb9bccfdd0c3890ae
|
Swift
|
garrincha33/Sonder
|
/Sonder/Algorithms.playground/Contents.swift
|
UTF-8
| 1,944
| 4.25
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
//-- searching a binary tree
//1
// 10
// / \
// 5 14
// / / \
// 1 11 20
//
class Node {
let value: Int
let leftChild: Node?
let rightChild: Node?
init(value: Int, leftChild: Node?, rightChild: Node?) {
self.value = value
self.leftChild = leftChild
self.rightChild = rightChild
}
}
//left node
let oneNode = Node(value: 1, leftChild: nil, rightChild: nil)
let fiveNode = Node(value: 5, leftChild: oneNode , rightChild: nil)
//rightNode
let twentyNode = Node(value: 20, leftChild: nil, rightChild: nil)
let elevanNode = Node(value: 11, leftChild: nil, rightChild: nil)
let fourteenNode = Node(value: 14, leftChild: elevanNode, rightChild: twentyNode)
//rootNode
let rootNode = Node(value: 10, leftChild: fiveNode, rightChild: fourteenNode)
func search(node: Node?, searchValue: Int) -> Bool {
//recursion calling the same method your already in with maybe different parameters
//base case to stop infinate loop
if node == nil {
return false
}
if node?.value == searchValue {
return true
} else if searchValue < node!.value {
return search(node: node?.leftChild, searchValue: searchValue)
} else {
return search(node: node?.rightChild, searchValue: searchValue)
}
}
func anotherSearch(node: Node?, searchValue: Int) -> Bool {
if node?.value == nil {
return false
} else if searchValue < node!.value {
return search(node: node?.leftChild, searchValue: searchValue)
} else {
return search(node: node?.rightChild, searchValue: searchValue)
}
}
search(node: rootNode, searchValue: 20)
| true
|
b22522df93ef1780178ce5a35684a7351558709e
|
Swift
|
PlatounOragnisation/app-platoun-ios
|
/Platoun/V1/Utils/UIKitUtils.swift
|
UTF-8
| 2,582
| 2.84375
| 3
|
[] |
no_license
|
//
// UIKitUtils.swift
// Platoun
//
// Created by Flavian Mary on 31/08/2020.
// Copyright © 2020 Flavian Mary. All rights reserved.
//
import UIKit
class UIKitUtils {
static func showAlert(in viewControler: UIViewController, message: String, completion: @escaping ()->Void) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
completion()
}))
viewControler.present(alert, animated: true, completion: nil)
}
static func showAlert(in viewControler: UIViewController, message: String, completionOK: @escaping ()->Void, completionCancel: @escaping ()->Void) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
completionOK()
}))
alert.addAction(UIAlertAction(title: "Annuler", style: .cancel, handler: { _ in
completionCancel()
}))
viewControler.present(alert, animated: true, completion: nil)
}
static func showAlert(in viewControler: UIViewController, message: String, action1Title: String, completionOK: @escaping ()->Void, action2Title: String, completionCancel: @escaping ()->Void) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: action1Title, style: .default, handler: { _ in
completionOK()
}))
alert.addAction(UIAlertAction(title: action2Title, style: .cancel, handler: { _ in
completionCancel()
}))
viewControler.present(alert, animated: true, completion: nil)
}
static func requestAlert(in viewControler: UIViewController, message: String, completion: @escaping (String)->Void) {
var textField: UITextField?
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alert.addTextField { (tf) in
textField = tf
tf.placeholder = "Entrée votre nom"
}
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
if let text = textField?.text, !text.isEmpty {
completion(text)
} else {
requestAlert(in: viewControler, message: message, completion: completion)
}
}))
viewControler.present(alert, animated: true, completion: nil)
}
}
| true
|
96cb76726a2071abf9afa106b6856f1979e5dfb4
|
Swift
|
iDoyoung/QuestWithCoreData
|
/QuestWithCoreData/Main/Main + Extension.swift
|
UTF-8
| 4,242
| 2.828125
| 3
|
[] |
no_license
|
//
// Main + Extension.swift
// QuestWithCoreData
//
// Created by ido on 2021/04/03.
//
import UIKit
extension MainViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
self.headerTitle()
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return selectedQuests.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as? TableViewCell else {
return UITableViewCell()
}
cell.selectionStyle = .none
let cellOfQuest = selectedQuests[indexPath.row]
cell.updateCellUI(quest: cellOfQuest)
cell.pinButton.tag = indexPath.row
cell.pinButton.addTarget(self, action: #selector(pinQuest(sender:)), for: .touchUpInside)
return cell
}
}
extension MainViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
showDetail(select: selectedQuests[indexPath.row])
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let alert = UIAlertController(title: "Give up", message: "You did not complete quest. \nAre you going to give up?", preferredStyle: .alert)
let deleteAction = UIAlertAction(title: "Give up", style: .destructive) { (_) in
let quest = self.selectedQuests[indexPath.row]
quest.isDone = true
self.viewModel.saveData()
self.selectedQuests = self.viewModel.uncompleted
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancelAction)
alert.addAction(deleteAction)
present(alert, animated: true, completion: nil)
}
}
}
extension MainViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.pinned.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) as? CollectionViewCell else {
return UICollectionViewCell()
}
let quest = viewModel.pinned[indexPath.item]
cell.updateCollectionViewUI(quest: quest)
cell.pinButton.tag = indexPath.item
cell.pinButton.addTarget(self, action: #selector(unpinPinnedQuest(sender:)), for: .touchUpInside)
cell.contentView.backgroundColor = UIColor(named: "Background")
return cell
}
}
extension MainViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let questOfDeadLine = viewModel.pinned[indexPath.item]
showDetail(select: questOfDeadLine)
}
}
extension MainViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let searching = textField.text
var searchedQuest: [Quest] {
viewModel.uncompleted.filter { $0.title!.contains(searching!) }
}
if !textField.text!.isEmpty {
selectedQuests = searchedQuest
seletedTitle = "Searched \(selectedQuests.count)"
//tableView.reloadData()
self.view.endEditing(true)
} else {
self.view.endEditing(true)
}
return true
}
}
extension MainViewController: QuestDelegate {
func updateQuestData() {
viewWillAppear(true)
selectedQuests = viewModel.uncompleted
}
}
| true
|
32c3f39517432a64e3f8cde7ce4a87d374ed2832
|
Swift
|
CodeKul/Blancco-Swift-iOS-Corporate-May-2020
|
/iOSDemos/JSONDemo/JSONDemo/UserDecodable.swift
|
UTF-8
| 406
| 2.796875
| 3
|
[] |
no_license
|
//
// UserDecodable.swift
// JSONDemo
//
// Created by Apple on 19/05/20.
// Copyright © 2020 Codekul. All rights reserved.
//
import Foundation
class UserDecodable: Codable {
let name, job, id, createdAt: String
init(name: String, job: String, id: String, createdAt: String) {
self.name = name
self.job = job
self.id = id
self.createdAt = createdAt
}
}
| true
|
d044643db9fd2531ae999812152eefae6dd29903
|
Swift
|
DebiteGit/iOSCitasMedicas
|
/TimeMedical/Extensions/HelperExtension.swift
|
UTF-8
| 1,475
| 3
| 3
|
[] |
no_license
|
//
// HelperExtension.swift
// TimeMedical
//
// Created by Carlos Espinoza on 18/09/18.
// Copyright © 2018 Carlos Espinoza. All rights reserved.
//
import Foundation
import UIKit
import JTAppleCalendar
extension UIView {
/**
Adds a vertical gradient layer with two **UIColors** to the **UIView**.
- Parameter topColor: The top **UIColor**.
- Parameter bottomColor: The bottom **UIColor**.
*/
func addVerticalGradientLayer(topColor:UIColor, bottomColor:UIColor) -> CAGradientLayer{
let gradient = CAGradientLayer()
gradient.frame = self.bounds
gradient.colors = [
topColor.cgColor,
bottomColor.cgColor
]
gradient.locations = [0.0, 1.0]
gradient.startPoint = CGPoint(x: 0, y: 0)
gradient.endPoint = CGPoint(x: 0, y: 1)
return gradient
}
}
extension UIViewController {
func alert(title: String, message: String) {
// create the alert
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
}
extension UIColor {
convenience init(colorWithHexValue value: Int, alpha :CGFloat = 1.0) {
self.init(
red : CGFloat((value & 0xFF0000) >> 16) / 255.0,
green : CGFloat((value & 0x00FF00) >> 16) / 255.0,
blue : CGFloat((value & 0x0000FF) >> 16) / 255.0,
alpha: alpha
)
}
}
| true
|
10a9461ce6fc3dadef6e0e49c4b655e030549f3b
|
Swift
|
amitf1978/HackerU
|
/חומר לתרגולים - אייפון/DelegatesExample/DelegateExample/ViewControllerB.swift
|
UTF-8
| 596
| 2.859375
| 3
|
[] |
no_license
|
//
// SecondViewController.swift
// DelegateExample
//
// Created by נדב אבנון on 07/03/2021.
import UIKit
class ViewControllerB: UIViewController {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func changeMainTextAction(_ sender: UIButton) {
// return if nothing is inserted
guard let text = textField?.text, !text.isEmpty else {
print("nothing was typed in")
return}
// do something with the text
print(text, "was typed in")
}
}
| true
|
84cc2eb25a48815caab1de9c4540f86002e0e99d
|
Swift
|
donmcbrien/SwiftUIFields
|
/Sources/SwiftUIFields/FieldsSectionStyle.swift
|
UTF-8
| 660
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// CustomSectionStyle.swift
// Fields
//
// Created by Don McBrien on 09/05/2021.
//
import SwiftUI
//MARK: - Custom Modifiers
struct FieldsSectionStyle: ViewModifier {
@EnvironmentObject var environment: FieldsEnvironment
var foregroundColor: Color?
func body(content: Content) -> some View {
content
.padding(.vertical)
.frame(maxWidth: .infinity)
.background(Color.yellow)
.font(.title2)
.foregroundColor(.blue)
}
}
extension View {
public func fieldsSectionStyle() -> some View {
ModifiedContent(
content: self,
modifier: FieldsSectionStyle()
)
}
}
| true
|
f4fe4292aca5f7b3c91cbf019df452a02eec035c
|
Swift
|
juliand665/AdCom-Helper
|
/AdCom Helper/Data Managers/PlayerManager.swift
|
UTF-8
| 2,070
| 2.578125
| 3
|
[] |
no_license
|
import GameKit
import Combine
import AdComData
final class PlayerManager: ObservableObject {
@Published private(set) var state = State.loading {
didSet {
if state.playerID != oldValue.playerID {
client = state.playerID.map(Client.init(playerID:))
}
}
}
@Published private(set) var client: Client? {
didSet { loadGameModel() }
}
@Published private(set) var userData: UserData?
@Published private(set) var isLoadingModel = false
private var request: AnyCancellable? {
didSet { isLoadingModel = request != nil }
}
var canLoadModel: Bool {
!isLoadingModel && client != nil
}
init(for player: GKLocalPlayer) {
player.authenticateHandler = { viewController, error in
if let error = error {
print("error while authenticating:", error)
self.state = .error(error)
} else if let viewController = viewController {
print("sign in requested!")
self.state = .signInRequested(viewController)
} else {
let playerID = player.deprecatedPlayerID
print("authenticated as \(playerID)")
self.state = .signedIn(playerID)
}
}
}
func loadGameModel() {
guard let client = client else { return }
isLoadingModel = true
request?.cancel()
request = client.getUserData().receive(on: RunLoop.main).sink(
receiveCompletion: ({
self.request = nil
switch $0 {
case .finished:
break
case .failure(let error):
self.userData = nil
print("error while loading game model:", error)
}
}),
receiveValue: ({
self.userData = $0.decoded()
})
)
}
enum State {
case loading
case signedIn(_ playerID: String)
case signInRequested(UIViewController)
case error(Error)
var playerID: String? {
switch self {
case .signedIn(let playerID):
return playerID
default:
return nil
}
}
}
}
// deprecated schmeprecated
private protocol PlayerIDProvider {
var playerID: String { get }
}
extension GKLocalPlayer: PlayerIDProvider {}
extension GKLocalPlayer {
var deprecatedPlayerID: String {
(self as PlayerIDProvider).playerID
}
}
| true
|
0a9ca483a1dd99df9462468a2e9cc54c134e7679
|
Swift
|
jom7flores/GalleryViewer
|
/GalleryViewer/Classes/Data/Providers/DefaultLocalImageProvider.swift
|
UTF-8
| 3,281
| 2.59375
| 3
|
[] |
no_license
|
//
// DefaultLocalImageProvider.swift
// GalleryViewer
//
// Created by Josue Flores on 1/13/21.
//
import Combine
import Photos
import UIKit
class DefaultLocalImageProvider: LocalImageProvider {
let imageLoadQueue: DispatchQueue
init() {
imageLoadQueue = DispatchQueue(label: "imageLoadingThread", qos: .userInitiated)
}
var status: PHAuthorizationStatus {
if #available(iOS 14, *) {
return PHPhotoLibrary.authorizationStatus(for: .readWrite)
} else {
return PHPhotoLibrary.authorizationStatus()
}
}
func requestMediaAccess() -> AnyPublisher<PHAuthorizationStatus, Never> {
guard status == .notDetermined else {
return Just(status).eraseToAnyPublisher()
}
return Future<PHAuthorizationStatus, Never> { promise in
DispatchQueue.main.async {
if #available(iOS 14, *) {
PHPhotoLibrary.requestAuthorization(for: .readWrite) { status in
promise(.success(status))
}
} else {
PHPhotoLibrary.requestAuthorization { status in
promise(.success(status))
}
}
}
}.eraseToAnyPublisher()
}
func fetchAssets() -> AnyPublisher<[PHAsset], Error> {
guard status == .authorized else {
return Fail(outputType: [PHAsset].self, failure: ImageProviderError.notAuthorized)
.eraseToAnyPublisher()
}
return Future { promise in
DispatchQueue.global().async {
let options = PHFetchOptions()
options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
options.predicate = NSPredicate(format: "mediaType == %ld", PHAssetMediaType.image.rawValue)
let result = PHAsset.fetchAssets(with: options)
promise(.success(result.objects(at: IndexSet(0..<result.count))))
}
}
.eraseToAnyPublisher()
}
func loadAsset(with identifier: String, mode: ImageProviderLoadingMode, targetSize: CGSize) -> AnyPublisher<UIImage?, Never> {
let value = PassthroughSubject<UIImage?, Never>()
imageLoadQueue.async { [value] in
let fetchResult = PHAsset.fetchAssets(withLocalIdentifiers: [identifier], options: nil)
guard let phAsset = fetchResult.firstObject else {
return
}
let options = PHImageRequestOptions()
options.version = .current
options.resizeMode = mode == .fast ? .fast : .exact
options.deliveryMode = mode == .fast ? .opportunistic : .highQualityFormat
options.isNetworkAccessAllowed = true
PHImageManager.default().requestImage(
for: phAsset,
targetSize: targetSize,
contentMode: .aspectFill,
options: options
) { image, _ in
value.send(image)
}
}
return value.eraseToAnyPublisher()
}
}
enum ImageProviderError: Error {
case notAuthorized
}
enum ImageProviderLoadingMode {
case fast
case exact
}
| true
|
961c21beb7bd18349bcdaa3452c173cb7f99b520
|
Swift
|
fossabot/Mia
|
/Playgrounds/Global Functions Demo.playground/Sources/Date+Formatted.swift
|
UTF-8
| 1,605
| 3.3125
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public extension Date {
// MARK: - Formatted Date - Style
/// Convenience method that returns a formatted string representing the receiver's date formatted to a given style, time zone and locale
///
/// - Parameters:
/// - dateStyle: The date style to use.
/// - timeZone: the time zone to use.
/// - locale: The local to use.
/// - Returns: A formatted string from date.
public func format(with dateStyle: DateFormatter.Style, timeZone: TimeZone = TimeZone.autoupdatingCurrent, locale: Locale = Locale.autoupdatingCurrent) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = dateStyle
dateFormatter.timeZone = timeZone
dateFormatter.locale = locale
return dateFormatter.string(from: self)
}
// MARK: - Formatted Date - String
/// Convenience method that returns a formatted string representing the receiver's date formatted to a given date format, time zone and locale
///
/// - Parameters:
/// - dateFormat: The date format to use.
/// - timeZone: the time zone to use.
/// - locale: The local to use.
/// - Returns: A formatted string from date.
public func format(with dateFormat: String, timeZone: TimeZone = TimeZone.autoupdatingCurrent, locale: Locale = Locale.autoupdatingCurrent) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = timeZone
dateFormatter.locale = locale
return dateFormatter.string(from: self)
}
}
| true
|
4da659b438b68d2e419f5280cb0aa8d2e9812695
|
Swift
|
lulzzz/Grab-N-Go-Express
|
/Grab n Go Express/Custom Controls/ShoppingCartControl.swift
|
UTF-8
| 4,461
| 2.71875
| 3
|
[] |
no_license
|
//
// ShoppingCartControl.swift
// Grab n Go Express
//
// Created by Adam Arthur on 10/14/15.
// Copyright © 2015 Adam Arthur. All rights reserved.
//
import UIKit
protocol ShoppingCartControlDelegate{
func itemAdded(_ product: Product)
func itemRemoved(_ product: Product)
func updateCartTotal(_ shoppingCart: ShoppingCart)
func cartCleared()
}
class ShoppingCartControl: UITableView, UITableViewDelegate, UITableViewDataSource {
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
var shoppingCartDelegate:ShoppingCartControlDelegate?
var items: [String] = []
//var products: [Product] = []
var products = [Product]()
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
backgroundColor = UIColor.clear
separatorStyle = UITableViewCellSeparatorStyle.none
delegate = self
dataSource = self
register(UITableViewCell.self, forCellReuseIdentifier: "cell")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func numberOfRows(inSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 15
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let clearView = UIView()
clearView.backgroundColor = UIColor.clear
return clearView
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell: UITableViewCell = dequeueReusableCell(withIdentifier: "cell")!
let bkColor = UIColor(red: 196/255, green: 209/255, blue: 148/255, alpha: 1.0)
cell.textLabel?.text = self.items[indexPath.section]
cell.backgroundColor = bkColor
cell.textLabel?.font = UIFont(name: "Arial", size: 26)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("You selected cell #\(indexPath.row)!")
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == UITableViewCellEditingStyle.delete) {
shoppingCartDelegate?.itemRemoved(products[indexPath.section])
items.remove(at: indexPath.section)
products.remove(at: indexPath.section)
updateCartTotal()
reloadData()
//deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
func addProduct(_ product: Product)
{
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.currency
let priceString = formatter.string(from: NSNumber(value: product.price))
let insertString: String = product.description + "\t\t\t" + priceString!
items.append(insertString)
products.append(product)
shoppingCartDelegate?.itemAdded(product)
updateCartTotal()
reloadData()
}
func clear()
{
products.removeAll()
items.removeAll()
updateCartTotal()
reloadData()
shoppingCartDelegate?.cartCleared()
}
func updateCartTotal()
{
let shoppingCart = ShoppingCart()
var cartTotal: Double = 0.00
for i in 0..<products.count
{
cartTotal += products[i].price
for (tax, _) in products[i].tax
{
cartTotal += products[i].tax[tax]!
}
}
shoppingCart.totalItemsInCart = products.count
shoppingCartDelegate?.updateCartTotal(shoppingCart)
}
}
| true
|
c8e9b7b7a1426d6aafaed04342e7667105dea2d2
|
Swift
|
josephkandi/GoodCity
|
/GoodCity/DonationItem.swift
|
UTF-8
| 3,109
| 2.609375
| 3
|
[] |
no_license
|
//
// DonationItem.swift
// GoodCity
//
// Created by Nick Aiwazian on 10/11/14.
// Copyright (c) 2014 codepath. All rights reserved.
//
import Foundation
@objc class DonationItem : PFObject, PFSubclassing {
// TODO: See if there is a way to use an enum with NSManaged since its not visible
// to Objective C
@NSManaged var user: GoodCityUser
@NSManaged var state: String
@NSManaged var condition: String
@NSManaged var itemDescription: String
@NSManaged var photo: PFFile
@NSManaged var driverUser: GoodCityUser
@NSManaged var pickupAddress: Address
@NSManaged var pickupScheduledAt: NSDate
@NSManaged var submittedAt: NSDate
// Must be called before Parse is initialized
override class func load() {
registerSubclass()
}
class func parseClassName() -> String! {
return "DonationItem"
}
func description() -> String {
return itemDescription
}
class func newItem(description: NSString, photo: UIImage, condition: NSString) -> DonationItem {
var donationItem = DonationItem()
donationItem.state = ItemState.Draft.rawValue
donationItem.condition = condition
donationItem.itemDescription = description
donationItem.user = GoodCityUser.currentUser()
donationItem.submittedAt = NSDate()
let w = CGFloat(320)
let h = CGFloat(480)
UIGraphicsBeginImageContext(CGSizeMake(w, h));
photo.drawInRect(CGRectMake(0, 0, w, h))
let smallImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
let data = UIImageJPEGRepresentation(smallImage, CGFloat(0.05));
let imageFile = PFFile(data: data)
donationItem.photo = imageFile
return donationItem
}
func submitToParse() {
self.saveInBackgroundWithBlock { (Bool succeeded, error: NSError!) -> Void in
if succeeded {
NSLog("Successfully saved a new donation item to Parse")
} else {
NSLog("Failed trying to save a new donation item to Parse: ")
NSLog(error.description)
}
}
}
// States is optional
class func getAllItemsWithStates(
completion: ParseResponse,
states: [ItemState]? = nil,
user: GoodCityUser? = GoodCityUser.currentUser(),
driverUser: GoodCityUser? = nil) {
var query = DonationItem.query()
if states != nil {
let stateStrings = states?.map { $0.rawValue }
query.whereKey("state", containedIn: stateStrings)
}
if user != nil {
query.whereKey("user", equalTo: user)
}
if driverUser != nil {
query.whereKey("driverUser", equalTo: driverUser)
}
query.includeKey("user")
query.includeKey("driverUser")
query.includeKey("pickupAddress")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
completion(objects: objects, error: error)
}
}
}
| true
|
ab9207368b3f1d3b25d769a2a2e4ef1e3d6b0d75
|
Swift
|
fadwaSAA/MeMe
|
/MemeMe/Meme1.swift
|
UTF-8
| 533
| 2.84375
| 3
|
[] |
no_license
|
//
// Meme1.swift
// MemeMe
//
// Created by فدوى العسكر on 19/03/1440 AH.
// Copyright © 1440 فدوى العسكر. All rights reserved.
//
import UIKit
struct Meme {
var topText:String!
var bottomText:String!
var originalImage:UIImage!
var memedImage:UIImage!
init (topText: String, bottomText: String, originalImage: UIImage, memedImage: UIImage){
self.topText=topText
self.bottomText=bottomText
self.originalImage=originalImage
self.memedImage=memedImage
}
}
| true
|
56121bd2450837023ba7e742b3548541c9e8fe42
|
Swift
|
WHuangz88/rxswift-composable-architecture
|
/Sources/ComposableArchitecture/Reducer.swift
|
UTF-8
| 10,832
| 2.71875
| 3
|
[] |
no_license
|
import CasePaths
import RxSwift
public struct Reducer<State, Action, Environment> {
private let reducer: (inout State, Action, Environment) -> Effect<Action>
public init(_ reducer: @escaping (inout State, Action, Environment) -> Effect<Action>) {
self.reducer = reducer
}
public static var empty: Reducer {
Self { _, _, _ in .none }
}
public static func combine(_ reducers: Reducer...) -> Reducer {
.combine(reducers)
}
public static func combine(_ reducers: [Reducer]) -> Reducer {
Self { value, action, environment in
.merge(reducers.map { $0.reducer(&value, action, environment) })
}
}
public func combined(with other: Reducer) -> Reducer {
.combine(self, other)
}
public func pullback<GlobalState, GlobalAction, GlobalEnvironment>(
state toLocalState: WritableKeyPath<GlobalState, State>,
action toLocalAction: CasePath<GlobalAction, Action>,
environment toLocalEnvironment: @escaping (GlobalEnvironment) -> Environment
) -> Reducer<GlobalState, GlobalAction, GlobalEnvironment> {
.init { globalState, globalAction, globalEnvironment in
guard let localAction = toLocalAction.extract(from: globalAction) else { return .none }
return self.reducer(
&globalState[keyPath: toLocalState],
localAction,
toLocalEnvironment(globalEnvironment)
)
.map(toLocalAction.embed)
}
}
public func pullback<GlobalState, GlobalAction, GlobalEnvironment>(
state toLocalState: CasePath<GlobalState, State>,
action toLocalAction: CasePath<GlobalAction, Action>,
environment toLocalEnvironment: @escaping (GlobalEnvironment) -> Environment,
breakpointOnNil: Bool = true,
file: StaticString = #fileID,
line: UInt = #line
) -> Reducer<GlobalState, GlobalAction, GlobalEnvironment> {
.init { globalState, globalAction, globalEnvironment in
guard let localAction = toLocalAction.extract(from: globalAction) else { return .none }
guard var localState = toLocalState.extract(from: globalState) else {
if breakpointOnNil {
breakpoint(
"""
---
Warning: Reducer.pullback@\(file):\(line)
"\(debugCaseOutput(localAction))" was received by a reducer when its state was \
unavailable. This is generally considered an application logic error, and can happen \
for a few reasons:
* The reducer for a particular case of state was combined with or run from another \
reducer that set "\(State.self)" to another case before the reducer ran. Combine or \
run case-specific reducers before reducers that may set their state to another case. \
This ensures that case-specific reducers can handle their actions while their state \
is available.
* An in-flight effect emitted this action when state was unavailable. While it may be \
perfectly reasonable to ignore this action, you may want to cancel the associated \
effect before state is set to another case, especially if it is a long-living effect.
* This action was sent to the store while state was another case. Make sure that \
actions for this reducer can only be sent to a view store when state is non-"nil". \
In SwiftUI applications, use "SwitchStore".
---
"""
)
}
return .none
}
defer { globalState = toLocalState.embed(localState) }
let effects = self.run(
&localState,
localAction,
toLocalEnvironment(globalEnvironment)
)
.map(toLocalAction.embed)
return effects
}
}
public func optional(
breakpointOnNil: Bool = true,
file: StaticString = #fileID,
line: UInt = #line
) -> Reducer<
State?, Action, Environment
> {
.init { state, action, environment in
guard state != nil else {
if breakpointOnNil {
breakpoint(
"""
---
Warning: Reducer.optional@\(file):\(line)
"\(debugCaseOutput(action))" was received by an optional reducer when its state was \
"nil". This is generally considered an application logic error, and can happen for a \
few reasons:
* The optional reducer was combined with or run from another reducer that set \
"\(State.self)" to "nil" before the optional reducer ran. Combine or run optional \
reducers before reducers that can set their state to "nil". This ensures that optional \
reducers can handle their actions while their state is still non-"nil".
* An in-flight effect emitted this action while state was "nil". While it may be \
perfectly reasonable to ignore this action, you may want to cancel the associated \
effect before state is set to "nil", especially if it is a long-living effect.
* This action was sent to the store while state was "nil". Make sure that actions for \
this reducer can only be sent to a view store when state is non-"nil". In SwiftUI \
applications, use "IfLetStore".
---
"""
)
}
return .none
}
return self.reducer(&state!, action, environment)
}
}
public func forEach<GlobalState, GlobalAction, GlobalEnvironment, ID>(
state toLocalState: WritableKeyPath<GlobalState, IdentifiedArray<ID, State>>,
action toLocalAction: CasePath<GlobalAction, (ID, Action)>,
environment toLocalEnvironment: @escaping (GlobalEnvironment) -> Environment,
breakpointOnNil: Bool = true,
file: StaticString = #fileID,
line: UInt = #line
) -> Reducer<GlobalState, GlobalAction, GlobalEnvironment> {
.init { globalState, globalAction, globalEnvironment in
guard let (id, localAction) = toLocalAction.extract(from: globalAction) else { return .none }
if globalState[keyPath: toLocalState][id: id] == nil {
if breakpointOnNil {
breakpoint(
"""
---
Warning: Reducer.forEach@\(file):\(line)
"\(debugCaseOutput(localAction))" was received by a "forEach" reducer at id \(id) when \
its state contained no element at this id. This is generally considered an application \
logic error, and can happen for a few reasons:
* This "forEach" reducer was combined with or run from another reducer that removed \
the element at this id when it handled this action. To fix this make sure that this \
"forEach" reducer is run before any other reducers that can move or remove elements \
from state. This ensures that "forEach" reducers can handle their actions for the \
element at the intended id.
* An in-flight effect emitted this action while state contained no element at this id. \
It may be perfectly reasonable to ignore this action, but you also may want to cancel \
the effect it originated from when removing an element from the identified array, \
especially if it is a long-living effect.
* This action was sent to the store while its state contained no element at this id. \
To fix this make sure that actions for this reducer can only be sent to a view store \
when its state contains an element at this id. In SwiftUI applications, use \
"ForEachStore".
---
"""
)
}
return .none
}
return self.reducer(
&globalState[keyPath: toLocalState][id: id]!,
localAction,
toLocalEnvironment(globalEnvironment)
)
.map { toLocalAction.embed((id, $0)) }
}
}
public func forEach<GlobalState, GlobalAction, GlobalEnvironment, Key>(
state toLocalState: WritableKeyPath<GlobalState, [Key: State]>,
action toLocalAction: CasePath<GlobalAction, (Key, Action)>,
environment toLocalEnvironment: @escaping (GlobalEnvironment) -> Environment,
breakpointOnNil: Bool = true,
file: StaticString = #fileID,
line: UInt = #line
) -> Reducer<GlobalState, GlobalAction, GlobalEnvironment> {
.init { globalState, globalAction, globalEnvironment in
guard let (key, localAction) = toLocalAction.extract(from: globalAction) else { return .none }
if globalState[keyPath: toLocalState][key] == nil {
if breakpointOnNil {
breakpoint(
"""
---
Warning: Reducer.forEach@\(file):\(line)
"\(debugCaseOutput(localAction))" was received by a "forEach" reducer at key \(key) \
when its state contained no element at this key. This is generally considered an \
application logic error, and can happen for a few reasons:
* This "forEach" reducer was combined with or run from another reducer that removed \
the element at this key when it handled this action. To fix this make sure that this \
"forEach" reducer is run before any other reducers that can move or remove elements \
from state. This ensures that "forEach" reducers can handle their actions for the \
element at the intended key.
* An in-flight effect emitted this action while state contained no element at this \
key. It may be perfectly reasonable to ignore this action, but you also may want to \
cancel the effect it originated from when removing a value from the dictionary, \
especially if it is a long-living effect.
* This action was sent to the store while its state contained no element at this \
key. To fix this make sure that actions for this reducer can only be sent to a view \
store when its state contains an element at this key.
---
"""
)
}
return .none
}
return self.reducer(
&globalState[keyPath: toLocalState][key]!,
localAction,
toLocalEnvironment(globalEnvironment)
)
.map { toLocalAction.embed((key, $0)) }
}
}
public func run(
_ state: inout State,
_ action: Action,
_ environment: Environment
) -> Effect<Action> {
self.reducer(&state, action, environment)
}
public func callAsFunction(
_ state: inout State,
_ action: Action,
_ environment: Environment
) -> Effect<Action> {
self.reducer(&state, action, environment)
}
}
| true
|
414329d2a66c96832a7f492660dfce3fa91ea63a
|
Swift
|
masterprash2/iosCleanArchitecture
|
/TestArchitecture/HomeModule/HomeViewData.swift
|
UTF-8
| 1,918
| 2.609375
| 3
|
[] |
no_license
|
//
// HomeViewData.swift
// TestArchitecture
//
// Created by Prashant Rathore on 04/12/19.
// Copyright © 2019 RG. All rights reserved.
//
import Foundation
import RxSwift
import RxRelay
// @saber.scope(App)
class HomeViewData {
private let canHideFetchButton = BehaviorRelay(value: true)
private let canHideResetButton = BehaviorRelay(value: false)
private let canHideActivityIndicator = BehaviorRelay(value: false)
private let message = BehaviorRelay(value: "Its working")
// @saber.inject
init() {
}
func obsereFetchButtonVisibilityChanges() -> Observable<Bool> {
return canHideFetchButton.asObservable()
}
func obsereResetButtonVisibilityChanges() -> Observable<Bool> {
return canHideResetButton.asObservable()
}
func obsereLoaderVisibilityChanges() -> Observable<Bool> {
return canHideActivityIndicator.asObservable()
}
func obsereMessage() -> Observable<String> {
return self.message.asObservable()
}
internal func resetToDefaultState() {
canHideFetchButton.accept(false)
canHideResetButton.accept(true)
canHideActivityIndicator.accept(true)
message.accept("Press the Fetch Button")
}
internal func showLoadingState() {
canHideFetchButton.accept(true)
canHideResetButton.accept(true)
canHideActivityIndicator.accept(false)
message.accept("Loading")
}
internal func showSuccess() {
canHideFetchButton.accept(true)
canHideResetButton.accept(false)
canHideActivityIndicator.accept(true)
message.accept("Succes")
}
internal func showFailure(errorMessage : String) {
canHideFetchButton.accept(true)
canHideResetButton.accept(false)
canHideActivityIndicator.accept(true)
message.accept(errorMessage)
}
}
| true
|
d099089fb33ca21cbeef5ad5a9e11152dbeafb3e
|
Swift
|
YasmineDwedar/IOS-swift-Movie-App
|
/Movie Project/Controller/MovieMenuCollectionViewController.swift
|
UTF-8
| 3,606
| 2.703125
| 3
|
[] |
no_license
|
import UIKit
import SDWebImage
import CoreData
import Alamofire
import SwiftyJSON
private let reuseIdentifier = "Cell"
class MovieMenuCollectionViewController: UICollectionViewController,DataDisplay {
var movie = Movie()
var results = [Movie]()
func fetchData(movieArr: [Movie]) {
results = movieArr
self.collectionView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
let Net = Network(displayRef: self)
Net.getData()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return results.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "item", for: indexPath) as! MovieCollectionViewCell
cell.imgPoster.sd_setImage(with: URL(string: "https://image.tmdb.org/t/p/w185/" + results[indexPath.row].poster), placeholderImage: nil)
cell.posterLbl.text = results[indexPath.row].title
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let mov :DetailsTableViewController = self.storyboard?.instantiateViewController(withIdentifier: "detailVc") as! DetailsTableViewController
print(results[indexPath.row])
mov.mobj = results[indexPath.row]
print("look here")
print(mov.mobj!)
self.navigationController?.pushViewController(mov, animated: true)
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
}
*/
}
| true
|
502263b0e44ae12e4adf88aa89e75347e918e75e
|
Swift
|
Daniel-Brestoiu/Nutrition-Tracker
|
/Nutrition-Tracker/Nutrition-Tracker/ManualInputPage.swift
|
UTF-8
| 3,883
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
//
// ManualInputPage.swift
// Nutrition-Tracker
//
// Created by Daniel Brestoiu on 2021-01-16.
//
import SwiftUICharts
import Foundation
import SwiftUI
import Combine
struct ManualInputPage: View {
@State var foodItem: String = ""
@State var calories: String = ""
@State var desiredDailyCalories:Double = 0
@State var inputDesiredDailyCalories: String = ""
@State var caloriesGoalPerDay: Double = 2200.0
@State var caloriesRemainingToday: Double = 2200.0
@State var caloriesToday: Double = 0.0
var body: some View{
// let screenRect = UIScreen.main.bounds
//let screenWidth = screenRect.width
//let screenHeight = screenRect.height
ZStack(){
Form{
VStack{
HStack(alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/){
Text("Food Item:")
.font(.callout)
.bold()
TextField("Food Name", text: $foodItem)
.multilineTextAlignment(.trailing)
}
Divider()
HStack{
Text("Number of Calories:")
.font(.callout)
.bold()
TextField("Calories", text: $calories)
.multilineTextAlignment(.trailing)
.keyboardType(.default)
.onReceive(Just(calories)){
newValue in
let filtered = newValue.filter{"0123456789".contains($0)}
if filtered != newValue{
let first6 = String(filtered.prefix(6))
self.calories = first6
}
if newValue.count > 6{
let first6 = String(filtered.prefix(6))
self.calories = first6
}
}
}
Divider()
Button("Submit"){
//let currentDayTime = Date()
let encodedCalories = (calories as NSString).doubleValue
let newCalories:Double = encodedCalories
caloriesToday += newCalories
caloriesRemainingToday -= newCalories
setCaloriesConsumedToday(input: caloriesToday)
setCaloriesRemainingToday(input: caloriesRemainingToday)
//Logic for actually recording this information
foodItem = ""
calories = ""
}
}
}
PieChartView(data: [caloriesToday, caloriesRemainingToday],
title: "Calories Consumed")
.frame(width:300, height: 300)
.padding(.top, 100)
}
.onAppear{
caloriesRemainingToday = Double(getCaloriesRemainingToday())
caloriesToday = Double(getCaloriesConsumedToday())
caloriesGoalPerDay = Double(getCaloriesPerDay())
}
}
}
struct ManualInputPage_Previews: PreviewProvider{
static var previews: some View{
ManualInputPage()
}
}
| true
|
75008d5fea4e2ef504ebc5744887d6f8db82f89d
|
Swift
|
palmin/GitHawk
|
/Classes/Views/BoundedImageSize.swift
|
UTF-8
| 625
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// BoundedImageSize.swift
// Freetime
//
// Created by Ryan Nystrom on 11/9/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
func BoundedImageSize(originalSize: CGSize, containerWidth: CGFloat) -> CGSize {
guard originalSize.width > containerWidth else {
return CGSize(
width: containerWidth,
height: min(originalSize.height, Styles.Sizes.maxImageHeight)
)
}
let ratio = originalSize.width / originalSize.height
return CGSize(
width: containerWidth,
height: min(ceil(containerWidth / ratio), Styles.Sizes.maxImageHeight)
)
}
| true
|
08b0fe213bdf1adfc4faf6a6b8b392f615a46dfe
|
Swift
|
robertgeifman/Natalie
|
/Support/Bindable.swift
|
UTF-8
| 3,008
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
//
// Bindable.swift
// CrossKit
//
// Created by Robert Geifman on 07/04/2019.
// Copyright © 2019 John Sundell. All rights reserved.
//
////////////////////////////////////////////////////////////
final public class Bindable<Value> {
private var observations = [(Value) -> Bool]()
private var lastValue: Value?
public init(_ value: Value? = nil) {
lastValue = value
}
public func bind<O: AnyObject, T>(_ sourceKeyPath: KeyPath<Value, T>,
to object: O, _ objectKeyPath: ReferenceWritableKeyPath<O, T>) {
addObservation(for: object) { object, observed in
let value = observed[keyPath: sourceKeyPath]
object[keyPath: objectKeyPath] = value
}
}
public func bind<O: AnyObject, T>(_ sourceKeyPath: KeyPath<Value, T>,
to object: O, _ objectKeyPath: ReferenceWritableKeyPath<O, T?>) {
addObservation(for: object) { object, observed in
let value = observed[keyPath: sourceKeyPath]
object[keyPath: objectKeyPath] = value
}
}
public func bind<O: AnyObject, T, R>(_ sourceKeyPath: KeyPath<Value, T>,
to object: O, _ objectKeyPath: ReferenceWritableKeyPath<O, R?>,
transform: @escaping (T) -> R?) {
addObservation(for: object) { object, observed in
let value = observed[keyPath: sourceKeyPath]
let transformed = transform(value)
object[keyPath: objectKeyPath] = transformed
}
}
private func addObservation<O: AnyObject>(for object: O, handler: @escaping (O, Value) -> Void) {
// If we already have a value available, we'll give the handler access to it directly.
lastValue.map { handler(object, $0) }
// Each observation closure returns a Bool that indicates whether the observation should still be kept alive, based on whether the observing object is still retained.
observations.append { [weak object] value in
guard let object = object else { return false }
handler(object, value)
return true
}
}
internal func update(with value: Value) {
lastValue = value
observations = observations.filter { $0(value) }
}
}
#if false
class ViewUserInfoController: NSViewController {
private let user: Bindable<User>
init(user: Bindable<User>) {
self.user = user
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
addNameLabel()
addHeaderView()
addFollowersLabel()
}
func addNameLabel() {
let label = NSTextField()
user.bind(\.name, to: label, \.text)
view.addSubview(label)
}
func addHeaderView() {
let header = NSTextField()
user.bind(\.colors.primary, to: header, \.backgroundColor)
view.addSubview(header)
}
func addFollowersLabel() {
let label = NSTextField()
user.bind(\.followersCount, to: label, \.text, transform: String.init)
view.addSubview(label)
}
}
class UserModelController {
let user: Bindable<User>
private let syncService: SyncService<User>
init(user: User, syncService: SyncService<User>) {
self.user = Bindable(user)
self.syncService = syncService
}
func applicationDidBecomeActive() {
syncService.sync(then: user.update)
}
}
#endif
| true
|
186ec6afcc35f31e550d2ccefa469522139ad76b
|
Swift
|
iridiumtao/iOS-practice
|
/iOS_practice_integrated/UserAccount/ShowUserDetailViewController.swift
|
UTF-8
| 2,336
| 2.640625
| 3
|
[] |
no_license
|
//
// ShowUserDetailViewController.swift
// iOS_practice_integrated
//
// Created by 歐東 on 2020/7/20.
// Copyright © 2020 歐東. All rights reserved.
//
import UIKit
class ShowUserDetailViewController: UIViewController {
@IBOutlet weak var userIconImageView: UIImageView!
@IBOutlet weak var testLabel: UILabel!
@IBOutlet weak var dataTypeTextView: UITextView!
@IBOutlet weak var dataContentTextView: UITextView!
@IBOutlet weak var tableView: UITableView!
var receivedIndexPathInTableView: Int? = nil
var receivedUUID: String? = nil
var receivedPassword: String? = nil
var userInfoArrayKey: [String] = []
var userInfoArrayValue: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
userIconImageView.layer.cornerRadius = userIconImageView.frame.size.height / 2
userIconImageView.layer.masksToBounds = true
userIconImageView.layer.borderWidth = 2
testLabel.text = "\(receivedIndexPathInTableView!)"
let accountDatabase = AccountDatabase()
let data = accountDatabase.loadSingleUserFullData(UUID: receivedUUID!, password: receivedPassword!)
userInfoArrayKey = data.userInfo.keys
userInfoArrayValue = data.userInfo.values
userIconImageView.image = UIImage(data:data.pictureData as Data, scale:1.0)
print(data.userInfo)
}
}
// MARK: - TableView
extension ShowUserDetailViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 9
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ShowUserDetailTableViewCell
cell.titleLabel.text = userInfoArrayKey[indexPath.row]
cell.dataLabel.text = userInfoArrayValue[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 66
} else {
return 44
}
}
}
| true
|
3af1dd8462b3440bb5ea9b8ea7dd9c3a146627ca
|
Swift
|
geekaurora/ReactiveListViewKit
|
/Example/ReactiveListViewKitDemo/Data Layer/Feed.swift
|
UTF-8
| 2,840
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
//
// Feed.swift
// ReactiveListViewKit
//
// Created by Cheng Zhang on 1/3/17.
// Copyright © 2017 Cheng Zhang. All rights reserved.
//
import CZUtils
import ReactiveListViewKit
/// Model of feed
class Feed: ReactiveListDiffable {
let feedId: String
let content: String?
let imageInfo: ImageInfo?
let user: User?
var userHasLiked: Bool
var likesCount: Int
// MARK: - NSCopying
func copy(with zone: NSZone? = nil) -> Any {
return codableCopy(with: zone)
}
// MARK: - Decodable
required init(from decoder: Decoder) throws {
/** Direct decode. */
let values = try decoder.container(keyedBy: CodingKeys.self)
feedId = try values.decode(String.self, forKey: .feedId)
userHasLiked = try values.decode(Bool.self, forKey: .userHasLiked)
user = try values.decode(User.self, forKey: .user)
/** Nested decode. */
// e.g. content = dict["caption"]["content"]
let caption = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .caption)
content = try caption.decode(String.self, forKey: .content)
let likes = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .likes)
likesCount = try likes.decode(Int.self, forKey: .likesCount)
let images = try values.nestedContainer(keyedBy: CodingKeys.self, forKey: .images)
imageInfo = try images.decode(ImageInfo.self, forKey: .imageInfo)
}
}
// MARK: - State
extension Feed: State {
func reduce(action: Action) {
switch action {
case let action as LikeFeedAction:
// React to `LikeFeedEvent`: flip `userHasLiked` flag
if action.feed.feedId == feedId {
userHasLiked = !userHasLiked
likesCount += userHasLiked ? 1 : -1
}
default:
break
}
}
}
// MARK: - Encodable
extension Feed {
enum CodingKeys: String, CodingKey {
case feedId = "id"
case userHasLiked = "user_has_liked"
case caption = "caption"
case content = "text"
case images = "images"
case imageInfo = "standard_resolution"
case likes = "likes"
case likesCount = "count"
case user
}
func encode(to encoder: Encoder) throws {
/** Direct encode. */
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(feedId, forKey: .feedId)
try container.encode(userHasLiked, forKey: .userHasLiked)
try container.encode(user, forKey: .user)
/** Nested encode. */
var caption = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .caption)
try caption.encode(content, forKey: .content)
var likes = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .likes)
try likes.encode(likesCount, forKey: .likesCount)
var images = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .images)
try images.encode(imageInfo, forKey: .imageInfo)
}
}
| true
|
0c59dda3bbf582456bb78a06a9da1fec6de5f72b
|
Swift
|
adamastern/decked
|
/Source/DecorationManager.swift
|
UTF-8
| 1,723
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// DecorationManager.swift
// pinch
//
// Created by Adam Stern on 21/04/2016.
// Copyright © 2016 TurboPython. All rights reserved.
//
import UIKit
public class DecorationManager {
weak public var decoration: ManagedDecoration?
public var presented = false
internal let dismissAfter: NSTimeInterval
private let onDismiss: (manager: DecorationManager, animated: Bool) -> Void
private var dismissalTimer: NSTimer?
internal init(decoration: ManagedDecoration, dismissAfter: NSTimeInterval, onDismiss: (manager: DecorationManager, animated: Bool) -> Void) {
self.decoration = decoration
self.onDismiss = onDismiss
self.dismissAfter = dismissAfter
}
deinit {
cancelDismissalTimer()
}
public func dismiss(animated: Bool) {
onDismiss(manager: self, animated: animated)
}
// MARK - lifecycle
internal func decorationDidAppear() {
self.presented = true
if dismissAfter > 0 {
startDismissalTimer()
}
}
internal func decorationWillDisappear() {
cancelDismissalTimer()
}
// MARK - dismissal timer
private func startDismissalTimer() {
cancelDismissalTimer()
dismissalTimer = NSTimer.scheduledTimerWithTimeInterval(dismissAfter, target: self, selector: #selector(dismissalTimerFired), userInfo: nil, repeats: false)
}
private func cancelDismissalTimer() {
if dismissalTimer != nil && dismissalTimer?.valid == true {
dismissalTimer!.invalidate()
dismissalTimer = nil
}
}
@objc private func dismissalTimerFired() {
dismiss(true)
}
}
| true
|
88b81abbd3cb822277c9a244031bf843e1ac782f
|
Swift
|
NicholasSieb/iOSElectSmart
|
/ElectSmart/HomeStoryTableViewCell.swift
|
UTF-8
| 2,354
| 2.578125
| 3
|
[] |
no_license
|
//
// HomeStoryTableViewCellController.swift
// ElectSmart
//
// Created by Stephen Gaschignard on 4/5/16.
// Copyright © 2016 Stephen Gaschignard. All rights reserved.
//
import UIKit
class HomeStoryTableViewCell: UITableViewCell {
var date: NSDate?
@IBOutlet weak var newsStoryTitleLabel: UILabel!
@IBOutlet weak var newsStorySourceLabel: UILabel!
@IBOutlet weak var newsStoryDateLabel: UILabel!
@IBOutlet weak var newsStoryContentLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
// Configure the story title
dispatch_async(dispatch_get_main_queue(), {
self.newsStoryTitleLabel.font = UIFont.boldSystemFontOfSize(21.0)
self.newsStoryTitleLabel.textColor = UIColor.blackColor()
// Configure the source appearance
self.newsStorySourceLabel.font = UIFont.boldSystemFontOfSize(11.0)
self.newsStorySourceLabel.textColor = UIColor.blackColor().colorWithAlphaComponent(0.7)
// Configure the date appearance
self.newsStoryDateLabel.font = UIFont.systemFontOfSize(11.0)
self.newsStoryDateLabel.textColor = UIColor.blackColor().colorWithAlphaComponent(0.5)
// Configure the story content
self.newsStoryContentLabel.font = UIFont.systemFontOfSize(15.0)
self.newsStoryContentLabel.textColor = UIColor.blackColor().colorWithAlphaComponent(0.7)
})
}
override func layoutSubviews() {
super.layoutSubviews()
dispatch_async(dispatch_get_main_queue(), {
self.newsStorySourceLabel.text = self.newsStorySourceLabel.text?.uppercaseString
self.newsStorySourceLabel.sizeToFit()
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = .ShortStyle
let dateString = formatter.stringFromDate(self.date!)
self.newsStoryDateLabel.text = dateString.uppercaseString
self.newsStoryDateLabel.setNeedsDisplay()
})
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| true
|
2d0c210ab4d1c0d5f3bacc74285d65e827f4f2c0
|
Swift
|
foodbodidev/foodbodi-iOS
|
/foodbody/FoodBody/ViewControllers/FodiMap/Company Information/CompanyInfoVC.swift
|
UTF-8
| 4,677
| 2.546875
| 3
|
[] |
no_license
|
//
// CompanyInfoVC.swift
// FoodBody
//
// Created by Phuoc on 7/26/19.
// Copyright © 2019 KPT. All rights reserved.
//
import UIKit
import GooglePlaces
class CompanyInfoVC: BaseVC {
@IBOutlet weak var nameTextField: FBTextField!
@IBOutlet weak var registerTextField: FBTextField!
@IBOutlet weak var presentationTextField: FBTextField!
@IBOutlet weak var addressTextField: FBTextField!
@IBOutlet weak var btnSubmit:UIButton!
let companyInfoRequest = CompanyInfoModel()
@IBOutlet weak var contentView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
addressTextField.delegate = self
setupLayout()
}
fileprivate func setupLayout() {
self.navigationController?.navigationBar.isHidden = false
nameTextField.textField.placeholder = "Name of company"
registerTextField.textField.placeholder = "Registration No."
presentationTextField.textField.placeholder = "Name of representative"
addressTextField.textField.placeholder = "Address"
}
@IBAction func actionSubmit() {
guard validateTextFiled() else {
return
}
companyInfoRequest.company_name = nameTextField.textField.text ?? ""
companyInfoRequest.registration_number = registerTextField.textField.text ?? ""
companyInfoRequest.representative_name = [presentationTextField.textField.text ?? ""]
companyInfoRequest.address = addressTextField.textField.text ?? ""
self.showLoading()
RequestManager.createRestaurant(request: companyInfoRequest) { (result, error) in
self.hideLoading()
if let result = result{
if result.isSuccess {
let restaurant = MyRestaurant.init(restaurant_id:result.id);
AppManager.restaurant = restaurant;
let verifyVC = VerifyVC.init(nibName: "VerifyVC", bundle: nil)
self.navigationController?.pushViewController(verifyVC, animated: true)
} else {
self.alertMessage(message: result.message)
}
}
if let error = error {
self.alertMessage(message: error.localizedDescription)
}
}
}
func validateTextFiled() -> Bool {
if nameTextField.textField.text!.isEmpty {
nameTextField.errorLabel.text = "Invalid Name of company"
nameTextField.showInvalidStatus()
return false
}
if registerTextField.textField.text!.isEmpty {
registerTextField.errorLabel.text = "Registration No."
registerTextField.showInvalidStatus()
return false
}
if presentationTextField.textField.text!.isEmpty {
presentationTextField.showInvalidStatus()
presentationTextField.errorLabel.text = "Invalid Name of representative"
return false
}
if addressTextField.textField.text!.isEmpty {
addressTextField.showInvalidStatus()
addressTextField.errorLabel.text = "Invalid Address"
return false
}
return true
}
func restaurantTableViewCellDidBeginSearchAddress() {
let seachAddressVC = GMSAutocompleteViewController()
seachAddressVC.delegate = self
present(seachAddressVC, animated: true, completion: nil)
}
}
extension CompanyInfoVC: GMSAutocompleteViewControllerDelegate {
func viewController(_ viewController: GMSAutocompleteViewController, didAutocompleteWith place: GMSPlace) {
companyInfoRequest.address = place.formattedAddress ?? ""
companyInfoRequest.lat = place.coordinate.latitude
companyInfoRequest.lng = place.coordinate.longitude
addressTextField.textField.text = place.formattedAddress ?? ""
dismiss(animated: true, completion: nil)
}
func viewController(_ viewController: GMSAutocompleteViewController, didFailAutocompleteWithError error: Error) {
print("Error: ", error.localizedDescription)
}
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
// Dismiss when the user canceled the action
dismiss(animated: true, completion: nil)
}
}
extension CompanyInfoVC: FBTextFieldDelegate {
func didBeginSearchPlace() {
addressTextField.resignFirstResponder()
restaurantTableViewCellDidBeginSearchAddress()
}
}
| true
|
6c43c6f6ce27ee7ee832e5b06fb26a4551a2e333
|
Swift
|
OffTheMark/AdventOfCode2020
|
/Day11/main.swift
|
UTF-8
| 1,561
| 3.40625
| 3
|
[] |
no_license
|
//
// main.swift
// Day11
//
// Created by Marc-Antoine Malépart on 2020-12-11.
//
import Foundation
import AdventOfCodeUtilities
import ArgumentParser
struct Day11: DayCommand {
@Argument(help: "Puzzle input path")
var puzzleInputPath: String
func run() throws {
let lines = try readLines()
let grid = Grid(lines: lines)
let part1Solution = part1(with: grid)
printTitle("Part 1", level: .title1)
print("Number of occupied seats:", part1Solution, terminator: "\n\n")
let part2Solution = part2(with: grid)
printTitle("Part 2", level: .title1)
print("Number of occupied seats:", part2Solution)
}
func part1(with grid: Grid) -> Int {
var previous = grid
var current = grid.nextAccordingToPart1()
while previous != current {
let next = current.nextAccordingToPart1()
previous = current
current = next
}
return current.contents.count(where: { coordinate, square in
return square == .occupiedSeat
})
}
func part2(with grid: Grid) -> Int {
var previous = grid
var current = grid.nextAccordingToPart2()
while previous != current {
let next = current.nextAccordingToPart2()
previous = current
current = next
}
return current.contents.count(where: { coordinate, square in
return square == .occupiedSeat
})
}
}
Day11.main()
| true
|
46617e5a1ed745b044dbd3b89cbaa07924550543
|
Swift
|
sachendraR/Countries
|
/Countries/ViewControllers/CountriesViewController/CountriesViewController.swift
|
UTF-8
| 4,588
| 2.703125
| 3
|
[] |
no_license
|
//
// CountriesViewController.swift
// Countries
//
// Created by Sachendra Singh on 11/01/21.
//
import UIKit
class CountriesViewController: BaseViewController {
var presenter: CountriesPresenter?
typealias ViewModelType = CountriesViewModel
@IBOutlet weak var collectionView: UICollectionView!
var dataSource:UICollectionViewDiffableDataSource<Int, Country>!
var indicatorView:UIView?
let pullDownToRefresh:UIRefreshControl = UIRefreshControl()
convenience init(withPresenter presenter:CountriesPresenter)
{
self.init(nibName:"CountriesViewController", bundle: .main)
self.presenter = presenter
self.presenter?.view = self
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Countries"
setupCollectionView()
pullDownToRefresh.addTarget(self,
action: #selector(refresh(_:)),
for: .valueChanged)
collectionView.refreshControl = pullDownToRefresh
presenter?.setupPresenter(withData: nil)
presenter?.fetchData()
}
@objc func refresh(_ sender:UIRefreshControl)
{
if sender.isRefreshing
{
presenter?.fetchData()
}
}
func setupCollectionView()
{
collectionView.register(UINib(nibName: "CountryCollectionViewCell",
bundle: .main),
forCellWithReuseIdentifier: CountryCollectionViewCell.identifier)
dataSource = UICollectionViewDiffableDataSource<Int, Country>(collectionView: collectionView, cellProvider: { (cv, indexPath, item) -> UICollectionViewCell? in
let cell = cv.dequeueReusableCell(withReuseIdentifier: CountryCollectionViewCell.identifier,
for: indexPath) as? CountryCollectionViewCell
cell?.update(withObject: item)
return cell
})
collectionView.collectionViewLayout = self.generateLayout()
collectionView.delegate = self
}
func generateLayout() -> UICollectionViewLayout
{
return UICollectionViewCompositionalLayout { (sectionIndex, environment) -> NSCollectionLayoutSection? in
return self.generateSectionLayout()
}
}
func generateSectionLayout() -> NSCollectionLayoutSection
{
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),
heightDimension: .absolute(50))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = itemSize
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize,
subitem: item,
count: 1)
let section = NSCollectionLayoutSection(group: group)
return section
}
}
extension CountriesViewController : View
{
func startedFetchingData() {
if !pullDownToRefresh.isRefreshing
{
self.indicatorView = self.view.showLoadingIndicator()
}
}
func updateUI(withViewModel viewModel: CountriesViewModel) {
let countries = viewModel.countries
var snapshot = NSDiffableDataSourceSnapshot<Int, Country>()
snapshot.appendSections([0])
snapshot.appendItems(countries, toSection: 0)
self.dataSource.apply(snapshot, animatingDifferences: true)
self.pullDownToRefresh.endRefreshing()
self.indicatorView?.removeFromSuperview()
}
func showError(error: Error) {
self.pullDownToRefresh.endRefreshing()
self.indicatorView?.removeFromSuperview()
super.showError(error) {
self.presenter?.fetchData()
}
}
}
extension CountriesViewController : UICollectionViewDelegate
{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let country = self.dataSource.snapshot().itemIdentifiers[indexPath.item]
let controller = ProvincesViewController(forCountry: country,
presenter: ProvincesPresenter())
self.navigationController?.pushViewController(controller, animated: true)
}
}
| true
|
dcac2bd577390bec0c8ee999f9593b61a049a55b
|
Swift
|
ChuaKaixin/twilio-live-interactive-video
|
/apps/ios/LiveVideo/LiveVideo/Views/Stream/StreamToolbar.swift
|
UTF-8
| 772
| 2.796875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Copyright (C) 2021 Twilio, Inc.
//
import SwiftUI
struct StreamToolbar<Content>: View where Content: View {
private let content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
HStack(spacing: 10) {
Spacer()
content()
Spacer()
}
.background(Color.background)
}
}
struct StreamToolbar_Previews: PreviewProvider {
static var previews: some View {
StreamToolbar {
StreamToolbarButton(image: Image(systemName: "arrow.left"), role: .destructive)
StreamToolbarButton(image: Image(systemName: "mic.slash.fill"))
}
.previewLayout(.sizeThatFits)
}
}
| true
|
341d6e996560aadd28a43335744392d491d17be2
|
Swift
|
kelson99/dogsAPIPractice
|
/DogApiReview/DogApiReview/ViewControllers/ProfileViewController.swift
|
UTF-8
| 4,018
| 2.65625
| 3
|
[] |
no_license
|
//
// ProfileViewController.swift
// DogApiReview
//
// Created by Kelson Hartle on 1/20/21.
//
import UIKit
import CoreData
import PieCharts
class ProfileViewController: UIViewController, PieChartDelegate, NSFetchedResultsControllerDelegate {
@IBOutlet weak var chartView: PieChart!
var blockOperations = [BlockOperation]()
var dogBreedDict = [String : Int]()
lazy var fetchResultsController: NSFetchedResultsController<SavedDog> = {
let fetchRequest: NSFetchRequest<SavedDog> = SavedDog.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "breed", ascending: true)]
// fetchRequest.predicate = NSPredicate(format: "user.name == %@", user?.name ?? "")
let frc = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: CoreDataStack.shared.mainContext,
sectionNameKeyPath: nil,
cacheName: nil)
frc.delegate = self
do {
try frc.performFetch()
} catch {
fatalError("Error performing fetch for frc: \(error)")
}
return frc
}()
override func viewDidLoad() {
super.viewDidLoad()
chartView.models = createModels()
chartView.layers = [createPlainTextLayer(), createTextWithLinesLayer()]
chartView.delegate = self
sortDogBreedByCount()
}
func sortDogBreedByCount() {
if let resultsFromFetch = fetchResultsController.fetchedObjects {
for x in resultsFromFetch {
if let dogBreed = x.breed {
if dogBreedDict[dogBreed] == nil {
dogBreedDict[dogBreed] = 1
} else {
dogBreedDict[dogBreed] = 1
}
}
}
}
let sortedDict = dogBreedDict.sorted { (one, two) -> Bool in
one.value < two.value
}
print(sortedDict)
}
func onSelected(slice: PieSlice, selected: Bool) {
print("Selected: \(selected), slice: \(slice)")
}
fileprivate func createModels() -> [PieSliceModel] {
let alpha: CGFloat = 0.5
return [
PieSliceModel(value: 3, color: UIColor.yellow.withAlphaComponent(alpha)),
PieSliceModel(value: 6, color: UIColor.blue.withAlphaComponent(alpha)),
PieSliceModel(value: 1, color: UIColor.green.withAlphaComponent(alpha))
]
}
fileprivate func createPlainTextLayer() -> PiePlainTextLayer {
let textLayerSettings = PiePlainTextLayerSettings()
textLayerSettings.viewRadius = 55
textLayerSettings.hideOnOverflow = true
textLayerSettings.label.font = UIFont.systemFont(ofSize: 8)
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
textLayerSettings.label.textGenerator = {slice in
return formatter.string(from: slice.data.percentage * 100 as NSNumber).map{"\($0)%"} ?? ""
}
let textLayer = PiePlainTextLayer()
textLayer.settings = textLayerSettings
return textLayer
}
fileprivate func createTextWithLinesLayer() -> PieLineTextLayer {
let lineTextLayer = PieLineTextLayer()
var lineTextLayerSettings = PieLineTextLayerSettings()
lineTextLayerSettings.lineColor = UIColor.lightGray
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 1
lineTextLayerSettings.label.font = UIFont.systemFont(ofSize: 14)
lineTextLayerSettings.label.textGenerator = {slice in
return formatter.string(from: slice.data.model.value as NSNumber).map{"\($0)"} ?? ""
}
lineTextLayer.settings = lineTextLayerSettings
return lineTextLayer
}
}
| true
|
108e3657c2f4d5a82c942b706acf1d5307dd62dc
|
Swift
|
MisnikovRoman/VKClient
|
/VKClient/Login/View/WhiteUIButton.swift
|
UTF-8
| 757
| 2.609375
| 3
|
[] |
no_license
|
//
// WhiteUIButton.swift
// VKClient
//
// Created by Роман Мисников on 10.07.2018.
// Copyright © 2018 Роман Мисников. All rights reserved.
//
import UIKit
@IBDesignable
class WhiteUIButton: UIButton {
// to edit properties in app
override func awakeFromNib() {
setupView()
}
// to edit properties in interface builder
override func prepareForInterfaceBuilder() {
// call only in interface builder for @IBDesignable
super.prepareForInterfaceBuilder()
setupView()
}
func setupView() {
self.layer.cornerRadius = self.bounds.height / 2
self.layer.borderWidth = 2.0
self.layer.borderColor = UIColor.white.cgColor
self.clipsToBounds = true
}
}
| true
|
3afc4062101c6879037bbab1ef60f4dfbc7cefb1
|
Swift
|
AaronTheTitan/EventCountdown
|
/EventCountdown/DatePlayground.playground/Contents.swift
|
UTF-8
| 800
| 3.265625
| 3
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import Cocoa
var str = "Hello, playground"
// Create a new date with the current time
NSDate *date = [NSDate new];
// Split up the date components
NSDateComponents *time = [[NSCalendar currentCalendar]
components:NSHourCalendarUnit | NSMinuteCalendarUnit
fromDate:date];
NSInteger seconds = ([time hour] * 60 * 60) + ([time minute] * 60);
UIDatePicker *picker = [UIDatePicker new];
[picker setDatePickerMode:UIDatePickerModeCountDownTimer];
[picker setCountDownDuration:seconds];
[[self view] addSubview:picker];
/////////////---------------------------
let currentDate = NSDate() // new date with current time
let time = NSDateComponents()
time.setValue(<#value: Int#>, forComponent: <#NSCalendarUnit#>)
let seconds = NSInteger
| true
|
85675db516c482181d0e0378f003cc83bd69146a
|
Swift
|
canhth/Weather
|
/Weather/Weather/Core/VIPER/Router/NavigationRouter.swift
|
UTF-8
| 2,587
| 2.609375
| 3
|
[] |
no_license
|
//
// NavigationRouter.swift
// Weather
//
// Created by Canh Tran Wizeline on 4/20/20.
// Copyright © 2020 CanhTran. All rights reserved.
//
import UIKit
class NavigationRouter: ViewRouter, NavigationRouterInterface {
private unowned let rootController: UINavigationController
private var popCompletions: [UIViewController: () -> Void] = [:]
init(rootController: UINavigationController) {
self.rootController = rootController
super.init(rootController: rootController)
rootController.delegate = self
}
override func toController() -> UINavigationController {
return rootController
}
// MARK: - Push & Pop
func push(_ view: ViewInterface, animated: Bool, hideBottomBar: Bool?, popCompletion: (() -> Void)?) {
let newController = view.toController()
if let hideBottomBar = hideBottomBar {
newController.hidesBottomBarWhenPushed = hideBottomBar
}
rootController.pushViewController(newController, animated: animated)
popCompletions[newController] = popCompletion
}
func popView(animated: Bool) {
if let controller = rootController.popViewController(animated: animated) {
runCompletion(for: controller)
}
}
// MARK: - Root Module
func setRootView(_ view: ViewInterface, animated: Bool, hideNavigationBar: Bool?) {
let newController = view.toController()
let oldControllers = rootController.viewControllers
rootController.setViewControllers([newController], animated: animated)
if let hideNavigationBar = hideNavigationBar {
rootController.isNavigationBarHidden = hideNavigationBar
}
oldControllers.reversed().forEach({ runCompletion(for: $0) })
}
}
private extension NavigationRouter {
func runCompletion(for controller: UIViewController) {
guard let completion = popCompletions[controller] else { return }
popCompletions.removeValue(forKey: controller)
completion()
}
}
extension NavigationRouter: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController,
didShow viewController: UIViewController,
animated: Bool) {
guard
let poppedViewController = navigationController.transitionCoordinator?.viewController(forKey: .from),
!navigationController.viewControllers.contains(poppedViewController)
else { return }
runCompletion(for: poppedViewController)
}
}
| true
|
fec7611780232d69f7b5e5c75c81e94e58453670
|
Swift
|
philmartin83/basicobjectdetection
|
/basicobjectdetection/ViewController.swift
|
UTF-8
| 4,359
| 2.875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Basic Object Detecton
//
// Created by Phil Martin on 09/06/2018.
// Copyright © 2018 Phil Martin. All rights reserved.
//
import UIKit
import AVKit
import Vision
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate, AVSpeechSynthesizerDelegate {
var btn = UIButton()
var theCameraViewLayer = AVCaptureVideoPreviewLayer()
var objectDetected : Bool = false
var objectType : String = ""
let speech = AVSpeechSynthesizer()
let descriptionLabel : UILabel = {
let label = UILabel()
label.textAlignment = .center
label.backgroundColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override func viewDidLoad() {
super.viewDidLoad()
speech.delegate = self
let session = AVCaptureSession()
session.sessionPreset = .photo
guard let captureDevice = AVCaptureDevice.default(for: .video) else { return }
guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return }
session.addInput(input)
session.startRunning()
let previewLayer = AVCaptureVideoPreviewLayer(session: session)
view.layer.addSublayer(previewLayer)
previewLayer.frame = view.frame
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "theQueue"))
session.addOutput(dataOutput)
}
func layoutDesciptionLabel()
{
view.addSubview(descriptionLabel)
descriptionLabel.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
descriptionLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
descriptionLabel.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
guard let model = try? VNCoreMLModel(for: Resnet50().model) else { return }
let request = VNCoreMLRequest(model: model) { (finishedReq, err) in
guard let results = finishedReq.results as? [VNClassificationObservation] else { return }
guard let objectObservation = results.first else { return }
print(objectObservation.identifier, objectObservation.confidence)
DispatchQueue.main.async {
self.descriptionLabel.text = "\(objectObservation.identifier) \(objectObservation.confidence * 100)"
let accuarcy = objectObservation.confidence * 100
if(accuarcy >= 89 && !self.objectDetected)
{
self.objectType = objectObservation.identifier
self.objectDetected = true
self.displayButton()
}
}
}
try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])
}
func displayButton()
{
if(self.objectDetected)
{
let objectedRecognied = UIAlertController.init(title: "Object Found", message: "Object found press 'Describe Object' to confirm", preferredStyle: UIAlertControllerStyle.alert)
objectedRecognied.addAction( UIAlertAction.init(title: "Describe Object", style: UIAlertActionStyle.default, handler: { (okAction) in
self.textToSpeachObject()
}))
self.present(objectedRecognied, animated: true, completion: nil)
}
}
func textToSpeachObject()
{
let myWords = "The object found is \(self.objectType)"
let talkToMe = AVSpeechUtterance(string: myWords)
talkToMe.rate = 0.55
speech.speak(talkToMe)
}
func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
perform(#selector(setDetectionToFalse), with: nil, afterDelay: 1.0)
}
@objc func setDetectionToFalse()
{
self.objectDetected = false
}
}
| true
|
4ef5ce3247c6bdf2e1527853852efab0197d9fca
|
Swift
|
HwangChanho/SeSAC_Lottery
|
/SeSAC_Lottery/Controller/WeatherViewController.swift
|
UTF-8
| 5,649
| 2.71875
| 3
|
[] |
no_license
|
//
// WeatherViewController.swift
// SeSAC_Lottery
//
// Created by ChanhoHwang on 2021/10/27.
//
import UIKit
import CoreLocation
import Kingfisher
class WeatherViewController: UIViewController {
let locationManager = CLLocationManager()
var lon: Double = 0
var lat: Double = 0
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet var labelOnView: [UIView]!
@IBOutlet weak var degreeLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var windyLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var greetingLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .black
setUp()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
// 아이폰 설정에서의 위치 서비스가 켜진 상태라면
if CLLocationManager.locationServicesEnabled() {
print("위치 서비스 On 상태")
locationManager.startUpdatingLocation() //위치 정보 받아오기 시작
} else {
print("위치 서비스 Off 상태")
}
}
@IBAction func locationButtonClicked(_ sender: UIButton) {
locationManager.startUpdatingLocation()
findAddress(lat: lat, long: lon)
WeatherAPIManager.shared.getWeatherApiData(lat: lat, lon: lon) {code, json in
switch code {
case 200:
var temp = json["main"]["temp"].doubleValue
temp = temp - 273.15
self.degreeLabel.text = "지금은 \(round(temp))℃ 에요"
let humidity = json["main"]["humidity"].doubleValue
self.humidityLabel.text = "\(humidity)% 만큼 습해요"
let wind = json["wind"]["speed"].doubleValue
self.windyLabel.text = "\(round((wind * 100) / 100))m/s의 바람이 불어요"
// https://openweathermap.org/img/wn/10d@2x.png
let icon = json["weather"][0]["icon"].stringValue
print(json)
print("icon: \(icon)")
let imageURL = URL(string: "\(Endpoint.weatherImageURL)\(icon)@2x.png")
self.imageView.kf.setImage(with: imageURL)
self.greetingLabel.text = "오늘도 행복한 하루 보내세요"
case 400:
print(json)
default:
print("error")
}
}
}
@IBAction func shareButtonClicked(_ sender: UIButton) {
}
@IBAction func reloadButtonClicked(_ sender: UIButton) {
}
func setUp() {
let formatter = DateFormatter()
formatter.dateFormat = "MM월 dd일 hh시 mm분"
let current_date_string = formatter.string(from: Date())
dateLabel.text = current_date_string
dateLabel.textColor = .white
dateLabel.font = .systemFont(ofSize: 20)
locationLabel.text = ""
locationLabel.textColor = .white
locationLabel.font = .systemFont(ofSize: 23)
imageView.backgroundColor = .white
setLabel(degreeLabel)
setLabel(humidityLabel)
setLabel(windyLabel)
setLabel(greetingLabel)
for i in 0 ... 4 {
labelOnView[i].backgroundColor = .white
labelOnView[i].layer.cornerRadius = 15
labelOnView[i].layer.masksToBounds = true
}
}
func setLabel(_ label: UILabel) {
label.backgroundColor = .white
label.textColor = .black
label.font = .systemFont(ofSize: 20)
}
// 주소 찾기
func findAddress(lat: CLLocationDegrees, long: CLLocationDegrees) {
let findLocation = CLLocation(latitude: lat, longitude: long)
let geocoder = CLGeocoder()
let locale = Locale(identifier: "Ko-kr") //원하는 언어의 나라 코드를 넣어주시면 됩니다.
geocoder.reverseGeocodeLocation(findLocation, preferredLocale: locale, completionHandler: {(placemarks, error) in
if let address: [CLPlacemark] = placemarks {
if let name: String = address.last?.name {
print(name)
self.locationLabel.text = name
} //전체 주소
}
})
}
}
extension WeatherViewController: CLLocationManagerDelegate {
// 위치 정보 계속 업데이트 -> 위도 경도 받아옴
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("didUpdateLocations")
if let location = locations.first {
lat = location.coordinate.latitude
lon = location.coordinate.longitude
}
}
// 위도 경도 받아오기 에러
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}
extension UIImageView {
func load(url: URL) {
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self?.image = image
}
}
}
}
}
}
| true
|
f7292e9837f831ee74978d26ecc8ef3db40d37cf
|
Swift
|
pereferrer/proyectoFinaliOS
|
/proyectoFinaliOS/Models/Responses/SingleTopicUpdateResponse.swift
|
UTF-8
| 551
| 2.640625
| 3
|
[] |
no_license
|
//
// SingleTopicUpdateResponse.swift
// Eh-Ho
//
// Created by Pere Josep Ferrer Ventura on 24/07/2019.
// Copyright © 2019 KeepCoding. All rights reserved.
//
import Foundation
struct SingleTopicUpdateResponse: Codable {
let basic_topic:basic_topic
}
struct basic_topic: Codable {
let id: Int
let title: String
let fancyTitle: String
let postsCount: Int
enum CodingKeys: String, CodingKey {
case id = "id"
case title = "title"
case fancyTitle = "fancy_title"
case postsCount = "posts_count"
}
}
| true
|
e1fc9afa92161ede769e28ef404fd342199372bc
|
Swift
|
nguyenvietluy123/FakeWeather
|
/FakeWeather/FakeWeather/Model/OvercastObj.swift
|
UTF-8
| 398
| 2.65625
| 3
|
[] |
no_license
|
//
// OvercastObj.swift
// FakeWeather
//
// Created by Luy Nguyen on 1/15/19.
// Copyright © 2019 Luy Nguyen. All rights reserved.
//
import UIKit
class OvercastObj: NSObject {
var title: String = ""
var img: UIImage = UIImage()
override init() {
super.init()
}
init(_ title: String, _ img: UIImage) {
self.title = title
self.img = img
}
}
| true
|
d83e99a4f35ea08bc81669e5dd9894e7175b6db4
|
Swift
|
dan12411/ACExam_Movie
|
/ACExam_Movie/SignViewController.swift
|
UTF-8
| 1,484
| 2.71875
| 3
|
[] |
no_license
|
//
// SecondViewController.swift
// ACExam_Movie
//
// Created by 洪德晟 on 2016/10/7.
// Copyright © 2016年 洪德晟. All rights reserved.
//
import UIKit
class SignViewController: UIViewController {
@IBOutlet weak var myTextField: UITextField!
@IBOutlet weak var contentView: UITextView!
var sign = [String]()
@IBAction func goButton(_ sender: UIButton) {
if let inputText = myTextField.text, inputText != "" {
sign.append(inputText)
switch sign.count {
case 1 :
contentView.text = sign[0]
case 2 :
contentView.text = "\(sign[0])\n\(sign[1])"
case 3 :
contentView.text = "\(sign[0])\n\(sign[1])\n\(sign[2])"
default :
let myAlert = UIAlertController(title: "簽名人次已達三人", message: "下次請早", preferredStyle: .alert)
let okAtion = UIAlertAction(title: "OK", style: .default, handler: nil)
myAlert.addAction(okAtion)
present(myAlert, animated: true, completion: nil)
}
myTextField.resignFirstResponder()
myTextField.text = ""
}
}
override func viewDidLoad() {
super.viewDidLoad()
contentView.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| true
|
4afbed0bdf4135cd47494e1949bd0efdcffeb27f
|
Swift
|
codesquad-member-2020/signup-6
|
/iOS/SignUp/SignUp/View/InputTextField.swift
|
UTF-8
| 1,138
| 2.734375
| 3
|
[] |
no_license
|
//
// InputTextField.swift
// SignUp
//
// Created by TTOzzi on 2020/03/24.
// Copyright © 2020 TTOzzi. All rights reserved.
//
import UIKit
class InputTextField: UITextField {
private var borderWidth: CGFloat = 0.8
var textChanged: (String) -> () = { _ in }
override init(frame: CGRect) {
super.init(frame: frame)
setProperties()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setProperties()
}
private func setProperties() {
self.layer.borderWidth = borderWidth
self.autocorrectionType = .no
disableAutoFill()
}
func disableAutoFill() {
if #available(iOS 12, *) {
textContentType = .oneTimeCode
} else {
textContentType = .init(rawValue: "")
}
}
func bind(callback: @escaping (String) -> ()) {
self.textChanged = callback
self.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
}
@objc func textFieldDidChange(_ textField: UITextField) {
self.textChanged(textField.text!)
}
}
| true
|
9fddedaaf9274ba3f16321c8020761ec2fb5b660
|
Swift
|
dbonates/Quark
|
/Tests/QuarkTests/HTTP/Message/BodyTests.swift
|
UTF-8
| 3,364
| 2.640625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
import XCTest
@testable import Quark
class BodyTests : XCTestCase {
let data: C7.Data = [0x00, 0x01, 0x02, 0x03]
func checkBodyProperties(_ body: Body) {
var bodyForBuffer = body
var bodyForReader = body
var bodyForWriter = body
XCTAssert(data == (try! bodyForBuffer.becomeBuffer()), "Garbled buffer bytes")
switch bodyForBuffer {
case .buffer(let d):
XCTAssert(data == d, "Garbled buffer bytes")
default:
XCTFail("Incorrect type")
}
bodyForReader.forceReopenDrain()
let readerDrain = Drain(stream: try! bodyForReader.becomeReader())
XCTAssert(data == readerDrain.data, "Garbled reader bytes")
switch bodyForReader {
case .reader(let reader):
bodyForReader.forceReopenDrain()
let readerDrain = Drain(stream: reader)
XCTAssert(data == readerDrain.data, "Garbed reader bytes")
default:
XCTFail("Incorrect type")
}
let writerDrain = Drain()
bodyForReader.forceReopenDrain()
do {
try bodyForWriter.becomeWriter()(writerDrain)
} catch {
XCTFail("Drain threw error \(error)")
}
XCTAssert(data == writerDrain.data, "Garbled writer bytes")
switch bodyForWriter {
case .writer(let closure):
let writerDrain = Drain()
bodyForReader.forceReopenDrain()
do {
try closure(writerDrain)
} catch {
XCTFail("Drain threw error \(error)")
}
XCTAssert(data == writerDrain.data, "Garbed writer bytes")
default:
XCTFail("Incorrect type")
}
}
func testWriter() {
let writer = Body.writer { stream in
try stream.write(self.data)
}
checkBodyProperties(writer)
}
func testReader() {
let drain = Drain(buffer: data)
let reader = Body.reader(drain)
checkBodyProperties(reader)
}
func testBuffer() {
let buffer = Body.buffer(data)
checkBodyProperties(buffer)
}
func testBodyEquality() {
let buffer = Body.buffer(data)
let drain = Drain(buffer: data)
let reader = Body.reader(drain)
let writer = Body.writer { stream in
try stream.write(self.data)
}
XCTAssertEqual(buffer, buffer)
XCTAssertNotEqual(buffer, reader)
XCTAssertNotEqual(buffer, writer)
XCTAssertNotEqual(reader, writer)
}
func testBecomeFailure() {
var body = Body.asyncReader(AsyncDrain())
XCTAssertThrowsError(try body.becomeBuffer())
XCTAssertThrowsError(try body.becomeReader())
XCTAssertThrowsError(try body.becomeWriter())
}
}
extension Body {
mutating func forceReopenDrain() {
if let drain = (try! self.becomeReader()) as? Drain {
drain.closed = false
}
}
}
extension BodyTests {
static var allTests : [(String, (BodyTests) -> () throws -> Void)] {
return [
("testWriter", testWriter),
("testReader", testReader),
("testBuffer", testBuffer),
("testBodyEquality", testBodyEquality),
("testBecomeFailure", testBecomeFailure),
]
}
}
| true
|
670418d7b7f384960436c72b1a240749077b6f05
|
Swift
|
terror26/Pokedex
|
/Pokedex3/pokeCell.swift
|
UTF-8
| 623
| 2.84375
| 3
|
[] |
no_license
|
//
// PokeCell.swift
// Pokedex3
//
// Created by Kanishk Verma on 05/08/17.
// Copyright © 2017 Kanishk Verma. All rights reserved.
//
import UIKit
class PokeCell: UICollectionViewCell {
@IBOutlet weak var thumbImg:UIImageView!
@IBOutlet weak var name:UILabel!
var pokemon : Pokemon!
required init?( coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.cornerRadius = 5.0
}
func ConfigureCell( _ pokemon: Pokemon) {
self.pokemon = pokemon
self.name.text = self.pokemon.name
thumbImg.image = UIImage(named: "\(self.pokemon.pokemonId)")
}
}
| true
|
96681d7bc87862b982e139eb8dd34f1ace4ef053
|
Swift
|
woligmeat/E-commerce_App
|
/E-commerce_App/E-commerce_App/Extension/CodableBundleExtension.swift
|
UTF-8
| 925
| 3.1875
| 3
|
[] |
no_license
|
//
// CodableBundleExtension.swift
// E-commerce_App
//
// Created by Damian Pedrycz on 05/04/2021.
//
import Foundation
extension Bundle {
func decode<T: Codable>( file: String) -> T {
// 1. Locate the JSON file
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle")
}
// 2. Create a property for the data
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) in bundle")
}
// 3. Create a decoder
let decoder = JSONDecoder()
// 4. Create a property for the decoded
guard let decodedData = try? decoder.decode(T.self, from: data) else {
fatalError("Failed to decode \(file) in bundle")
}
// 5. Return the ready-to-use data
return decodedData
}
}
| true
|
7a61da10dd307ae0d027db5f514e70c8070fde46
|
Swift
|
tkober/DistributedApplication
|
/AVA/AVATopology.swift
|
UTF-8
| 7,481
| 2.90625
| 3
|
[] |
no_license
|
//
// AVATopology.swift
// AVA
//
// Created by Thorsten Kober on 22.10.15.
// Copyright © 2015 Thorsten Kober. All rights reserved.
//
import Foundation
let OBSERVER_NAME = "Observer"
let OBSERVER_PORT: UInt16 = 5000
let NODE_START_PORT: UInt16 = OBSERVER_PORT+1
/**
Ein Tupel, welches die Anzahl an Knoten und Kanten einer Topologie enthält.
*/
typealias AVATopologyDimension = (vertexCount: Int, edgeCount: Int)
/**
Repräsentiert eine Topologie als Menge adjazenter Knoten.
*/
class AVATopology: NSObject {
/**
Die Adjazenzen der Topologie.
*/
var adjacencies: [AVAAdjacency]
/**
Aller Knoten der Topologie.
*/
var vertices: [AVAVertex]
/**
Die Dimension, sprich Anzahl an Kanten und Knote , der Topologie.
*/
var dimension: AVATopologyDimension {
get {
return (self.vertices.count, self.adjacencies.count)
}
}
/**
Gibt alle Knoten zurück, die zu einem gegebenen Knoten adjazent sind.
- parameters:
- vertex: Der Knoten, dessen adjazente Knoten gesucht sind.
- returns: Alle adjazenten Knoten.
*/
func adjacentVerticesForVertex(vertex: AVAVertexName) -> [AVAVertex] {
var result: [AVAVertex] = []
for adjacency in adjacencies {
if adjacency.v1 == vertex {
result.append(self.vertextForName(adjacency.v2)!)
} else if adjacency.v2 == vertex {
result.append(self.vertextForName(adjacency.v1)!)
}
}
return result
}
override var description: String {
var result = "\(super.description) {"
for adjacency in self.adjacencies {
result += "\n\t\(adjacency)"
}
result += "\n}"
return result
}
// Querying Vertices
func vertextForName(name: AVAVertexName) -> AVAVertex? {
for vertex in self.vertices {
if vertex.name == name {
return vertex
}
}
return nil
}
func verticesInStandby() -> [AVAVertex] {
var result = [AVAVertex]()
for vertex in self.vertices {
if vertex.hasRepotedStandby {
result.append(vertex)
}
}
return result
}
// MARK: | Initializer
private init(vertices: [AVAVertex], adjacencies: [AVAAdjacency]) {
self.vertices = vertices
self.adjacencies = [AVAAdjacency]()
super.init()
for adjacency in adjacencies {
let alreadyIncluded = self.adjacencies.contains({ (item: AVAAdjacency) -> Bool in
return item == adjacency
})
if !alreadyIncluded {
self.adjacencies.append(adjacency)
}
}
}
convenience init(json: AVAJSON) throws {
let verticesJSON = json[TOPOLOGY_VERTICES] as! [AVAJSON]
let vertices = try AVAVertex.verticesFromJSON(verticesJSON)
var adjacencies = [AVAAdjacency]()
if json[TOPOLOGY_COMPLETE_GRAPH] != nil && ((json[TOPOLOGY_COMPLETE_GRAPH])! as! NSNumber).boolValue {
for var i = 0; i < vertices.count-1; i++ {
for var j = i+1; j < vertices.count; j++ {
let v1 = vertices[i]
let v2 = vertices[j]
adjacencies.append(AVAAdjacency(v1: v1.name, v2: v2.name))
}
}
} else {
let adjacenciesJSON = json[TOPOLOGY_ADJACENCIES] as! [[AVAJSON]]
for adjacencyJSON in adjacenciesJSON {
adjacencies.append(AVAAdjacency(json: adjacencyJSON))
}
}
self.init(vertices: vertices, adjacencies: adjacencies)
}
convenience init(data: NSData) throws {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
try self.init(json: json)
}
convenience init(jsonPath: String) throws {
let data = NSData(contentsOfFile: jsonPath)!
try self.init(data: data)
}
/**
Erzeugt eine neue zufällige Topologie mit einer gegeben Dimension.
- parameters:
- dimension: Die Dimension der zu erzeugenden Topologie.
*/
convenience init(randomWithDimension dimension: AVATopologyDimension) throws {
// Nodes
var vertices = [AVAVertex]()
for (var i = 1; i <= dimension.vertexCount; i++) {
vertices.append(AVAVertex(name: "\(i)", ip: "localhost", port: NODE_START_PORT+UInt16(i), attributes: nil))
}
var adjacencies = [AVAAdjacency]()
var j = 0
var v1: AVAVertexName
while (adjacencies.count < dimension.edgeCount) {
v1 = vertices[j].name
var v2 = v1
while (v1 == v2) {
v2 = vertices[Int(arc4random_uniform(UInt32(vertices.count)))].name
}
let newAdjacency = AVAAdjacency(v1: v1, v2: v2)
let alreadyIncluded = adjacencies.contains({ (item: AVAAdjacency) -> Bool in
return item == newAdjacency
})
if !alreadyIncluded {
adjacencies.append(newAdjacency)
j++
j = j % dimension.vertexCount
}
}
// Observer
let observerVertex = AVAVertex(name: OBSERVER_NAME, ip: "localhost", port: OBSERVER_PORT, attributes: nil)
for vertex in vertices {
adjacencies.append(AVAAdjacency(v1: observerVertex.name, v2: vertex.name))
}
vertices.append(observerVertex)
let topologyJSON = AVATopology.jsonFromVertices(vertices, adjacencies: adjacencies)
try self.init(json: topologyJSON)
}
// MARK: | Export
func topologyExcludingObserver() -> AVATopology {
var vertices = [AVAVertex]()
var adjacencies = [AVAAdjacency]()
for vertex in self.vertices {
if vertex.name != OBSERVER_NAME {
vertices.append(vertex)
}
}
for adjacency in self.adjacencies {
if adjacency.v1 != OBSERVER_NAME && adjacency.v2 != OBSERVER_NAME {
adjacencies.append(adjacency)
}
}
return AVATopology(vertices: vertices, adjacencies: adjacencies)
}
private static func jsonFromVertices(vertices: [AVAVertex], adjacencies: [AVAAdjacency]) -> NSDictionary {
var verticesJSON = [[String: AnyObject]]()
for vertex in vertices {
verticesJSON.append(vertex.toJSON())
}
var adjacenciesJSON = [[String]]()
for adjacency in adjacencies {
adjacenciesJSON.append(adjacency.toJSON())
}
return [
TOPOLOGY_VERTICES: verticesJSON,
TOPOLOGY_ADJACENCIES: adjacenciesJSON
]
}
func toData() throws -> NSData {
let topologyJSON = AVATopology.jsonFromVertices(self.vertices, adjacencies: self.adjacencies)
return try NSJSONSerialization.dataWithJSONObject(topologyJSON, options: NSJSONWritingOptions.PrettyPrinted)
}
}
| true
|
45e30406559bd9332ae675b7161db160acb54c21
|
Swift
|
changjiashuai/SwiftUIKit
|
/Sources/SwiftUIKit/Views/Lists/MenuListText.swift
|
UTF-8
| 1,121
| 3.203125
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// MenuListText.swift
// SwiftUIKit
//
// Created by Daniel Saidi on 2021-02-11.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import SwiftUI
/**
This list item can be used to display several lines of text.
*/
public struct MenuListText: View {
public init(_ text: String) {
self.text = text
}
public init(text: String) {
self.init(text)
}
private let text: String
public var body: some View {
Text(text)
.lineSpacing(8)
.padding(.vertical, 13)
}
}
struct MenuListText_Previews: PreviewProvider {
static var previews: some View {
MenuListText("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
}
}
| true
|
7d2c0fcf20a211da17e00b8386250df0925cad35
|
Swift
|
arjunhanswal/unicharm
|
/UniCharm/misc/StoryboardScene.swift
|
UTF-8
| 855
| 3.125
| 3
|
[] |
no_license
|
//
// StoryboardScene.swift
//
//
import Foundation
import UIKit
class StoryboardScene {
static let Main: UIStoryboard = {
return UIStoryboard(name: "Main", bundle: nil)
}()
}
extension UIStoryboard {
func controllerExists(withIdentifier: String) -> Bool {
if let availableIdentifiers = self.value(forKey: "identifierToNibNameMap") as? [String: Any] {
return availableIdentifiers[withIdentifier] != nil
}
return false
}
func instantiateViewController<VC: UIViewController>(withClass: VC.Type) -> VC {
let identifier = NSStringFromClass(withClass as AnyClass).components(separatedBy: ".")[1]
guard controllerExists(withIdentifier: identifier) else {
fatalError("Failed to instantiate viewController")
}
return instantiateViewController(withIdentifier: identifier) as! VC
}
}
| true
|
70aea62cab4ee4b5764922ae54f99fc27d18f6c3
|
Swift
|
nguyentruongky/User-Defined-Setting-iOS
|
/ConfigurationSettingDemo/ViewController.swift
|
UTF-8
| 1,522
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ViewController.swift
// ConfigurationSettingDemo
//
// Created by Ky Nguyen on 4/7/18.
// Copyright © 2018 kynguyen. All rights reserved.
//
import UIKit
let config: Configuration = {
if let app = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String {
if app == "Red" {
return RedConfiguration()
}
else {
return GreenConfiguration()
}
}
return RedConfiguration()
}()
class ViewController: UIViewController {
@IBOutlet weak var appNameLabel: UILabel!
@IBOutlet weak var versionLabel: UILabel!
@IBOutlet weak var buildLabel: UILabel!
@IBOutlet weak var bundleIdLabel: UILabel!
@IBOutlet weak var blogLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
func setupView() {
view.backgroundColor = config.themeColor
appNameLabel.textColor = config.textColor
versionLabel.textColor = config.textColor
buildLabel.textColor = config.textColor
bundleIdLabel.textColor = config.textColor
blogLabel.textColor = config.textColor
appNameLabel.text = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
versionLabel.text = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
buildLabel.text = Bundle.main.infoDictionary?["CFBundleVersion"] as? String
bundleIdLabel.text = Bundle.main.bundleIdentifier
}
}
| true
|
709a734109916d10ad74a5a78e9a78181dda9fe0
|
Swift
|
thanhmamce/FreshFoodForTet
|
/VinMartPlus/Modules/Base/BaseWireFrame.swift
|
UTF-8
| 2,400
| 2.625
| 3
|
[] |
no_license
|
//
// BaseWireFrame.swift
// Taxi Dispatching
//
// Created by KODAK on 2/16/17.
// Copyright © 2017 Enthusiastic Team. All rights reserved.
//
import UIKit
protocol BaseWireFrameInterface {
func dismissInterface()
func popInterface()
func presentLaunchScreenViewInterface()
}
class BaseWireFrame: NSObject {
weak var basePresentedViewController: UIViewController?
func getInterfaceFromStoryboard(_ name: String, presentInterface identifier: String) -> UIViewController {
let storyBoard = UIStoryboard(name: name, bundle: Bundle.main)
let viewController = storyBoard.instantiateViewController(withIdentifier: identifier) // as! BaseViewController
return viewController
}
func getInterfaceFromStoryboardEx(_ name: String, presentInterface identifier: String) -> UIViewController {
let storyBoard = UIStoryboard(name: name, bundle: Bundle.main)
let viewController = storyBoard.instantiateViewController(withIdentifier: identifier) // as! BaseViewController
return viewController
}
func getInterfaceFromStoryboardForTableView(_ name: String, presentInterface identifier: String) -> UIViewController {
let storyBoard = UIStoryboard(name: name, bundle: Bundle.main)
let viewController = storyBoard.instantiateViewController(withIdentifier: identifier) // as! BaseTableViewController
return viewController
}
}
extension BaseWireFrame: BaseWireFrameInterface {
func dismissInterface() {
main_thread {
self.basePresentedViewController?.dismiss(animated: true, completion: nil)
}
}
func popInterface() {
main_thread {
_ = self.basePresentedViewController?.navigationController?.popViewController(animated: true)
}
}
func presentLaunchScreenViewInterface() {
let launchScreenWireFrame = LaunchScreenWireFrame()
if let presentedViewController = basePresentedViewController {
main_thread {
launchScreenWireFrame.presentInterfaceFromViewController(from: presentedViewController,
presentWireFrame: launchScreenWireFrame)
}
}
}
}
// Animation
extension BaseWireFrame: UIViewControllerTransitioningDelegate {
}
| true
|
a733300a883026f8bded695e32f9b15b51653d31
|
Swift
|
Charnpreet/MovieTrailers
|
/UpcomingMovies/Views/UIButton.swift
|
UTF-8
| 1,057
| 2.78125
| 3
|
[] |
no_license
|
//
// UIButton.swift
// UpcomingMovies
//
// Created by CHARNPREET SINGH on 10/6/20.
// Copyright © 2020 CHARNPREET SINGH. All rights reserved.
//
import UIKit
extension UIButton {
static func getUIButton (parentView: UIView, img: UIImage, topAnchor: CGFloat,leadingAnchor: CGFloat,trailingAnchor: CGFloat,bottomAnchor: CGFloat)->UIButton{
let playButton = UIButton(frame: .zero)
playButton.backgroundColor = .clear
playButton.setImage( img, for: .normal)
//playButton.isUserInteractionEnabled = false
parentView.addSubview(playButton)
ConstraintView.shared.setUpConstraints(ParentView: parentView, childView: playButton, topAnchor: topAnchor,leadingAnchor: leadingAnchor,trailingAnchor: trailingAnchor,bottomAnchor: bottomAnchor)
return playButton
}
static func getButton(parentView: UIView, img: UIImage)->UIButton{
let playButton = UIButton(frame: .zero)
playButton.setImage( img, for: .normal)
parentView.addSubview(playButton)
return playButton
}
}
| true
|
4253d252e8d19bfcea3d787b079626eb99803fda
|
Swift
|
myandy/shi_ios
|
/shishi/UI/Share/ShareImageCollectionViewCell.swift
|
UTF-8
| 1,674
| 2.640625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ShareImageCollectionViewCell.swift
// shishi
//
// Created by tb on 2017/7/9.
// Copyright © 2017年 andymao. All rights reserved.
//
import UIKit
class ShareImageCollectionViewCell: UICollectionViewCell {
public var isItemSelected = false
public lazy var imageView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func setupUI() {
self.contentView.clipsToBounds = true
self.setupViews()
self.setupConstraints()
}
internal func setupViews() {
self.contentView.backgroundColor = UIColor("#A9A9AB")
self.contentView.addSubview(self.imageView)
}
internal func setupConstraints() {
self.imageView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
}
public func updateSelectedStatus(isSelected: Bool) {
if self.isItemSelected == isSelected {
return
}
self.isItemSelected = isSelected
let insets = self.isItemSelected ? UIEdgeInsets(top: 3, left: 3, bottom: 3, right: 3) : UIEdgeInsets.zero
UIView.animate(withDuration: 0.25) { [weak self] () in
self?.imageView.snp.remakeConstraints { (make) in
make.edges.equalToSuperview().inset(insets)
}
self?.contentView.layoutIfNeeded()
}
}
}
| true
|
3dc2cf1ac442c4347bff60a673f0d7643c74f75e
|
Swift
|
CiyLei/GTAV_Controll_Client
|
/gtav_test/CellController.swift
|
UTF-8
| 845
| 2.625
| 3
|
[] |
no_license
|
//
// CellController.swift
// gtav_test
//
// Created by ChenLei on 16/12/4.
// Copyright © 2016年 ChenLei. All rights reserved.
//
import UIKit
class CellController: UITableViewCell {
var label_text:UILabel!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
label_text = UILabel(frame: CGRect(x:15, y:0, width:self.contentView.frame.width - 65, height:self.contentView.frame.height))
label_text.numberOfLines = 0
self.contentView.addSubview(label_text)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 类方法 重用标识符
class func cellID () -> String {
return "CustomWriteCell"
}
}
| true
|
fcebeb5b59f7009805240bc3112f5f1109dea781
|
Swift
|
loutskiy/Zaym-iOS
|
/Zaym/Models/SupportAnswer.swift
|
UTF-8
| 1,658
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
//
// SupportAnswer.swift
// Zaym
//
// Created by Mikhail Lutskiy on 11.03.2018.
// Copyright © 2018 Mikhail Lutskii. All rights reserved.
//
import Foundation
import ObjectMapper
import Alamofire
import AlamofireObjectMapper
class SupportAnswer:Mappable {
var id: Int?
var support_ticket_id: Int?
var user_id: Int?
var user: User?
var text: String?
var date_issue: String?
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
id <- (map["id"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } }))
support_ticket_id <- (map["support_ticket_id"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } }))
user_id <- (map["user_id"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } }))
user <- map["user"]
text <- map["text"]
date_issue <- map["date_issue"]
}
func add () {
Alamofire.request(ApiUrl.addAnswerToTicketId(support_ticket_id!), method: .post, parameters: Mapper().toJSON(self)).validate(statusCode: 200..<300).responseObject { (response: DataResponse<SupportAnswer>) in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}
}
func delete () {
Alamofire.request(ApiUrl.deleteAnswerById(id!, ticketId: support_ticket_id!), method: .delete, parameters: Mapper().toJSON(self)).validate(statusCode: 200..<300).response { (response) in
}
}
}
| true
|
9e7a41af483837538c5b9f4fd4edd34a59624c52
|
Swift
|
alexander-schaller/enigma-ios-app
|
/EnigmaI/Extensions.swift
|
UTF-8
| 2,978
| 3.234375
| 3
|
[] |
no_license
|
//
// Extensions.swift
// EnigmaI
//
// Created by Alexander John Schaller on 11/06/19.
// Copyright © 2019 Alex Schaller. All rights reserved.
//
import Foundation
import UIKit
// MARK: Adons
extension String {
// Returns the ith character of a string
subscript (i: Int) -> Character {
return self[index(startIndex, offsetBy: i)]
}
// Indexing
subscript (i: Int) -> String {
return String(self[i] as Character)
}
var roman: Int {
switch self {
case "I":
return 0
case "II":
return 1
case "III":
return 2
case "IV":
return 3
case "V":
return 4
default:
return 0
}
}
}
extension Character {
// Returns the formatted ascii value of a character as an integer
public func formattedAsciiValue () -> Int {
let asciiValue = Int(self.asciiValue!) - 65
return asciiValue
}
}
extension Int {
// Returns the formatted character from an integer through ascii
public func formattedCharacterFromAscii () -> Character {
let unicodeScalar = UnicodeScalar(self + 65)
let character = Character(unicodeScalar!)
return character
}
}
extension Collection {
public func chunk(n: Int) -> [SubSequence] {
var res: [SubSequence] = []
var i = startIndex
var j: Index
while i != endIndex {
j = index(i, offsetBy: n, limitedBy: endIndex) ?? endIndex
res.append(self[i..<j])
i = j
}
return res
}
}
extension ViewController: UITextFieldDelegate {
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return textField != self.OutputTextView
}
}
// Extenstion for the StackView to get a property that adds a background and curves the corner
extension UIStackView {
public func addBackground(color: UIColor, cornerRadius: CGFloat) {
let subView = UIView(frame: bounds)
subView.backgroundColor = color
subView.layer.cornerRadius = cornerRadius
subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
insertSubview(subView, at: 0)
}
}
extension UITextField {
// Makes a rounded text field with a specific corner radius and background color
public func addRoundedCornersAndBackground(backgroundColor: UIColor, cornerRadius: CGFloat) {
self.borderStyle = .roundedRect
self.backgroundColor = backgroundColor
//self.layer.cornerRadius = cornerRadius
//self.clipsToBounds = true
}
}
extension UIButton {
// Adds rounded corners and a background color to a button
public func formatToSpec(backgroundColor: UIColor, cornerRadius: CGFloat) {
self.backgroundColor = backgroundColor
self.layer.cornerRadius = cornerRadius
}
}
| true
|
37494fe77969282b19362ecf06220c98bc33b53c
|
Swift
|
andrebasrau/BliBliProject
|
/BliBliTestProject/ViewModel/Picker.swift
|
UTF-8
| 2,013
| 2.59375
| 3
|
[] |
no_license
|
//
// Picker.swift
// Project Bli Bli
//
// Created by andre basra utama on 12/03/21.
//
import Foundation
import PhotosUI
import SwiftUI
struct Picker : UIViewControllerRepresentable {
@Binding var pick : Bool;
@Binding var img : Data;
func makeUIViewController(context: Context) -> PHPickerViewController {
var config = PHPickerConfiguration ();
config.selectionLimit = 1;
let controller = PHPickerViewController (configuration : config);
controller.delegate = context.coordinator;
return controller;
}
func makeCoordinator() -> Coordinator {
return Picker.Coordinator (parent: self);
}
func updateUIViewController (_ uiViewController : PHPickerViewController, context : Context){
}
class Coordinator : NSObject,PHPickerViewControllerDelegate {
var parent : Picker;
init (parent : Picker){
self.parent = parent
}
func picker (_ pciker : PHPickerViewController, didFinishPicking results: [PHPickerResult]){
if (results.isEmpty){
self.parent.pick.toggle();
return
}
let item = results.first!.itemProvider;
if item.canLoadObject(ofClass: UIImage.self){
if item.canLoadObject(ofClass: UIImage.self){
item.loadObject(ofClass: UIImage.self) { (image, error) in
if error != nil {return}
let imageData = image as! UIImage;
DispatchQueue.main.async {
self.parent.img = imageData.jpegData(compressionQuality: 0.5)!
self.parent.pick.toggle();
}
}
}
}
}
}
}
| true
|
b138b347f67cff78dabfea6c20dc5eb6c3ac8745
|
Swift
|
LIFX/AudioKit
|
/Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/FM Oscillator.xcplaygroundpage/Contents.swift
|
UTF-8
| 4,596
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
//: ## FM Oscillator
//: Open the timeline view to use the controls this playground sets up.
//:
import AudioKitPlaygrounds
import AudioKit
import AudioKitUI
var oscillator = AKFMOscillator()
oscillator.amplitude = 0.1
oscillator.rampDuration = 0.1
AudioKit.output = oscillator
try AudioKit.start()
class LiveView: AKLiveViewController {
// UI Elements we'll need to be able to access
var frequencySlider: AKSlider!
var carrierMultiplierSlider: AKSlider!
var modulatingMultiplierSlider: AKSlider!
var modulationIndexSlider: AKSlider!
var amplitudeSlider: AKSlider!
var rampDurationSlider: AKSlider!
override func viewDidLoad() {
addTitle("FM Oscillator")
addView(AKButton(title: "Start FM Oscillator") { button in
oscillator.isStarted ? oscillator.stop() : oscillator.play()
button.title = oscillator.isStarted ? "Stop FM Oscillator" : "Start FM Oscillator"
})
let presets = ["Stun Ray", "Wobble", "Fog Horn", "Buzzer", "Spiral"]
addView(AKPresetLoaderView(presets: presets) { preset in
switch preset {
case "Stun Ray":
oscillator.presetStunRay()
oscillator.start()
case "Wobble":
oscillator.presetWobble()
oscillator.start()
case "Fog Horn":
oscillator.presetFogHorn()
oscillator.start()
case "Buzzer":
oscillator.presetBuzzer()
oscillator.start()
case "Spiral":
oscillator.presetSpiral()
oscillator.start()
default:
break
}
self.frequencySlider?.value = oscillator.baseFrequency
self.carrierMultiplierSlider?.value = oscillator.carrierMultiplier
self.modulatingMultiplierSlider?.value = oscillator.modulatingMultiplier
self.modulationIndexSlider?.value = oscillator.modulationIndex
self.amplitudeSlider?.value = oscillator.amplitude
self.rampDurationSlider?.value = oscillator.rampDuration
})
addView(AKButton(title: "Randomize") { _ in
oscillator.baseFrequency = self.frequencySlider.randomize()
oscillator.carrierMultiplier = self.carrierMultiplierSlider.randomize()
oscillator.modulatingMultiplier = self.modulatingMultiplierSlider.randomize()
oscillator.modulationIndex = self.modulationIndexSlider.randomize()
})
frequencySlider = AKSlider(property: "Frequency",
value: oscillator.baseFrequency,
range: 0 ... 800,
format: "%0.2f Hz"
) { frequency in
oscillator.baseFrequency = frequency
}
addView(frequencySlider)
carrierMultiplierSlider = AKSlider(property: "Carrier Multiplier",
value: oscillator.carrierMultiplier,
range: 0 ... 20
) { multiplier in
oscillator.carrierMultiplier = multiplier
}
addView(carrierMultiplierSlider)
modulatingMultiplierSlider = AKSlider(property: "Modulating Multiplier",
value: oscillator.modulatingMultiplier,
range: 0 ... 20
) { multiplier in
oscillator.modulatingMultiplier = multiplier
}
addView(modulatingMultiplierSlider)
modulationIndexSlider = AKSlider(property: "Modulation Index",
value: oscillator.modulationIndex,
range: 0 ... 100
) { index in
oscillator.modulationIndex = index
}
addView(modulationIndexSlider)
amplitudeSlider = AKSlider(property: "Amplitude", value: oscillator.amplitude) { amplitude in
oscillator.amplitude = amplitude
}
addView(amplitudeSlider)
rampDurationSlider = AKSlider(property: "Ramp Duration",
value: oscillator.rampDuration,
range: 0 ... 10,
format: "%0.3f s"
) { time in
oscillator.rampDuration = time
}
addView(rampDurationSlider)
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
| true
|
0d6298903ca79bac31d76e289949fbea9f70d1e0
|
Swift
|
Flo2503/P12-PetRescue
|
/PetRescue/Firebase Service/UserManager.swift
|
UTF-8
| 4,241
| 3.0625
| 3
|
[] |
no_license
|
//
// UsersManager.swift
// PetRescue
//
// Created by Flo on 25/04/2020.
// Copyright © 2020 Flo. All rights reserved.
// swiftlint:disable void_return
import Foundation
import Firebase
import FirebaseAuth
import FirebaseDatabase
class UserManager {
// MARK: - Properties, instances
private var user: User?
private var users: [User]?
private let storage = Storage.storage()
private let dataBase = Database.database()
static let currentUserId = Auth.auth().currentUser?.uid
// MARK: - Firebase Methods
///Create user on Firebase Database and create user on Firebase authentification with password and email
func createUser(email: String, password: String, name: String, firstName: String, callback: @escaping (Bool) -> ()) {
Auth.auth().createUser(withEmail: email, password: password) { (_, success) in
if success != nil {
callback(false)
return
} else {
let ref = Database.database().reference()
if let userID = Auth.auth().currentUser?.uid {
ref.child("users").child(userID).setValue(["name": name, "firstName": firstName, "emailAddress": email, "userId": userID])
}
}
callback(true)
}
}
///Log in on Firebase with emaild and password
func login(withEmail email: String, password: String, callback: @escaping (Bool) -> ()) {
Auth.auth().signIn(withEmail: email, password: password) { (_, success) in
if success != nil {
callback(false)
return
}
callback(true)
}
}
///Allow to logout on firebase. Return true when done
func signOut() -> Bool {
do {
try Auth.auth().signOut()
return true
} catch {
return false
}
}
///Allow to retrieve user information observing path on Firebase: users/userId
func retrieveUser(callback: @escaping (_ currentUser: User) -> Void) {
let ref = Database.database().reference()
if let userId = Auth.auth().currentUser?.uid {
let path = ref.child("users").child(userId)
path.observe(.value, with: { snapshot in
if let user = User(snapshot: snapshot) {
self.user = user
callback(user)
}
})
}
}
///Allow to retrieve second user information observing path on Firebase: users/userId
func retrieveChatUser(userChatId: String, callback: @escaping (_ chatUser: User) -> Void) {
let ref = Database.database().reference()
let path = ref.child("users").child(userChatId)
path.observe(.value, with: { snapshot in
if let user = User(snapshot: snapshot) {
self.user = user
callback(user)
}
})
}
///Send an email to the user to reset his password
func sendPasswordReset(withEmail email: String, callback: @escaping (Bool) -> ()) {
Auth.auth().sendPasswordReset(withEmail: email) { success in
if success != nil {
callback(false)
return
}
callback(true)
}
}
///Allow to change password on Firebase Database
func updatePassword(password: String, callback: @escaping (Bool) -> ()) {
Auth.auth().currentUser?.updatePassword(to: password) { success in
if success != nil {
callback(false)
return
}
callback(true)
}
}
/// Allow to edit email on FIrebase database
func updateEmail(email: String, callback: @escaping (Bool) -> ()) {
Auth.auth().currentUser?.updateEmail(to: email) { success in
if success != nil {
callback(false)
return
} else {
let ref = self.dataBase.reference()
if let userID = Auth.auth().currentUser?.uid {
ref.child("users").child(userID).updateChildValues(["emailAddress": email])
}
}
callback(true)
}
}
}
| true
|
eb583c298ce13e20907c08a3d7af466b86f4fc88
|
Swift
|
lucifer-thebeast/WebViewAccessibility
|
/WebViewAccessibility/ViewController.swift
|
UTF-8
| 1,626
| 2.78125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// WebViewAccessibility
//
// Created by Gualtiero Frigerio on 07/05/2020.
// Copyright © 2020 Gualtiero Frigerio. All rights reserved.
//
import UIKit
import WebKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
webView.frame = self.view.frame
self.view.addSubview(webView)
if let bundlePath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "html") {
let request = URLRequest(url: URL(fileURLWithPath: bundlePath))
webView.load(request)
}
NotificationCenter.default.addObserver(self, selector: #selector(preferredContentSizeChanged(_:)), name: UIContentSizeCategory.didChangeNotification, object: nil)
}
private var webView = WKWebView()
private var useCustomFont = true
private func notifyFontSize(newSize:CGFloat) {
let javascriptFunction = "fontSizeChanged(\(newSize))"
webView.evaluateJavaScript(javascriptFunction) { (result, error) in
print("font size changed in webview")
}
}
@objc private func preferredContentSizeChanged(_ notification: Notification) {
if let userInfo = notification.userInfo,
let contentSize = userInfo["UIContentSizeCategoryNewValueKey"] {
print("new category \(contentSize) type = \(type(of: contentSize))")
}
let font = UIFont.preferredFont(forTextStyle: .body)
if useCustomFont {
notifyFontSize(newSize: font.pointSize)
}
else {
webView.reload()
}
}
}
| true
|
3762b8af2a9a6d518d9e6ba358f0177f3565332a
|
Swift
|
keita6321/NewMemoTask
|
/NiftyMemo/DetailTaskViewController.swift
|
UTF-8
| 6,121
| 2.515625
| 3
|
[] |
no_license
|
//
// DetailViewController.swift
// NiftyMemo
//
// Created by nttr on 2017/08/23.
// Copyright © 2017年 nttr. All rights reserved.
//
import UIKit
import NCMB
import SVProgressHUD
import UserNotifications
class DetailTaskViewController: UIViewController {
@IBOutlet var textDatePicker: UITextField!
@IBOutlet var datePicker: UIDatePicker!
@IBOutlet var saveButton: UIButton!
@IBOutlet var doneButton: UIButton!
let center = UNUserNotificationCenter.current()
//var limit :String = ""
@IBOutlet var memoTextView: UITextView!
var selectedMemo: NCMBObject!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
memoTextView.text = selectedMemo.object(forKey: "text") as! String
//textDatePicker.text = format(date: selectedMemo.object(forKey: "limit") as! Date)
//showDatePicker()
//textDatePicker.text = selectedMemo.object(forKey: "limit") as! String
datePicker.date = selectedMemo.object(forKey: "limit") as! Date
saveButton.frame.size.height = saveButton.frame.width // ボタンを正方形にする
saveButton.layer.cornerRadius = saveButton.frame.width / 2 // 角丸のサイズ(丸ボタン)
doneButton.frame.size.height = doneButton.frame.width // ボタンを正方形にする
doneButton.layer.cornerRadius = doneButton.frame.width / 2 // 角丸のサイズ(丸ボタン)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//--------datepicker------------
func showDatePicker(){
//Formate Date
datePicker.datePickerMode = .date
//ToolBar
let toolbar = UIToolbar();
toolbar.sizeToFit()
print(type(of: toolbar))
//done button & cancel button
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action: "donedatePicker")
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.bordered, target: self, action: "cancelDatePicker")
toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false)
// add toolbar to textField
textDatePicker.inputAccessoryView = toolbar
// add datepicker to textField
textDatePicker.inputView = datePicker
}
func donedatePicker(){
//For date formate
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
textDatePicker.text = formatter.string(from: datePicker.date)
//dismiss date picker dialog
self.view.endEditing(true)
}
func cancelDatePicker(){
//cancel button dismiss datepicker dialog
self.view.endEditing(true)
}
@IBAction func pickerValueChanged(_ sender: Any) {
let calendar = Calendar.current
let formatter = DateFormatter()
let formatter2 = DateFormatter()
var now = Date()
var count = calendar.dateComponents([.second], from: now, to: datePicker.date).second
formatter.dateFormat = "YYYY/MM/dd"
//pickerLabel1.text = formatter.string(from: datePicker2.date)
formatter2.dateFormat = "hh:mm a"
//pickerLabel2.text = formatter2.string(from: datePicker2.date)
//alertCountLabel.text = String(describing: count!)
let formatter3 = DateFormatter()
formatter3.dateFormat = "YYYY/MM/dd hh:mm a"
print("start\(formatter3.string(from: now))")
print("end\(formatter3.string(from: datePicker.date))")
print(String(describing: count!))
}
func format(date:Date)->String{
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-MM-dd"
let strDate = dateformatter.string(from: date)
return strDate
}
//------------------------------
//メモの内容を変更
@IBAction func update(){
selectedMemo.setObject(memoTextView.text, forKey: "text")
selectedMemo.setObject(datePicker.date, forKey: "limit")
selectedMemo.saveInBackground { (error) in
if error != nil{
SVProgressHUD.showError(withStatus: error?.localizedDescription)
}
else{
//self.postNotification()
self.navigationController?.popViewController(animated: true)
}
let content = UNMutableNotificationContent()
let calendar = Calendar.current
let now = Date()
if(self.datePicker.date>now){
content.title = "タスク期限の通知";
content.body = self.memoTextView.text
content.sound = UNNotificationSound.default()
var count = calendar.dateComponents([.second], from: now, to: self.datePicker.date).second
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: TimeInterval(count as! Int), repeats: false)
let request = UNNotificationRequest.init(identifier: "Alert", content: content, trigger: trigger)
self.center.add(request)
print("アラートをセットしました")
}
}
}
@IBAction func done(){
selectedMemo.setObject(true, forKey: "done")
selectedMemo.saveInBackground { (error) in
if(error != nil){
SVProgressHUD.showError(withStatus: error?.localizedDescription)
}
else{
print("change doneFlag")
self.navigationController?.popViewController(animated: true)
}
}
}
func postNotification() {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateTask"), object: nil, userInfo: ["updateTaskFlag": true])
}
}
| true
|
499add61f4db70c89be11259b402a994d75b0217
|
Swift
|
andyrewlee/iosprac
|
/02intermediateswift/14 - Hash Table II/answer/14_HashTableII/14_HashTableII/SinglyNode.swift
|
UTF-8
| 329
| 2.765625
| 3
|
[] |
no_license
|
//
// SinglyNode.swift
// 14_HashTableII
//
// Created by Jae Hoon Lee on 7/6/15.
// Copyright © 2015 Jae Hoon Lee. All rights reserved.
//
import Foundation
class SinglyNode<T>: Node<T> {
var next: SinglyNode<T>?
init(value: T, nextNode: SinglyNode<T>?) {
self.next = nextNode
super.init(value: value)
}
}
| true
|
e8a8b1b802612cf2bfccf3d9a9edc347db005a7c
|
Swift
|
mnfro/GoogleVisionKit
|
/GoogleVisionKit/VisionKit/VisionAPIModel.swift
|
UTF-8
| 2,943
| 2.703125
| 3
|
[] |
no_license
|
//
// VisionAPIModel.swift
// GoogleVisionKit
//
// Created by mnfro on 05/2020.
// Copyright © 2020 Manfredi Schiera (@mnfro). All rights reserved.
//
import Foundation
struct VisionKit: Codable {
var responses : [Response]?
}
struct Response: Codable {
var fullTextAnnotation : FullTextAnnotation?
struct FullTextAnnotation: Codable {
var text : String?
var pages : [Page]?
struct Page: Codable {
var blocks : [Block]?
struct Block: Codable {
var paragraphs : [Paragraph]?
struct Paragraph: Codable {
var words : [Word]?
struct Word: Codable {
var symbols : [Symbol]?
struct Symbol: Codable {
var text : String?
var property : Property?
struct Property: Codable {
var detectedBreak : DetectedBreak?
struct DetectedBreak: Codable {
var type : String?
}
}
}
}
}
}
}
}
}
extension Response {
var parseText: [String] {
var paragraphs: [String] = []
var lines: [String] = []
for page in (fullTextAnnotation?.pages)! {
for block in (page.blocks)! {
var block_paragraph = ""
for paragraph in (block.paragraphs)! {
var para = ""
var line = ""
for word in (paragraph.words)! {
for symbol in (word.symbols)! {
line += (symbol.text)!
if symbol.property?.detectedBreak?.type == "SPACE" {
line += " "
}
if symbol.property?.detectedBreak?.type == "EOL_SURE_SPACE" {
line += " "
lines.append(line)
para += line
line = ""
}
if symbol.property?.detectedBreak?.type == "LINE_BREAK" {
lines.append(line)
para += line
line = ""
}
}
}
block_paragraph += para
}
paragraphs.append(block_paragraph)
}
}
return paragraphs
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.