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
3851487cc22abcfc1f884e4154f3c0af788a399b
Swift
The-Cage-s-Farm/theCagesFam
/CagesFarm/CagesFarm/Nodes/FaceCharacters.swift
UTF-8
560
2.59375
3
[]
no_license
// // FaceCharacters.swift // CagesFarm // // Created by Gilberto Magno on 4/6/21. // // import Foundation import SpriteKit import UIKit public class FaceCharacters: SKSpriteNode, ImageRetriever { var textures :[SKTexture] = [] let characterName: String? = "tony" var isTalking = false var actualImageID = 0 var feeling: String = "Smiling" required init?(coder aDecoder: NSCoder) { fatalError("NSCoding not supported") } init() { super.init(texture: textures[0], color: .clear, size: textures[0].size()) } }
true
a11aab10dea140fadabdb2aebfa77d39ffcc081d
Swift
GuruDev920/LifeApp
/Life/Utils/Utils.swift
UTF-8
805
2.609375
3
[]
no_license
// // Utils.swift // Life // // Created by XianHuang on 6/24/20. // Copyright © 2020 Yun Li. All rights reserved. // import Foundation import UIKit //import SCLAlertView class Utils { static let shared = Utils() func isValidEmail(_ email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: email) } } class MyFont: NSObject { static let MontserratLight = "Montserrat-Light" static let MontserratMedium = "Montserrat-Medium" static let MontserratRegular = "Montserrat-Regular" static let MontserratBold = "Montserrat-Bold" static let MontserratSemiBold = "Montserrat-SemiBold" }
true
6e4d896afdc515ce893d2012d10b663667437c2e
Swift
chinhphamnhu/TrelloNavigation
/Source/TrelloFunction.swift
UTF-8
1,181
3.125
3
[ "MIT" ]
permissive
// // TrelloFunction.swift // TrelloNavigation // // Created by DianQK on 15/11/12. // Copyright © 2015年 Qing. All rights reserved. // import UIKit /// Taste Function Programming // TODO: Combine CGPoint typealias TransformPoint = (CGPoint) -> CGPoint func add(x: CGFloat) -> TransformPoint { return { point in return CGPoint(x: point.x + x, y: point.y) } } func add(y: CGFloat) -> TransformPoint { return { point in return CGPoint(x: point.x, y: point.y + y) } } func add(x: CGFloat, y: CGFloat) -> TransformPoint { return { point in return add(y: y)( add(x: x)(point) ) } } extension UIBezierPath { func addSquare(center: CGPoint, width: CGFloat) { self.move(to: add(x: center.x - width / 2.0, y: center.y - width / 2.0)(center)) self.addLine(to: add(x: center.x + width / 2.0, y: center.y - width / 2.0)(center)) self.addLine(to: add(x: center.x + width / 2.0, y: center.y + width / 2.0)(center)) self.addLine(to: add(x: center.x - width / 2.0, y: center.y + width / 2.0)(center)) self.addLine(to: add(x: center.x - width / 2.0, y: center.y - width / 2.0)(center)) } }
true
59806a763a3465cdc77ab4937bd6f68beabf84a8
Swift
amyyiyan/FilmApp
/Helper/CoreDataHelper.swift
UTF-8
1,480
2.90625
3
[]
no_license
// // CoreDataHelper.swift // FilmApp // // Created by Amy Liu on 7/26/18. // Copyright © 2018 Amy Liu. All rights reserved. // import UIKit import CoreData struct CoreDataHelper { static let context: NSManagedObjectContext = { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { fatalError() } let persistentContainer = appDelegate.persistentContainer let context = persistentContainer.viewContext return context }() static func newImage() -> ImageWithAttributes { let freshImage = NSEntityDescription.insertNewObject(forEntityName: "ImageWithAttributes", into: context) as! ImageWithAttributes return freshImage } static func saveImage() { do { try context.save() } catch let error { print("Could not save \(error.localizedDescription)") } } static func delete(freshImage: ImageWithAttributes) { context.delete(freshImage) print("deleted image") saveImage() } static func retrieveImage() -> [ImageWithAttributes] { do { let fetchRequest = NSFetchRequest<ImageWithAttributes>(entityName: "ImageWithAttributes") let results = try context.fetch(fetchRequest) return results } catch let error { print("Could not fetch \(error.localizedDescription)") return [] } } }
true
78bde350a93173a341971b4f16772ca64ccd9885
Swift
jsivanes/Mobile
/Swift/Tutoriel/Gesture.playground/Contents.swift
UTF-8
732
3.140625
3
[]
no_license
//: Playground - noun: a place where people can play import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let gesture = UIPanGestureRecognizer(target: self, action: #selector(panGesture(_:))) view.addGestureRecognizer(gesture) } func panGesture(gesture: UIPanGestureRecognizer) { switch gesture.state { case .began: print("began") case .changed: print("changed to \(gesture.location(in: view))") case .ended: print("ended") case .cancelled, .failed: print("cancelled, failled") case .possible: print("Possible") } } }
true
b8f064bfc87ef2e93569cb20c950016dfd9e34ac
Swift
jamesjosephb/CryptoPayIOS
/CryptoPay/Views/GlobalViewsAndFunctions.swift
UTF-8
4,317
3.078125
3
[]
no_license
// // GlobalViewsAndFunctions.swift // CryptoPay // // Created by JamesJoseph Burch on 7/1/20. // Copyright © 2020 James Burch. All rights reserved. // import SwiftUI struct LabelTextField: View { var label: String var placeHolder: String @Binding var userInput: String var body: some View { VStack(alignment: .leading) { Text(label)//.font(.caption) TextField(placeHolder, text: $userInput) .padding(.all) .background((Color("lightGreyColor"))) .cornerRadius(15.0) }.padding(.horizontal, 15) } } struct LabelNumField: View { var label: String @Binding var placeHolder: Int @Binding var userInput: Int @State var placeHolderString = "" @State var userInputString = "" func IntToString() { placeHolderString = String(self.placeHolder) userInputString = String(self.userInput) } func StringtoInt() { userInput = Int(userInputString)! } var body: some View { LabelTextField(label: label, placeHolder: placeHolderString, userInput: $userInputString) .onAppear(perform: IntToString) .onDisappear(perform: StringtoInt) .keyboardType(.numberPad) } } struct DropDownPicker: View { var label: String @State private var menuToggle = false @Binding var activeOption: String var dropDownOptions: [String] var body: some View { VStack(alignment: .leading) { Text(label) .padding(.bottom, 10) VStack { Button(action: { self.menuToggle.toggle() }) { HStack { Text(self.activeOption) Spacer() } } if menuToggle { ForEach(dropDownOptions, id: \.self) {option in Button(action: { self.activeOption = option self.menuToggle.toggle() }) { Text(option) .padding(.bottom) } } } } .padding(17) .background((Color("lightGreyColor"))) .cornerRadius(15.0) } .padding(.horizontal, 15) .padding(.bottom, 9) } } struct DismissingKeyboard: ViewModifier { func body(content: Content) -> some View { content .onTapGesture { let keyWindow = UIApplication.shared.connectedScenes .filter({$0.activationState == .foregroundActive}) .map({$0 as? UIWindowScene}) .compactMap({$0}) .first?.windows .filter({$0.isKeyWindow}).first keyWindow?.endEditing(true) } } } struct DateSelector: View { @Binding var selectedDate: Date let minDate: Date let maxDate: Date var label: String var body: some View { VStack(alignment: .leading) { Text(label) DatePicker("Date", selection: $selectedDate, in: minDate...maxDate, displayedComponents: .date) .labelsHidden() .frame(width: 270, height: 80, alignment: .center) .clipped() .padding(.all) .background((Color("lightGreyColor"))) .cornerRadius(15.0) }.padding(.horizontal) } } func intToStringAmount(_ amount: Int) -> String { var StringAmount = String(amount) if StringAmount.count == 1 { StringAmount = "0.0" + StringAmount } else if StringAmount.count == 2 { StringAmount = "0." + StringAmount } else { StringAmount.insert(".", at: StringAmount.index(StringAmount.endIndex, offsetBy: -2)) } StringAmount.insert("$", at: StringAmount.startIndex) return StringAmount } struct RoundedButton: View { var body: some View { Button(action: {}) { Text("ADD SITE") .font(.headline) .foregroundColor(.white) .padding() .background(Color.green) .cornerRadius(15.0) } } }
true
e8b82c1c87caa92c99c06a08ba34c2b281f5fb54
Swift
wjling/WUtils
/WUtils/Sources/UIImage/UIImage+Init.swift
UTF-8
910
2.8125
3
[]
no_license
// // UIImage+Init.swift // WUtils // // Created by wjling on 2021/9/15. // import Foundation import UIKit public extension UIImage { convenience init(color: UIColor, size: CGSize, roundingCorners: UIRectCorner = .allCorners, cornerRadius: Double) { let renderer = UIGraphicsImageRenderer.init(size: size) let img = renderer.image { context in let rectPath = UIBezierPath.init(roundedRect: CGRect.init(origin: .zero, size: size), byRoundingCorners: roundingCorners, cornerRadii: CGSize.init(width: cornerRadius, height: cornerRadius)) context.cgContext.addPath(rectPath.cgPath) color.setFill() context.cgContext.fillPath() } if let cgImage = img.cgImage { self.init(cgImage: cgImage, scale: UIScreen.main.scale, orientation: UIImage.Orientation.up) } else { self.init() } } }
true
e52abe4caff2e773a06770f6ef07c25366e6634a
Swift
mattpolzin/JSONAPI
/Tests/JSONAPITestingTests/Comparisons/ArrayCompareTests.swift
UTF-8
2,600
3.1875
3
[ "MIT" ]
permissive
// // ArrayCompareTests.swift // JSONAPITestingTests // // Created by Mathew Polzin on 11/14/19. // import XCTest @testable import JSONAPITesting final class ArrayCompareTests: XCTestCase { func test_same() { let arr1 = ["a", "b", "c"] let arr2 = ["a", "b", "c"] let comparison = arr1.compare(to: arr2) { str1, str2 in str1 == str2 ? .same : .differentValues(str1, str2) } XCTAssertEqual( comparison, [.same, .same, .same] ) XCTAssertEqual(comparison.map(\.description), ["same", "same", "same"]) XCTAssertEqual(comparison.map(BasicComparison.init(reducing:)), [.same, .same, .same]) XCTAssertEqual(comparison.map(BasicComparison.init(reducing:)).map(\.description), ["same", "same", "same"]) } func test_differentLengths() { let arr1 = ["a", "b", "c"] let arr2 = ["a", "b"] let comparison1 = arr1.compare(to: arr2) { str1, str2 in str1 == str2 ? .same : .differentValues(str1, str2) } XCTAssertEqual( comparison1, [.same, .same, .missing] ) XCTAssertEqual(comparison1.map(\.description), ["same", "same", "missing"]) XCTAssertEqual(comparison1.map(BasicComparison.init(reducing:)), [.same, .same, .different("array length 1", "array length 2")]) let comparison2 = arr2.compare(to: arr1) { str1, str2 in str1 == str2 ? .same : .differentValues(str1, str2) } XCTAssertEqual( comparison2, [.same, .same, .missing] ) XCTAssertEqual(comparison2.map(\.description), ["same", "same", "missing"]) XCTAssertEqual(comparison2.map(BasicComparison.init(reducing:)), [.same, .same, .different("array length 1", "array length 2")]) } func test_differentValues() { let arr1 = ["c", "b", "a"] let arr2 = ["a", "b", "c"] let comparison = arr1.compare(to: arr2) { str1, str2 in str1 == str2 ? .same : .differentValues(str1, str2) } XCTAssertEqual( comparison, [.differentValues("c", "a"), .same, .differentValues("a", "c")] ) XCTAssertEqual(comparison.map(\.description), ["c ≠ a", "same", "a ≠ c"]) } func test_reducePrebuilt() { let prebuilt = ArrayElementComparison.prebuilt("hello world") XCTAssertEqual(BasicComparison(reducing: prebuilt), .prebuilt("hello world")) XCTAssertEqual(BasicComparison(reducing: prebuilt).description, "hello world") } }
true
3a4b10e93b3319fc06e8add61e6824008206e5ff
Swift
prinomen/social_demo2
/social_demo2/SettingsVC.swift
UTF-8
4,866
2.953125
3
[]
no_license
import UIKit class SettingsVC: UITableViewController, UITextFieldDelegate { let colorSection = ["My Color"] let miscSection = ["Help & Feedback"] // Gets the header view as a UITableViewHeaderFooterView and changes the section header text color, font, etc. override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView headerView.textLabel!.textColor = black headerView.textLabel!.font = UIFont(name: "Avenir Next", size: 17) } override func viewWillAppear(animated: Bool) { self.tableView.reloadData() // reload the entire table (this will update the section header text so that it sets it to the current userColor) } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = tableView.dequeueReusableCellWithIdentifier("MyCustomTableViewCell", forIndexPath: indexPath) return cell } else if indexPath.section == 1 { let cell = tableView.dequeueReusableCellWithIdentifier("settingsCell", forIndexPath: indexPath) let title = colorSection[indexPath.row] as String cell.textLabel?.text = title cell.textLabel!.font = UIFont(name:"Avenir Next", size:18) cell.textLabel!.textColor = UIColor(rgb: 0x474747) if cell.textLabel?.text == "My Color" { cell.accessoryType = UITableViewCellAccessoryType(rawValue: 1)! } return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("settingsCell", forIndexPath: indexPath) let title = miscSection[indexPath.row] as String cell.textLabel?.text = title cell.textLabel!.font = UIFont(name:"Avenir Next", size:18) cell.textLabel!.textColor = UIColor(rgb: 0x474747) if cell.textLabel?.text == "Help & Feedback" { cell.accessoryType = UITableViewCellAccessoryType(rawValue: 1)! } return cell } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return "Name" case 1: return "Color" default: return nil } } // This method fires when any of the cells are touched override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // Setting up variables & constants let selectedSection = indexPath.section let selectedRow = indexPath.row var selectedItem : String? // Set the "selectedSection" variable to the selected cell if selectedSection == 0 { selectedItem = "Enter your name" } else if selectedSection == 1 && selectedRow == 0 { selectedItem = "My Color" } else if selectedSection == 2 { selectedItem = "Help & Feedback" } // Look at the selectedItem variable. If it's the "My color" or "Help & feedback", trigger the segue to the respective scene. switch selectedItem! { case "My Color": self.performSegueWithIdentifier("showMyColor", sender: self) case "Help & Feedback": self.performSegueWithIdentifier("showHelp", sender: self) default: break } } // Resign first responder when return key is pressed func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) return false } override func viewDidLoad() { super.viewDidLoad() view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTap:")) // add a gesture recognizer to dismiss keyboard when tapping anywhere outside the text field // Prevents the default behavior of the nav bar "Back" button (which is a title from the previous screen) and instead uses an empty string, resulting in just a < chevron self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.Plain, target:nil, action:nil) } // Dismisses keyboard when tapping anywhere outside the text field func handleTap(sender: UITapGestureRecognizer) { if sender.state == .Ended { view.endEditing(true) } sender.cancelsTouchesInView = false } }
true
8c819c84f6b263fb5083be8556cfba8bd189060d
Swift
davidellus/Pedroproject
/DivineTap_Alpha 2.0/DivineTap(pedro Rev)/GameViewController.swift
UTF-8
1,522
2.515625
3
[]
no_license
// // GameViewController.swift // MyFirst // // Created by Paolo Buia on 08/11/2019. // Copyright © 2019 Paolo Buia. All rights reserved. // import UIKit import SpriteKit import CoreMotion class GameViewController: UIViewController { var motionManager = CMMotionManager() override func viewDidLoad() { super.viewDidLoad() let scene = GameScene(size: view.bounds.size) let scene2 = MenuScene(size: view.bounds.size) let scene3 = GameOverScene(size: view.bounds.size) let skView = view as! SKView skView.showsFPS = true skView.showsNodeCount = true skView.ignoresSiblingOrder = true scene.scaleMode = .resizeFill skView.presentScene(scene2) UIView.appearance().isExclusiveTouch = true } override var prefersStatusBarHidden: Bool { return true } override func viewDidAppear(_ animated: Bool) { motionManager.gyroUpdateInterval = 0 motionManager.startGyroUpdates(to: OperationQueue.current!) { (data, error) in if let myData = data { if myData.rotationRate.y > 2 { print("detect shake") player.addShield() self.motionManager.gyroUpdateInterval = 4 DispatchQueue.main.asyncAfter(deadline: .now() + 4) { self.motionManager.gyroUpdateInterval = 0 } } } } } }
true
a711c63d69eb7735c8545e12a39a37d5210907b5
Swift
ZHRhodes/Whaler
/Whaler/Shared/Models/User/User.swift
UTF-8
1,499
3.03125
3
[]
no_license
// // User.swift // Whaler // // Created by Zachary Rhodes on 9/7/20. // Copyright © 2020 Whaler. All rights reserved. // import Foundation import UIKit protocol FullNameProviding { var firstName: String { get } var lastName: String { get } } extension FullNameProviding { var initials: String { let firstInitial = firstName.first.map(String.init) ?? "" let lastInitial = lastName.first.map(String.init) ?? "" return firstInitial.uppercased() + lastInitial.uppercased() } var fullName: String { return "\(firstName) \(lastName)" } } protocol ColorProviding { var color: UIColor { get } } typealias NameAndColorProviding = FullNameProviding & ColorProviding struct User: Codable, FullNameProviding, ColorProviding { let id: String let email: String let firstName: String let lastName: String let isAdmin: Bool let organizationId: String // let workspaces: [WorkspaceRemote]? let organization: Organization? var color: UIColor { return ColorProvider.default.color(for: id) } } extension User: SimpleItem { var name: String { [firstName, lastName].joined(separator: " ") } var icon: UIImage? { return nil } } extension User: Equatable {} class ColorProvider { static let `default` = ColorProvider(colors: UIColor.brandColors) private let colors: [UIColor] init(colors: [UIColor]) { self.colors = colors } func color(for id: String) -> UIColor { return colors[abs(id.hash) % colors.count] } }
true
a8499c47f3d10279c67e37e82b2c67530757092a
Swift
CWood994/CrazyCoop
/day/Game/ButtonNode.swift
UTF-8
3,156
2.78125
3
[]
no_license
// // ButtonNode.swift // day // // Created by Benjamin Stammen on 11/7/16. // Copyright © 2016 Benjamin Stammen. All rights reserved. // import SpriteKit class ButtonNode : SKSpriteNode { private var selected = false override init(texture: SKTexture?, color: UIColor, size: CGSize) { super.init(texture: texture, color: color, size: size) self.initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initialize() } func initialize() { self.isUserInteractionEnabled = true } func buttonSeleted() { } func buttonDeselected() { } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.selected = true self.buttonSeleted() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: UITouch = touches.first! let location: CGPoint = touch.location(in: self.parent!) if !self.contains(location) { self.selected = false self.buttonDeselected() } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { if (self.selected) { self.selected = false self.buttonDeselected() self.buttonPressed() } } func buttonPressed() { debugPrint("Button press not overridden") } } class PauseButtonNode : ButtonNode { var gameScene : GameScene? override func initialize() { super.initialize() self.zPosition = GameConstants.LayerConstants.UILayer + 1 } override func buttonSeleted() { self.run(SKAction.scale(to: 1.5, duration: 0.05)) } override func buttonDeselected() { self.run(SKAction.scale(to: 2, duration: 0.05)) } override func buttonPressed() { if let game: GameScene = self.gameScene { if (game.showingMenu) { game.hideMenu() } else { game.showMenu() } } } } class RestartButtonNode : ButtonNode { var gameScene : GameScene? override func buttonSeleted() { self.run(SKAction.scale(to: 0.8, duration: 0.05)) } override func buttonDeselected() { self.run(SKAction.scale(to: 1, duration: 0.05)) } override func buttonPressed() { if let game: GameScene = self.gameScene { game.viewController.restartGame() } } } class MenuButtonNode : ButtonNode { var gameScene : GameScene? override func buttonSeleted() { self.run(SKAction.scale(to: 0.8, duration: 0.05)) } override func buttonDeselected() { self.run(SKAction.scale(to: 1, duration: 0.05)) } override func buttonPressed() { if let game: GameScene = self.gameScene { //game.viewController.AddNewGameToFirebase(score:score,streak:maxStreak) //TODO: call this line when game is over only game.viewController.exitGame() } } }
true
cb2d9448a921e90720da1678176f989e0bd79abc
Swift
lukaskasa/Eclipse
/Eclipse/Utilities/Extensions/String.swift
UTF-8
758
3.21875
3
[]
no_license
// // String.swift // Eclipse // // Created by Lukas Kasakaitis on 19.09.19. // Copyright © 2019 Lukas Kasakaitis. All rights reserved. // import Foundation extension String { /// Method used to return a readable date consisting of day and month func toReadableDate() -> String? { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" var calendar = Calendar(identifier: .gregorian) calendar.locale = Locale(identifier: "en_US_POSIX") guard let date = formatter.date(from: self) else { return nil } let day = calendar.component(.day, from: date) let month = calendar.component(.month, from: date) return "\(day) \(calendar.shortMonthSymbols[month - 1])" } }
true
9ba7789b2a7ae93b91d0bf7b2b04e110c7b64abd
Swift
sujindab/fmf
/findmyfriend/viewController/signUpViewController.swift
UTF-8
2,489
2.640625
3
[]
no_license
// // infoViewController.swift // findmyfriend // // Created by BIG on 9/11/2563 BE. // import UIKit import FirebaseAuth import FirebaseFirestore class signUpViewController: UIViewController { @IBOutlet weak var firstNameTextField: UITextField! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var signUpBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ // func validateFields() -> String? { // // if firstNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || emailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" || passwordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" { // // return "Please fill all field" // // } // // let cleanedPassword = passwordTextField.text!.trimmingCharacters(in:.whitespacesAndNewlines) // // // return nil // } @IBAction func signUpTap(_ sender: Any) { let firstname = firstNameTextField.text!.trimmingCharacters(in:.whitespacesAndNewlines) let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) let pass = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines) Auth.auth().createUser(withEmail: email, password: pass){ (result,err) in if err != nil { print(err) } else { let db = Firestore.firestore() db.collection("users").addDocument(data: ["username":firstname,"email":email,"password":pass,"uid":result!.user.uid]) {(error) in } self.transitionToHome() } } } func transitionToHome(){ let homeViewController = storyboard?.instantiateViewController(identifier: Constants.Storyboard.homeViewController) as? homeViewController view.window?.rootViewController = homeViewController view.window?.makeKeyAndVisible() } }
true
c9b5afe0999e65000fa2ef0d5a760331cc2a5f2c
Swift
eucboet9/GraphCalculator
/GraphCalculator/Evaluator/BinaryOperation.swift
UTF-8
628
3.046875
3
[]
no_license
// // BinaryOperation.swift // Parser // // Created by Руслан Тхакохов on 07.08.15. // Copyright (c) 2015 Руслан Тхакохов. All rights reserved. // import Foundation class BinaryOperation: Evaluatable { //abstract let left: Evaluatable? let right: Evaluatable? init(left: Evaluatable?, right: Evaluatable?) { self.left = left self.right = right } func evaluate(x: Number?, y: Number?, z: Number?) -> Number? { return calc(left?.evaluate(x, y: y, z: z), b: right?.evaluate(x, y: y, z: z)) } func calc(a: Number?, b: Number?) -> Number? { //abstract return nil } }
true
9c5c8720123118910ec54b9f535aa30408609b55
Swift
filiponegrao/GenteBoa
/GenteBoaBeta/DAOParse.swift
UTF-8
10,891
2.78125
3
[]
no_license
// // DAOParse.swift // GenteBoa // // Created by Filipo Negrao on 02/11/15. // Copyright © 2015 Filipo Negrao. All rights reserved. // import Foundation import Parse import UIKit private let data : DAOParse = DAOParse() class DAOParse { init() { } class var sharedInstance : DAOParse { return data } func getUsersWithString(string: String, callback: (results : [MetaPeople]) -> Void) -> Void { var info = [MetaPeople]() let query = PFUser.query() query?.whereKey("name", containsString: string) query?.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in if(objects != nil) { print("\(objects?.count) Usuarios encontrados") for object in objects! { let email = object.valueForKey("email") as! String let name = object.valueForKey("name") as! String let university = object.valueForKey("university") as! String let course = object.valueForKey("course") as! String let period = object.valueForKey("period") as! Int let photo = object["profileImage"] as! PFFile photo.getDataInBackgroundWithBlock({ (data: NSData?, error: NSError?) -> Void in if(data != nil) { let image = UIImage(data: data!) let people = MetaPeople(email: email, name: name, photo: image!, university: university, course: course, period: period) info.append(people) } else { print("Erro ao acarregar photo: \(error)") } if(object == objects!.last) { callback(results: info) } }) } callback(results: [MetaPeople]()) } }) } func getProfileImage(username: String, callback: (image: UIImage?) -> Void) -> Void { let query = PFUser.query() query?.whereKey("username", equalTo: username) query?.getFirstObjectInBackgroundWithBlock({ (user: PFObject?, error: NSError?) -> Void in if(user != nil) { let photo = user?.objectForKey("profileImage") as! PFFile photo.getDataInBackgroundWithBlock({ (data: NSData?, error: NSError?) -> Void in if(data != nil) { callback(image: UIImage(data: data!)!) } else { callback(image: nil) } }) } else { callback(image: nil) } }) } func getRandomUserDifferentFromGroup(group: [String], course: String?, callback: (people: People?) -> Void ) -> Void { let query = PFUser.query()! query.whereKey("email", notContainedIn: group) query.whereKey("username", notEqualTo: DAOUser.sharedInstance.getEmail()) query.whereKeyExists("university") query.whereKeyExists("course") query.whereKeyExists("period") query.whereKeyExists("about") if(course != nil) { let filter = course! query.whereKey("course", equalTo: filter) } query.findObjectsInBackgroundWithBlock({ (objects: [PFObject]?, error: NSError?) -> Void in print(objects?.count) if(objects != nil && objects?.count != 0) { // if(objects?.count == 1) // { // DAOPeople.sharedInstance.peopleSeen = [String]() // } let n = objects!.count let index = Int(arc4random_uniform(UInt32(n))) let object = objects![index] let email = object["email"] as! String let name = object["name"] as! String let university = object["university"] as! String let period = object["period"] as! Int let about = object["about"] as! String let hiscourse = object["course"] as! String print("selecionado \(name) de curso \(hiscourse) e curso desejado era \(course)") let photo = object["profileImage"] as! PFFile let feedbacks = PFQuery(className: "Feedbacks") feedbacks.whereKey("user", equalTo: object) feedbacks.findObjectsInBackgroundWithBlock({ (objects2: [PFObject]?, error2: NSError?) -> Void in var positivas = [Hashtag]() var negativas = [Hashtag]() if(objects2 != nil) { var palavrasPositivas = [String]() var palavrasNegativas = [String]() for object2 in objects2! { let positiva = object2["positives"] as! [String] let negativa = object2["negatives"] as! [String] palavrasPositivas += positiva palavrasNegativas += negativa } positivas = Hashtag.sintetizarHashtags(palavrasPositivas) negativas = Hashtag.sintetizarHashtags(palavrasNegativas) positivas = Hashtag.ordernarHashtags(positivas) negativas = Hashtag.ordernarHashtags(negativas) photo.getDataInBackgroundWithBlock({ (data: NSData?, error: NSError?) -> Void in let image = UIImage(data: data!)! let person = People(email: email, name: name, photo: image, university: university, course: hiscourse, period: period, about: about, positivas: positivas, negativas: negativas) callback(people: person) }) } }) } else { print("Usuario nao encontrado") callback(people: nil) } }) } func feedbackUser(username: String, positive: [String], negative: [String]) { let query = PFUser.query()! query.whereKey("username", equalTo: username) query.getFirstObjectInBackgroundWithBlock { (user: PFObject?, error: NSError?) -> Void in if(user != nil) { let feedback = PFObject(className: "Feedbacks") feedback["user"] = user feedback["positives"] = positive feedback["negatives"] = negative feedback.saveEventually() } } } func getUser(email: String, callback: (people: People?) -> Void) -> Void { let query = PFUser.query() query?.whereKey("email", equalTo: email) query?.whereKeyExists("university") query?.whereKeyExists("course") query?.whereKeyExists("period") query?.whereKeyExists("about") query?.getFirstObjectInBackgroundWithBlock({ (object: PFObject?, error: NSError?) -> Void in if(object != nil) { let email = object!["email"] as! String let name = object!["name"] as! String let university = object!["university"] as! String let period = object!["period"] as! Int let about = object!["about"] as! String let hiscourse = object!["course"] as! String let photo = object!["profileImage"] as! PFFile let feedbacks = PFQuery(className: "Feedbacks") feedbacks.whereKey("user", equalTo: object!) feedbacks.findObjectsInBackgroundWithBlock({ (objects2: [PFObject]?, error2: NSError?) -> Void in var positivas = [Hashtag]() var negativas = [Hashtag]() if(objects2 != nil) { var palavrasPositivas = [String]() var palavrasNegativas = [String]() for object2 in objects2! { let positiva = object2["positives"] as! [String] let negativa = object2["negatives"] as! [String] palavrasPositivas += positiva palavrasNegativas += negativa } positivas = Hashtag.sintetizarHashtags(palavrasPositivas) negativas = Hashtag.sintetizarHashtags(palavrasNegativas) positivas = Hashtag.ordernarHashtags(positivas) negativas = Hashtag.ordernarHashtags(negativas) photo.getDataInBackgroundWithBlock({ (data: NSData?, error: NSError?) -> Void in let image = UIImage(data: data!)! let person = People(email: email, name: name, photo: image, university: university, course: hiscourse, period: period, about: about, positivas: positivas, negativas: negativas) callback(people: person) }) } }) } else { callback(people: nil) } }) } }
true
6c82df350927b14f0ff996fcc7d58d414dc6984c
Swift
VirgilSecurity/virgil-sdk-pfs-x
/Source/Client/EphemeralCardValidator.swift
UTF-8
1,497
2.6875
3
[ "BSD-3-Clause" ]
permissive
// // EphemeralCardValidator.swift // VirgilSDKPFS // // Created by Oleksandr Deundiak on 6/15/17. // Copyright © 2017 VirgilSecurity. All rights reserved. // import Foundation import VirgilSDK class EphemeralCardValidator { let crypto: VSSCryptoProtocol private var verifiers: [String: VSSPublicKey] = [:] init(crypto: VSSCryptoProtocol) { self.crypto = crypto } func addVerifier(withId verifierId: String, publicKeyData: Data) throws { guard let publicKey = self.crypto.importPublicKey(from: publicKeyData) else { throw SecureChat.makeError(withCode: .importingVerifier, description: "Error importing verifier public key.") } self.verifiers[verifierId] = publicKey } func validate(cardResponse: VSSCardResponse) -> Bool { let fingerprint = self.crypto.calculateFingerprint(for: cardResponse.snapshot) let cardId = fingerprint.hexValue guard cardId == cardResponse.identifier else { return false } for verifier in self.verifiers { guard let signature = cardResponse.signatures[verifier.key], signature.count > 0 else { return false } do { try self.crypto.verify(fingerprint.value, withSignature: signature, using: verifier.value) } catch { return false } } return true } }
true
b89cabee0ffd31596bf63d9857ee02c32d807fea
Swift
JrGoodle/ElementsOfProgramming
/ElementsOfProgrammingTests/Chapter03Tests.swift
UTF-8
4,199
3.28125
3
[]
no_license
// // Chapter03Tests.swift // ElementsOfProgrammingTests // import XCTest import EOP class Chapter03Tests: XCTestCase { func testConceptBinaryOperation() { Concept.binaryOperation(op: minusInt, x: 7) Concept.binaryOperation(op: timesInt, x: 8) } func testPowerLeftAssociated() { // (-2 - -2) - -2 = 2 XCTAssert(powerLeftAssociated(-2, power: 3, operation: minusInt) == 2) // ((-2 - -2) - -2) - -2 = 4 XCTAssert(powerLeftAssociated(-2, power: 4, operation: minusInt) == 4) algorithmPower(pow: powerLeftAssociated) } func testPowerRightAssociated() { // -2 - (-2 - -2) = -2 XCTAssert(powerRightAssociated(-2, power: 3, operation: minusInt) == -2) // -2 - (-2 - (-2 - -2) = 0 XCTAssert(powerRightAssociated(-2, power: 4, operation: minusInt) == 0) algorithmPower(pow: powerRightAssociated) } func testPower_N() { algorithmPower(pow: power_0) algorithmPower(pow: power_1) algorithmPower(pow: power_2) algorithmPower(pow: power_3) } func testPowerAccumulate() { algorithmPowerAccumulate(pow: powerAccumulate_0) algorithmPowerAccumulate(pow: powerAccumulate_1) algorithmPowerAccumulate(pow: powerAccumulate_2) algorithmPowerAccumulate(pow: powerAccumulate_3) algorithmPowerAccumulate(pow: powerAccumulate_4) algorithmPowerAccumulatePositive(pow: powerAccumulatePositive_0) algorithmPowerAccumulate(pow: powerAccumulate_5) algorithmPowerAccumulatePositive(pow: powerAccumulatePositive) algorithmPowerAccumulate(pow: powerAccumulate) } func testPower() { algorithmPower(pow: power) algorithmPowerWithIdentity(pow: power) } func testConceptInteger() { typealias N = Int Concept.integer(n: 7) } func testFibonacci() { typealias N = Int typealias Fib = Pair<N, N> Concept.binaryOperation(op: fibonacciMatrixMultiply, x: Fib(m0: 1, m1: 0)) let f10 = Fib(m0: 55, m1: 34) let f11 = Fib(m0: 89, m1: 55) let f21 = fibonacciMatrixMultiply(x: f10, y: f11) XCTAssert(f21.m0 == 10946 && f21.m1 == 6765) XCTAssert(fibonacci(n: 10) == 55) XCTAssert(fibonacci(n: 20) == 6765) } func minusInt(a: Int, b: Int) -> Int { return a - b } func timesInt(a: Int, b: Int) -> Int { return a * b } func algorithmPower(pow: (Int, Int, BinaryOperation<Int>) -> Int) { XCTAssert(pow(1, 1, timesInt) == 1) XCTAssert(pow(10, 1, timesInt) == 10) XCTAssert(pow(1, 10, timesInt) == 1) XCTAssert(pow(2, 2, timesInt) == 4) XCTAssert(pow(2, 10, timesInt) == 1024) XCTAssert(pow(10, 2, timesInt) == 100) } func algorithmPowerAccumulate(pow: (Int, Int, Int, BinaryOperation<Int>) -> Int) { XCTAssert(pow(1, 99, 1, timesInt) == 99 * 1) XCTAssert(pow(10, 99, 1, timesInt) == 99 * 10) XCTAssert(pow(1, 99, 10, timesInt) == 99 * 1) XCTAssert(pow(2, 99, 2, timesInt) == 99 * 4) XCTAssert(pow(2, 99, 10, timesInt) == 99 * 1024) XCTAssert(pow(10, 99, 2, timesInt) == 99 * 100) XCTAssert(pow(1, 99, 0, timesInt) == 99) } func algorithmPowerAccumulatePositive(pow: (Int, Int, Int, BinaryOperation<Int>) -> Int) { XCTAssert(pow(1, 99, 1, timesInt) == 99 * 1) XCTAssert(pow(10, 99, 1, timesInt) == 99 * 10) XCTAssert(pow(1, 99, 10, timesInt) == 99 * 1) XCTAssert(pow(2, 99, 2, timesInt) == 99 * 4) XCTAssert(pow(2, 99, 10, timesInt) == 99 * 1024) XCTAssert(pow(10, 99, 2, timesInt) == 99 * 100) } func algorithmPowerWithIdentity(pow: (Int, Int, BinaryOperation<Int>, Int) -> Int) { XCTAssert(pow(1, 1, timesInt, 1) == 1) XCTAssert(pow(10, 1, timesInt, 1) == 10) XCTAssert(pow(1, 10, timesInt, 1) == 1) XCTAssert(pow(2, 2, timesInt, 1) == 4) XCTAssert(pow(2, 10, timesInt, 1) == 1024) XCTAssert(pow(10, 2, timesInt, 1) == 100) XCTAssert(pow(1, 0, timesInt, 1) == 1) XCTAssert(pow(1, 0, timesInt, 99) == 99) } }
true
75dcdd81a04e0996904a15553e36c822dff4fe34
Swift
pablosanchez027/Movie-Finder
/Movie-Finder/SearchResultsViewController.swift
UTF-8
2,691
2.609375
3
[]
no_license
// // SearchResultsViewController.swift // Movie-Finder // // Created by Alumno on 25/10/18. // Copyright © 2018 Pablo. All rights reserved. // import Foundation import UIKit import Alamofire import AlamofireImage class SearchResultsViewController: UIViewController { var urlAPI : String = "https://www.omdbapi.com/?apikey=5aec3ba9&i=" var movieURL: String = "" @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var lblAño: UILabel! @IBOutlet weak var lblDirector: UILabel! @IBOutlet weak var lblDuracion: UILabel! @IBOutlet weak var lblRating: UILabel! @IBOutlet weak var lblGenero: UILabel! @IBOutlet weak var imgPoster: UIImageView! var movie: DatosSearchRequest? override func viewDidLoad() { super.viewDidLoad() if let movieSeleccionada = movie { movieURL = "\(urlAPI)" + movieSeleccionada.movieimdbID Alamofire.request(movieURL).responseJSON { response in if let diccionarioRespuesta = response.result.value as? NSDictionary { if let movieTitle = diccionarioRespuesta.value(forKey: "Title") as? String { self.lblTitle.text = movieTitle } if let movieAño = diccionarioRespuesta.value(forKey: "Year") as? String { self.lblAño.text = movieAño } if let movieDirector = diccionarioRespuesta.value(forKey: "Director") as? String { self.lblDirector.text = movieDirector } if let movieDuracion = diccionarioRespuesta.value(forKey: "Runtime") as? String { self.lblDuracion.text = movieDuracion } if let movieRating = diccionarioRespuesta.value(forKey: "Metascore") as? String { self.lblRating.text = movieRating } if let movieGenero = diccionarioRespuesta.value(forKey: "Genre") as? String { self.lblGenero.text = movieGenero } if let moviePosterURL = diccionarioRespuesta.value(forKey: "Poster") as? String { Alamofire.request(moviePosterURL).responseImage { response in self.imgPoster.image = response.result.value } } } } } } @IBAction func tapBack(_ sender: Any) { self.dismiss(animated: true, completion: nil) } }
true
38cdb419bc8c9801447efed9c03a84d6c58a52b9
Swift
shaomin4896/walking_support
/Siri/Firestore/FirebaseIO.swift
UTF-8
548
2.796875
3
[ "MIT" ]
permissive
import UIKit import Firebase class FirebaseIO: NSObject { func addnew(username:String!,faceID:String! ,completion:@escaping () -> ()){ let data = ["username": username ] db.collection("userList").document(faceID).setData([ "username": username, "latitude": lati, "longitude": long ]) { (error) in if let error = error { print(error) }else{ print("Document added with ID:") } } completion() } }
true
71a4aa5187918efae0d78c28cc7b0c5a693ef3af
Swift
rastersize/BungieNetAPI
/Sources/Models/DestinyDefinitionsDestinyActivityRewardDefinition.swift
UTF-8
2,369
2.984375
3
[]
no_license
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation /** Activities can refer to one or more sets of tooltip-friendly reward data. These are the definitions for those tooltip friendly rewards. */ public struct DestinyDefinitionsDestinyActivityRewardDefinition: APIModel { /** The "Items provided" in the reward. This is almost always a pointer to a DestinyInventoryItemDefintion for an item that you can't actually earn in-game, but that has name/description/icon information for the vague concept of the rewards you will receive. This is because the actual reward generation is non-deterministic and extremely complicated, so the best the game can do is tell you what you'll get in vague terms. And so too shall we. Interesting trivia: you actually *do* earn these items when you complete the activity. They go into a single-slot bucket on your profile, which is how you see the pop-ups of these rewards when you complete an activity that match these "dummy" items. You can even see them if you look at the last one you earned in your profile-level inventory through the BNet API! Who said reading documentation is a waste of time? */ public var rewardItems: [DestinyDestinyItemQuantity]? /** The header for the reward set, if any. */ public var rewardText: String? public init(rewardItems: [DestinyDestinyItemQuantity]? = nil, rewardText: String? = nil) { self.rewardItems = rewardItems self.rewardText = rewardText } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: StringCodingKey.self) rewardItems = try container.decodeArrayIfPresent("rewardItems") rewardText = try container.decodeIfPresent("rewardText") } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: StringCodingKey.self) try container.encodeIfPresent(rewardItems, forKey: "rewardItems") try container.encodeIfPresent(rewardText, forKey: "rewardText") } public static func == (lhs: DestinyDefinitionsDestinyActivityRewardDefinition, rhs: DestinyDefinitionsDestinyActivityRewardDefinition) -> Bool { guard lhs.rewardItems == rhs.rewardItems else { return false } guard lhs.rewardText == rhs.rewardText else { return false } return true } }
true
c535cff321d088c0e2730326bc03efc2872ed9c0
Swift
WonderTommy/Ace_the_Term_SwiftUI
/GradeCalculator/Utility/NumberStringFilter.swift
UTF-8
674
3.21875
3
[]
no_license
// // NumberStringFilter.swift // GradeCalculator // // Created by Hao Li on 2020-08-15. // Copyright © 2020 Hao Li. All rights reserved. // import Foundation class NumberStringFilter: ObservableObject { @Published var value: String { didSet { let filteredValue = value.filter { $0.isNumber || $0 == "." } if value != filteredValue { value = filteredValue } } } init() { value = "" } init(value: Double) { self.value = String(value) } public func getValueByDouble() -> Double { return Double(self.value) ?? 0.0 } }
true
e144b84ccee30cab53f87b7072b8da50212241f1
Swift
convalida/FoodyPOS-iOS
/FoodyPOS/Model/UserManager.swift
UTF-8
5,139
2.78125
3
[]
no_license
// // UserManager.swift // FoodyPOS // // Created by Tutist Dev on 09/08/18. // Copyright © 2018 com.tutist. All rights reserved. // import Foundation ///Class for saving and retrieving data used throughout the project. class UserManager { /** Method to save data to UserDefaults using User.swift class. If userName, isActive, restaurantID, tax, restaurantName, role in User class is not null, set userName, isActive, restaurantID, tax, restaurantName, role to values of User.swift class. If value of role is Manager, set isManager to true, else set isManager to false. */ static func saveUserDataIntoDefaults(user:User) { if let userName = user.userName { self.userName = userName } if let isActive = user.isActive { self.isActive = isActive } if let restaurantID = user.restaurantID { self.restaurantID = restaurantID } if let tax = user.tax { self.tax = tax } if let restaurentName = user.restaurentName { self.restaurentName = restaurentName } if let role = user.role { self.role = role if role == "Manager" { self.isManager = true }else { self.isManager = false } } if let acctId = user.acctId{ self.acctId=acctId } } public static var acctId:String? { set(newValue){ UserDefaults.standard.setValue(newValue, forKey: "acctId") } get{ return UserDefaults.standard.value(forKey: "acctId") as? String } } /// Get and set userName public static var userName:String? { set(newValue) { UserDefaults.standard.setValue(newValue, forKey: "userName") } get { return UserDefaults.standard.value(forKey: "userName") as? String } } /// Get and set isActive status public static var isActive:String? { set(newValue) { UserDefaults.standard.setValue(newValue, forKey: "isActive") } get { return UserDefaults.standard.value(forKey: "isActive") as? String } } /// Get and set restaurantID public static var restaurantID:String? { set(newValue) { UserDefaults.standard.setValue(newValue, forKey: "restaurantID") } get { return UserDefaults.standard.value(forKey: "restaurantID") as? String } } /// Get and set tax public static var tax:String? { set(newValue) { UserDefaults.standard.setValue(newValue, forKey: "tax") } get { return UserDefaults.standard.value(forKey: "tax") as? String } } /// Get and set restaurentName public static var restaurentName:String? { set(newValue) { UserDefaults.standard.setValue(newValue, forKey: "restaurentName") } get { return UserDefaults.standard.value(forKey: "restaurentName") as? String } } /// Get and set role public static var role:String? { set(newValue) { UserDefaults.standard.setValue(newValue, forKey: "role") } get { return UserDefaults.standard.value(forKey: "role") as? String } } /// Get and set isRemember public static var isRemember:Bool { set(newValue) { UserDefaults.standard.set(newValue, forKey: "isRemember") } get { return UserDefaults.standard.bool(forKey: "isRemember") } } /// Get and set email public static var email:String? { set(newValue) { UserDefaults.standard.setValue(newValue, forKey: "email") } get { return UserDefaults.standard.value(forKey: "email") as? String } } /// Get and set password public static var password:String? { set(newValue) { UserDefaults.standard.setValue(newValue, forKey: "password") } get { return UserDefaults.standard.value(forKey: "password") as? String } } /// Get and set isManager public static var isManager:Bool { set(newValue) { UserDefaults.standard.set(newValue, forKey: "isManager") } get { return UserDefaults.standard.bool(forKey: "isManager") } } /// Get and set isLogin public static var isLogin:Bool { set(newValue) { UserDefaults.standard.set(newValue, forKey: "isLogin") } get { return UserDefaults.standard.bool(forKey: "isLogin") } } ///Get and set token public static var token:String? { set(newValue) { UserDefaults.standard.setValue(newValue, forKey: "token") } get { return UserDefaults.standard.value(forKey: "token") as? String } } }
true
802e4f3f9216852bb3ff72e800074e109dbf4d47
Swift
logeshvijayan/Login_Mockup
/Login Model/Login Model/View Controller/ViewController.swift
UTF-8
1,196
2.671875
3
[]
no_license
// // ViewController.swift // Login Model // // Created by logesh on 12/13/19. // Copyright © 2019 logesh. All rights reserved. // import UIKit //MARK: - Class class ViewController: UIViewController { //MARK: - Outlets and Action @IBOutlet weak var backGround: UIImageView! @IBOutlet weak var userName: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var confrimPasswordTextField: UITextField! @IBOutlet weak var saveButton: UIButton! @IBOutlet weak var tabBar: UITabBar! //MARK: - Class Instances let KeyChain : KeyChainModel = KeyChainModel() @IBAction func saveButton(_ sender: Any) { if passwordTextField.text == confrimPasswordTextField.text && userName.text != " " { KeyChain.saveUserCredentials(userName: userName.text!, password: passwordTextField.text!) } } override func viewDidLoad() { super.viewDidLoad() } } extension ViewController : UITextFieldDelegate{ func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
true
5f960dc4e4e8c699569720c269e67c84cbb3ee8f
Swift
dronchekk/dz-swift
/dz1 Rachitskiy/dz1 Rachitskiy/main.swift
UTF-8
1,728
3.265625
3
[]
no_license
// // main.swift // dz1 Rachitskiy // // Created by Andrey rachitsky on 13.09.2021. // import Foundation //MARK: - Задача нумеро уно let firstParametr:Double = 1 let secondParametr:Double = 0 let thirdParametr:Double = -6 let discriminant = secondParametr * secondParametr - 4 * firstParametr * thirdParametr let korenPartFirst = pow(discriminant,0.5) - secondParametr let korenPartSecond = 0 - secondParametr - pow(discriminant,0.5) let korenPartThird = 2 * firstParametr let korenFirst = korenPartFirst/korenPartThird let korenSecond = korenPartSecond/korenPartThird if discriminant > 0 { print("V yravnenii 2 kornya") print("Perviy koren \(korenFirst)") print("Vtoroi koren \(korenSecond)") } else if discriminant == 0 { print("V yravnenii 1 koren") print("koren \(korenFirst)") // print("koren \(korenSecond)") проверка на вшивость } else { print("No solutions") } //MARK: -Задача нумеро дос let firstKatet:Double = 6 let secondKatet:Double = 8 let triangleSquare = (firstKatet * secondKatet)/2 let triangleHypotenuse = pow((firstKatet * firstKatet + secondKatet * secondKatet),0.5) let trianglePerimeter = triangleHypotenuse + firstKatet + secondKatet print("Ploshad treygolnika = \(triangleSquare)") print("Gipotenuza treygolnika = \(triangleHypotenuse)") print("Perimetr treygolnika = \(trianglePerimeter)") //MARK: -Задача нумеро трез let summaVklada: Double = 1000 let godovoiProcent: Double = 6/100/12 let kolichestvoMecyacev: Array<Int> = [1,2,3,4,5] var doxod = summaVklada for _ in kolichestvoMecyacev { doxod = doxod + doxod * godovoiProcent } print("Vash doxod pocle vklada v bank na 5 let sostavit \(doxod-summaVklada)")
true
833f95d735d9f46a4e05386b11c1ef94062c9585
Swift
code-guy21/TeamMoney
/MangoHacks/MangoHacks/MenuBar.swift
UTF-8
2,268
2.609375
3
[]
no_license
// // MenuBar.swift // MangoHacks // // Created by Miguel Chavez on 2/25/17. // Copyright © 2017 Miguel Chavez. All rights reserved. // import LBTAComponents import UIKit class MenuBar: DatasourceCell { override var datasourceItem: Any?{ didSet{ } } //here we make a lable for the name Red let statusLabel: UILabel = { let label = UILabel() label.text = "We all need alot of good ass Beer" label.font = UIFont.systemFont(ofSize: 16) // label.backgroundColor = .red return label }() //this make a spot for the image in the twitter app Blue let profileImageView: UIImageView = { let imageView = UIImageView() imageView.image = #imageLiteral(resourceName: "Miguel") imageView.layer.cornerRadius = 20 imageView.layer.masksToBounds = true imageView.clipsToBounds = true // imageView.layer.cornerRadius = 25 // imageView.layer.masksToBounds = true; imageView.layer.borderWidth = 2.0 imageView.layer.borderColor = UIColor.blue.cgColor // imageView.backgroundColor = .blue return imageView }() override func setupViews() { super.setupViews() let blackBackgroundView = UIView() blackBackgroundView.backgroundColor = .black //addSubview(blackBackgroundView) //separatorLineView.isHidden = false //separatorLineView.backgroundColor = UIColor(r: 0, g: 0, b: 0) // all the subareas in the cell (add JmenuItem to JmenuBar) addSubview(statusLabel) addSubview(profileImageView) //profileImage Blue profileImageView.anchor(self.topAnchor, left: self.leftAnchor, bottom: nil, right: nil, topConstant: 1, leftConstant: 10, bottomConstant: 0, rightConstant: 0, widthConstant: 40, heightConstant: 40) //statusLable Red statusLabel.anchor(profileImageView.topAnchor, left: profileImageView.rightAnchor, bottom: nil, right: self.rightAnchor, topConstant: 10, leftConstant: 15 , bottomConstant: 0, rightConstant: 0, widthConstant: 150, heightConstant: 20) } }
true
287c8a364e07554a6ff68ffd105feea4782c1567
Swift
AntiPavel/bow
/Tests/BowTests/Data/ResultTest.swift
UTF-8
935
2.921875
3
[ "Apache-2.0" ]
permissive
import XCTest import SwiftCheck @testable import Bow enum ResultError: Int, Error { case warning case fatal case unknown } class ResultTest: XCTestCase { func generateEither(_ x: Int) -> Either<ResultError, Int> { return x % 2 == 0 ? Either.left(.warning): Either.right(x) } func generateValidated(_ x: Int) -> Validated<ResultError, Int> { return x % 2 == 0 ? Validated.invalid(.fatal) : Validated.valid(x) } func testResultEitherIsomorphism() { property("Either and Result are isomorphic") <- forAll { (x: Int) in return self.generateEither(x).toResult().toEither() == self.generateEither(x) } } func testResultValidateIsomorphism() { property("Validated and Result are isomorphic") <- forAll { (x: Int) in return self.generateValidated(x).toResult().toValidated() == self.generateValidated(x) } } }
true
489f263497d9ce4388d51f26c987c40e0dd068d8
Swift
dmytrostriletskyi/DOU
/DOU/Articles/AttributedUIViews/ArticleEmbedYoutubeVideoAttributedUIView.swift
UTF-8
2,717
2.734375
3
[]
no_license
import Foundation import SwiftUI import Atributika class ArticleEmbedYoutubeVideoAttributedUIView { let url: URL private var attributedLabel: AttributedLabel private let style = Style_() init(url: URL) { self.url = url let youtubeVideoIdentifier: String = url.absoluteString.components(separatedBy: "/").last! let html = "<p>Вiдео: <a href=\"https://www.youtube.com/watch?v=\(youtubeVideoIdentifier)\" target=\"_blank\">https://www.youtube.com/watch?v=\(youtubeVideoIdentifier)</a><p>" let attributedLabel = AttributedLabel() attributedLabel.numberOfLines = 0 let all = Style.font( .systemFont( ofSize: style.textSize ) ) let paragraph = Style( "p" ).baselineOffset( style.paragraphLineSPacing ).obliqueness( style.emphasizedTextObliqueness ).foregroundColor(.gray) let link = Style("a").foregroundColor( style.linkColor, .normal ).foregroundColor( .brown, .highlighted ).underlineStyle( style.linkUnderlineStyle ) let tags = [ all, paragraph, link ] let attributedText = html.style(tags: tags).styleAll(all) attributedLabel.attributedText = attributedText attributedLabel.onClick = { _, detection in switch detection.type { case .tag(let tag): if let href = tag.attributes["href"] { if let url = URL(string: href) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } default: break } } self.attributedLabel = attributedLabel } func get() -> AttributedLabel { return self.attributedLabel } func getHeight() -> CGFloat { let screenWidth = CGFloat(UIScreen.main.bounds.size.width) let attributedLabelSize = self.attributedLabel.sizeThatFits( CGSize(width: screenWidth - 40, height: CGFloat.greatestFiniteMagnitude) ) return attributedLabelSize.height } struct Style_ { let emphasizedTextObliqueness: Float = 0.24 let textSize: CGFloat = 16 let paragraphLineSPacing: Float = 2 let linkColor: Atributika.Color = Atributika.Color(red: 0.09, green: 0.46, blue: 0.67, alpha: 1.00) let linkUnderlineStyle = NSUnderlineStyle.single let telegramRegerenceColor = #colorLiteral(red: 0.9032747149, green: 0.9623904824, blue: 0.9787710309, alpha: 1) } }
true
1d76e6ee7a8c9bac930132597bc2a6c37181d885
Swift
LeTarrask/Exercises
/Exercises/Views/KenzoView.swift
UTF-8
1,953
2.9375
3
[]
no_license
//// //// KenzoView.swift //// Exercises //// //// Created by Alex Luna on 25/02/2021. //// // //import SwiftUI // //// https://www.instagram.com/p/CLou6OKgZbz/ //// copiei o código do post, mas esta view precisa de vários outros views internos. pode ser um exercício construir todas elas. // //struct KenzoView: View { // // @State var selected = colorData // @State var isBlue = false // @State var checkout = false // @State var selectedSize = 0 // // var body: some View { // ZStack(alignment: .bottom) { // content // .navigationBarTitle("Beach Slipers", displayMode: .inline) // .overlay(BottomBar(checkout: $checkout) // .opacity(checkout ? 0 : 1 ), alignment: .bottom) // VisualEffectBlur(blurStyle: .systemUltraThinMaterial) // .edgesIgnoringSafeArea(.all) // .opacity(checkout ? 1 : 0) // .onTapGesture{ checkout.toggle() } // if checkout { // CheckoutView(checkout: $checkout) // .transition(.moveAndFade) // .animation(.easeInOut(duration: 0.7)) // } // } // } // // var content: some View { // ScrollView { // StretchingHeader { // ProductionAsset(isBlue: $isBlue) // } // VStack(alignment: .leading, spacing: 20) { // ProductSize(selectedSize: $selectedSize) // ProductPrice() // HStack(spacing: 15) { // ForEach(selected.indices) { item in // CirclePickerView(selected: selected[item], isBlue: $isBlue) // } // } // Spacer() // }.padding() // } // } //} // //struct KenzoView_Previews: PreviewProvider { // static var previews: some View { // KenzoView() // } //}
true
ab7447486a6ad048befdc2c2f9ff182efee9a7fa
Swift
wayni208/SFSafeSymbols
/Tests/SFSafeSymbolsTests/SwiftUI/SwiftUILabelExtensionTests.swift
UTF-8
891
2.578125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
@testable import SFSafeSymbols #if !os(watchOS) import XCTest #if canImport(SwiftUI) import SwiftUI class LabelExtensionTests: XCTestCase { /// Tests, whether the `Label` retrieved via SFSafeSymbols can be retrieved without a crash func testInit() { if #available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) { for symbol in TestHelper.allSymbolsWithVariants { print("Testing validity of \"\(symbol.rawValue)\" via Label init") // If this doesn't crash, everything works fine _ = Label("Title", systemSymbol: symbol) } } else { print("To test the Label initializer, iOS 14, macOS 11.0 or tvOS 14 is required.") } } } #else class JustFail: XCTestCase { func justFail() { XCTFail("SwiftUI should be available when testing.") } } #endif #endif
true
4a3517d559e7e94ad60a6a975e1cca25a957fa3b
Swift
ReemKatmeh/On-The_Map
/on the map/TableVCell.swift
UTF-8
592
2.640625
3
[]
no_license
// // TableVCell.swift // on the map // // Created by reem katmeh on 28/02/2019 // Copyright © 2019 reemkt. All rights reserved. // import Foundation import UIKit class TableVCell : UITableViewCell { @IBOutlet weak var fullNameLabel: UILabel! @IBOutlet weak var mediaURL: UILabel! var locationData: StudentLocation? { didSet { updateUI() } } func updateUI() { fullNameLabel.text = "\(locationData?.firstName ?? " ") \(locationData?.lastName ?? " ")" mediaURL.text = "\(locationData?.mediaURL ?? " ")" } }
true
8452ab912897c1c88bc0a16345dacdec33596e6c
Swift
no4aTuk/experimentalProject
/Common/Common/Utils/FontConfig.swift
UTF-8
2,556
2.828125
3
[]
no_license
// // FontConfig.swift // Common // // Created by itsmuffintime on 09.02.2020. // Copyright © 2020 itsmuffintime. All rights reserved. // import Foundation import UIKit public class FontConfigItem: Codable { var type: AppFontType = .regular var size: CGFloat = 10.0 var font: UIFont { switch type { case .regular: return .systemFont(ofSize: size)//.systemFont(ofSize: fontSize, weight: .regular) case .bold: return .boldSystemFont(ofSize: size) case .italic: return .italicSystemFont(ofSize: size) case .medium: return .systemFont(ofSize: size, weight: .medium) } //return UIFont(name: self.rawValue, size: fontSize) ?? UIFont.systemFont(ofSize: fontSize) } } public enum AppFontType: String, Codable { case regular case bold case italic case medium // var fontSize: CGFloat { // switch self { // case .regular: return 16 // case .bold: return 20 // case .italic: return 18 // case .medium: return 17 // } // } // // var font: UIFont { // switch self { // case .regular: return .systemFont(ofSize: fontSize)//.systemFont(ofSize: fontSize, weight: .regular) // case .bold: return .boldSystemFont(ofSize: fontSize) // case .italic: return .italicSystemFont(ofSize: fontSize) // case .medium: return .systemFont(ofSize: fontSize, weight: .medium) // } // //return UIFont(name: self.rawValue, size: fontSize) ?? UIFont.systemFont(ofSize: fontSize) // } } //TODO think about enum FontConfigEnum { case titleFont case subTitleFont case descriptionFont } extension UIFont { static func appFont(fontType: FontConfigEnum) -> UIFont { switch fontType { case .titleFont: return ThemeManager.shared.fontConfig.titleFont.font case .subTitleFont: return ThemeManager.shared.fontConfig.subTitleFont.font case .descriptionFont: return ThemeManager.shared.fontConfig.descriptionFont.font } } } //END TODO think about public class FontConfig: Codable { public var titleFont: FontConfigItem = .init() public var subTitleFont: FontConfigItem = .init() public var descriptionFont: FontConfigItem = .init() public static func loadConfig() -> FontConfig { do { let resourceURL = Bundle.main.url(forResource: "font_config", withExtension: "plist")! let data = try Data(contentsOf: resourceURL) //return try JSONDecoder().decode(FontConfig.self, from: data) return try PropertyListDecoder().decode(FontConfig.self, from: data) } catch { fatalError("Error load config") } } }
true
478ba94b50a7ad8baaf5deade5548ecc5db2c751
Swift
AlexGozhulovsky/GasStations
/gaSPopularity/Extensions/UIViewController+Alert.swift
UTF-8
584
2.5625
3
[]
no_license
// // GasStationsViewController.swift // gaSPopularity // // Created by Oleksandr Hozhulovskyi on 07.11.2020. // import UIKit protocol ErrorShowable { func showError(_ errorString: String) } extension ErrorShowable where Self: UIViewController { func showError(_ errorString: String) { let alert = UIAlertController(title: "Error", message: errorString, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel)) present(alert, animated: true) } }
true
93b500dc3a529e87892f00555cf8170e02510a3a
Swift
kyaing/KDYDemo
/KDYDemo/KDYDemo/Swift/Base_Swift/MyPlayground.playground/Pages/Inheritance Page.xcplaygroundpage/Contents.swift
UTF-8
1,174
4.125
4
[]
no_license
//: [Previous](@previous) import Foundation var str = "Hello, Inheritance" class Vehicle { var currentSpeed = 0.0 var description: String { return "traveling at \(currentSpeed) miles per hour" } func makeNoise() { //什么也不做-因为车辆不一定会有噪音 } } let someVehicle = Vehicle() print("Vehicle: \(someVehicle.description)") class Bicyle: Vehicle { var hasBasket = false } let bicyle = Bicyle() bicyle.hasBasket = true class Tandem: Bicyle { var currentNumberOfPassengers = 0 //重写方法 override func makeNoise() { print("Not make nosise") } } class Car: Vehicle { var gear = 1 //重写属性 override var description: String { return super.description + " in gear \(gear)" } } let car = Car() car.currentSpeed = 25 car.gear = 3 print("Car: \(car.description)") class AutomaticCar: Car { override var currentSpeed: Double { didSet { gear = Int(currentSpeed / 10.0) + 1 } } } let automatiCar = AutomaticCar() automatiCar.currentSpeed = 35 print("AutomaticCar: \(automatiCar.description)") //: [Next](@next)
true
59064fdc55645dbb06d9229e71855391eaad4369
Swift
mattgallagher/CwlViews
/Sources/CwlViews/Core/Utilities/CwlPreferredFonts.swift
UTF-8
3,681
2.640625
3
[ "ISC" ]
permissive
// // CwlPreferredFonts.swift // CwlUtils // // Created by Matt Gallagher on 11/3/19. // Copyright © 2019 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any purpose with or without // fee is hereby granted, provided that the above copyright notice and this permission notice // appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS // SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE // AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, // NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE // OF THIS SOFTWARE. // #if os(iOS) import UIKit @available(iOSApplicationExtension 8.2, *) public extension UIFont { static func preferredFont(forTextStyle style: UIFont.TextStyle, weight: UIFont.Weight = .regular, slant: Float = 0) -> UIFont { let base = UIFontDescriptor.preferredFontDescriptor(withTextStyle: style) let traits: [UIFontDescriptor.TraitKey: Any] = [.weight: weight, .slant: slant] let modified = base.addingAttributes([.traits: traits]) return UIFont(descriptor: modified, size: 0) } } public func preferredFontSize(forTextStyle style: UIFont.TextStyle) -> CGFloat { return UIFontDescriptor.preferredFontDescriptor(withTextStyle: style).pointSize } #endif #if os(macOS) import AppKit @available(OSXApplicationExtension 10.11, *) public extension NSFont { enum TextStyle { case controlContent case label case menu case menuBar case message case monospacedDigit case palette case system case titleBar case toolTips } enum TextSize { case controlMini case controlRegular case controlSmall case label case points(CGFloat) case system case title1 case title2 } static func preferredFont(forTextStyle style: TextStyle, size: TextSize = .system, weight: NSFont.Weight = .regular, slant: CGFloat = 0) -> NSFont { let pointSize: CGFloat switch size { case .controlMini: pointSize = NSFont.systemFontSize(for: .mini) case .controlRegular: pointSize = NSFont.systemFontSize(for: .regular) case .controlSmall: pointSize = NSFont.systemFontSize(for: .small) case .label: pointSize = NSFont.labelFontSize case .points(let other): pointSize = other case .system: pointSize = NSFont.systemFontSize case .title1: pointSize = NSFont.systemFontSize + 5 case .title2: pointSize = NSFont.systemFontSize + 2 } let base: NSFont switch style { case .controlContent: base = NSFont.controlContentFont(ofSize: pointSize) case .label: base = NSFont.labelFont(ofSize: pointSize) case .menu: base = NSFont.menuFont(ofSize: pointSize) case .menuBar: base = NSFont.menuBarFont(ofSize: pointSize) case .message: base = NSFont.messageFont(ofSize: pointSize) case .monospacedDigit: base = NSFont.monospacedDigitSystemFont(ofSize: pointSize, weight: weight) case .palette: base = NSFont.paletteFont(ofSize: pointSize) case .system: base = NSFont.systemFont(ofSize: pointSize) case .titleBar: base = NSFont.titleBarFont(ofSize: pointSize) case .toolTips: base = NSFont.toolTipsFont(ofSize: pointSize) } let traits: [NSFontDescriptor.TraitKey: Any] = [.weight: weight, .slant: slant] let modified = base.fontDescriptor.addingAttributes([.traits: traits]) return NSFont(descriptor: modified, size: 0) ?? base } } #endif
true
7b53eb7a505b3abbecd4c018176506652b5b37af
Swift
lamantin-group/yandex-checkout-payments-swift
/YandexCheckoutPayments/Private/Atomic Design/Molecules/ItemViews/IconItemView/IconItemView.swift
UTF-8
6,240
2.65625
3
[ "MIT" ]
permissive
import UIKit /// Simple multiline text and icon View final class IconItemView: UIView { /// Textual content var title: String { set { titleLabel.styledText = newValue } get { return titleLabel.styledText ?? "" } } /// Icon content var icon: UIImage { set { iconView.image = newValue } get { return iconView.image } } /// Badge image var badge: UIImage? { set { badgeImageView.image = newValue badgeImageView.isHidden = newValue == nil } get { return badgeImageView.image } } let titleLabel: UILabel = { $0.setStyles(UILabel.DynamicStyle.body, UILabel.Styles.doubleLine) return $0 }(UILabel()) let iconView: IconView = { $0.imageView.setStyles(UIImageView.Styles.dynamicSize) return $0 }(IconView()) private(set) lazy var badgeImageView: UIImageView = { $0.setStyles(UIImageView.Styles.badge) $0.isHidden = true return $0 }(UIImageView()) private var activeConstraints: [NSLayoutConstraint] = [] // MARK: - Initializers required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } override init(frame: CGRect) { super.init(frame: frame) setupView() } deinit { unsubscribeFromNotifications() } // MARK: - Setup view private func setupView() { backgroundColor = .clear layoutMargins = UIEdgeInsets(top: Space.double, left: Space.double, bottom: Space.double, right: Space.double) subscribeOnNotifications() setupSubviews() setupConstraints() } private func setupSubviews() { let subviews: [UIView] = [ iconView, badgeImageView, titleLabel, ] subviews.forEach { $0.translatesAutoresizingMaskIntoConstraints = false self.addSubview($0) } } private func setupConstraints() { NSLayoutConstraint.deactivate(activeConstraints) if UIApplication.shared.preferredContentSizeCategory.isAccessibilitySizeCategory { activeConstraints = [ iconView.top.constraint(equalTo: topMargin), iconView.leading.constraint(equalTo: leadingMargin), iconView.trailing.constraint(lessThanOrEqualTo: trailingMargin), titleLabel.leading.constraint(equalTo: leadingMargin), titleLabel.trailing.constraint(equalTo: trailingMargin), titleLabel.bottom.constraint(equalTo: bottomMargin), titleLabel.top.constraint(equalTo: iconView.bottom, constant: Space.double), ] } else { activeConstraints = [ iconView.top.constraint(greaterThanOrEqualTo: topMargin), iconView.bottom.constraint(lessThanOrEqualTo: bottomMargin), titleLabel.bottom.constraint(lessThanOrEqualTo: bottomMargin), titleLabel.top.constraint(greaterThanOrEqualTo: topMargin), titleLabel.centerY.constraint(equalTo: centerY), iconView.centerY.constraint(equalTo: centerY), iconView.leading.constraint(equalTo: leadingMargin), titleLabel.leading.constraint(equalTo: iconView.trailing, constant: Space.double), titleLabel.trailing.constraint(equalTo: trailingMargin), ] let lowPriorityConstraints: [NSLayoutConstraint] = [ iconView.top.constraint(equalTo: topMargin), iconView.bottom.constraint(equalTo: bottomMargin), titleLabel.top.constraint(equalTo: topMargin), titleLabel.bottom.constraint(equalTo: bottomMargin), ] titleLabel.setContentHuggingPriority(.required, for: .vertical) titleLabel.setContentCompressionResistancePriority(.required, for: .vertical) titleLabel.setContentHuggingPriority(.required, for: .horizontal) iconView.setContentHuggingPriority(.required, for: .vertical) iconView.setContentCompressionResistancePriority(.required, for: .vertical) iconView.setContentHuggingPriority(.required, for: .horizontal) iconView.setContentCompressionResistancePriority(.required, for: .horizontal) lowPriorityConstraints.forEach { $0.priority = .highest } activeConstraints += lowPriorityConstraints } activeConstraints += [ iconView.width.constraint(equalTo: iconView.height), badgeImageView.bottom.constraint(equalTo: iconView.bottom, constant: Space.single), badgeImageView.trailing.constraint(equalTo: iconView.trailing, constant: Space.single), ] NSLayoutConstraint.activate(activeConstraints) } // MARK: - Accessibility @objc private func accessibilityReapply() { titleLabel.applyStyles() iconView.applyStyles() setupConstraints() } // MARK: - Notifications private func subscribeOnNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(accessibilityReapply), name: UIContentSizeCategory.didChangeNotification, object: nil) } private func unsubscribeFromNotifications() { NotificationCenter.default.removeObserver(self) } } // MARK: - IconItemViewInput extension IconItemView: IconItemViewInput {} // MARK: - ListItemView extension IconItemView: ListItemView { var leftSeparatorInset: CGFloat { return titleLabel.frame.minX } }
true
6e8a43f67a9d52906f0509966e01f75cd154a7e0
Swift
Keffury1/ios-sprint-challenge-random-users
/Random Users/View Controllers/UserDetailViewController.swift
UTF-8
1,180
2.921875
3
[]
no_license
// // UserDetailViewController.swift // Random Users // // Created by Bobby Keffury on 11/9/19. // Copyright © 2019 Erica Sadun. All rights reserved. // import UIKit class UserDetailViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var phoneNumberLabel: UILabel! @IBOutlet weak var emailAddressLabel: UILabel! var user: User? { didSet { updateViews() } } override func viewDidLoad() { super.viewDidLoad() updateViews() } private func updateViews() { guard isViewLoaded else { return } let firstName = (user?.name.title)! + "." + " " + (user?.name.first)! let lastName = user!.name.last nameLabel.text = firstName + " " + lastName phoneNumberLabel.text = user?.phone emailAddressLabel.text = user?.email guard let url = user?.picture.large else { return } if let data = try? Data(contentsOf: url) { imageView.image = UIImage(data: data) imageView.layer.cornerRadius = 12 } } }
true
3f2d4d9b28264c6fbe778ce5f96bbbca270eb835
Swift
loohawe/AsynDisplayDemo
/AsynDisplayDemo/Modules/ArticleModule.swift
UTF-8
2,023
2.65625
3
[ "Apache-2.0" ]
permissive
// // ArticleModule.swift // AsynDisplayDemo // // Created by luhao on 5/21/17. // Copyright © 2017 loohawe. All rights reserved. // import UIKit class ArticleModule: AsynDisplayUnit, AsynFetcherBinded { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var imageView: UIImageView! override init() { super.init() /** 再也不手写 constraint 了 用 xib 拉界面 */ if let articleView = Bundle.main.loadNibNamed("ArticleModule", owner: self, options: nil)?.first as? UIView { articleView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(articleView) let views = ["article": articleView] view.addConstraints([NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[article(>=100)]-0-|", options: [], metrics: nil, views: views), NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[article(>=96)]-0-|", options: [], metrics: nil, views: views), ].flatMap({$0})) self.titleLabel.setViewStatus(.placeholder) self.subtitleLabel.setViewStatus(.placeholder) self.imageView.setViewStatus(.placeholder) } } /** 网络请求到达, 准备重新绘制界面 */ func fetchedDataModel(model: AsynFetchModel?) -> Void { self.titleLabel.setViewStatus(.norman) self.subtitleLabel.setViewStatus(.norman) self.imageView.setViewStatus(.norman) if let article = model as? ArticleModel { if article.status == .success { self.titleLabel.text = article.title self.subtitleLabel.text = article.subtitle self.imageView.image = UIImage(named: article.imageName) } else { } } self.refreshLayout() } }
true
8c1a0dfe2f44a9d13409e832e6bf7afdf719acc9
Swift
MillerTechnologyPeru/SmartLock
/Xcode/LockKit/Model/CoreData/EventManagedObject.swift
UTF-8
6,591
2.859375
3
[ "MIT" ]
permissive
// // EventManagedObject.swift // LockKit // // Created by Alsey Coleman Miller on 9/6/19. // Copyright © 2019 ColemanCDA. All rights reserved. // import Foundation import CoreData import CoreLock import Predicate public class EventManagedObject: NSManagedObject { @nonobjc public class var eventType: LockEvent.EventType { fatalError("Implemented by subclass") } internal static func initWith(_ value: LockEvent, lock: LockManagedObject, context: NSManagedObjectContext) -> EventManagedObject { switch value { case let .setup(event): return SetupEventManagedObject(event, lock: lock, context: context) case let .unlock(event): return UnlockEventManagedObject(event, lock: lock, context: context) case let .createNewKey(event): return CreateNewKeyEventManagedObject(event, lock: lock, context: context) case let .confirmNewKey(event): return ConfirmNewKeyEventManagedObject(event, lock: lock, context: context) case let .removeKey(event): return RemoveKeyEventManagedObject(event, lock: lock, context: context) } } public static func find(_ id: UUID, in context: NSManagedObjectContext) throws -> EventManagedObject? { try context.find(identifier: id as NSUUID, propertyName: #keyPath(EventManagedObject.identifier), type: EventManagedObject.self) } } internal extension LockEvent { init?(managedObject: EventManagedObject) { switch managedObject { case let eventManagedObject as SetupEventManagedObject: guard let event = Setup(managedObject: eventManagedObject) else { return nil } self = .setup(event) case let eventManagedObject as UnlockEventManagedObject: guard let event = Unlock(managedObject: eventManagedObject) else { return nil } self = .unlock(event) case let eventManagedObject as CreateNewKeyEventManagedObject: guard let event = CreateNewKey(managedObject: eventManagedObject) else { return nil } self = .createNewKey(event) case let eventManagedObject as ConfirmNewKeyEventManagedObject: guard let event = ConfirmNewKey(managedObject: eventManagedObject) else { return nil } self = .confirmNewKey(event) case let eventManagedObject as RemoveKeyEventManagedObject: guard let event = RemoveKey(managedObject: eventManagedObject) else { return nil } self = .removeKey(event) default: assertionFailure("Invalid \(managedObject)") return nil } } } // MARK: - Fetch public extension EventManagedObject { /// Fetch the key specified by the event. func key(in context: NSManagedObjectContext) throws -> KeyManagedObject? { guard let key = self.key else { assertionFailure("Missing key value") return nil } return try context.find(id: key, type: KeyManagedObject.self) } } public extension LockManagedObject { func lastEvent(in context: NSManagedObjectContext) throws -> EventManagedObject? { return try lastEvents(count: 1, in: context).first } func lastEvents(count: Int, in context: NSManagedObjectContext) throws -> [EventManagedObject] { let fetchRequest = NSFetchRequest<EventManagedObject>() fetchRequest.entity = EventManagedObject.entity() fetchRequest.fetchBatchSize = count fetchRequest.fetchLimit = count fetchRequest.includesSubentities = true fetchRequest.shouldRefreshRefetchedObjects = false fetchRequest.returnsObjectsAsFaults = true fetchRequest.includesPropertyValues = false fetchRequest.sortDescriptors = [ NSSortDescriptor( key: #keyPath(EventManagedObject.date), ascending: false ) ] //let predicate = (.keyPath(#keyPath(EventManagedObject.lock.identifier)) == .value(self.identifier!)) fetchRequest.predicate = NSPredicate( format: "%K == %@", #keyPath(EventManagedObject.lock), self ) return try context.fetch(fetchRequest) } } // MARK: - Store internal extension NSManagedObjectContext { @discardableResult func insert(_ events: [LockEvent], for lock: LockManagedObject) throws -> [EventManagedObject] { return try events.map { try insert($0, for: lock) } } @discardableResult func insert(_ event: LockEvent, for lock: LockManagedObject) throws -> EventManagedObject { try EventManagedObject.find(event.id, in: self) ?? EventManagedObject.initWith(event, lock: lock, context: self) } @discardableResult func insert(_ events: [LockEvent], for lock: UUID) throws -> [EventManagedObject] { let managedObject = try find(id: lock, type: LockManagedObject.self) ?? LockManagedObject(id: lock, name: "", context: self) return try insert(events, for: managedObject) } @discardableResult func insert(_ event: LockEvent, for lock: UUID) throws -> EventManagedObject { let managedObject = try find(id: lock, type: LockManagedObject.self) ?? LockManagedObject(id: lock, name: "", context: self) return try insert(event, for: managedObject) } } // MARK: - Predicate public extension LockEvent.Predicate { func toFoundation(lock: UUID? = nil) -> NSPredicate { // CoreData predicate var subpredicates = [Predicate]() if let lock = lock { subpredicates.append( #keyPath(EventManagedObject.lock.identifier) == lock ) } if let keys = self.keys, keys.isEmpty == false { subpredicates.append( #keyPath(EventManagedObject.key).in(keys) ) } if let start = self.start { subpredicates.append( #keyPath(EventManagedObject.date) >= start ) } if let end = self.end { subpredicates.append( #keyPath(EventManagedObject.date) <= end ) } let predicate: Predicate = subpredicates.isEmpty ? .value(true) : .compound(.and(subpredicates)) return predicate.toFoundation() } }
true
2e4561e7f776c882a53b090a24788cbc3ec93ca9
Swift
nhatminh2912/firstExam
/ViewController.swift
UTF-8
7,196
2.71875
3
[]
no_license
// // ViewController.swift // toanhoc // // Created by ios on 11/9/16. // Copyright © 2016 ios. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBOutlet weak var signLbl: UILabel! @IBOutlet weak var lbl_p1: UILabel! @IBOutlet weak var lbl_p2: UILabel! @IBOutlet weak var btn_b1: UIButton! @IBOutlet weak var btn_b2: UIButton! @IBOutlet weak var btn_b3: UIButton! @IBAction func btn_act(_ sender: UIButton) { setRandom() } func setRandom() { let random1 = Int(arc4random_uniform(4)) + 1 let random2 = Int(arc4random_uniform(4)) + 1 // print("\(random1) \(random2)") lbl_p1.text = String(random1) lbl_p2.text = String(random2) setResult(randomA: random1, randomB: random2) } //22 //1 // * - // * + // * / // + - // - / //3 4 //Hien thi ket qua // tinh ket - (1 2 3) // ketqua + - 1 so nao day func setResult(randomA: Int, randomB: Int) { let randompt = Int(arc4random_uniform(4)) let randomvt = Int(arc4random_uniform(3)) if randompt == 0 { signLbl.text = "+" } else if randompt == 1 { signLbl.text = "-" } else if randompt == 2 { signLbl.text = "x" } else { signLbl.text = ":" } // tinh ket qua //1 // 2 +2 = 4 //4 5 3 if randomvt == 0 { if randompt == 0 { //+ btn_b1.setTitle(String(sum(p1: randomA, p2: randomB)) , for: .normal) btn_b2.setTitle(String(sum(p1: randomA, p2: randomB) + Int(arc4random_uniform(4) + 1)) , for: .normal) btn_b3.setTitle(String(sum(p1: randomA, p2: randomB) - Int(arc4random_uniform(4) + 1)) , for: .normal) } else if randompt == 1 { //- btn_b1.setTitle(String(sub(p1: randomA, p2: randomB) - Int(arc4random_uniform(4) + 1)) , for: .normal) btn_b2.setTitle(String(sub(p1: randomA, p2: randomB)) , for: .normal) btn_b3.setTitle(String(sub(p1: randomA, p2: randomB) + Int(arc4random_uniform(4) + 1)) , for: .normal) } else if randompt == 2 {//* btn_b1.setTitle(String(multi(p1: randomA, p2: randomB) + Int(arc4random_uniform(4) + 1)) , for: .normal) btn_b2.setTitle(String(multi(p1: randomA, p2: randomB) - Int(arc4random_uniform(4) + 1)) , for: .normal) btn_b3.setTitle(String(multi(p1: randomA, p2: randomB)) , for: .normal) } else if randompt == 3 { // / btn_b1.setTitle(String(format: "%.1f", div(p1: randomA, p2: randomB)) , for: .normal) btn_b2.setTitle(String(format: "%.1f", div(p1: randomA, p2: randomB) - Float(arc4random_uniform(4) + 1)) , for: .normal) btn_b3.setTitle(String(format: "%.1f", div(p1: randomA, p2: randomB) + Float(arc4random_uniform(4) + 1)) , for: .normal) } } else if randomvt == 1 { if randompt == 0 { btn_b1.setTitle(String(sum(p1: randomA, p2: randomB) - Int(arc4random_uniform(4) + 2)) , for: .normal) btn_b2.setTitle(String(sum(p1: randomA, p2: randomB) + Int(arc4random_uniform(4) + 2)) , for: .normal) btn_b3.setTitle(String(sum(p1: randomA, p2: randomB)) , for: .normal) } else if randompt == 1 { btn_b1.setTitle(String(sub(p1: randomA, p2: randomB)) , for: .normal) btn_b2.setTitle(String(sub(p1: randomA, p2: randomB) + Int(arc4random_uniform(4) + 2)) , for: .normal) btn_b3.setTitle(String(sub(p1: randomA, p2: randomB) - Int(arc4random_uniform(4) + 2)) , for: .normal) } else if randompt == 2 { btn_b1.setTitle(String(multi(p1: randomA, p2: randomB) - Int(arc4random_uniform(4) + 2)) , for: .normal) //0.75 btn_b2.setTitle(String(multi(p1: randomA, p2: randomB)) , for: .normal) //-1 btn_b3.setTitle(String(multi(p1: randomA, p2: randomB) + Int(arc4random_uniform(4) + 2)) , for: .normal) //12 } else if randompt == 3 { btn_b1.setTitle(String(format: "%.1f", div(p1: randomA, p2: randomB) + Float(arc4random_uniform(4) + 2)) , for: .normal) btn_b2.setTitle(String(format: "%.1f", div(p1: randomA, p2: randomB)) , for: .normal) btn_b3.setTitle(String(format: "%.1f", div(p1: randomA, p2: randomB) - Float(arc4random_uniform(4) + 2)) , for: .normal) } } else if randomvt == 2 { if randompt == 0 { btn_b1.setTitle(String(sum(p1: randomA, p2: randomB) + Int(arc4random_uniform(4) + 3)) , for: .normal) btn_b2.setTitle(String(sum(p1: randomA, p2: randomB)) , for: .normal) btn_b3.setTitle(String(sum(p1: randomA, p2: randomB) - Int(arc4random_uniform(4) + 3)) , for: .normal) } else if randompt == 1 { btn_b1.setTitle(String(sub(p1: randomA, p2: randomB) - Int(arc4random_uniform(4) + 3) ) , for: .normal) btn_b2.setTitle(String(sub(p1: randomA, p2: randomB) + Int(arc4random_uniform(4) + 3)) , for: .normal) btn_b3.setTitle(String(sub(p1: randomA, p2: randomB)) , for: .normal) } else if randompt == 2 { btn_b1.setTitle(String(multi(p1: randomA, p2: randomB)) , for: .normal) btn_b2.setTitle(String(multi(p1: randomA, p2: randomB) + Int(arc4random_uniform(4) + 3)) , for: .normal) btn_b3.setTitle(String(multi(p1: randomA, p2: randomB) - Int(arc4random_uniform(4) + 3)) , for: .normal) } else if randompt == 3 { btn_b1.setTitle(String(format: "%.1f", div(p1: randomA, p2: randomB) + Float(arc4random_uniform(4) + 3)) , for: .normal) btn_b2.setTitle(String(format: "%.1f", div(p1: randomA, p2: randomB) - Float(arc4random_uniform(4) + 3)) , for: .normal) btn_b3.setTitle(String(format: "%.1f", div(p1: randomA, p2: randomB)) , for: .normal) } } // print("randompt = \(randompt)") if randompt == 0 { signLbl.text = "+" } else if randompt == 1 { signLbl.text = "-" } else if randompt == 2 { signLbl.text = "x" } else { signLbl.text = ":" } } //Tinh tong func sum(p1: Int, p2: Int) -> Int { return p1+p2; } func sub(p1: Int, p2: Int) -> Int { return p1-p2; } func multi(p1: Int, p2: Int) -> Int{ return p1*p2 } func div(p1: Int, p2: Int) -> Float{ //print("ket nqua \(Float(p1)/Float(p2))") return Float(p1)/Float(p2) } }
true
e03e507f5a6c1093f9f0259c1fa71b43413d3890
Swift
CrazyMillerGitHub/InTouch
/InTouchApp/Service Layer/Services/ImageDownloadingService.swift
UTF-8
1,258
2.8125
3
[]
no_license
// // ImageDownloadingService.swift // InTouchApp // // Created by Михаил Борисов on 17/04/2019. // Copyright © 2019 Mikhail Borisov. All rights reserved. // import Foundation protocol IImageService { func loadNewImages(pageNumber: Int, completionHandler: @escaping ([PhotoApiModel]?, String?) -> Void) } class PhotoService: IImageService { let requestSender: IRequestSender init(requestSender: IRequestSender) { self.requestSender = requestSender } func loadNewImages(pageNumber: Int, completionHandler: @escaping ([PhotoApiModel]?, String?) -> Void) { let requestConfig = RequestsFactory.photoImages(pageNumber: pageNumber) loadImages(requestConfig: requestConfig, completionHandler: completionHandler) } private func loadImages(requestConfig: RequestConfig<PhotoParser>, completionHandler: @escaping ([PhotoApiModel]?, String?) -> Void) { requestSender.send(requestConfig: requestConfig) { (result: Result<[PhotoApiModel]>) in switch result { case .success(let photos): completionHandler(photos, nil) case .error(let error): completionHandler(nil, error) } } } }
true
5ba62f98a0565dcd27cd48be8238da154c6eb318
Swift
vincent-coetzee/TVClock
/Clock/Value Models/ValueHolder.swift
UTF-8
394
2.6875
3
[]
no_license
// // ValueHolder.swift // ValueModels // // Created by Vincent Coetzee on 2017/06/29. // Copyright © 2017 MacSemantics. All rights reserved. // import Foundation class ValueHolder<T>:AbstractModel { var value:T? { didSet { changed(aspect:"value") } } init(value:T) { self.value = value } }
true
ba449ec6869dd19ac002b95bcf08c5c9be9b4d35
Swift
thelowlypeon/simple-observable
/SimpleObservableTests/PropertyTest.swift
UTF-8
878
2.796875
3
[]
no_license
// // PropertyTest.swift // SimpleObservableTests // // Created by Peter Compernolle on 9/30/18. // Copyright © 2018 Peter Compernolle. All rights reserved. // import XCTest @testable import SimpleObservable class PropertyTest: XCTestCase { var initialValue = "initial string" let newValue = "new value" var observableString: Property<String>! var observableOptionalString: Property<String?>! override func setUp() { observableString = Property<String>(initialValue) } func testInitialValue() { XCTAssertEqual(observableString.value, initialValue) } func testMutatingValue() { observableString.value = newValue XCTAssertEqual(observableString.value, newValue) } func testNilLiteralInitializer() { observableOptionalString = Property<String?>() XCTAssertNil(observableOptionalString.value) } }
true
88fa61c2e9195644459e56cf6f499887f5b8da62
Swift
kurenkovmichael/FoursquareKurenkov
/FoursquareKurenkov/Services/Storage/UserDefaults/UserDefaultsAuthorizationStorage.swift
UTF-8
811
2.515625
3
[]
no_license
import Foundation class UserDefaultsAuthorizationStorage: AuthorizationServiceStorage { private let userDefaults = UserDefaults() private let accessCodeKey = "AccessCode" private let authTokenKey = "AuthToken" func restoreAccessCode() -> String? { return userDefaults.string(forKey: accessCodeKey) } func storeAccessCode(_ accessCode: String?) { userDefaults.set(accessCode, forKey: accessCodeKey) } func restoreAuthToken() -> String? { return userDefaults.string(forKey: authTokenKey) } func storeAauthToken(_ aauthToken: String?) { userDefaults.set(aauthToken, forKey: authTokenKey) } func clean() { userDefaults.removeObject(forKey: accessCodeKey) userDefaults.removeObject(forKey: authTokenKey) } }
true
fd324245a39fd62350c2bf02c06fdf63c46494d0
Swift
k11k/CountriesInfoApp
/CountryInfo/Common/Classes/ActivityTracker.swift
UTF-8
1,657
2.84375
3
[]
no_license
import Foundation import RxSwift import RxCocoa public class ActivityTracker: SharedSequenceConvertibleType { public typealias E = Bool public typealias SharingStrategy = DriverSharingStrategy private let lock = NSRecursiveLock() private let variable = BehaviorRelay(value: false) private let loading: SharedSequence<SharingStrategy, Bool> private var numberOfActivities: Int = 0 public init() { loading = variable.asDriver() .distinctUntilChanged() } fileprivate func trackActivityOfObservable<O: ObservableConvertibleType>(_ source: O) -> Observable<O.E> { return source.asObservable() .do(onNext: { _ in self.sendStopLoading() }, onError: { _ in self.sendStopLoading() }, onCompleted: { self.sendStopLoading(decrement: false) }, onSubscribe: subscribed) } private func subscribed() { lock.lock() variable.accept(true) numberOfActivities += 1 lock.unlock() } private func sendStopLoading(decrement: Bool = true) { lock.lock() if decrement && numberOfActivities > 0 { numberOfActivities -= 1 } variable.accept(numberOfActivities > 0) lock.unlock() } public func asSharedSequence() -> SharedSequence<SharingStrategy, E> { return loading } } extension ObservableConvertibleType { public func trackActivity(_ activityIndicator: ActivityTracker) -> Observable<E> { return activityIndicator.trackActivityOfObservable(self) } }
true
5b654c4950e6594b7d43c52ba8d7af8d23c5f796
Swift
bloukingfisher/photon-tinker-ios
/Photon-Tinker/DeviceInfoSliderCell.swift
UTF-8
1,208
2.75
3
[ "Apache-2.0" ]
permissive
// // Created by Raimundas Sakalauskas on 2019-06-12. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation class DeviceInfoSliderCell: UITableViewCell { @IBOutlet weak var titleLabel: ParticleLabel! @IBOutlet weak var valueLabel: ParticleLabel! @IBOutlet weak var iconImage: DeviceTypeIcon! func setup(title: String, value:Any) { self.titleLabel.setStyle(font: ParticleStyle.BoldFont, size: ParticleStyle.RegularSize, color: ParticleStyle.PrimaryTextColor) self.valueLabel.setStyle(font: ParticleStyle.RegularFont, size: ParticleStyle.RegularSize, color: ParticleStyle.PrimaryTextColor) self.titleLabel.text = title if let type = value as? ParticleDeviceType { self.iconImage.isHidden = false self.valueLabel.isHidden = false self.iconImage.setDeviceType(type) self.valueLabel.text = type.description } else if let text = value as? String { self.iconImage.isHidden = true self.valueLabel.isHidden = false self.valueLabel.text = text } else { self.iconImage.isHidden = true self.valueLabel.isHidden = true } } }
true
46e0e97ec6841248ffba2e116a28d5919e56a8af
Swift
Lab262/LeituraDeBolsoIOS
/LeituraDeBolso/LeituraDeBolso/ContentTableViewCell.swift
UTF-8
1,549
2.609375
3
[]
no_license
// // ContentTableViewCell.swift // LeituraDeBolso // // Created by Huallyd Smadi on 29/08/16. // Copyright © 2016 Lab262. All rights reserved. // import UIKit class ContentTableViewCell: UITableViewCell { static let identifier = "contentCell" @IBOutlet weak var authorReadingLabel: UILabel! @IBOutlet weak var contentReadingLabel: UILabel! var reading: Reading? { didSet { updateUI() } } override func didMoveToWindow() { if ApplicationState.sharedInstance.currentUser!.isModeNight { self.setNightMode() } else { self.setNormalMode() } } override func layoutSubviews() { self.contentReadingLabel.setSizeFont(ApplicationState.sharedInstance.currentUser!.sizeFont) } override func awakeFromNib() { super.awakeFromNib() } func updateUI () { self.authorReadingLabel.text = reading?.author self.contentReadingLabel.text = reading?.content } func setNightMode () { self.authorReadingLabel.textColor = UIColor.white self.contentReadingLabel.textColor = UIColor.white self.backgroundColor = UIColor.readingModeNightBackground() } func setNormalMode () { self.authorReadingLabel.textColor = UIColor.black self.contentReadingLabel.textColor = UIColor.black self.backgroundColor = UIColor.white } }
true
51055b19efe50d8098a15c955368c16ab9b0675f
Swift
GeekInTheClass/Clubadmin
/Clubadmin/DetailViewController.swift
UTF-8
1,107
2.75
3
[]
no_license
// // ViewController.swift // Clubadmin // // Created by cadenzah on 21/03/2019. // Copyright © 2019 cadenzah. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var myButton: UIButton! @IBOutlet weak var myLabel: UILabel! @IBOutlet weak var myImage1: UIImageView! @IBOutlet weak var detailLabel: UILabel! var TaskForView:Task? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let childView = UIView(frame: CGRect(x:10, y:10, width:100, height: 100)) self.view.addSubview(childView) } override func viewWillAppear(_ animated: Bool) { // myLabel.text = "뷰가 나타났다!" // let pororiImage:UIImage = #imageLiteral(resourceName: "porori") // myImage1.image = pororiImage //UI 업데이트 print(TaskForView?.taskName) // view controller에 있는 label에 누른 taskName을 출력. detailLabel.text = TaskForView?.taskName } }
true
a4c13dc5a96983ee05634de317d60a47b206571a
Swift
verygoodsecurity/vgs-collect-ios
/Sources/VGSCardIOCollector/CardIODataMapper/VGSCardIODataMapUtils.swift
UTF-8
6,642
2.953125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // VGSCardIODataMapUtils.swift // VGSCardIOCollector // import Foundation import VGSCollectSDK /// Holds mapping utils for scanned card data. internal final class VGSCardIODataMapUtils { // MARK: - Constants /// Valid months range. private static let monthsRange = 1...12 // MARK: - Interface /// Maps scanned expiration data to expected format. /// - Parameters: /// - data: `VGSCardIOExpirationDate` object, scanned expiry date data. /// - scannedDataType: `CradIODataType` object, CardIO data type. /// - Returns: `String?`, formatted string or `nil`. internal static func mapCardExpirationData(_ data: VGSCardIOExpirationDate, scannedDataType: CradIODataType) -> String? { switch scannedDataType { case .cardNumber, .cvc: return nil case .expirationDate: return mapDefaultExpirationDate(data.month, scannedExpYear: data.year) case .expirationDateLong: return mapLongExpirationDate(data.month, scannedExpYear: data.year) case .expirationMonth: return mapMonth(data.month) case .expirationYear: return mapYear(data.year) case .expirationYearLong: return mapYearLong(data.year) case .expirationDateShortYearThenMonth: return mapExpirationDateWithShortYearFirst(data.month, scannedExpYear: data.year) case .expirationDateLongYearThenMonth: return mapLongExpirationDateWithLongYearFirst(data.month, scannedExpYear: data.year) } } // MARK: - Helpers /// Maps scanned exp month and year to valid format (MM/YY). /// - Parameters: /// - scannedExpMonth: `UInt` object, scanned expiry month. /// - scannedExpYear: `UInt` object, scanned expiry year. /// - Returns: `String?`, composed text or nil if scanned info is invalid. private static func mapDefaultExpirationDate(_ scannedExpMonth: UInt, scannedExpYear: UInt) -> String? { guard let month = mapMonth(scannedExpMonth), let year = mapYear(scannedExpYear) else { return nil } return "\(month)\(year)" } /// Maps scanned exp month and year to valid format starting with year (YY/MM). /// - Parameters: /// - scannedExpMonth: `UInt` object, scanned expiry month. /// - scannedExpYear: `UInt` object, scanned expiry year. /// - Returns: `String?`, composed text or nil if scanned info is invalid. private static func mapExpirationDateWithShortYearFirst(_ scannedExpMonth: UInt, scannedExpYear: UInt) -> String? { guard let month = mapMonth(scannedExpMonth), let year = mapYear(scannedExpYear) else { return nil } return "\(year)\(month)" } /// Maps scanned exp month and year to long expiration date format (MM/YYYY). /// - Parameters: /// - scannedExpMonth: `UInt` object, scanned expiry month. /// - scannedExpYear: `UInt` object, scanned expiry year. /// - Returns: `String?`, composed text or nil if scanned info is invalid. private static func mapLongExpirationDate(_ scannedExpMonth: UInt, scannedExpYear: UInt) -> String? { guard let month = mapMonth(scannedExpMonth), let longYear = mapYearLong(scannedExpYear) else { return nil } return "\(month)\(longYear)" } /// Maps scanned exp month and year to long expiration date format starting with year (YYYY/MM). /// - Parameters: /// - scannedExpMonth: `UInt` object, scanned expiry month. /// - scannedExpYear: `UInt` object, scanned expiry year. /// - Returns: `String?`, composed text or nil if scanned info is invalid. private static func mapLongExpirationDateWithLongYearFirst(_ scannedExpMonth: UInt, scannedExpYear: UInt) -> String? { guard let month = mapMonth(scannedExpMonth), let longYear = mapYearLong(scannedExpYear) else { return nil } return "\(longYear)\(month)" } /// Maps scanned expiry month to short format (MM) string. /// - Parameter scannedExpYear: `UInt` object, scanned expiry year. /// - Returns: `String?`, year text or nil if scanned info is invalid. private static func mapMonth(_ scannedExpMonth: UInt) -> String? { guard let month = monthInt(from: scannedExpMonth) else {return nil} let formattedMonthString = formatMonthString(from: month) return formattedMonthString } /// Maps scanned expiry year to short format (YY) string. /// - Parameter scannedExpYear: `UInt` object, scanned expiry year. /// - Returns: `String?`, year text or nil if scanned info is invalid. private static func mapYear(_ scannedExpYear: UInt) -> String? { guard let year = yearInt(from: scannedExpYear) else {return nil} // CardIO holds year in long format (2025), convert to short (25) format manually. return shortYearString(from: year) } /// Maps scanned expiry year to long format (YYYY) string. /// - Parameter scannedExpYear: `UInt` object, scanned expiry year. /// - Returns: `String?`, year text or nil if scanned info is invalid. private static func mapYearLong(_ scannedExpYear: UInt) -> String? { guard let year = yearInt(from: scannedExpYear) else {return nil} return "\(year)" } /// Converts year to long format string. /// - Parameter longYear: `UInt` object, should be short year. /// - Returns: `String` with long year format. private static func shortYearString(from longYear: UInt) -> String { return String("\(longYear)".suffix(2)) } /// Checks if month (UInt) is valid. /// - Parameter month: `UInt` object, month to verify. /// - Returns: `Bool` object, `true` if is valid. private static func isMonthValid(_ month: UInt) -> Bool { return monthsRange ~= Int(month) } /// Checks if year (Int) is valid. /// - Parameter year: `UInt` object, year to verify. /// - Returns: `Bool` object, `true` if is valid. private static func isYearValid(_ year: UInt) -> Bool { // CardIO returns year in long format: `2025`. return year >= VGSCalendarUtils.currentYear } /// Provides month Int. /// - Parameter month: `UInt` object, month from CardIO. /// - Returns: `UInt?`, valid month or `nil`. private static func monthInt(from month: UInt) -> UInt? { guard isMonthValid(month) else { return nil } return month } /// Provides year Int. /// - Parameter year: `UInt` object, year from CardIO. /// - Returns: `UInt?`, valid year or `nil`. private static func yearInt(from year: UInt) -> UInt? { guard isYearValid(year) else { return nil } return year } /// Formats month int. /// - Parameter monthInt: `UInt` object, should be month. /// - Returns: `String` object, formatted month. private static func formatMonthString(from monthInt: UInt) -> String { // Add `0` for month less than 10. let monthString = monthInt < 10 ? "0\(monthInt)" : "\(monthInt)" return monthString } }
true
ed0bf2912308fe089facccb1b76616f1dda40cf8
Swift
MAdisurya/relic-runners
/RelicRunners/RelicRunners/RelicRunners/Components/Menu/Windows/ArmourWindow.swift
UTF-8
1,542
2.53125
3
[]
no_license
// // ArmourWindow.swift // RelicRunners // // Created by Mario Adisurya on 19/02/19. // Copyright © 2019 Mario Adisurya. All rights reserved. // import SpriteKit class ArmourWindow: ItemWindow { private let m_ArmourModel = RRArmour(); override init(inventoryWindow: InventoryWindow) { super.init(inventoryWindow: inventoryWindow); self.m_ItemType = .armour; // Get current equipped sword slot // Must be called after generateWeaponSlots() for i in 0..<m_ItemArray.count { if (m_ItemArray[i].getItemName() == RRGameManager.shared.getInventoryManager().retrieveArmour()) { m_EquippedItemSlot = m_ItemArray[i]; m_ItemArray[i].enableBorder(); } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func generateWeaponSlots() { super.generateWeaponSlots(); // Add armour to armour array for i in 0..<m_ArmourModel.armourArray.count { let armourSlot = ItemSlot(name: m_ArmourModel.armourArray[i], itemType: .armour, itemWindow: self); armourSlot.texture = SKTexture(imageNamed: m_ArmourModel.armourArray[i]); armourSlot.texture?.filteringMode = .nearest; m_ItemArray.append(armourSlot); // Add armour slot to window self.addChild(armourSlot); } positionSlots(); } }
true
5fa9f129ade7fd414ea8ab3909836b02d2867cab
Swift
utsav475908/catsDogs
/CatsDogs/Flow/PushAuthFlow.swift
UTF-8
1,533
2.625
3
[]
no_license
// // PushAuthFlow.swift // CatsDogs // // Created by Danil Lahtin on 10.06.2020. // Copyright © 2020 Danil Lahtin. All rights reserved. // import Foundation import Core import UI final class PushAuthFlow: Flow { private let userDefaults: UserDefaults private let loginRequest: LoginRequest private let navigationController: UINavigationControllerProtocol private let onComplete: () -> () private let onError: (Error) -> () init(userDefaults: UserDefaults, loginRequest: LoginRequest, navigationController: UINavigationControllerProtocol, onComplete: @escaping () -> (), onError: @escaping (Error) -> ()) { self.userDefaults = userDefaults self.loginRequest = loginRequest self.navigationController = navigationController self.onComplete = onComplete self.onError = onError } func start() { let vc = LoginViewController() vc.loadViewIfNeeded() vc.didSkip = { [userDefaults, onComplete] in userDefaults.hasSkippedAuth = true onComplete() } vc.didLogin = { [loginRequest, onComplete, onError] in loginRequest.start(credentials: $0, { switch $0 { case .success: onComplete() case .failure(let error): onError(error) } }) } navigationController.setViewControllers([vc], animated: true) } }
true
5bebe8b2a89e6dcc8b6cd85a4d976bfe042735c4
Swift
HIROYA1225/AlarmAppSwift
/AlarmAppSwift/Model/CurrentTime.swift
UTF-8
1,009
3.1875
3
[]
no_license
// // CurrentTime.swift // AlarmAppSwift // // Created by HIRO on 2021/02/20. // import Foundation //現在時間の取得と表示する class CurrentTime{ var timer: Timer? var currentTime: String? var df = DateFormatter() weak var delegate: SleepingViewController? init(){ if timer == nil{ //タイマーをセット、一秒ごとにupdateCurrentTimeを呼び出す timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCurrentTime), userInfo: nil, repeats: true) } } @objc private func updateCurrentTime(){ //フォーマットの指定 df.dateFormat = "HH:mm" //タイムゾーンを端末のものに合わせる df.timeZone = TimeZone.current //現在の時間をフォーマットに合わせて設定する let timezoneDate = df.string(from: Date()) currentTime = timezoneDate delegate?.updateTime(currentTime!) } }
true
63ff7aedc1c7cf942d1659220067e30bd48929bb
Swift
tokyovigilante/CesiumKit
/CesiumKit/Renderer/ShaderSource.swift
UTF-8
11,704
3
3
[ "Apache-2.0" ]
permissive
// // ShaderSource.swift // CesiumKit // // Created by Ryan Walklin on 7/03/15. // Copyright (c) 2015 Test Toast. All rights reserved. // import Foundation private class DependencyNode: Equatable { var name: String var glslSource: String var dependsOn = [DependencyNode]() var requiredBy = [DependencyNode]() var evaluated: Bool = false init ( name: String, glslSource: String, dependsOn: [DependencyNode] = [DependencyNode](), requiredBy: [DependencyNode] = [DependencyNode](), evaluated: Bool = false) { self.name = name self.glslSource = glslSource self.dependsOn = dependsOn self.requiredBy = requiredBy self.evaluated = evaluated } } private func == (left: DependencyNode, right: DependencyNode) -> Bool { return left.name == right.name && left.glslSource == right.glslSource } /** * An object containing various inputs that will be combined to form a final GLSL shader string. * * @param {Object} [options] Object with the following properties: * @param {String[]} [options.sources] An array of strings to combine containing GLSL code for the shader. * @param {String[]} [options.defines] An array of strings containing GLSL identifiers to <code>#define</code>. * @param {String} [options.pickColorQualifier] The GLSL qualifier, <code>uniform</code> or <code>varying</code>, for the input <code>czm_pickColor</code>. When defined, a pick fragment shader is generated. * @param {Boolean} [options.includeBuiltIns=true] If true, referenced built-in functions will be included with the combined shader. Set to false if this shader will become a source in another shader, to avoid duplicating functions. * * @exception {DeveloperError} options.pickColorQualifier must be 'uniform' or 'varying'. * * @example * // 1. Prepend #defines to a shader * var source = new Cesium.ShaderSource({ * defines : ['WHITE'], * sources : ['void main() { \n#ifdef WHITE\n gl_FragColor = vec4(1.0); \n#else\n gl_FragColor = vec4(0.0); \n#endif\n }'] * }); * * // 2. Modify a fragment shader for picking * var source = new Cesium.ShaderSource({ * sources : ['void main() { gl_FragColor = vec4(1.0); }'], * pickColorQualifier : 'uniform' * }); * * @private */ struct ShaderSource { var sources: [String] var defines: [String] var pickColorQualifier: String? let includeBuiltIns: Bool fileprivate let _commentRegex = "/\\*\\*[\\s\\S]*?\\*/" fileprivate let _versionRegex = "/#version\\s+(.*?)\n" fileprivate let _lineRegex = "\\n" fileprivate let _czmRegex = "\\bczm_[a-zA-Z0-9_]*" init (sources: [String] = [String](), defines: [String] = [String](), pickColorQualifier: String? = nil, includeBuiltIns: Bool = true) { assert(pickColorQualifier == nil || pickColorQualifier == "uniform" || pickColorQualifier == "varying", "options.pickColorQualifier must be 'uniform' or 'varying'.") self.defines = defines self.sources = sources self.pickColorQualifier = pickColorQualifier self.includeBuiltIns = includeBuiltIns } /** * Create a single string containing the full, combined vertex shader with all dependencies and defines. * * @returns {String} The combined shader string. */ func createCombinedVertexShader () -> String { return combineShader(false) } /** * Create a single string containing the full, combined fragment shader with all dependencies and defines. * * @returns {String} The combined shader string. */ func createCombinedFragmentShader () -> String { return combineShader(true) } func combineShader(_ isFragmentShader: Bool) -> String { // Combine shader sources, generally for pseudo-polymorphism, e.g., czm_getMaterial. var combinedSources = "" for (i, source) in sources.enumerated() { // #line needs to be on its own line. combinedSources += "\n#line 0\n" + sources[i]; } combinedSources = removeComments(combinedSources) var version: String? = nil // Extract existing shader version from sources let versionRange = combinedSources[_versionRegex].range() if versionRange.location != NSNotFound { version = (combinedSources as NSString).substring(with: versionRange) combinedSources.replace(version!, "\n") } // Replace main() for picked if desired. if pickColorQualifier != nil { // FIXME: pickColorQualifier /*combinedSources = combinedSources.replace(/void\s+main\s*\(\s*(?:void)?\s*\)/g, 'void czm_old_main()'); combinedSources += '\ \n' + pickColorQualifier + ' vec4 czm_pickColor;\n\ void main()\n\ {\n\ czm_old_main();\n\ if (gl_FragColor.a == 0.0) {\n\ discard;\n\ }\n\ gl_FragColor = czm_pickColor;\n\ }';*/ } // combine into single string var result = "" // #version must be first // defaults to #version 100 if not specified if version != nil { result = "#version " + version! } // Prepend #defines for uber-shaders for define in defines { if define.characters.count != 0 { result += "#define " + define + "\n" } } // append built-ins if includeBuiltIns { result += getBuiltinsAndAutomaticUniforms(combinedSources) } // reset line number result += "\n#line 0\n" // append actual source result += combinedSources return result } fileprivate func removeComments (_ source: String) -> String { // strip doc comments so we don't accidentally try to determine a dependency for something found // in a comment var newSource = source let commentBlocks = newSource[_commentRegex].matches() if commentBlocks.count > 0 { for comment in commentBlocks { let numberOfLines = comment[_lineRegex].matches().count // preserve the number of lines in the comment block so the line numbers will be correct when debugging shaders var modifiedComment = "" for lineNumber in 0..<numberOfLines { modifiedComment += "//\n" } newSource = newSource.replace(comment, modifiedComment) } } return newSource } fileprivate func getBuiltinsAndAutomaticUniforms(_ shaderSource: String) -> String { // generate a dependency graph for builtin functions var dependencyNodes = [DependencyNode]() let root = getDependencyNode("main", glslSource: shaderSource, nodes: &dependencyNodes) generateDependencies(root, dependencyNodes: &dependencyNodes) sortDependencies(&dependencyNodes) // Concatenate the source code for the function dependencies. // Iterate in reverse so that dependent items are declared before they are used. return Array(dependencyNodes.reversed()) .reduce("", { $0 + $1.glslSource + "\n" }) .replace(root.glslSource, "") } fileprivate func getDependencyNode(_ name: String, glslSource: String, nodes: inout [DependencyNode]) -> DependencyNode { var dependencyNode: DependencyNode? // check if already loaded for node in nodes { if node.name == name { dependencyNode = node } } if dependencyNode == nil { // strip doc comments so we don't accidentally try to determine a dependency for something found // in a comment let newGLSLSource = removeComments(glslSource) // create new node dependencyNode = DependencyNode(name: name, glslSource: newGLSLSource) nodes.append(dependencyNode!) } return dependencyNode! } fileprivate func generateDependencies(_ currentNode: DependencyNode, dependencyNodes: inout [DependencyNode]) { if currentNode.evaluated { return } currentNode.evaluated = true // identify all dependencies that are referenced from this glsl source code let czmMatches = deleteDuplicates(currentNode.glslSource[_czmRegex].matches()) for match in czmMatches { if (match != currentNode.name) { var elementSource: String? = nil if let builtin = Builtins[match] { elementSource = builtin } else if let uniform = AutomaticUniforms[match] { elementSource = uniform.declaration(match) } else { logPrint(.warning, "uniform \(match) not found") } if elementSource != nil { let referencedNode = getDependencyNode(match, glslSource: elementSource!, nodes: &dependencyNodes) currentNode.dependsOn.append(referencedNode) referencedNode.requiredBy.append(currentNode) // recursive call to find any dependencies of the new node generateDependencies(referencedNode, dependencyNodes: &dependencyNodes) } } } } fileprivate func sortDependencies(_ dependencyNodes: inout [DependencyNode]) { var nodesWithoutIncomingEdges = [DependencyNode]() var allNodes = [DependencyNode]() while (dependencyNodes.count > 0) { let node = dependencyNodes.removeLast() allNodes.append(node) if node.requiredBy.count == 0 { nodesWithoutIncomingEdges.append(node) } } while nodesWithoutIncomingEdges.count > 0 { let currentNode = nodesWithoutIncomingEdges.remove(at: 0) dependencyNodes.append(currentNode) for i in 0..<currentNode.dependsOn.count { // remove the edge from the graph let referencedNode = currentNode.dependsOn[i] let index = referencedNode.requiredBy.index(of: currentNode) if (index != nil) { referencedNode.requiredBy.remove(at: index!) } // if referenced node has no more incoming edges, add to list if referencedNode.requiredBy.count == 0 { nodesWithoutIncomingEdges.append(referencedNode) } } } // if there are any nodes left with incoming edges, then there was a circular dependency somewhere in the graph var badNodes = [DependencyNode]() for node in allNodes { if node.requiredBy.count != 0 { badNodes.append(node) } } if badNodes.count != 0 { var message = "A circular dependency was found in the following built-in functions/structs/constants: \n" for node in badNodes { message += node.name + "\n" } assertionFailure(message) } } }
true
f63bf5a621168cf056176e12e65b88b39820110d
Swift
aechangom/farmanet
/farmanet/farmanet/PharmacyCell/PharmacyCellViewModel.swift
UTF-8
1,143
2.953125
3
[]
no_license
// // PharmacyCellViewModel.swift // farmanet // // Created by Andres Efrain Chango Macas on 5/15/21. // import Foundation class PharmacyCellViewModel { let pharmacy: Pharmacy init(pharmacy: Pharmacy ) { self.pharmacy = pharmacy } var localName: String { return pharmacy.localName } var localAddress: String { return pharmacy.localAddress } var localLocalize: String { return pharmacy.localidadName } var description: String { return self.convertPharmacyToString(pharmacy: pharmacy) } func convertPharmacyToString(pharmacy: Pharmacy) -> String { var resultado: String = "" let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted do { let jsonData = try encoder.encode(pharmacy) if let jsonString = String(data: jsonData, encoding: .utf8) { print(jsonString) resultado = jsonString } } catch { print(error.localizedDescription) resultado = MessageText.shared.errorConversion } return resultado } }
true
61779c7f55f4565abfe0d503720ca2700fcd61d8
Swift
salamehM/Todoey
/Todoey/Controllers/TodoListViewController.swift
UTF-8
3,647
2.96875
3
[]
no_license
// // ViewController.swift // Todoey // // Created by Salameh on 7/29/19. // Copyright © 2019 Mhammad Salameh. All rights reserved. // import UIKit class TodoListViewController: UITableViewController{ @IBOutlet var theNoteTableView: UITableView! var itemCells = [Item]() let dataFilePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Item.plist") override func viewDidLoad() { super.viewDidLoad() let firstNewItem = Item() firstNewItem.itemName = "First Item" itemCells.append(firstNewItem) let secondNewItem = Item() secondNewItem.itemName = "Second Item" itemCells.append(secondNewItem) let thirdNewItem = Item() thirdNewItem.itemName = "Third Item" itemCells.append(thirdNewItem) // if let items = defaults.array(forKey: "StoredItemCells") as? [Item] { // itemCells = items // } //theNoteTableView.delegate = self // Do any additional setup after loading the view. loadItems() } // Return the tableview cell count override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemCells.count } // Set cell Content override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) let item = itemCells[indexPath.row] cell.textLabel?.text = item.itemName cell.accessoryType = item.done ? .checkmark : .none return cell } // On tableview cell click override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { itemCells[indexPath.row].done = !itemCells[indexPath.row].done saveItems() tableView.deselectRow(at: indexPath, animated: true) } @IBAction func addToDoItemBtn(_ sender: UIBarButtonItem) { var textField = UITextField() let alert = UIAlertController(title: "Add Todoey App", message: "", preferredStyle: .alert) let action = UIAlertAction(title: "Add Item", style: .default) { (action) in let newItem = Item() newItem.itemName = textField.text! self.itemCells.append(newItem) self.saveItems() } alert.addTextField { (alertTextField) in alertTextField.placeholder = "Create Item to Add" textField = alertTextField } alert.addAction(action) present(alert, animated: true, completion: nil) } func saveItems(){ let encoder = PropertyListEncoder() do { let data = try encoder.encode(itemCells) try data.write(to:dataFilePath!) } catch { print("Error Encoding data \(error)") } //self.defaults.set(self.itemCells,forKey: "StoredItemCells") self.tableView.reloadData() } func loadItems(){ if let data = try? Data(contentsOf: dataFilePath!) { let decoder = PropertyListDecoder() do{ itemCells = try decoder.decode([Item].self, from: data) } catch { print("ERROR DECODING \(error)") } } } }
true
9e5af517bf140bef124744dd6b81023b7dca2b69
Swift
cyhunter/Geometria
/Tests/GeometriaTests/Generalized/Protocols/Vector/VectorComparableTests.swift
UTF-8
6,371
2.75
3
[ "MIT" ]
permissive
import XCTest import Geometria class VectorComparableTests: XCTestCase { func testMin() { let vec1 = Vector2i(x: 2, y: -3) let vec2 = Vector2i(x: -1, y: 4) XCTAssertEqual(min(vec1, vec2), Vector2i(x: -1, y: -3)) } func testMax() { let vec1 = Vector2i(x: 2, y: -3) let vec2 = Vector2i(x: -1, y: 4) XCTAssertEqual(max(vec1, vec2), Vector2i(x: 2, y: 4)) } func testMinimalComponentIndex() { XCTAssertEqual(TestVectorComparable(x: -1, y: 2).minimalComponentIndex, 0) XCTAssertEqual(TestVectorComparable(x: 1, y: -2).minimalComponentIndex, 1) } func testMinimalComponentIndex_equalXY() { XCTAssertEqual(TestVectorComparable(x: 1, y: 1).minimalComponentIndex, 1) } func testMaximalComponentIndex() { XCTAssertEqual(TestVectorComparable(x: -1, y: 2).maximalComponentIndex, 1) XCTAssertEqual(TestVectorComparable(x: 1, y: -2).maximalComponentIndex, 0) } func testMaximalComponentIndex_equalXY() { XCTAssertEqual(TestVectorComparable(x: 1, y: 1).maximalComponentIndex, 1) } func testGreaterThan() { XCTAssertTrue(TestVectorComparable(x: 1, y: 1) > TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: 0, y: 1) > TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: 1, y: 0) > TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: 0, y: 0) > TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: -1, y: 0) > TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: 0, y: -1) > TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: -1, y: -1) > TestVectorComparable(x: 0, y: 0)) } func testGreaterThan_mismatchedScalarCount_returnsFalse() { XCTAssertFalse(TestVectorComparable(x: 1, y: 1, scalarCount: 1) > TestVectorComparable(x: 0, y: 0)) } func testGreaterThanOrEqualTo() { XCTAssertTrue(TestVectorComparable(x: 1, y: 1) >= TestVectorComparable(x: 0, y: 0)) XCTAssertTrue(TestVectorComparable(x: 0, y: 1) >= TestVectorComparable(x: 0, y: 0)) XCTAssertTrue(TestVectorComparable(x: 1, y: 0) >= TestVectorComparable(x: 0, y: 0)) XCTAssertTrue(TestVectorComparable(x: 0, y: 0) >= TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: -1, y: 0) >= TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: 0, y: -1) >= TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: -1, y: -1) >= TestVectorComparable(x: 0, y: 0)) } func testGreaterThanOrEqualTo_mismatchedScalarCount_returnsFalse() { XCTAssertFalse(TestVectorComparable(x: 1, y: 1, scalarCount: 1) >= TestVectorComparable(x: 0, y: 0)) } func testLessThan() { XCTAssertFalse(TestVectorComparable(x: 1, y: 1) < TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: 0, y: 1) < TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: 1, y: 0) < TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: 0, y: 0) < TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: -1, y: 0) < TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: 0, y: -1) < TestVectorComparable(x: 0, y: 0)) XCTAssertTrue(TestVectorComparable(x: -1, y: -1) < TestVectorComparable(x: 0, y: 0)) } func testLessThan_mismatchedScalarCount_returnsFalse() { XCTAssertFalse(TestVectorComparable(x: -1, y: -1, scalarCount: 1) < TestVectorComparable(x: 0, y: 0)) } func testLessThanOrEqualTo() { XCTAssertFalse(TestVectorComparable(x: 1, y: 1) <= TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: 0, y: 1) <= TestVectorComparable(x: 0, y: 0)) XCTAssertFalse(TestVectorComparable(x: 1, y: 0) <= TestVectorComparable(x: 0, y: 0)) XCTAssertTrue(TestVectorComparable(x: 0, y: 0) <= TestVectorComparable(x: 0, y: 0)) XCTAssertTrue(TestVectorComparable(x: -1, y: 0) <= TestVectorComparable(x: 0, y: 0)) XCTAssertTrue(TestVectorComparable(x: 0, y: -1) <= TestVectorComparable(x: 0, y: 0)) XCTAssertTrue(TestVectorComparable(x: -1, y: -1) <= TestVectorComparable(x: 0, y: 0)) } func testLessThanOrEqualTo_mismatchedScalarCount_returnsFalse() { XCTAssertFalse(TestVectorComparable(x: -1, y: -1, scalarCount: 1) <= TestVectorComparable(x: 0, y: 0)) } func testMinimalComponent() { XCTAssertEqual(TestVectorComparable(x: -1, y: 2).minimalComponent, -1) XCTAssertEqual(TestVectorComparable(x: 1, y: -2).minimalComponent, -2) } func testMaximalComponent() { XCTAssertEqual(TestVectorComparable(x: -1, y: 2).maximalComponent, 2) XCTAssertEqual(TestVectorComparable(x: 1, y: -2).maximalComponent, 1) } } private struct TestVectorComparable: VectorComparable { typealias Scalar = Double var x: Double var y: Double var scalarCount: Int subscript(index: Int) -> Double { get { switch index { case 0: return x case 1: return y default: fatalError("index out of bounds") } } set { switch index { case 0: x = newValue case 1: y = newValue default: fatalError("index out of bounds") } } } init(x: Double, y: Double, scalarCount: Int = 2) { self.x = x self.y = y self.scalarCount = scalarCount } init(repeating scalar: Double) { self.init(x: scalar, y: scalar) } static func pointwiseMin(_ lhs: TestVectorComparable, _ rhs: TestVectorComparable) -> TestVectorComparable { TestVectorComparable(x: min(lhs.x, rhs.x), y: min(lhs.y, rhs.y)) } static func pointwiseMax(_ lhs: TestVectorComparable, _ rhs: TestVectorComparable) -> TestVectorComparable { TestVectorComparable(x: max(lhs.x, rhs.x), y: max(lhs.y, rhs.y)) } }
true
35d2730ff71fed0c1f0e7c082518a435097a01a7
Swift
hirotosuzuki/iphone-android-ml
/ch3/NaturalLanguageEx/NaturalLanguageEx/ViewController.swift
UTF-8
5,544
2.96875
3
[]
no_license
import UIKit import CoreML import Vision import NaturalLanguage //(1) //自然言語処理 class ViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var textView: UITextView! @IBOutlet weak var lblText: UILabel! @IBOutlet weak var segmentedControl: UISegmentedControl! //==================== //ライフサイクル //==================== //ロード完了時に呼ばれる override func viewDidLoad() { super.viewDidLoad() //UI self.textView.layer.borderColor = UIColor.black.cgColor self.textView.layer.borderWidth = 1.0 self.textView.layer.cornerRadius = 8.0 self.textView.layer.masksToBounds = true //自然言語処理の実行 analyze() } //==================== //イベント //==================== //セグメントコントロール変更時に呼ばれる @IBAction func onValueChanged(sender: UISegmentedControl) { //自然言語処理の実行 analyze() } //テキストビュー完了時に呼ばれる func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { self.textView.resignFirstResponder() //自然言語処理の実行 analyze() return false; } return true; } //==================== //自然言語処理 //==================== //自然言語処理の実行 func analyze() { if self.textView.text == nil || self.textView.text!.isEmpty {return} if self.segmentedControl.selectedSegmentIndex == 0 { self.language(self.textView.text!) } else if self.segmentedControl.selectedSegmentIndex == 1 { self.tokenize(self.textView.text!) } else if self.segmentedControl.selectedSegmentIndex == 2 { self.tagging(self.textView.text!) } else if self.segmentedControl.selectedSegmentIndex == 3 { self.lemmaization(self.textView.text!) } else if self.segmentedControl.selectedSegmentIndex == 4 { self.namedEntry(self.textView.text!) } } //(2)言語判定 func language(_ text: String) { //言語判定の実行 let tagger = NLTagger(tagSchemes: [.language]) tagger.string = text let language = tagger.dominantLanguage!.rawValue //対応しているタグスキームの取得 let schemes = NLTagger.availableTagSchemes( for: .word, language: NLLanguage(rawValue: language)) var schemesText = "Schemes :\n" for scheme in schemes { schemesText += " \(scheme.rawValue)\n" } //UIの更新 self.lblText.text = "Language : \(language)\n\n\(schemesText)" } //(3)トークン化 func tokenize(_ text: String) { self.lblText.text = "" //トークン化の準備 let tokenizer = NLTokenizer(unit: .word) tokenizer.string = text //トークン化の実行 tokenizer.enumerateTokens(in: text.startIndex..<text.endIndex) { tokenRange, _ in self.lblText.text = self.lblText.text!+text[tokenRange]+"\n" return true } } //(4)品詞タグ付け func tagging(_ text: String) { self.lblText.text = "" //品詞タグ付けの準備 let tagger = NLTagger(tagSchemes: [.lexicalClass]) tagger.string = text //品詞タグ付けの実行 let options: NLTagger.Options = [.omitPunctuation, .omitWhitespace] tagger.enumerateTags(in: text.startIndex..<text.endIndex, unit: .word, scheme: .lexicalClass, options: options) { tag, tokenRange in self.lblText.text = self.lblText.text!+text[tokenRange]+" : "+tag!.rawValue+"\n" return true } } //(5)レンマ化 func lemmaization(_ text: String) { self.lblText.text = "" //レンマ化の準備 let tagger = NLTagger(tagSchemes: [.lemma]) tagger.string = text let options: NLTagger.Options = [.omitPunctuation, .omitWhitespace] //レンマ化の実行 tagger.enumerateTags(in: text.startIndex..<text.endIndex, unit: .word, scheme: .lemma, options: options) { tag, tokenRange in if tag != nil { self.lblText.text = self.lblText.text!+text[tokenRange]+" : "+tag!.rawValue+"\n" } return true } } //(6)固有表現抽出 func namedEntry(_ text: String) { self.lblText.text = "" //固有表現抽出の準備 let tagger = NLTagger(tagSchemes: [.nameType]) tagger.string = text let options: NLTagger.Options = [.omitPunctuation, .omitWhitespace, .joinNames] //固有表現抽出の実行 tagger.enumerateTags(in: text.startIndex..<text.endIndex, unit: .word, scheme: .nameType, options: options) { tag, tokenRange in let tags: [NLTag] = [.personalName, .placeName, .organizationName] if let tag = tag, tags.contains(tag) { self.lblText.text = self.lblText.text!+text[tokenRange]+" : "+tag.rawValue+"\n" } return true } } }
true
11b586a1576e297234e3fb3338e7e4e65519a618
Swift
silverhammermba/CreativeKitchen
/Creative Kitchen/CategoryViewModel.swift
UTF-8
313
2.59375
3
[]
no_license
// // CategoryViewModel.swift // Creative Kitchen // // Created by Maxwell Anselm on 4/18/20. // Copyright © 2020 Max. All rights reserved. // import Foundation struct CategoryViewModel { let name: String let options: [String] func sample() -> String { return options.randomElement()! } }
true
5bdbbd05f2c26b52d386a5026af86fe458829202
Swift
DG0BAB/Apocha
/Sources/Receipts.swift
UTF-8
10,143
2.609375
3
[]
no_license
// // Receipts.swift // Apocha // // Created by Joachim Deelen on 26.10.16. // Copyright © 2016 micabo software UG. All rights reserved. // import Foundation // #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) // MARK: - Receipt /** A Receipt provides all the receipt fields for an App-Receipt. It bundles all the Receipt Fields from the payload of the receipt file that was created during the purchase of an App from the MacApp Store or during an In-App-Purchase. If the Receipt is from an In-App-Purchase, the property `inAppPurchaseReceipts` holds the corresponding Receipt Fields. **See also:** [Receipt Validation Programming Guide - Receipt Fields](https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ReceiptFields.html#//apple_ref/doc/uid/TP40010573-CH106-SW1) */ public struct Receipt { /// The app’s bundle identifier. /// This corresponds to the value of CFBundleIdentifier in the Info.plist file. let bundleIdentifier: String /// The app’s version number. /// This corresponds to the value of CFBundleVersion (in iOS) or CFBundleShortVersionString (in OS X) in the Info.plist. let appVersion: String /// An opaque value used, with other data, to compute the SHA-1 hash during validation. let opaqueValue: Data ///A SHA-1 hash, used to validate the receipt. let sha1Hash: Data /** An Array with in-app purchase receipts. **From the Receipt Validation Programming Guide:** The in-app purchase receipt for a consumable product is added to the receipt when the purchase is made. It is kept in the receipt until your app finishes that transaction. After that point, it is removed from the receipt the next time the receipt is updated—for example, when the user makes another purchase or if your app explicitly refreshes the receipt. The in-app purchase receipt for a non-consumable product, auto-renewable subscription, non-renewing subscription, or free subscription remains in the receipt indefinitely. */ let inAppPurchaseReceipts: [InAppPurchaseReceipt]? /// The version of the app that was originally purchased. /// This corresponds to the value of CFBundleVersion (in iOS) or CFBundleShortVersionString (in OS X) in the /// Info.plist file when the purchase was originally made. /// In the sandbox environment, the value of this field is always “1.0”. let originalApplicationVersion: String /** The date when the app receipt was created. When validating a receipt, use this date to validate the receipt’s signature. - note: *From the Receipt Validation Programming Guide:* Many cryptographic libraries default to using the device’s current time and date when validating a pkcs7 package, but this may not produce the correct results when validating a receipt’s signature. For example, if the receipt was signed with a valid certificate, but the certificate has since expired, using the device’s current date incorrectly returns an invalid result. Therefore, make sure your app always uses the date from the Receipt Creation Date field to validate the receipt’s signature. */ let receiptCreationDate: Date /// The date that the app receipt expires. /// This key is present only for apps purchased through the Volume Purchase Program. If this key is not present, /// the receipt does not expire. When validating a receipt, compare this date to the current date to determine whether /// the receipt is expired. Do not try to use this date to calculate any other information, such as the time remaining /// before expiration. let receiptExpirationDate: Date? } // MARK: - InAppPurchaseReceipt public struct InAppPurchaseReceipt { let quantity: Int let productIdentifier: String let transactionIdentifier: String let originalTransactionIdentifier: String let purchaseDate: Date let originalPurchaseDate: Date let subscriptionExpirationDate: Date? let cancellationDate: Date? let appItemId: String? let externalVersionIdentifier: String? let webOrderLineItemId: Int? } // MARK: - Custom Operator /// Conjunction Operator to chain calls together that return an OSStatus Value infix operator >>>: LogicalConjunctionPrecedence private func >>>(result: OSStatus, function: @autoclosure () -> OSStatus) -> OSStatus { if result == noErr { return function() } return result } // MARK: - RawReceipt /** A RawReceipt contains the encrypted data of the Receipt exactly how it is stored at a given URL. A RawReceipt is initialized with an URL. During initialization, the receipt is read and contents are stored within an internal Buffer of type Data. Use the decode function to decrypt the RwaReceipt into a DecodedReceipt */ open class RawReceipt { private let url: URL private let data: Data /** Initialize a RawReceipt with the contents of a receipt at a given URL - parameter url:The URL of the receipt - throws: ApochaError.invalidReceipt In case there is no receipt at the given URL or the receipt can not be read. */ public init(url: URL) throws { do { data = try Data(contentsOf: url) self.url = url } catch let error { throw ApochaError.invalidReceiptURL(error) } } /** Decode the receipt and create a DecodedReceipt out of it. - throws: ApochaError.decodingReceipt(DecodingFailures) - returns: DecodedReceipt */ public func decode() throws -> DecodedReceipt { var itemFormat: SecExternalFormat = .formatPKCS7 var itemType: SecExternalItemType = .itemTypeUnknown var outItems: CFArray? let importStatus = SecItemImport(data as CFData, nil, &itemFormat, &itemType, [SecItemImportExportFlags.pemArmour], nil, nil, &outItems) guard let certificates = outItems as? [SecCertificate], importStatus == noErr, certificates.count == 3 else { throw ApochaError.decodingReceipt(.retrievingCertificates) } var decoder: CMSDecoder? var content: CFData? var numberOfSigners: Int = 0 var signerStatus: CMSSignerStatus = .unsigned var certificateVerificationStatus: OSStatus = OSStatus(CSSM_TP_CERTVERIFY_STATUS(CSSM_TP_CERTVERIFY_UNKNOWN)) let bytes: UnsafeMutablePointer<UInt8> = UnsafeMutablePointer.allocate(capacity: data.count) data.copyBytes(to: bytes, count: data.count) let basicX509Policy: SecPolicy = SecPolicyCreateBasicX509() let status = CMSDecoderCreate(&decoder) >>> CMSDecoderUpdateMessage(decoder!, bytes, data.count) >>> CMSDecoderFinalizeMessage(decoder!) >>> CMSDecoderCopyContent(decoder!, &content) >>> CMSDecoderGetNumSigners(decoder!, &numberOfSigners) >>> CMSDecoderCopySignerStatus(decoder!, 0, basicX509Policy, true, &signerStatus, nil, &certificateVerificationStatus) guard let payload = content as Data?, status == noErr else { throw ApochaError.decodingReceipt(.retrievingPayload) } return DecodedReceipt(certificates: certificates, payload: payload, numSigners: numberOfSigners, signerStatus: signerStatus, certVerificationStatus: CSSM_TP_CERTVERIFY_STATUS(certificateVerificationStatus)) } } // MARK: - Decoded Receipt /** A DecodedReceipt contains the decrypted data of a RawReceipt. Create a DecodedReceipt by calling the decode function of a RawReceipt. Then check the desired values, like certificates, signerStatus, numSigners in your application code if they match what you expect. Try to obfuscate these checks as good as possible. */ public struct DecodedReceipt { /// The Certificates used to sign this receipt public let certificates: [SecCertificate]? /// The number of certificates used to sign the receipt public var numCertificates: Int { guard let num = certificates?.count else { return 0 } return num } /// The number of signers. Check, if it matches the expected number of signers public let numSigners: Int /// Signer Status. Check if this matches the desired status. public let signerStatus: CMSSignerStatus /// The verifications status of the certificates. Check, if this matches the disired status. public let certVerificationStatus: CSSM_TP_CERTVERIFY_STATUS private let payload: Data? /** Initialzes a DecodedReceipt with the given values. - parameters: - certificates: An array with certificates - payload: The encrypted raw payload of the receipt - numSigners: The number of signers. Default = 0 - signerStatus: The signer status. Default is .unsigned - certVerificationStatus: The status of the certificate verification. Default = CSSM_TP_CERTVERIFY_UNKNOWN */ public init(certificates: [SecCertificate], payload: Data, numSigners: Int = 0, signerStatus: CMSSignerStatus = .unsigned, certVerificationStatus: CSSM_TP_CERTVERIFY_STATUS = CSSM_TP_CERTVERIFY_STATUS(CSSM_TP_CERTVERIFY_UNKNOWN)) { self.certificates = certificates self.payload = payload self.numSigners = numSigners self.signerStatus = signerStatus self.certVerificationStatus = certVerificationStatus } /** Retrieves the values for the given certificate. The values are returned as a nested dictionary. - parameter certificate: Certificate of type SecCertificate to get the values from - throws: ApochaError.retrievingCertificateValues(Error) - returns: A dictionary of type [String : Any] */ public func valuesFromCertificate(_ certificate: SecCertificate) throws -> [String : Any]? { var error: Unmanaged<CFError>? guard let result = SecCertificateCopyValues(certificate, nil, &error) as? [String : Any] else { throw ApochaError.retrievingCertificateValues(error as! Error) } return result } /** The Receipt with all the values that you might be interested in and that you should use withinh your App. Actually this is the decrypted payload of this DecodedReceipt. The returned Receipt holds all the properties as descriped in the section Receipt Fields of the Receipt Validation Programming Guide. **See also:** [Receipt Validation Programming Guide - Receipt Fields](https://developer.apple.com/library/content/releasenotes/General/ValidateAppStoreReceipt/Chapters/ReceiptFields.html#//apple_ref/doc/uid/TP40010573-CH106-SW1) */ public lazy var receipt: Receipt? = { guard let payload = self.payload else { return nil } return Receipt(payload: payload) }() }
true
1c7f7e53e1cde06fe7ec733eaceafa139b723ce9
Swift
patelpra337/ios-guided-project-starter-core-data-i-basics
/Tasks/Tasks/Model/Task+Convenience.swift
UTF-8
850
3.078125
3
[]
no_license
// // Task+Convenience.swift // Tasks // // Created by patelpra on 4/21/20. // Copyright © 2020 Lambda School. All rights reserved. // import Foundation import CoreData // We need a way to initialzie a Task object give its properties extension Task { @discardableResult convenience init(identifier: UUID = UUID(), name: String, notes: String?, complete: Bool = false, context: NSManagedObjectContext) { // Set up the NSManagedObject portion of the Task object self.init(context: context) // Assign our unique values to the attributes we created in the data model file self.identifier = identifier self.name = name self.notes = notes self.complete = complete } }
true
40a818e344bddd8bd390f31b39fdd749dc0f1c6d
Swift
miinucolortherapy/TableViewTools
/Sources/TableViewManager/Extensions/TableViewManager+UITableViewDataSourcePrefetching.swift
UTF-8
1,173
2.703125
3
[ "MIT" ]
permissive
// // TableViewManager+UITableViewDataSourcePrefetching.swift // TableViewTools // // Created by Artem Novichkov on 22/12/2016. // Copyright © 2016 Rosberry. All rights reserved. // import UIKit.UITableView extension TableViewManager: UITableViewDataSourcePrefetching { public func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { var cellItems = [TableViewCellItemProtocol]() for indexPath in indexPaths { if let cellItem = self[indexPath] { cellItems.append(cellItem) } } for (index, cellItem) in cellItems.enumerated() { if let cellItem = cellItem as? TableViewCellItemDataSourcePrefetching { cellItem.prefetchData(for: tableView, at: indexPaths[index]) } } } public func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) { for indexPath in indexPaths { if let cellItem = self[indexPath] as? TableViewCellItemDataSourcePrefetching { cellItem.cancelPrefetchingData(for: tableView, at: indexPath) } } } }
true
1889443798d78290b5401cb120b53b6869d185f1
Swift
TejaRamMurthy/SwiftAFNetworkingDemo
/SwiftAFNetworkingDemo/WeatherHTTPClient.swift
UTF-8
2,391
2.796875
3
[]
no_license
// // WeatherHTTPClient.swift // SwiftAFNetworkingDemo // // Created by Richard Lee on 8/13/14. // Copyright (c) 2014 Weimed. All rights reserved. // import Foundation import CoreLocation @objc protocol WeatherHTTPClientDelegate { optional func weatherHTTPClient(#client: WeatherHTTPClient, didUpdateWithWeather weather: AnyObject) optional func weatherHTTPClient(#client: WeatherHTTPClient, didFailWithError error: NSError) } // Reference: https://developer.worldweatheronline.com/ - How to apply YOUR API KEY let WorldWeatherOnlineAPIKey = "PASTE YOUR API KEY HERE" let WorldWeatherOnlineURLString = "http://api.worldweatheronline.com/free/v1/" let WeatherHTTPClientSharedInstance = WeatherHTTPClient(baseURL: NSURL.URLWithString(WorldWeatherOnlineURLString)) class WeatherHTTPClient: AFHTTPSessionManager { var delegate: WeatherHTTPClientDelegate? required init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override init(baseURL url: NSURL!) { super.init(baseURL: url, sessionConfiguration: nil) requestSerializer = AFJSONRequestSerializer() responseSerializer = AFJSONResponseSerializer() requestSerializer.setValue(WorldWeatherOnlineAPIKey, forHTTPHeaderField: "X-Api-Key") requestSerializer.setValue("3", forHTTPHeaderField: "X-Api-Version") } class var sharedInstance: WeatherHTTPClient { return WeatherHTTPClientSharedInstance } func updateWeatherAtLocation(#location: CLLocation, forNumberOfDays number: UInt) { var parameters = ["num_of_days": number, "format": "json", "key": WorldWeatherOnlineAPIKey] as Dictionary parameters["q"] = NSString(format: "%f,%f", location.coordinate.latitude, location.coordinate.longitude) //parameters["q"] = "32.35,141.43" self.GET("weather.ashx", parameters: parameters, success: { (task: NSURLSessionDataTask!, responseObject: AnyObject!) -> Void in self.delegate?.weatherHTTPClient?(client: self, didUpdateWithWeather: responseObject) var weather = responseObject as NSDictionary NSLog(weather.description) }, failure: { (task: NSURLSessionDataTask!, error: NSError!) -> Void in NSLog("GET failed: %@", error) self.delegate?.weatherHTTPClient?(client: self, didFailWithError: error) }) } }
true
954bbb31513cdcdf2efc60f137e61af1fd84d168
Swift
akramhusseini/NYTimesMostPopular
/NYTimesMostPopular/MVP/service/mostPopularService.swift
UTF-8
955
2.625
3
[ "MIT" ]
permissive
// // mostPopularService.swift // NYTimesMostPopular // // Created by Akram Samir Akram Husseini on 5/25/20. // Copyright © 2020 Akram Samir Akram Husseini. All rights reserved. // import Foundation class mostPopularService { init() { } /** calls API to lead news items - Parameter: none - Returns: none */ func getNews(completion: @escaping (NSDictionary?, Error?) -> Void) { let url = "https://api.nytimes.com/svc/mostpopular/v2/viewed/7.json" let Parms : [String:String] = ["api-key":"L5YbAz2Yqi0FmXILU7L1W9yYFKu2U17Z"] httpManager.get(url: url, parameters: Parms) { (result, error) in if let error = error { // debugPrint(error.localizedDescription) completion(nil, error) } else if let result = result { completion(result, error) } } } }
true
41cff4e10de47c73e2c8074e8ec0402bae3bf103
Swift
pmanna/LetsGetCheckedDevChallenge
/LetsGetCheckedApp/Classes/Utils/CloudService.swift
UTF-8
6,805
2.734375
3
[]
no_license
// // CloudService.swift // // Created by Paolo Manna on 23/02/2017. // import Foundation /* A bit of explanation here: It would have been possible, and seemingly more natural, to use a serial DispatchQueue or OperationQueue to achieve the same serial behaviour for the service, however canceling a specific task would have been hard */ public class CloudService { static let session = URLSession(configuration: .ephemeral) static var queueReqs = true var headers: [String:String] var urlProtocol = "https" var serviceString = "localhost:8080" var basePath = "" var tasks = [URLSessionDataTask]() var lock = NSLock() #if DEBUG || TEST var timeStart: TimeInterval = 0.0 #endif // MARK:- Methods required public init(token aToken: String? = nil) { headers = [String:String]() headers["Content-Type"] = "application/json" headers["Cache-Control"] = "No-Cache" headers["Accept"] = "*/*" headers["Accept-Encoding"] = "gzip, deflate" if let token = aToken { headers["Authorization"] = "Bearer " + token } } func enqueue(task: URLSessionDataTask) { // Add task to the queue: it will be removed when response arrives // Under lock to support multi-threading if lock.lock(before: Date.distantFuture) { #if DEBUG || TEST print("Queueing task \(tasks.count)") #endif tasks.append(task) // If it's the only element in the queue, start it if tasks.count == 1 { #if DEBUG || TEST print("Starting task 0") timeStart = Date.timeIntervalSinceReferenceDate #endif task.resume() } lock.unlock() } } func dequeue() { guard tasks.count > 0 else { return } if lock.lock(before: Date.distantFuture) { #if DEBUG || TEST print("Dequeueing task 0 of \(tasks.count): response took \(((Date.timeIntervalSinceReferenceDate - timeStart) * 1000.0).rounded() / 1000.0) secs") #endif tasks.remove(at: 0) // If there's another element in the queue, start it if tasks.count > 0 { #if DEBUG || TEST print("Starting task 0 of \(tasks.count)") timeStart = Date.timeIntervalSinceReferenceDate #endif tasks[0].resume() } lock.unlock() } } func cancelPending() { guard tasks.count > 0 else { return } if lock.lock(before: Date.distantFuture) { #if DEBUG || TEST print("Trying to cancel task 0") #endif tasks.first?.cancel() lock.unlock() dequeue() } } func cancelAll() { guard tasks.count > 0 else { return } if lock.lock(before: Date.distantFuture) { for task in tasks { task.cancel() } tasks.removeAll() lock.unlock() } } func send(request: URLRequest, convert:Bool, completion: @escaping (Error?, Any?) -> Void) -> Void { let task = CloudService.session.dataTask(with: request) { (data, response, error) in if let httpResponse = response as? HTTPURLResponse { if httpResponse.statusCode < 200 || httpResponse.statusCode > 399 { let serverMsg = HTTPURLResponse.localizedString(forStatusCode: httpResponse.statusCode) completion(NSError(domain: Bundle.main.bundleIdentifier!, code: httpResponse.statusCode, userInfo: [NSLocalizedDescriptionKey: serverMsg]), nil) self.dequeue() return } let responseHeaders = httpResponse.allHeaderFields if let contentType = responseHeaders["Content-Type"] as? String, !contentType.contains("application/json") { completion(NSError(domain: Bundle.main.bundleIdentifier!, code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid response: not a JSON payload"]), nil) self.dequeue() return } } if convert { var responseObject: Any? = nil if data != nil && data!.count > 0 { responseObject = try? JSONSerialization.jsonObject(with: data!, options: [.mutableContainers]) } completion(error, responseObject) } else { completion(error,data) } self.dequeue() } if CloudService.queueReqs { enqueue(task: task) } else { task.resume() } } func get(endpoint: String, parameters: [String:String] = [:], convert:Bool = true, completion: @escaping (Error?, Any?) -> Void) -> Void { var queryString = "" for aKey in parameters.keys { if let paramValue = (parameters[aKey])?.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { if queryString.count > 1 { queryString.append("&") } else { queryString.append("?") } queryString.append("\(aKey)=\(paramValue)") } } var request = URLRequest(url: URL(string: "\(urlProtocol)://\(serviceString)\(basePath)/\(endpoint)\(queryString)")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30.0) request.httpMethod = "GET" request.allHTTPHeaderFields = headers send(request: request, convert: convert, completion: completion) } func prepareBody(with parameters: [String:Any]) -> Data? { if #available(iOS 11, *) { return try? JSONSerialization.data(withJSONObject: parameters, options: [.sortedKeys]) } else { return try? JSONSerialization.data(withJSONObject: parameters, options: []) } } func post(endpoint: String, parameters: [String:Any], convert:Bool = true, completion: @escaping (Error?, Any?) -> Void) -> Void { var request = URLRequest(url: URL(string: "\(urlProtocol)://\(serviceString)\(basePath)/\(endpoint)")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30.0) request.httpMethod = "POST" request.allHTTPHeaderFields = headers request.httpBody = prepareBody(with: parameters) send(request: request, convert: convert, completion: completion) } func put(endpoint: String, parameters: [String:Any], convert:Bool = true, completion: @escaping (Error?, Any?) -> Void) -> Void { var request = URLRequest(url: URL(string: "\(urlProtocol)://\(serviceString)\(basePath)/\(endpoint)")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30.0) request.httpMethod = "PUT" request.allHTTPHeaderFields = headers request.httpBody = prepareBody(with: parameters) send(request: request, convert: convert, completion: completion) } }
true
49989ef6791eccc362bda224983d3c8123d165c8
Swift
sashatop1/moneyBudget
/budgetManager/Extensions.swift
UTF-8
456
3.21875
3
[]
no_license
import Foundation extension Array where Element: Hashable { var unique: [Element] { return self.reduce([]) { $0.contains($1) ? $0 : $0 + [$1] } } } extension NumberFormatter { static var customFormatter: NumberFormatter { let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.maximumFractionDigits = 4 formatter.roundingMode = .halfEven return formatter } }
true
1ea3cb1aad2a1cfdef790acbfe79c4b1f95fa92a
Swift
seeshaughnessy/WeFly
/WeFly/Shapes/Squares.swift
UTF-8
771
3.328125
3
[]
no_license
// // Squares.swift // WeFly // // Created by Chris Shaughnessy on 4/12/21. // import SwiftUI struct Squares: View { //MARK: - PROPERTIES let angle: Double = 30 let numberOfSquares: Int = 5 let multiplier: Int = 25 let size: CGFloat = 180 //MARK: - BODY var body: some View { ZStack { ForEach(0..<numberOfSquares) { i in Square() .border(Color.black.opacity(0.05)) .frame(width: size - CGFloat(i * multiplier), height: size - CGFloat(i * multiplier), alignment: .center) .rotationEffect(Angle(degrees: angle), anchor: .center) } } } } //MARK: - PREVIEW struct Squares_Previews: PreviewProvider { static var previews: some View { Squares() } }
true
0ec97247868ee90a4b6909feebb53ba9b3130ae1
Swift
nhat292/iosproject
/iosproject/helpers/AlertUtils.swift
UTF-8
1,706
2.71875
3
[]
no_license
// // AlertUtils.swift // iosproject // // Created by Nguyen Van Nhat on 9/10/18. // Copyright © 2018 Nguyen Van Nhat. All rights reserved. // import Foundation import UIKit typealias Confirm = (Int, Any?) -> () class AlertUtils { class func textFieldAlert(title: String?, message: String?, keyboardType: UIKeyboardType, placeholder: String, confirm: Confirm?) -> UIAlertController { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.applyAppStyle() alert.addTextField { (textField) in textField.font = UIFont.systemFont(ofSize: 15) textField.textAlignment = .center textField.placeholder = placeholder textField.keyboardType = keyboardType } alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (a) in confirm?(0, alert.textFields![0].text!) })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (alert) in confirm?(1, nil) })) return alert } class func alert(title: String?, message: String?, ok: String?, cancel: String?, confirm: Confirm?) -> UIAlertController { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.applyAppStyle() if ok != nil { alert.addAction(UIAlertAction(title: ok, style: .default, handler: { (a) in confirm?(0, nil) })) } if cancel != nil { alert.addAction(UIAlertAction(title: cancel, style: .cancel, handler: { (alert) in confirm?(1, nil) })) } return alert } }
true
973fe773550bbb7a6074dcd5edd1914ac600f989
Swift
Sam1247/Graphical-Set
/Graphical Set/View/PlayingCardView.swift
UTF-8
2,297
2.921875
3
[]
no_license
// // PlayingCardView.swift // Graphical Set // // Created by Abdalla Elsaman on 7/5/19. // Copyright © 2019 Dumbies. All rights reserved. // import UIKit class PlayingCardView: UIView { var count : Count? var kind : Kind? var shadding : Shadding? var color : Color? func setVarients(count: Count, kind: Kind, shadding: Shadding, color: Color) { self.count = count self.kind = kind self.shadding = shadding self.color = color } override init(frame: CGRect) { super.init(frame: frame) self.frame = frame self.backgroundColor = .white self.clipsToBounds = true self.layer.borderWidth = 1 self.layer.borderColor = UIColor.gray.cgColor self.layer.cornerRadius = 1 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { var shapes = [ShapeView]() for _ in 0..<count!.rawValue { let newShape = ShapeView(frame: frame) newShape.translatesAutoresizingMaskIntoConstraints = false newShape.kind = kind newShape.color = color newShape.shadding = shadding newShape.isOpaque = false shapes.append(newShape) } let stack = UIStackView(arrangedSubviews: shapes) stack.translatesAutoresizingMaskIntoConstraints = false stack.axis = .vertical stack.spacing = frame.height/16 stack.distribution = .fillEqually addSubview(stack) // constrains stack.leftAnchor.constraint(equalTo: leftAnchor, constant: frame.width * Constants.marginRatio).isActive = true stack.rightAnchor.constraint(equalTo: rightAnchor, constant: -frame.width * Constants.marginRatio).isActive = true stack.heightAnchor.constraint(equalToConstant: frame.height * CGFloat(shapes.count) / 3 - frame.height * Constants.marginRatio).isActive = true stack.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true } } extension CGPoint { func offsetBy(dx: CGFloat, dy: CGFloat) -> CGPoint { return CGPoint(x: x + dx, y: y + dy) } }
true
efe88af370d480778bb9b3ba1fd3327fac249e34
Swift
Abay99/IOS_Tasks-Projects
/MapTask/MapTask/CellModel.swift
UTF-8
1,253
2.796875
3
[]
no_license
// // CellModel.swift // MapTask // // Created by Abai Kalikov on 28.03.18. // Copyright © 2018 Abai Kalikov. All rights reserved. // import Foundation import Cartography class CellModel: UITableViewCell{ lazy var titleLabel: UILabel = { var label = UILabel() label.font = UIFont.boldSystemFont(ofSize: 23 / 736 * UIScreen.main.bounds.height) return label }() lazy var subtitleLabel:UILabel = { var label = UILabel() label.font = UIFont.systemFont(ofSize: 20 / 736 * UIScreen.main.bounds.height) return label }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(titleLabel) addSubview(subtitleLabel) setupConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupConstraints(){ constrain(titleLabel, self){ tl, s in tl.top == s.top + 10 tl.left == s.left + 10 } constrain(subtitleLabel, titleLabel, self){ sl, tl, s in sl.top == tl.top + 40 sl.left == s.left + 10 } } }
true
3fc97827833ed8499c74caf97c57320ea1fa1b4a
Swift
samyanez94/Swift-Algorithms
/InsertionSort.playground/Sources/InsertionSort.swift
UTF-8
1,067
4.0625
4
[ "MIT" ]
permissive
import Foundation public extension Array where Element: Comparable { /// Insertion sort works similarly to the algorithm that people often use to sort bridge hands. This is to consider the cards one at a time, inserting each into its proper place among those already considered. /// /// - Complexity: O(n^2) mutating func insertionSort() { insertionSort(orderCriteria: <) } /// Insertion sort works similarly to the algorithm that people often use to sort bridge hands. This is to consider the cards one at a time, inserting each into its proper place among those already considered. /// /// - Complexity: O(n^2) /// /// - Parameter orderCriteria: Closure used to sort the array. mutating func insertionSort(orderCriteria: (Element, Element) -> Bool) { for i in stride(from: 1, to: count, by: 1) { for j in stride(from: i, to: 0, by: -1) { if orderCriteria(self[j], self[j - 1]) { swapAt(j, j - 1) } } } } }
true
f005098860dee8dea2f3c0b0621fe0b1c414058d
Swift
codecet/CalmMeditation
/WatchKit Extension/WatchMeditations.swift
UTF-8
1,421
2.703125
3
[]
no_license
import WatchKit import Foundation import UIKit class WatchMeditations: WKInterfaceController { @IBOutlet var table: WKInterfaceTable! /* MARK: Initialising /////////////////////////////////////////// */ override func awake(withContext context: Any?) { super.awake(withContext: context) table.setNumberOfRows(Constants.Meditations.MEDITATIONS_ALL.count, withRowType: "MeditationRow") for index in 0..<Constants.Meditations.MEDITATIONS_ALL.count{ guard let controller = table.rowController(at: index) as? MeditationRow else { continue } let meditation = Constants.Meditations.MEDITATIONS_ALL[index] as [Any] controller.meditation = meditation } } /* MARK: Table Functionality /////////////////////////////////////////// */ override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) { let meditation = Constants.Meditations.MEDITATIONS_ALL[rowIndex] as [Any] presentController(withName: "WatchMeditation", context: meditation) } } class MeditationRow: NSObject { @IBOutlet var titleLabel: WKInterfaceLabel! @IBOutlet var imageGroup: WKInterfaceGroup! @IBOutlet var image: WKInterfaceImage! var meditation: [Any]? { didSet { guard let meditation = meditation else { return } titleLabel.setText((meditation[2] as! String)) imageGroup.setCornerRadius(5) image.setImage(UIImage(named: (meditation[0] as! String))) } } }
true
5a263fcd72b7b061624255a6391bb98e69a8f684
Swift
mitchproulx/MobileSwiftGraphics
/GraphicsProject/ViewController.swift
UTF-8
4,280
2.734375
3
[]
no_license
// // ViewController.swift // GraphicsProject // // Mitchell Proulx // 7660132 // import UIKit import Metal class ViewController: UIViewController { var device: MTLDevice! // direct connection to the GPU var metalLayer: CAMetalLayer! // for drawing to the screen var pipelineState: MTLRenderPipelineState! // keeps track of compiled render pipeline var commandQueue: MTLCommandQueue! // ordered list of commands sent to the GPU var timer: CADisplayLink! // called everytime device screen refreshes var projectionMatrix: Matrix4! var lastFrameTimestamp: CFTimeInterval = 0.0 //var objectToDraw: Triangle! var objectToDraw: Cube! override func viewDidLoad() { super.viewDidLoad() device = MTLCreateSystemDefaultDevice() // for access to the GPU // load projectionMatrix projectionMatrix = Matrix4.makePerspectiveView( angle: Float(85).radians, aspectRatio: Float(self.view.bounds.size.width / self.view.bounds.size.height), nearZ: 0.01, farZ: 100.0) metalLayer = CAMetalLayer() // for drawing to screen metalLayer.framebufferOnly = true // apple recommends for perfomance issues metalLayer.pixelFormat = .bgra8Unorm // 8 bytes for blue, green, red, alpha (normalized 0-1) metalLayer.frame = view.layer.frame // set frame of the layerto match the frame of the view metalLayer.device = device // specify the device the layer should use // add new layer as a sub layer view.layer.addSublayer(metalLayer) //objectToDraw = Triangle(device: device) objectToDraw = Cube(device: device) // access any of the precompiled shaders in the project (MTLLibrary) let mtlDefaultLibrary = device.newDefaultLibrary()! let fragShader_Program = mtlDefaultLibrary.makeFunction(name: "shade_fragment") let vertShader_Program = mtlDefaultLibrary.makeFunction(name: "shade_vertex") // set up render pipeline with vertex & fragement shaders let pipelineStateDescriptor = MTLRenderPipelineDescriptor() pipelineStateDescriptor.vertexFunction = vertShader_Program pipelineStateDescriptor.fragmentFunction = fragShader_Program pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm // compile pipeline configuration pipelineState = try! device.makeRenderPipelineState(descriptor: pipelineStateDescriptor) // tell GPU to execute commands commandQueue = device.makeCommandQueue() // app will call gameloop() when screen refreshes timer = CADisplayLink(target: self, selector: #selector(ViewController.gameloop)) timer.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode) } func render() { guard let drawable = metalLayer?.nextDrawable() else { return } let worldModelMatrix = Matrix4() worldModelMatrix.translate(x: 0.0, y: 0.0, z: -7.0) worldModelMatrix.rotateAround(x: Float(20).radians, y: 0.0, z: 0.0) objectToDraw.render(commandQueue: commandQueue, pipelineState: pipelineState, drawable: drawable, parentModelViewMatrix: worldModelMatrix, projectionMatrix: projectionMatrix ,clearColor: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // 1 func newFrame(displayLink: CADisplayLink){ if lastFrameTimestamp == 0.0 { lastFrameTimestamp = displayLink.timestamp } // 2 let elapsed: CFTimeInterval = displayLink.timestamp - lastFrameTimestamp lastFrameTimestamp = displayLink.timestamp // 3 gameloop(timeSinceLastUpdate: elapsed) } func gameloop(timeSinceLastUpdate: CFTimeInterval) { // 4 objectToDraw.updateWithDelta(delta: timeSinceLastUpdate) // 5 autoreleasepool { self.render() } } }
true
832dffcbbee598498e6854e9ebf33f4fc891206e
Swift
TrendingTechnology/swift-css
/Sources/SwiftCss/Properties/FlexWrap.swift
UTF-8
809
3.375
3
[ "WTFPL" ]
permissive
// // FlexWrap.swift // SwiftCss // // Created by Tibor Bodecs on 2021. 07. 10.. // public enum FlexWrapValue: String { /// Default value. Specifies that the flexible items will not wrap case nowrap /// Specifies that the flexible items will wrap if necessary case wrap /// Specifies that the flexible items will wrap, if necessary, in reverse order case wrapReverse = "wrap-reverse" /// Sets this property to its default value. case initial /// Inherits this property from its parent element. case inherit } public func FlexWrap(_ value: String) -> Property { Property(name: "flex-wrap", value: value) } /// Specifies whether the flexible items should wrap or not public func FlexWrap(_ value: FlexWrapValue = .nowrap) -> Property { FlexWrap(value.rawValue) }
true
5133755d22f976fef6eea420ee17095cc6e2389e
Swift
comister/YACA
/YACA/AppDelegate.swift
UTF-8
4,942
2.671875
3
[]
no_license
// // AppDelegate.swift // YACA // // Created by Andreas Pfister on 03/12/15. // Copyright © 2015 Andy P. All rights reserved. // import UIKit import Contacts import EventKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let contactStore = CNContactStore() let eventStore = EKEventStore() let locationManager = CLLocationManager() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. CoreDataStackManager.sharedInstance().saveContext() { print("saved Core Data context, now shutting down !") } } // MARK: - Adding this function to AppDelegate to have access from everywhere (which would be possible otherwise as well, for sure) func checkContactsAuthorizationStatus(_ completionHandler: @escaping (_ accessGranted: Bool) -> Void) { let status = CNContactStore.authorizationStatus(for: CNEntityType.contacts) switch(status) { case CNAuthorizationStatus.authorized: completionHandler(true) case CNAuthorizationStatus.denied, CNAuthorizationStatus.notDetermined: self.contactStore.requestAccess(for: CNEntityType.contacts, completionHandler: { (access, accessError) -> Void in if access { completionHandler(access) } else { if status == CNAuthorizationStatus.denied { completionHandler(false) } } }) default: completionHandler(false) } } func checkCalendarAuthorizationStatus(_ completionHandler: @escaping (_ accessGranted: Bool) -> Void) { let status = EKEventStore.authorizationStatus(for: EKEntityType.event) switch(status) { case EKAuthorizationStatus.authorized: completionHandler(true) case EKAuthorizationStatus.denied, EKAuthorizationStatus.notDetermined: self.eventStore.requestAccess(to: EKEntityType.event, completion: {(access, accessError) -> Void in if access { completionHandler(access) } else { if status == EKAuthorizationStatus.denied { completionHandler(false) } } }) default: completionHandler(false) } } func backgroundThread(_ delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) { DispatchQueue.global(qos: .background).async { background?() let popTime = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) if let completion = completion { DispatchQueue.main.asyncAfter(deadline: popTime) { completion() } } } } }
true
2619fb47e8f4ed34fe5932227181c805f2142bbe
Swift
szotp/Arrange
/ArrangeTests/ArrangeTests.swift
UTF-8
7,171
2.640625
3
[ "MIT" ]
permissive
// // ArrangeTests.swift // ArrangeTests // // Created by krzat on 29/10/16. // Copyright © 2016 krzat. All rights reserved. // import XCTest import Arrange class BigView : UIView {} extension CGRect { func assertEqual(to expected : CGRect, file: StaticString = #file, line: UInt = #line) { XCTAssertEqual(self, expected, file:file, line:line) } } class ArrangeTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testOneToOne(_ arrangement : [ArrangementItem], expected : CGRect, file: StaticString = #file, line: UInt = #line) { let view = bigView() let subview = smallView() view.arrange(arrangement, subview) view.layoutIfNeeded() XCTAssertEqual(subview.frame, expected, file:file, line:line) } func testPadding() { testOneToOne([.fill(1)], expected: CGRect(x: 1, y: 1, width: 98, height: 98)) testOneToOne([.fill(-1)], expected: CGRect(x: -1, y: -1, width: 102, height: 102)) testOneToOne([.left(1), .top(1)], expected: CGRect(x: 1, y: 1, width: 10, height: 10)) testOneToOne([.right(1), .bottom(1)], expected: CGRect(x: 89, y: 89, width: 10, height: 10)) } func testScrollable() { let view = UIView() let height = view.heightAnchor.constraint(equalToConstant: 110) //height.priority = UILayoutPriorityRequired-1 height.isActive = true let container = bigView().arrange( [.scrollable], view ) let scrollView = container.subviews.first as? UIScrollView container.layoutIfNeeded() XCTAssertNotNil(scrollView) XCTAssertEqual(view.frame, CGRect(x: 0, y: 0, width: 100, height: 110)) XCTAssertEqual(scrollView!.frame, CGRect(x: 0, y: 0, width: 100, height: 100)) XCTAssertTrue(scrollView!.subviews.contains(view.superview!) || scrollView!.subviews.contains(view)) } func testDefaultStacking() { let top = smallView() let middle = unsizedView() let bottom = smallView() let container = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)).arrange( [], top, middle, bottom ) container.layoutIfNeeded() XCTAssertEqual(top.frame, CGRect(x: 0, y: 0, width: 100, height: 10)) XCTAssertEqual(middle.frame, CGRect(x: 0, y: 10, width: 100, height: 80)) XCTAssertEqual(bottom.frame, CGRect(x: 0, y: 90, width: 100, height: 10)) } func bigView() -> UIView { return BigView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) } func smallView() -> UIView { let subview = UIView() let width = subview.widthAnchor.constraint(equalToConstant: 10) width.priority = UILayoutPriorityDefaultLow width.isActive = true let height = subview.heightAnchor.constraint(equalToConstant: 10) height.priority = UILayoutPriorityDefaultLow height.isActive = true return subview } func unsizedView() -> UIView { return UIView() } func testOverlay() { let a = unsizedView() let b = unsizedView() let container = bigView() container.arrange([.overlaying], a,b) container.layoutIfNeeded() XCTAssertEqual(a.frame, container.bounds) XCTAssertEqual(b.frame, container.bounds) } func testEqualize() { let a = unsizedView() let b = unsizedView() let container = bigView() do { container.arrange( [.equalSizes], a, b ) container.layoutIfNeeded() XCTAssertEqual(a.frame, CGRect(x: 0, y: 0, width: 100, height: 50)) XCTAssertEqual(b.frame, CGRect(x: 0, y: 50, width: 100, height: 50)) } do { container.arrange( [.equalSizes, .horizontal], a, b ) container.layoutIfNeeded() XCTAssertEqual(a.frame, CGRect(x: 0, y: 0, width: 50, height: 100)) XCTAssertEqual(b.frame, CGRect(x: 50, y: 0, width: 50, height: 100)) } } func testCentered() { testOneToOne( [.centered], expected: CGRect(x: 45, y: 45, width: 10, height: 10) ) testOneToOne( [.centeredVertically, .left(0)], expected: CGRect(x: 0, y: 45, width: 10, height: 10) ) testOneToOne( [.centeredHorizontally, .top(0)], expected: CGRect(x: 45, y: 0, width: 10, height: 10) ) } func testStyle() { let view = UILabel().style{ $0.text = "x" } XCTAssertEqual(view.text, "x") } func testTopAndSides() { let big = bigView() let small = smallView() big.arrange([.topAndSides(0)], small) big.layoutIfNeeded() XCTAssertEqual(small.frame, CGRect(x: 0, y: 0, width: 100, height: 10)) } func testCustomExtension() { let view = bigView() view.arrange([.hidden]) assert(view.isHidden) } func testViewControllerArrange() { let viewController = UIViewController() viewController.view = bigView() let view = smallView() viewController.arrange([.topAndSides(0)], view) viewController.view.layoutIfNeeded() XCTAssertEqual(view.superview, viewController.view) XCTAssertEqual(view.frame, CGRect(x: 0, y: 0, width: 100, height: 10)) //smallView should be aligned to layoutGuides, but offsets will not be visible in the test } func testCustomAnchor() { let big = bigView() let center = smallView() big.arrange([.centered], center) let other = smallView() let closure : Arrangement.Closure = { $0.bottomAnchor = center.topAnchor } big.arrange([.before(closure)], other) big.layoutIfNeeded() XCTAssertEqual(other.frame, CGRect(x: 0, y: 0, width: 100, height: 45)) } func testStackViewCustomization() { let big = bigView() let a = smallView() let b = smallView() let closure : Arrangement.Closure = { $0.stackView?.spacing = 20 } big.arrange([.after(closure), .equalSizes], a, b) big.layoutIfNeeded() XCTAssertEqual(a.frame, CGRect(x: 0, y: 0, width: 100, height: 40)) } } extension ArrangementItem { static var hidden : ArrangementItem { return .after({ context in context.superview.isHidden = true }) } }
true
e214fa6e0629c3e3878dbcf8e7bcd24027ca663e
Swift
cool-sp/leetcode
/AllProblems/AllProblems/archive-20201228/0135.candy.swift
UTF-8
598
3.421875
3
[]
no_license
// // 0135.candy.swift // AllProblems // // Created by liuning on 2020/12/25. // import Foundation func candy(_ ratings: [Int]) -> Int { guard ratings.count > 0 else { return 0 } var candyArr = Array(repeating: 1, count: ratings.count) for i in 1..<ratings.count { if ratings[i] > ratings[i-1] { candyArr[i] = candyArr[i-1] + 1 } } for j in stride(from: ratings.count-2, to: -1, by: -1) { if ratings[j] > ratings[j+1] { candyArr[j] = max(candyArr[j], candyArr[j+1] + 1) } } return candyArr.reduce(0, +) }
true
86901140f556f9816716f9653fba11314ead4490
Swift
buuuuutek/ya-note
/Notes/NotesTests/TestNote.swift
UTF-8
2,167
3.359375
3
[]
no_license
// // TestNote.swift // NotesTests // // Created by Волнухин Виктор on 06/07/2019. // Copyright © 2019 Волнухин Виктор. All rights reserved. // import XCTest @testable import Notes class TestNote: XCTestCase { var minimumNote: Note! var notStandartNote: Note! override func setUp() { minimumNote = Note(title: "Today things", content: "Today todo list:", importance: .usual) notStandartNote = Note(uid: UUID().uuidString, title: "My mom dirthday party", content: "1. Invite grand parents;\n2.Cook tasty cookies;\n3.Buy balloons.", color: .purple, importance: .important, selfDestructionDate: Date().addingTimeInterval(1000000)) } func testDefaultValue() { let defaultValue = DefaultValue(of: minimumNote) defaultValue.testUid() defaultValue.testColor() defaultValue.testDestructionDate() } func testNotDefaultValue() { let notDefaultValue = NotDefaultValue(of: notStandartNote) notDefaultValue.testUid() notDefaultValue.testColor() notDefaultValue.testImportance() notDefaultValue.testDestructionDate() } } // Проверки записи значений по умолчанию fileprivate class DefaultValue { let note: Note init(of note: Note) { self.note = note } func testUid() { XCTAssertFalse(note.uid.isEmpty) } func testColor() { XCTAssertTrue(note.color == .white) } func testDestructionDate() { XCTAssertNil(note.selfDestructionDate) } } // Проверки записи значений отличных от значений по умолчанию fileprivate class NotDefaultValue { let note: Note init(of note: Note) { self.note = note } func testUid() { XCTAssertFalse(note.uid.isEmpty) } func testColor() { XCTAssertNotEqual(note.color, UIColor.white) } func testImportance() { XCTAssertNotEqual(note.importance, Importance.usual) } func testDestructionDate() { XCTAssertNotNil(note.selfDestructionDate) } }
true
9a6560b3121c121333b05748eeb0d2397e9c158e
Swift
gionoa/FoodFinder
/FoodFinder/ViewModels/MapViewModel.swift
UTF-8
647
2.71875
3
[]
no_license
// // MapViewModel.swift // FoodFinder // // Created by Giovanni Noa on 8/12/20. // Copyright © 2020 Giovanni Noa. All rights reserved. // import Foundation import MapKit protocol MapViewModelDelegate: class { func didFetchRestaurants(_ restaurants: [Restaurant]) } class MapViewModel: NSObject { weak var delegate: MapViewModelDelegate? init(with restaurantProviding: RestaurantProviding, locationManager: CLLocationManager) { manager = locationManager } private var userLocation: CLLocation? private let manager: CLLocationManager func requestUserLocation() { manager.requestLocation() } }
true
052b32c5b26f02176bd51c188bce0a5862f66788
Swift
elisauhura/CircuitLab
/CircuitLab.playground/Sources/Protocols/CLKProbe.swift
UTF-8
325
3.015625
3
[]
no_license
import Foundation public typealias CLKProbeID = Int public protocol CLKProber { func receive(newState: CLKState) } public protocol CLKProbeable { func add(prober: CLKProber) -> CLKProbeID func remove(proberAt proberId: CLKProbeID) func probe() -> CLKState var probes: [Int: CLKProber] {get set} }
true
fd7349269fde6edf3e0fc89e0bbfe81aa0b9a8e8
Swift
rozenamah/Zearh
/Rozenamah/Scenes/Settings/Report/ReportInteractor.swift
UTF-8
1,104
2.890625
3
[]
no_license
import UIKit protocol ReportBusinessLogic { func reportSubject(_ reportForm: ReportForm) func validate(_ reportForm: ReportForm?) -> Bool } class ReportInteractor: ReportBusinessLogic { var presenter: ReportPresentationLogic? var worker = ReportWorker() // MARK: Business logic func reportSubject(_ reportForm: ReportForm) { worker.reportDoctor(reportForm) { (error) in if let error = error { self.presenter?.presentError(.unknown(error)) } else { self.presenter?.reportSent() } } } func validate(_ reportForm: ReportForm?) -> Bool { var allFieldsValid = true // Validate subject if reportForm?.subject == nil { allFieldsValid = false presenter?.presentError(.subjectMissing) } // Validate text if reportForm?.text == nil || reportForm?.text!.isEmpty == true { allFieldsValid = false presenter?.presentError(.messageMissing) } return allFieldsValid } }
true
aa7c2fc30057ba5c79799dac76d200b2f34d9dba
Swift
fabiorm-pls/MyMedia
/MyMedia/MainView.swift
UTF-8
821
2.65625
3
[]
no_license
// // ContentView.swift // MyMedia // // Created by Fabio Rodriguez Martinez on 25/10/2021. // import SwiftUI struct MainView: View { //menu @State private var isActive : Bool = false var body: some View { NavigationView{ VStack(spacing:0){ HeaderView() TimeView() ButtonsView() Spacer() } // Para que no quede un espacio arriba (barra de navegación) ya que metemos una custom .navigationBarTitle("") .navigationBarHidden(true) .background(Color.black) .edgesIgnoringSafeArea(.bottom) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { MainView() } }
true
1e03958b446e8328c2528af361a8cdd82751649b
Swift
altonlau/Foodie
/Foodie/Views/HoursView.swift
UTF-8
6,042
2.890625
3
[ "Apache-2.0" ]
permissive
// // HoursView.swift // Foodie // // Created by Alton Lau on 2016-09-17. // Copyright © 2016 Alton Lau. All rights reserved. // import UIKit class HoursView: UIView { //# MARK: - Constants private let kTextSeparation: CGFloat = 8.0 private let kUnknownFontSize: CGFloat = 20.0 private let kUnknownText = "Opening Hours Not Found" private let unknownLabel = UILabel() private let mondayLabel = UILabel() private let tuesdayLabel = UILabel() private let wednesdayLabel = UILabel() private let thursdayLabel = UILabel() private let fridayLabel = UILabel() private let saturdayLabel = UILabel() private let sundayLabel = UILabel() private let weekdayStrings = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] //# MARK: - Variables var hours: [Hours] { didSet { reloadHours() } } //# MARK: - Init init() { self.hours = [] super.init(frame: .zero) setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //# MARK: - Private Methods private func reloadHours() { unknownLabel.isHidden = !hours.isEmpty if hours.isEmpty { return } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "h:mma" for hour in hours { let text = "\(dateFormatter.string(from: hour.from)) - \(dateFormatter.string(from: hour.to))" switch hour.weekday { case .sunday: sundayLabel.text = text case .monday: mondayLabel.text = text case .tuesday: tuesdayLabel.text = text case .wednesday: wednesdayLabel.text = text case .thursday: thursdayLabel.text = text case .friday: fridayLabel.text = text case .saturday: saturdayLabel.text = text } } let components = Calendar.current.dateComponents([.weekday, .hour, .minute], from: Date()) guard let hour = components.hour, let minute = components.minute, let weekday = components.weekday else { return } let fromComponents = Calendar.current.dateComponents([.weekday, .hour], from: hours[weekday - 1].from) let toComponents = Calendar.current.dateComponents([.weekday, .hour, .minute], from: hours[weekday - 1].to) guard let fromHour = fromComponents.hour, var toHour = toComponents.hour, let toMinute = toComponents.minute else { return } toHour = toHour == 0 ? 24 : toHour if (hour >= fromHour && hour < toHour) || (hour == toHour && minute <= toMinute) { backgroundColor = UIColor.foodieLightGreen } else { backgroundColor = UIColor.foodieLightRed } } private func setup() { setupViews() } private func setupViews() { let weekdayStackView = UIStackView() for weekdayString in weekdayStrings { let weekdayLabel = UILabel() weekdayLabel.font = UIFont.boldSystemFont(ofSize: weekdayLabel.font.pointSize) weekdayLabel.text = weekdayString weekdayLabel.textColor = UIColor.foodieGray weekdayStackView.addArrangedSubview(weekdayLabel) } weekdayStackView.alignment = .trailing weekdayStackView.axis = .vertical weekdayStackView.spacing = kTextSeparation weekdayStackView.translatesAutoresizingMaskIntoConstraints = false let hoursStackView = UIStackView(arrangedSubviews: [mondayLabel, tuesdayLabel, wednesdayLabel, thursdayLabel, fridayLabel, saturdayLabel, sundayLabel]) for label in [mondayLabel, tuesdayLabel, wednesdayLabel, thursdayLabel, fridayLabel, saturdayLabel, sundayLabel] { label.textColor = UIColor.foodieGray } hoursStackView.alignment = .leading hoursStackView.axis = .vertical hoursStackView.spacing = kTextSeparation hoursStackView.translatesAutoresizingMaskIntoConstraints = false let horizontalStackView = UIStackView(arrangedSubviews: [weekdayStackView, hoursStackView]) horizontalStackView.alignment = .center horizontalStackView.axis = .horizontal horizontalStackView.spacing = kTextSeparation * 2 horizontalStackView.translatesAutoresizingMaskIntoConstraints = false addSubview(horizontalStackView) let unknownLabel = UILabel() unknownLabel.backgroundColor = UIColor.white unknownLabel.font = UIFont.systemFont(ofSize: kUnknownFontSize) unknownLabel.text = kUnknownText unknownLabel.textAlignment = .center unknownLabel.textColor = UIColor.foodieGray unknownLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(unknownLabel) addConstraints([ NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: horizontalStackView, attribute: .centerX, multiplier: 1, constant: 0), NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: horizontalStackView, attribute: .centerY, multiplier: 1, constant: 0), NSLayoutConstraint(item: unknownLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: unknownLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: self, attribute: .trailing, relatedBy: .equal, toItem: unknownLabel, attribute: .trailing, multiplier: 1, constant: 0), NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: unknownLabel, attribute: .bottom, multiplier: 1, constant: 0) ]) } }
true
2ecdeb53c22e843baaecf318499c00b4074c70a6
Swift
elenamene/CapsulePrivateStorage
/Project/PrivateVault App/Code/UI/GalleryView.swift
UTF-8
1,053
2.953125
3
[ "MIT" ]
permissive
// // GalleryView.swift // PrivateVault // // Created by Emilio Peláez on 19/2/21. // import SwiftUI struct GalleryView: View { @State var contentMode: ContentMode = .fill @State var selectedItem: Item? var columns: [GridItem] { [ GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible()) ] } var data: [Item] = (1...6) .map { "file\($0)" } .compactMap { UIImage(named: $0) } .map(Item.init) var body: some View { ScrollView { LazyVGrid(columns: columns) { ForEach(data) { item in Color.red.aspectRatio(1, contentMode: .fill) .overlay( item.placeholder .resizable() .aspectRatio(contentMode: contentMode) ) .clipped() .onTapGesture { } } } } .navigation(item: $selectedItem, destination: quickLookView) } @ViewBuilder func quickLookView(_ item: Item) -> some View { QuickLookView(title: item.id.description, url: URL(string: "")) } } struct GalleryView_Previews: PreviewProvider { static var previews: some View { GalleryView() } }
true
3b9e38ed71accef932528ec487ea4d72523108bc
Swift
WaterMyPlants3/ios-team
/WaterMyPlants/WaterMyPlants/Core Data/CoreDataStack.swift
UTF-8
3,522
2.703125
3
[ "MIT" ]
permissive
// // CoreDataStack.swift // WaterMyPlants // // Created by Patrick Millet on 2/1/20. // Copyright © 2020 WaterMyPlants3. All rights reserved. // import Foundation import CoreData // MARK: - Protocols protocol PersistentStoreControllerDelegate: NSFetchedResultsControllerDelegate {} extension NSManagedObjectContext: PersistentContext {} class CoreDataStack: NSObject, PersistentStoreController { // MARK: - Properties static let shared = CoreDataStack() weak var delegate: PersistentStoreControllerDelegate? lazy var container = setUpContainer() lazy var fetchedResultsController = setUpResultsController() private var rootContext: NSManagedObjectContext { container.viewContext } var allItems: [Persistable]? { fetchedResultsController.fetchedObjects } var itemCount: Int { fetchedResultsController.sections?[0].numberOfObjects ?? 0 } var mainContext: PersistentContext { rootContext } // MARK: - Setup func setUpContainer() -> NSPersistentContainer { let container = NSPersistentContainer(name: "WaterMyPlants") container.loadPersistentStores { _, error in if let error = error { fatalError("Failed to load persistent stores: \(error)") } } container.viewContext.automaticallyMergesChangesFromParent = true return container } func setUpResultsController() -> NSFetchedResultsController<Plant> { let moc = mainContext let fetchRequest: NSFetchRequest<Plant> = Plant.fetchRequest() fetchRequest.sortDescriptors = [ NSSortDescriptor(key: "h2oFrequency", ascending: false)] let frc = NSFetchedResultsController( fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: nil, cacheName: nil) frc.delegate = self.delegate do { try frc.performFetch() } catch { NSLog("Error initializing fetched results controller: \(error)") } return frc } // MARK: - CRUD Methods func create(item: Persistable, in context: PersistentContext?) throws { let thisContext = fetchContext(context) try thisContext.save() } func fetchItem(at indexPath: IndexPath) -> Persistable? { return fetchedResultsController.object(at: indexPath) } func deleteShort(itemAtIndexPath indexPath: IndexPath, in context: PersistentContext?) throws { let thisContext = fetchContext(context) let entry = fetchedResultsController.object(at: indexPath) try delete(entry, in: thisContext) } func delete(_ item: Persistable?, in context: PersistentContext?) throws { let thisContext = fetchContext(context) guard let entry = item as? Plant else { throw NSError() } thisContext.delete(entry) try save(in: thisContext) } func save(in context: PersistentContext?) throws { let thisContext = fetchContext(context) var saveError: Error? thisContext.performAndWait { do { try thisContext.save() } catch { saveError = error } } if let error = saveError { throw error } } func fetchContext(_ context: PersistentContext?) -> NSManagedObjectContext { if let context = context { return context } else { return rootContext } } }
true
ee2161c1c50709923cd6a84b6a2c927cc81b563c
Swift
Yutiy/battery_swift
/ios/Classes/SwiftBatteryPlugin.swift
UTF-8
2,652
2.625
3
[]
no_license
import Flutter import UIKit public class SwiftBatteryPlugin: NSObject, FlutterPlugin, FlutterStreamHandler { private var _eventSink: FlutterEventSink? public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? { self._eventSink = events; UIDevice.current.isBatteryMonitoringEnabled = true self.sendBatteryStateEvent() NotificationCenter.default.addObserver( self, selector: #selector(self.onBatteryStateDidChange), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil ) return nil } public func onCancel(withArguments arguments: Any?) -> FlutterError? { self._eventSink = nil; NotificationCenter.default.removeObserver(self) return nil } public static func register(with registrar: FlutterPluginRegistrar) { // 本类型对象 let instance = SwiftBatteryPlugin() let methodChannel = FlutterMethodChannel(name: "plugins.yutiy/battery", binaryMessenger: registrar.messenger()) registrar.addMethodCallDelegate(instance, channel: methodChannel) let eventChannel = FlutterEventChannel(name: "plugins.yutiy/charging", binaryMessenger: registrar.messenger()) eventChannel.setStreamHandler(instance) } public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { if (call.method == "getBatteryLevel") { let batteryLevel = getBatteryLevel() if (batteryLevel != -1) { result(batteryLevel) } else { result(FlutterError(code: "UNAVAILABLE", message: "Battery info unavailable, don't use Simulator!", details: nil)) } } else { result(FlutterMethodNotImplemented) } } @objc public func onBatteryStateDidChange(_ notification: NSNotification) { self.sendBatteryStateEvent() } // 获取电量 private func getBatteryLevel() -> Int { let device = UIDevice.current device.isBatteryMonitoringEnabled = true if (device.batteryState == UIDeviceBatteryState.unknown) { return -1 } else { return Int(device.batteryLevel * 100) } } // 获取电池状态 private func sendBatteryStateEvent() { if (!(_eventSink != nil)) { return } // 发送通知给Flutter端 let device = UIDevice.current switch (device.batteryState) { case .full: _eventSink?("full") case .charging: _eventSink?("charging") case .unplugged: _eventSink?("discharging") default: _eventSink?(FlutterError(code: "UNAVAILABLE", message: "Charging status unavailable", details: nil)) } } }
true
1764a70e70a6d9a489224e2bbef6e6c7c562af6b
Swift
tschob/bachelor-thesis
/Source Code/bachelorarbeit-prototyp/Core/Controller/Debug/Context/Detail/BSCContextDetailSections.swift
UTF-8
1,910
2.8125
3
[ "MIT", "CC-BY-3.0", "CC-BY-NC-SA-4.0" ]
permissive
// // BSCContextDetailSections.swift // bachelorarbeit-prototyp // // Created by Hans Seiffert on 12.01.16. // Copyright © 2016 Hans Seiffert. All rights reserved. // import UIKit enum BSCContextDetailSections: Int { case Location = 0 case Date case Device case Motion case Weather static func allCases(context: BSCContext?) -> Int { return 5 } func numberOfRows() -> Int { return self.dynamicType.rowTypeForSection(self.rawValue)?.numberOfRows ?? 0 } static func rowForIndexPath(indexPath: NSIndexPath) -> BSCContextTableViewCellRowType? { return self.rowTypeForSection(indexPath.section)?.init(rawValue: indexPath.row) } static func rowTypeForSection(section: Int) -> BSCContextTableViewCellRowType.Type? { if let sectionType = BSCContextDetailSections(rawValue: section) { switch sectionType { case .Location: return BSCContextTableViewLocationSectionRowType.self case .Date: return BSCContextTableViewDateSectionRowType.self case .Device: return BSCContextTableViewDeviceSectionRowType.self case .Motion: return BSCContextTableViewMotionSectionRowType.self case .Weather: return BSCContextTableViewWeatherSectionRowType.self } } else { return nil } } func titleOfSection() -> String? { switch self { case .Location: return L("context.detail.location.section.title") case .Date: return L("context.detail.date.section.title") case .Device: return L("context.detail.device.section.title") case .Motion: return L("context.detail.motion.section.title") case .Weather: return L("context.detail.weather.section.title") } } static func percentageFromTotalWeight(section: Int) -> Float { return self.rowTypeForSection(section)?.percentageFromTotalWeight() ?? Float(0) } func shouldShowSectionHeader() -> Bool { switch self { case .Location: return false default: return true } } }
true
0f028ae0782d4e34784b3c2dee20ec653f7ab11b
Swift
miltonpl/TinderLikeUI
/TinderLikeUI/Common/ViewFiles/ContactView/Controller/ContactView.swift
UTF-8
4,563
2.671875
3
[]
no_license
// // ContactView.swift // TinderLikeUI // // Created by Milton Palaguachi on 10/28/20. // Copyright © 2020 Milton. All rights reserved. // import UIKit enum ContactType { case phone case cell case email case message } class ContactView: UIView { @IBOutlet weak var contentView: UIView! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var myImageView: UIImageView! @IBOutlet weak var tableView: UITableView! { didSet { self.tableView.delegate = self self.tableView.dataSource = self self.tableView.estimatedRowHeight = 100 self.tableView.tableFooterView = UIView() self.tableView.isScrollEnabled = false self.tableView.allowsSelection = false self.tableView.register(ContactTableViewCell.nib(), forCellReuseIdentifier: ContactTableViewCell.identifier) } } var contactDetails = [(type: ContactType, content: String)]() override init(frame: CGRect) { super.init(frame: frame) self.initSubviews() } required init?(coder: NSCoder) { super.init(coder: coder) self.initSubviews() } func initSubviews() { let nib = UINib(nibName: String(describing: type(of: self)), bundle: nil) nib.instantiate(withOwner: self, options: nil) addSubview(self.contentView) contentView.translatesAutoresizingMaskIntoConstraints = false let constraints = [ contentView.topAnchor.constraint(equalTo: self.topAnchor), contentView.bottomAnchor.constraint(equalTo: self.bottomAnchor), contentView.leadingAnchor.constraint(equalTo: self.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: self.trailingAnchor) ] NSLayoutConstraint.activate(constraints) } func configure(contact: Contact) { if let phone = contact.homePhone { self.contactDetails.append((.phone, phone)) } if let email = contact.email { self.contactDetails.append((.email, email)) } if let cell = contact.cellPhone { self.contactDetails.append((.cell, cell)) self.contactDetails.append((.message, cell)) } self.tableView.reloadData() if let strUrl = contact.url, let url = URL(string: strUrl) { self.imageView.downloadImage(url) self.imageView.layer.cornerRadius = imageView.frame.width/2 self.imageView.layer.borderWidth = 1 self.imageView.layer.borderColor = CustomCGColor.grey self.myImageView.layer.cornerRadius = myImageView.frame.width/2 self.myImageView.layer.borderColor = CustomCGColor.grey self.myImageView.layer.borderWidth = 1 } } func makeACall() { let strPhone = "holelelle" let number = strPhone.components(separatedBy: CharacterSet.decimalDigits.inverted) .joined() print(number) if let url = URL(string: "tel://\(number)"), UIApplication.shared.canOpenURL(url) { if #available(iOS 10, *) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } else { UIApplication.shared.openURL(url) } } else { print("Did Not work") } } } extension ContactView: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { contactDetails.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "ContactTableViewCell", for: indexPath) as? ContactTableViewCell else { fatalError("Unable to dequeueResuableCell with Identifier CantactTableViewCell") } let item = contactDetails[indexPath.row] print(item) switch item.type { case .phone: cell.configure(image: UIImage(named: "phone"), name: item.content) case .cell: cell.configure(image: UIImage(named: "cell"), name: item.content) case .email: cell.configure(image: UIImage(named: "email"), name: item.content) case .message: cell.configure(image: UIImage(named: "messages"), name: item.content) } return cell } }
true
d865c29517ea810015af41923e34fb957a664705
Swift
marcoconti83/targone
/Sources/OptionalArgument.swift
UTF-8
4,091
3.015625
3
[ "MIT" ]
permissive
//Copyright (c) Marco Conti 2015 // // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. import Foundation /** An optional command line argument An optional argument: - requires a following additional value - has a label that starts with "--" or "-" - is optional e.g. the `speed` argument in do.swift --speed 10 */ public class OptionalArgument<T> : TypedCommandLineArgument<T> where T: InitializableFromString { /** Returns an optional argument. - parameter label: the label. If the flag prefix ("--") is missing, will automatically add it - parameter shortLabel: the short version of the label (e.g. "-f"). If the short flag prefix is missing, will automatically add it - parameter help: the help text used to describe the parameter - parameter defaultValue: if the argument is not present on the command line, it will be set to the given default value. If no default value is given, it will be set to `nil` - parameter choices: a list of possible values for the argument. Passing an argument that is not in this list (if the list is specified) will result in a parsing error - throws: One of `ArgumentInitError` in case there is an error in the labels that are used */ public init( label: String, shortLabel : String? = nil, defaultValue : T? = nil, help : String? = nil, choices: [T]? = nil ) throws { try super.init( label: label.addLongFlagPrefix(), style: ArgumentStyle.optional, shortLabel: shortLabel?.addShortFlagPrefix(), defaultValue : defaultValue, help : help, choices: choices ) } /** Returns an optional argument. This is the error-free version of the other `init`. It will assert in case of error. - parameter label: the label. If the flag prefix ("--") is missing, will automatically add it - parameter shortLabel: the short version of the label (e.g. "-f"). If the short flag prefix is missing, will automatically add it - parameter help: the help text used to describe the parameter - parameter defaultValue: if the argument is not present on the command line, it will be set to the given default value. If no default value is given, it will be set to `nil` - parameter choices: a list of possible values for the argument. Passing an argument that is not in this list (if the list is specified) will result in a parsing error */ public convenience init( _ label: String, shortLabel : String? = nil, defaultValue : T? = nil, help : String? = nil, choices: [T]? = nil ) { do { try self.init( label: label, shortLabel: shortLabel, defaultValue: defaultValue, help: help, choices: choices) } catch let error as Any { ErrorReporting.die(error) } } }
true
74124635fac97fda79f56c79eb645e7b239b3b60
Swift
objective-audio/iOSDC2018
/FlowGraphSample/Door.swift
UTF-8
1,723
3.546875
4
[ "MIT" ]
permissive
// // Door.swift // import FlowGraph // ドアの状態 class Door: FlowGraphType { private(set) var isOpen: Bool = false { didSet { print("isOpen \(self.isOpen)") if let handler = self.isOpenHandler { handler(self.isOpen) } } } var isOpenHandler: ((Bool) -> Void)? enum WaitingState { case closed case opened } enum RunningState { case opening case closing } enum EventKind { case open case close } typealias Event = (kind: EventKind, object: Door) private let graph: FlowGraph<Door> init() { let builder = FlowGraphBuilder<Door>() // 閉じている builder.add(waiting: .closed) { event in if case .open = event.kind { return .run(.opening, event) } else { return .stay } } // 開いている builder.add(waiting: .opened) { event in if case .close = event.kind { return .run(.closing, event) } else { return .stay } } // 開く builder.add(running: .opening) { event in event.object.isOpen = true return .wait(.opened) } // 閉じる builder.add(running: .closing) { event in event.object.isOpen = false return .wait(.closed) } self.graph = builder.build(initial: .closed) } func run(_ kind: EventKind) { self.graph.run((kind, self)) } }
true
1c3a1a842c4f4e2296263b75e9a7cdc5ea147f06
Swift
wddwycc/cocoa-utility
/NSDate_extension.swift
UTF-8
1,426
3.09375
3
[]
no_license
import Foundation import UIKit extension NSDate{ func dateComponents() -> NSDateComponents{ let calendar = NSCalendar.currentCalendar() let dateComponents = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second], fromDate: self) return dateComponents } func timeIntervelToNow() -> String{ if self.compare(NSDate()) == NSComparisonResult.OrderedDescending { return "刚才" } let interval = NSDate().timeIntervalSinceDate(self) if interval < 60 * 60 { return "\(Int(interval / 60))分钟前" } if interval < 60 * 60 * 24 { return "\(Int(interval / 3600))小时前" } if interval < 60 * 60 * 24 * 365 { return "\(Int(interval) / Int(60 * 60 * 24)))天前" } return "\(Int(interval) / Int(60 * 60 * 24 * 365)))年前" } // Sample: 2016/7/13 15:14 func presentation() -> String { let component = self.dateComponents() return "\(component.year)/\(component.month.addZeroPrefix())/\(component.day.addZeroPrefix()) \(component.hour.addZeroPrefix()):\(component.minute.addZeroPrefix())" } } private extension Int { func addZeroPrefix() -> String { if self >= 10 { return "\(self)" } return "0\(self)" } }
true
3940e9852517e3d1c016a9ab58d90d43bdbfd508
Swift
benSmith1981/IOS-Programming-Book
/FunctionMonster/FunctionMonster/main.swift
UTF-8
669
3.328125
3
[]
no_license
// // main.swift // FunctionMonster // // Created by Ben Smith on 16/02/2017. // Copyright © 2017 Ben Smith. All rights reserved. // import Foundation //Exercise here: https://docs.google.com/document/d/1txrgI2NEimlw3D7Rf_IupzXObUpgsk1IQvRQvLWaTsw/edit?usp=sharing //create bones var boyBones: [Bone] = [] for loopCounter in 1...10 { var bone = Bone.init(type: boneType.boyBone, crunched: false) boyBones.append(bone) } var theBoy = Boy.init(name: "Ben", type: humanType.boy, bones: boyBones) var BonePod = Monster.init(age: 1000, name: "The Function Monster", monsterTeeth: .sharp) var bonesReturned = BonePod.eatHuman(human: theBoy) print(bonesReturned)
true
a06947b47fd54cdfa782341223a3718641c7f595
Swift
Rawls-Portfolio/CS4222-Sudoku
/Sudoku/Models and Structures/PuzzleModel.swift
UTF-8
5,588
2.859375
3
[]
no_license
// // PuzzleModel.swift // Sudoku // // Created by Amanda Rawls on 11/27/17. // Copyright © 2017 Amanda Rawls. All rights reserved. // import Foundation class PuzzleModel { // MARK: - Properties private var solution: [Int] private var puzzle = [Cell]() private let difficulty: Int private var undoHistory = [Cell]() private var _mode: Mode private var _active: Value private var _lastHighlights = [Int]() private var _lastConflict = [Int]() var needsUpdate = [Int]() var active: Value { get { return _active } set { _active = newValue } } var mode: Mode { get { return _mode } set { _mode = newValue } } let getSwiftyRandom: swiftFuncPtr = { return Int32(arc4random_uniform(UInt32(Int32.max))) } // MARK: - Methods init(targetScore: Int32) { _mode = .solution _active = .one // obtain valid solution let data: UnsafeMutablePointer<UInt8> = generateSolution(getSwiftyRandom) let generatedSolution = Array(UnsafeBufferPointer(start: data, count: 81)) // obtain puzzle from given solution and save difficulty value let generatedPuzzle = Array(UnsafeBufferPointer(start: data, count: 81)) let solutionPointer = UnsafeMutablePointer<UInt8>(mutating: generatedSolution) let puzzlePointer = UnsafeMutablePointer<UInt8>(mutating: generatedPuzzle) difficulty = Int(generatePuzzle(solutionPointer, puzzlePointer, MAX_ITER, MAX_SCORE, targetScore)) // save puzzle and solution solution = generatedSolution.map{Int($0)} generatedPuzzle.map{Int($0)}.forEach{(value) in let cellValue = Value.of(value) let position = Position(arrayIndex: puzzle.count) let newCell = Cell(position: position, solution: cellValue) puzzle.append(newCell) } print("actual difficulty: \(difficulty)") free(data) //dynamically allocated in the generator } func toggleMode(){ mode = mode.toggle } func getCell(for cell: Int)-> Cell { return puzzle[cell] } func showHint(for cell: Int) { removeEffects() puzzle[cell].solution = Value.of(solution[cell]) puzzle[cell].state = .permanent needsUpdate.append(cell) } func setPermanentState(of cell: Int){ puzzle[cell].state = .permanent needsUpdate.append(cell) } func getNoteValue(for cell: Int) -> Value? { if puzzle[cell].notes.count == 1 { return puzzle[cell].notes.first! } else { return nil } } // damn I love high order functions❣️ func getActiveIndices() -> [Int] { return puzzle.filter{$0.solution == _active}.map{$0.position.toIndex} } func applyHighlights(to cells: [Int]){ cells.forEach{(cell) in puzzle[cell].highlight = true } needsUpdate += cells _lastHighlights = cells } func removeEffects(){ _lastHighlights.forEach{(cell) in puzzle[cell].highlight = false } needsUpdate += _lastHighlights _lastHighlights.removeAll() _lastConflict.forEach{(cell) in puzzle[cell].conflict = false } needsUpdate += _lastConflict _lastConflict.removeAll() } func clearSolution(for cell: Int){ guard puzzle[cell].state != .permanent else { return } puzzle[cell].state = .neutral puzzle[cell].solution = nil needsUpdate.append(cell) } func clearNotes(for cell: Int){ puzzle[cell].notes.removeAll() needsUpdate.append(cell) } func clearAll(){ for cell in 0..<81{ clearSolution(for: cell) clearNotes(for: cell) puzzle[cell].state = puzzle[cell].solution == nil ? .neutral : .permanent puzzle[cell].conflict = false puzzle[cell].highlight = false } } func toggleNote(of value: Value, for cell: Int){ removeEffects() guard mode == .notes, puzzle[cell].solution == nil else { return } if let valueIndex = puzzle[cell].notes.index(of: value) { puzzle[cell].notes.remove(at: valueIndex) } else { puzzle[cell].notes.append(value) } } func setSolution(of value: Value, for position: Position) { removeEffects() func validSolution(of value: Value, for position: Position) -> Bool { var success = true let checkList = Position.colIndices(position.col) + Position.rowIndices(position.row) + Position.blockIndices(position.block) checkList.filter{$0 != position.toIndex}.forEach{(cell) in if let solution = puzzle[cell].solution, solution == value { puzzle[cell].conflict = true _lastConflict.append(cell) success = false } } return success } let cell = position.toIndex guard puzzle[cell].state != .permanent else { return } if validSolution(of: value, for: position) { puzzle[cell].solution = value puzzle[cell].state = .solution puzzle[cell].notes.removeAll() } else { puzzle[cell].conflict = true _lastConflict.append(cell) needsUpdate += _lastConflict } } }
true
f4cc7293519d4c59fd28a55feeb6357620e15336
Swift
NghiemTrung/LearnSwift
/Day02/Day02/main.swift
UTF-8
2,141
3.265625
3
[]
no_license
// // main.swift // Day02 // // Created by Trung on 10/11/19. // Copyright © 2019 Trung. All rights reserved. // import Foundation //var y: Int? //let x: Int! // //// //func checkGurafEls(){ // guard let a = y else { // print("y: \(y)") // return // } // print(a) //} // //checkGurafEls() // //func checkIfLet() { // if let a = y { // print(a) // print("+++++++++++") // } else { // print("y: \(y)") // } //} //checkIfLet() // //func checkSwitch() { // // khai báo biến option // let option = 15 // switch option { // case 0...10: // print("Case 0...10") // // fallthrough: Thực thi trường hợp tiếp theo //// fallthrough // case 11...20: // print("Case 11...20") // // fallthrough: Thực thi trường hợp tiếp theo //// fallthrough // case 21...30: // print("Case 21...30") // default: // print("Default case") // } //} // //checkSwitch() //Xeploai() //InSoTrongKhoang() // Chọn bài tập từ các lựa chọn func ChonBaiTap () { print("moi lua chon cac bai tap bang cach nhap tu ban phim so thu tu bai tap do") print("5. Bai tap 5") print("6. Bai tap 6") print("7. Bai tap 7") print("8. Bai tap 8") print("9. Bai tap 9") print("lua chon cua ban la: ", terminator: "") let LuaChon = InputIntFromKeyboradWithinRange(Begin: 5, End: 9) switch LuaChon { case 5: Bai05() TiepTucChonBaiTap() case 6: Bai06() TiepTucChonBaiTap() case 7: Bai07() TiepTucChonBaiTap() case 8: Bai08() TiepTucChonBaiTap() case 9: Bai09() TiepTucChonBaiTap() default: TiepTucChonBaiTap() break } } func TiepTucChonBaiTap() { print("Co muon tiep tuc kiem tra cac bai tap? (C/k):", terminator: "") let TiepTuc = readLine()! if (TiepTuc.lowercased() == "c") { ChonBaiTap() } else if (TiepTuc.lowercased() == "k"){ print("Tam Biet") } else { TiepTucChonBaiTap() } } ChonBaiTap()
true
606aa61432057e5fc3080f6c5cc6c16f6d89adf5
Swift
veraabad/ContributionCenter
/ContributionCenter/LogInViewController.swift
UTF-8
4,506
2.59375
3
[]
no_license
// // LogInViewController.swift // ContributionCenter // // Created by Abad Vera on 4/24/15. // Copyright (c) 2015 Abad Vera. All rights reserved. // import UIKit import LocalAuthentication class LogInViewController: UIViewController { // UIButton @IBOutlet weak var procederBttn: UIButton! // Blur for background of button var blur:UIVisualEffectView! var backView:UIView! // Color var colorBack = UIColor(red: 10/255, green: 206/255, blue: 225/255, alpha: 1.0) // Corner radius var cornerRad:CGFloat! = 2 // Device interface var deviceInterface:UIUserInterfaceIdiom! var objectid:String! override func viewDidLoad() { super.viewDidLoad() // Find out which device were on deviceInterface = UIDevice.currentDevice().userInterfaceIdiom } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { // Add blurred background to UIButton backView = UIView(frame: CGRectMake(0, 0, procederBttn.frame.width, procederBttn.frame.height)) backView.backgroundColor = colorBack backView.alpha = 0.2 backView.layer.cornerRadius = cornerRad backView.clipsToBounds = true backView.userInteractionEnabled = false blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light)) blur.frame = CGRectMake(0, 0, procederBttn.frame.width, procederBttn.frame.height) blur.layer.cornerRadius = cornerRad blur.clipsToBounds = true blur.userInteractionEnabled = false procederBttn.addSubview(backView) procederBttn.addSubview(blur) procederBttn.sendSubviewToBack(backView) procederBttn.sendSubviewToBack(blur) } // Update frame of blur with rotation override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { blur.frame = CGRectMake(0, 0, procederBttn.frame.width, procederBttn.frame.height) backView.frame = CGRectMake(0, 0, procederBttn.frame.width, procederBttn.frame.height) } func requestFingerprintAuthentication() { let context = LAContext() var authError: NSError? let authenticationReason = "Porfavor registrese con su huella" // Check if device has fingerprint reader // If so then lets authenticate do { let err = NSErrorPointer() try context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error:err) context.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: authenticationReason, reply: { (success: Bool, error: NSError?) -> Void in if success { dispatch_async(dispatch_get_main_queue(), { print("Woohoo") self.showVC("AuthenticatedVC") }) } else { dispatch_async(dispatch_get_main_queue(), { print("Unable to Authenticate: \(err)") self.showVC("AuthenticatedVC") }) } }) } catch let error as NSError { authError = error print("We're in the simulator") let vc = self.storyboard?.instantiateViewControllerWithIdentifier("SideBarController") as! AVSideBarController self.showViewController(vc, sender: self) } } func showVC(stringID: String) { let storyBoard = UIStoryboard(name: "Main", bundle: nil) let viewC = storyBoard.instantiateViewControllerWithIdentifier(stringID) as UIViewController self.showViewController(viewC, sender: self) } // Action for when the "Proceder" button has been pressed @IBAction func procedeAction(sender: AnyObject) { // If iPhone then user fingerprint to login if deviceInterface == .Phone { requestFingerprintAuthentication() } else if deviceInterface == .Pad { showVC("AuthenticationVC") // If iPad then go to QRAuthentication /*let vc = self.storyboard?.instantiateViewControllerWithIdentifier("SideBarController") as! AVSideBarController self.showViewController(vc, sender: self)*/ } } }
true
5953bbb3b3295700edd51a330b5d3664c37664ad
Swift
DianaGeorgievaa/nine-mens-morris
/Sources/nine-mens-morris/GameMessages.swift
UTF-8
1,037
3.25
3
[]
no_license
/// Enum with the game messages enum GameMessages: CustomStringConvertible { case emptyPositionMessage case validPositionMessage case positionOccupiedBySelfTokenMessage case validOpponentPositionMessage case positionNotInCombinationMessage case validNeighbourPositionMessage var description: String { switch self { case .emptyPositionMessage: return "Please, choose empty position" case .validPositionMessage: return "Please, choose valid position" case .positionOccupiedBySelfTokenMessage: return "Please, choose valid position which is occupied by your token" case .validOpponentPositionMessage: return "Please, choose valid opponent position" case .positionNotInCombinationMessage: return "Please, choose opponent position which is not in nine mens morris combination" case .validNeighbourPositionMessage: return "Please, choose valid neighbour position" } } }
true
2d11d69d4d72b53d133bfd55a1720e584dfa50bf
Swift
PacktPublishing/Mastering-iOS-14-Programming-4th-Edition
/Chapter 10 - Core ML/TextAnalyzerCloud_completed/TextAnalyzer/ViewController.swift
UTF-8
2,800
2.828125
3
[ "MIT" ]
permissive
import UIKit import Vision import NaturalLanguage class ViewController: UIViewController { @IBOutlet var textView: UITextView! var model: SentimentPolarity? override func viewDidLoad() { super.viewDidLoad() textView.layer.cornerRadius = 6 textView.layer.borderColor = UIColor.lightGray.cgColor textView.layer.borderWidth = 1 } @IBAction func analyze() { let wordCount = getWordCounts(from: textView.text) if model != nil { guard let prediction = try? model?.prediction(input: wordCount) else { return } showResult(prediction: prediction) return } //1 _ = MLModelCollection.beginAccessing(identifier: "SentimentPolarityCollection") { [self] result in //2 var modelURL: URL? switch result { case .success(let collection): modelURL = collection.entries["SentimentPolarity"]?.modelURL case .failure(let error): handleCollectionError(error) } //3 let result = loadSentimentClassifier(url: modelURL) //4 switch result { case .success(let sentimentModel): model = sentimentModel guard let prediction = try? model?.prediction(input: wordCount) else { return } showResult(prediction: prediction) case .failure(let error): handleModelLoadError(error) } } } private func loadSentimentClassifier(url: URL?) -> Result<SentimentPolarity, Error> { if let modelUrl = url { return Result { try SentimentPolarity(contentsOf: modelUrl)} } else { return Result { try SentimentPolarity(configuration: .init())} } } private func showResult(prediction: SentimentPolarityOutput) { displayModalMessage("Your text is rated: \(prediction.classLabel)") } private func handleCollectionError(_ error: Error) { displayModalMessage("Error downloading the model collection") } private func handleModelLoadError(_ error: Error) { displayModalMessage("Error loading the model") } private func displayModalMessage(_ msg: String) { DispatchQueue.main.async { [self] in let alert = UIAlertController(title: nil, message: msg, preferredStyle: .alert) let okayAction = UIAlertAction(title: "Okay", style: .default, handler: nil) alert.addAction(okayAction) self.present(alert, animated: true, completion: nil) } } func getWordCounts(from string: String) -> [String: Double] { let tokenizer = NLTokenizer(unit: .word) tokenizer.string = string var wordCount = [String: Double]() tokenizer.enumerateTokens(in: string.startIndex..<string.endIndex) { range, attributes in let word = String(string[range]) wordCount[word] = (wordCount[word] ?? 0) + 1 return true } return wordCount } }
true
85a370977b7c40631b472f92016d3c5802419e41
Swift
artyom-razinov/Swiftorio
/Frameworks/DataRaw/Sources/Model/NonGame/PrototypeNames/Prototypes/BeaconPrototypeName.swift
UTF-8
74
2.65625
3
[]
no_license
public enum BeaconPrototypeName: String, PrototypeName { case beacon }
true
bbe7b4044166a47e578bbad22e1a5a73ecceb706
Swift
jinjaimie/berri
/berri/models.swift
UTF-8
1,466
2.53125
3
[]
no_license
// // models.swift // berri // // Created by stlp on 5/29/21. // import Foundation import SwiftUI import Firebase class MTransaction: NSObject, ObservableObject { @Published var id: String @Published var account: String @Published var date: String @Published var name: String @Published var value: Double @Published var incomeType: String = "" @Published var category: String @Published var convDate: Date = Date() @Published var isIncome: Bool = false init(id: String, account: String, date: String, name: String, value: Double, category: String) { self.id = id self.account = account self.date = date self.name = name self.value = value self.category = category } init(id: String, account: String, date: String, name: String, value: Double, incomeType: String, category: String) { self.id = id self.account = account self.date = date self.name = name self.value = value self.incomeType = incomeType self.category = category } } class NewTransaction: ObservableObject { @Published var accountOut: String = "" @Published var accountIn: String = "" @Published var date: String = "" @Published var name: String = "" @Published var value: Double = 0.0 @Published var incomeType: String = "" @Published var category: String = "" @Published var convDate: Date = Date() }
true
1825892c2642e90bdfab5364a79e4e898fefe924
Swift
rthm/FoundationTools
/Sources/FoundationTools/NotificationNameObserved.swift
UTF-8
1,103
2.90625
3
[]
no_license
// // File.swift // // // Created by rthmadmin on 2019-11-18. // import Foundation open class NotificationNameObserved: NotificationNameObserving { public var observing: NoName { _observing } open var onObservation: ((Any?) -> Void)? private var observer: Any? deinit { guard let o = observer else { return } notificationCenter.removeObserver(o, name: observing, object: nil) } private let _observing: NoName public init(name: NoName) { _observing = name } public convenience init(name: NoName, queue: OperationQueue? = nil, observation: ((Any?) -> Void)? = nil) { self.init(name: name) onObservation = observation observer = notificationCenter.addObserver(forName: name, object: nil, queue: queue, using: observed) } public func observed(_ notification: Notification) { let name = notification.name switch name { case observing: onObservation?(notification.object) default: debugPrint("Notification \(name) observed") } } }
true
08055dae41a3b2ca0948365cd0019b8902523ee1
Swift
LeeShiYoung/Swift4_Tips
/Swift4_Tips.playground/Pages/属性观察.xcplaygroundpage/Contents.swift
UTF-8
748
3.828125
4
[ "Apache-2.0" ]
permissive
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) class MyCalss { let oneYearInsecond: TimeInterval = 365 * 24 * 60 * 60 var date: NSDate { willSet { let d = date print("即将将日期从\(d)设至\(newValue)") } didSet { if (date.timeIntervalSinceNow > oneYearInsecond) { print("设定的时间太晚了") date = NSDate().addingTimeInterval(oneYearInsecond) } print("已经将日期从\(oldValue)设定至\(date)") } } init() { date = NSDate() } } let foo = MyCalss() foo.date = foo.date.addingTimeInterval(100_000_000)
true