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
31beecb23cc21d3b06786029ae92fa90c3462464
Swift
pajlotapps/Pajlot-TimeCalc-Pro
/Pajlot TimeCalc Pro/Options/OptionsVC.swift
UTF-8
2,238
2.515625
3
[]
no_license
import UIKit class OptionsVC: UIViewController { //MARK: IBOutlets declarations @IBOutlet weak var optionsTV: UITextView! @IBOutlet weak var languageLbl: UILabel! @IBOutlet weak var contactLbl: UILabel! @IBOutlet weak var donateLbl: UILabel! @IBOutlet weak var rateLbl: UILabel! @IBOutlet weak var versionLabel: UILabel! //MARK: IBActions declarations @IBAction func rateAppBtn(sender: AnyObject) { rateApp(appId: "id1342113626") { success in print("RateApp \(success)") } } //MARK: App Life cycle override func viewDidLoad() { super.viewDidLoad() if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String { versionLabel.text = "Ver " + version } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.setNavigationBarHidden(false, animated: animated) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setUpLanguage() self.navigationController?.setNavigationBarHidden(true, animated: animated) } //MARK: Additional functions func rateApp(appId: String, completion: @escaping ((_ success: Bool)->())) { guard let url = URL(string : "itms-apps://itunes.apple.com/app/" + appId) else { completion(false) return } guard #available(iOS 10, *) else { completion(UIApplication.shared.openURL(url)) return } UIApplication.shared.open(url, options: [:], completionHandler: completion) } func setUpLanguage() { optionsTV.text = NSLocalizedString("OptionsText", comment: "OptionsText label") languageLbl.text = NSLocalizedString("OptionsLanguageLbl", comment: "OptionsLanguage label") contactLbl.text = NSLocalizedString("OptionsContactLbl", comment: "OptionsContact label") donateLbl.text = NSLocalizedString("DonateTitle", comment: "OptionsDonate label") rateLbl.text = NSLocalizedString("OptionsRateLbl", comment: "OptionsRate label") } }
true
f3f1743a946ec7bcc046e34ad8d82b432b651796
Swift
PattoMotto/imdb
/IMDB/MovieListModule/MovieListModuleBuilder.swift
UTF-8
778
2.765625
3
[]
no_license
//Pat import Foundation struct MovieListModuleBuilder { static func build(searchTitle: String, movies: [MovieModel], isFinalPage: Bool) -> MovieListViewController { let viewController = MovieListViewController() let presenter = MovieListPresenter() let interactor = MovieListInteractor() let service = SearchServiceImpl(output: interactor) presenter.title = searchTitle presenter.movies = movies presenter.view = viewController presenter.interactor = interactor presenter.isFinalPage = isFinalPage interactor.output = presenter interactor.service = service viewController.output = presenter return viewController } }
true
a016bedd3072ca3f480ad69eaa79d375343e6941
Swift
KaiTeuber/CodeChallange
/CodeChallange/CodeChallange/Communication/PostsFavorites.swift
UTF-8
1,636
2.890625
3
[]
no_license
// // Filesystem.swift // CodeChallange // // Created by Kai-Marcel Teuber on 18.09.19. // Copyright © 2019 App-Developers.de. All rights reserved. // import Foundation final public class PostsFavorites: MutatePostsProtocol { // MARK: - init public init(storage: FileStorage) { self.storage = storage let jsonDecoder = JSONDecoder() if let data = storage.load() { self.favorites = try! jsonDecoder.decode([Post].self, from: data) } else { NSLog("No data found on disc - let's init a ffresh one") self.favorites = [] } } // MARK: - overrides // MARK: - Protocol GetPostsProtocol public func getPosts(success: @escaping ([Post]) -> Void, failed: () -> Void) { success(favorites) } // MARK: - Protocol GetPostsProtocol public func addPost(_ post: Post) { if !favorites.contains(post) { favorites.append(post) } } public func deletePost(_ post: Post) { if let index = favorites.firstIndex(of: post) { favorites.remove(at: index) } } public func contains(_ post: Post) -> Bool { return favorites.firstIndex(of: post) != nil } // MARK: - public public func save() { let jsonEncoder = JSONEncoder() guard let data = try? jsonEncoder.encode(favorites) else { NSLog("failed to create data") return } storage.save(data: data) } // MARK: - private private var favorites: [Post] private let storage: FileStorage }
true
0f336fdc92c1cc3050390a306ef54f551d8f3883
Swift
gdollardollar/GMKeyboard
/Source/AnimatedKeyboardObserver.swift
UTF-8
2,228
3.234375
3
[ "MIT" ]
permissive
// // AnimatedKeyboardObserver.swift // Pods // // Created by gdollardollar on 12/4/16. // import Foundation /// Layer on top of `KeyboardObserver` that simplifies animating /// the layout updates. /// This protocol simply provides a default implementation to /// `keyboardWillChange(frameInView:animationDuration:animationOptions:userInfo:)` /// that calls `animateKeyboardChange(frameInView:,userInfo:) in an animation /// block with the appropriate duration and options. public protocol AnimatedKeyboardObserver: KeyboardObserver { /// Use this method to prevent animation in certain cases. /// /// For example, you might want to disable animations as long as /// a scrollview is dragged /// /// - Parameters: /// - frame: the keyboard frame in the view controller's view /// - userInfo: the keyboard notification user info /// - Returns: true if it should animate func shouldAnimateKeyboardChange(frameInView frame: CGRect, userInfo: [AnyHashable: Any]) -> Bool /// Function called when the keyboard frame changes. /// This function is called in an animation block with /// the appropriate values. /// /// - Parameters: /// - frame: the keyboard frame in the view controller's view /// - userInfo: the keyboard notification user info func animateKeyboardChange(frameInView frame: CGRect, userInfo: [AnyHashable: Any]) } extension AnimatedKeyboardObserver { public func shouldAnimateKeyboardChange(frameInView frame: CGRect, userInfo: [AnyHashable: Any]) -> Bool { return true } public func keyboardWillChange(frameInView frame: CGRect, animationDuration: TimeInterval, animationOptions: UIView.AnimationOptions, userInfo: [AnyHashable: Any]) { guard shouldAnimateKeyboardChange(frameInView: frame, userInfo: userInfo) else { return } UIView.animate(withDuration: animationDuration, delay: 0, options: [animationOptions, .beginFromCurrentState], animations: { () -> Void in self.animateKeyboardChange(frameInView: frame, userInfo: userInfo) }, completion: nil) } }
true
680810a3d2e199e2a0d8169d7ddfbe6dfe7e090f
Swift
ThangaAyyanar/swift
/Advent of Code/Day 9/Tests/Day 9Tests/Day_9Tests.swift
UTF-8
2,831
3
3
[]
no_license
import XCTest @testable import Day_9 final class Day_9Tests: XCTestCase { func test_part1_sample() { let fileURL = Bundle.module.url(forResource: "test", withExtension: "txt")! let contents = try! String(contentsOf: fileURL, encoding: .utf8) let allInputs = contents.components(separatedBy: .newlines) var new_inputs = [[Int]]() for input in allInputs { var new_int_arr = [Int]() for char in input { new_int_arr.append(Int(String(char))!) } if new_int_arr.isEmpty == false { new_inputs.append(new_int_arr) } } let day9 = Day_9(inputs: new_inputs) let result = day9.part1() print(result) } func test_part1() { let fileURL = Bundle.module.url(forResource: "input", withExtension: "txt")! let contents = try! String(contentsOf: fileURL, encoding: .utf8) let allInputs = contents.components(separatedBy: .newlines) var new_inputs = [[Int]]() for input in allInputs { var new_int_arr = [Int]() for char in input { new_int_arr.append(Int(String(char))!) } if new_int_arr.isEmpty == false { new_inputs.append(new_int_arr) } } let day9 = Day_9(inputs: new_inputs) let result = day9.part1() print(result) } func test_part2_sample() { let fileURL = Bundle.module.url(forResource: "test", withExtension: "txt")! let contents = try! String(contentsOf: fileURL, encoding: .utf8) let allInputs = contents.components(separatedBy: .newlines) var new_inputs = [[Int]]() for input in allInputs { var new_int_arr = [Int]() for char in input { new_int_arr.append(Int(String(char))!) } if new_int_arr.isEmpty == false { new_inputs.append(new_int_arr) } } let day9 = Day_9(inputs: new_inputs) let result = day9.part2() print(result) } func test_part2() { let fileURL = Bundle.module.url(forResource: "input", withExtension: "txt")! let contents = try! String(contentsOf: fileURL, encoding: .utf8) let allInputs = contents.components(separatedBy: .newlines) var new_inputs = [[Int]]() for input in allInputs { var new_int_arr = [Int]() for char in input { new_int_arr.append(Int(String(char))!) } if new_int_arr.isEmpty == false { new_inputs.append(new_int_arr) } } let day9 = Day_9(inputs: new_inputs) let result = day9.part2() print(result) } }
true
091fe2bd6ffc298664b656fa933b991d2db17901
Swift
LorenHan/Tip-for-day
/TimeAnywhere/TimeAnywhere/ViewController.swift
UTF-8
2,218
2.546875
3
[ "MIT" ]
permissive
// // ViewController.swift // TimeAnywhere // // Created by alexiuce  on 2017/7/25. // Copyright © 2017年 alexiuce . All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet weak var imgBtn: NSButton! override func viewDidLoad() { super.viewDidLoad() // NSWorkspace.shared().notificationCenter.addObserver(self, selector: #selector(ViewController.updateWorkspace(_:)), name: .NSWorkspaceActiveSpaceDidChange, object: nil) // Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.updateTopAppInfo), userInfo: nil, repeats: true) // Do any additional setup after loading the view. // /** 创建手势识别 */ // let clickGesture = NSClickGestureRecognizer(target: self, action: #selector(clcikedMouse(_:))) // /** 将手势识别器添加到imageView */ // imageView.addGestureRecognizer(clickGesture) // 去除点击时的灰色效果 imgBtn.isTransparent = true } override func viewDidAppear() { super.viewDidAppear() let win = view.window // print(view.window) // win?.backgroundColor = NSColor.red // win?.styleMask // win?.dockTile.showsApplicationBadge = false // NSApp.dockTile.badgeLabel = "12" // print(win!.dockTile.badgeLabel) // win?.isMovableByWindowBackground = true DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) { // win?.dockTile.badgeLabel = "20" win?.makeKeyAndOrderFront(nil) } } } extension ViewController{ @objc fileprivate func updateWorkspace(_ notification : NSNotification){ self.view.window?.makeKeyAndOrderFront(nil) print(notification) } @objc fileprivate func updateTopAppInfo(){ print(NSWorkspace.shared().frontmostApplication ?? "no no") } } // MARK: handle event listion extension ViewController{ @objc fileprivate func clcikedMouse(_ gesuter: NSClickGestureRecognizer){ print("clicked mouse") } }
true
a8955ba5516e99c7f392248fa1336b2c78b3e793
Swift
bitmovin/bitmovin-player-ios-samples
/BasicPlaylist/BasicPlaylist/ViewController.swift
UTF-8
3,202
2.78125
3
[]
no_license
// // Bitmovin Player iOS SDK // Copyright (C) 2021, Bitmovin Inc, All Rights Reserved // // This source code and its use and distribution, is subject to the terms // and conditions of the applicable license agreement. // import UIKit import BitmovinPlayer class ViewController: UIViewController { var player: Player! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .black // Create a player configuration with the default settings let playerConfig = PlayerConfig() // Use the PlayerFactory to create a new player instance with the provided configuration player = PlayerFactory.create(playerConfig: playerConfig) // Listen to player events player.add(listener: self) // Create player view and pass the player instance to it let playerView = PlayerView(player: player, frame: .zero) playerView.autoresizingMask = [.flexibleHeight, .flexibleWidth] playerView.frame = view.bounds view.addSubview(playerView) view.bringSubviewToFront(playerView) let sources = createPlaylist() // Configure playlist-specific options let playlistOptions = PlaylistOptions(preloadAllSources: false) // Create a playlist configuration containing the playlist items (sources) and the playlist options let playlistConfig = PlaylistConfig( sources: sources, options: playlistOptions ) // Load the playlist configuration into the player instance player.load(playlistConfig: playlistConfig) } override var prefersStatusBarHidden: Bool { true } func createPlaylist() -> [Source] { var sources = [Source]() guard let streamUrl1 = URL(string: "https://bitmovin-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8"), let streamUrl2 = URL(string: "https://bitmovin-a.akamaihd.net/content/sintel/hls/playlist.m3u8") else { return sources } let firstSourceConfig = SourceConfig(url: streamUrl1, type: .hls) firstSourceConfig.title = "Art of Motion" let firstSource = SourceFactory.create(from: firstSourceConfig) // Listen to events from this source firstSource.add(listener: self) sources.append(firstSource) let secondSourceConfig = SourceConfig(url: streamUrl2, type: .hls) secondSourceConfig.title = "Sintel" let secondSource = SourceFactory.create(from: secondSourceConfig) // Listen to events from this source secondSource.add(listener: self) sources.append(secondSource) return sources } } extension ViewController: SourceListener { func onEvent(_ event: SourceEvent, source: Source) { let sourceIdentifier = source.sourceConfig.title ?? source.sourceConfig.url.absoluteString dump(event, name: "[Source Event] - \(sourceIdentifier)", maxDepth: 1) } } extension ViewController: PlayerListener { func onEvent(_ event: Event, player: Player) { dump(event, name: "[Player Event]", maxDepth: 1) } }
true
2f1f4de1160e75c1ed8764f88574d2d8240175c1
Swift
Sajjon/CachingService
/Tests/Source/Cache/MockedCacheForInteger.swift
UTF-8
959
2.921875
3
[ "MIT" ]
permissive
// // MockedCacheForInteger.swift // CachingServiceTests // // Created by Alexander Cyon on 2017-11-15. // Copyright © 2017 Alexander Cyon. All rights reserved. // import Foundation enum ValueOrEmpty<Value: Equatable>: Equatable { case value(Value) case empty } extension ValueOrEmpty { static func ==(lhs: ValueOrEmpty<Value>, rhs: ValueOrEmpty<Value>) -> Bool { switch (lhs, rhs) { case (.value(let lhsValue), .value(let rhsValue)): return lhsValue == rhsValue case (.empty, .empty): print(".empty == .empty?? Defining as `false`"); return false default: return false } } } extension ValueOrEmpty { var value: Value? { switch self { case .value(let value): return value default: return nil } } } final class MockedCacheForInteger: BaseMockedCache<Int> { init(mockedEvent: MockedEvent<Int>) { super.init(event: mockedEvent) } }
true
c4186492dc277b37d500cfabc658d59544b1f042
Swift
GowthamKudupudi/Fair
/Fair/MetalViewController.swift
UTF-8
3,917
2.640625
3
[]
no_license
// // ViewController.swift // HelloMetal // // Created by Gowtham Kudupudi on 21/04/17. // Copyright © 2017 Gowtham Kudupudi. All rights reserved. // import UIKit import Metal protocol MetalViewControllerDelegate : class { func updateLogic(timeSinceLastUpdate: CFTimeInterval) func renderObjects(drawable: CAMetalDrawable) } class MetalViewController: UIViewController { var device: MTLDevice! var metalLayer: CAMetalLayer! var pipelineState: MTLRenderPipelineState! var commandQueue: MTLCommandQueue! var timer: CADisplayLink! var projectionMatrix: Matrix4! var lastFrameTimestamp: CFTimeInterval = 0.0 weak var metalViewControllerDelegate: MetalViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. projectionMatrix = Matrix4.makePerspectiveViewAngle(Matrix4.degrees(toRad: 85.0), aspectRatio: Float(self.view.bounds.size.width / self.view.bounds.size.height), nearZ: 0.01, farZ: 100.0) device = MTLCreateSystemDefaultDevice() metalLayer = CAMetalLayer() metalLayer.device = device metalLayer.pixelFormat = .bgra8Unorm metalLayer.framebufferOnly = true view.layer.addSublayer(metalLayer) // 1 let defaultLibrary = device.makeDefaultLibrary()! let fragmentProgram = defaultLibrary.makeFunction(name: "basic_fragment") let vertexProgram = defaultLibrary.makeFunction(name: "basic_vertex") // 2 let pipelineStateDescriptor = MTLRenderPipelineDescriptor() pipelineStateDescriptor.vertexFunction = vertexProgram pipelineStateDescriptor.fragmentFunction = fragmentProgram pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm // 3 pipelineState = try! device.makeRenderPipelineState(descriptor: pipelineStateDescriptor) commandQueue = device.makeCommandQueue() timer = CADisplayLink(target: self, selector: #selector(MetalViewController.newFrame(displayLink:))) timer.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode) } //1 override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let window = view.window { let scale = window.screen.nativeScale let layerSize = view.bounds.size //2 view.contentScaleFactor = scale metalLayer.frame = CGRect(x: 0, y: 0, width: layerSize.width, height: layerSize.height) metalLayer.drawableSize = CGSize(width: layerSize.width * scale, height: layerSize.height * scale) } projectionMatrix = Matrix4.makePerspectiveViewAngle(Matrix4.degrees(toRad: 85.0), aspectRatio: Float(self.view.bounds.size.width / self.view.bounds.size.height), nearZ: 0.01, farZ: 100.0) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func render() { guard let drawable = metalLayer?.nextDrawable() else {return} self.metalViewControllerDelegate?.renderObjects(drawable: drawable) } @objc 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 self.metalViewControllerDelegate?.updateLogic(timeSinceLastUpdate: timeSinceLastUpdate) // 5 autoreleasepool { self.render() } } }
true
3386070bd6957cd09baded21a3dd67cfcc89eff2
Swift
matthewlui/RestGerrit
/Sources/RestGerrit/Protocols/Endpoint.swift
UTF-8
472
2.640625
3
[]
no_license
// // Endpoint.swift // RestGerrit // // Created by Matthew Lui on 16/2/2018. // Copyright © 2018 Chatboy.xyz. All rights reserved. // import Foundation public protocol Endpoint { static var name: String { get } var params: [Param] { get } mutating func add(param: Param) } internal protocol InternalEndpoint { var params: [Param] { get set } } extension InternalEndpoint { mutating func add(param: Param) { params.append(param) } }
true
a4994edb1653bc722eca7deeedf924bbb84c7e02
Swift
pisces/FunctionalSwiftKit
/Example/Tests/ArrayTest.swift
UTF-8
2,155
2.96875
3
[ "MIT", "BSD-2-Clause" ]
permissive
// // ArrayTest.swift // FunctionalSwiftKit_Tests // // Created by KWANG HYOUN KIM on 08/02/2019. // Copyright © 2019 CocoaPods. All rights reserved. // import XCTest @testable import FunctionalSwiftKit class ArrayTest: XCTestCase { func testGroupedForStrings() { let source = ["A", "A", "B", "C"] let grouped = source.grouped { $0 } XCTAssertEqual(3, grouped.count) XCTAssertEqual(2, grouped["A"]?.count ?? 0) XCTAssertEqual(1, grouped["B"]?.count ?? 0) XCTAssertEqual(1, grouped["C"]?.count ?? 0) XCTAssertEqual(["A", "A"], grouped["A"]) XCTAssertEqual(["B"], grouped["B"]) XCTAssertEqual(["C"], grouped["C"]) } func testGroupedForModels() { let source = [Model(uid: "A"), Model(uid: "A"), Model(uid: "B"), Model(uid: "C")] let grouped = source.grouped { $0.uid } XCTAssertEqual(3, grouped.count) XCTAssertEqual(2, grouped["A"]?.count ?? 0) XCTAssertEqual(1, grouped["B"]?.count ?? 0) XCTAssertEqual(1, grouped["C"]?.count ?? 0) XCTAssertEqual([Model(uid: "A"), Model(uid: "A")], grouped["A"]) XCTAssertEqual([Model(uid: "B")], grouped["B"]) XCTAssertEqual([Model(uid: "C")], grouped["C"]) } func testSubtracted() { let source = [Model(uid: "A"), Model(uid: "B")] let other = [Model(uid: "A")] let subtracted = source.subtracted(other) XCTAssertEqual(1, subtracted.count) XCTAssertTrue(subtracted.contains(Model(uid: "B"))) XCTAssertFalse(subtracted.contains(Model(uid: "A"))) XCTAssertEqual([Model(uid: "B")], subtracted) } func testUniqued() { let source = [Model(uid: "A"), Model(uid: "A"), Model(uid: "B"), Model(uid: "B")] let uniqued = source.uniqued() XCTAssertEqual(2, uniqued.count) XCTAssertEqual([Model(uid: "A"), Model(uid: "B")], uniqued) } } struct Model: Hashable { let uid: String var hashValue: Int { return uid.hashValue } static func ==(lhs: Model, rhs: Model) -> Bool { return lhs.uid == rhs.uid } }
true
5af2ba0233f1cb42a6fd69b8d233b71940cf21c6
Swift
bankutia/EUweather-SwiftUI
/EUweather-SwiftUI/UseCase/CurrentWeatherDisplaying/WeatherRowViewModel.swift
UTF-8
1,016
2.921875
3
[]
no_license
// // WeatherDisplayRowViewModel.swift // EUerayher-SwiftUI // // Created by ALi on 2019. 12. 26.. // Copyright © 2019. ALi. All rights reserved. // import SwiftUI class WeatherRowViewModel: ObservableObject, Identifiable, WeatherServiceInjecting { var cityName: String { currentWeather.city.name } var degree: String { currentWeather.degree.toDisplayString() } var iconUrl: URL? { service.getWeatherIconUrl(for: currentWeather.iconName.imageFileName) } var cityCode: String { currentWeather.city.code } private let currentWeather: CurrentWeather private lazy var service: WeatherService = { inject() }() init(currentWeather: CurrentWeather) { self.currentWeather = currentWeather } } private extension String { var imageFileName: String { "\(self)@2x.png" } } private extension Double { func toDisplayString() -> String { "\(Int(self.rounded()))\u{00b0}" } }
true
26767b06afa1f2f412c8c58d7740b5e084d8f05a
Swift
brysonSaclausa/ios-photo-collection
/iosPhotoCollection/iosPhotoCollection/PhotosCollectionViewController.swift
UTF-8
3,850
2.671875
3
[]
no_license
// // PhotosCollectionViewController.swift // iosPhotoCollection // // Created by B$hady on 6/11/20. // Copyright © 2020 Lambda School. All rights reserved. // import UIKit class PhotosCollectionViewController: UICollectionViewController { let photoController = PhotoController() let themeHelper = ThemeHelper() func setTheme() { guard let currentTheme = themeHelper.themePreference else { return } if currentTheme == "Dark" { collectionView.backgroundColor = UIColor(named: "Dark") } else { collectionView.backgroundColor = UIColor(named: "Light") } } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) themeHelper.setTheme(viewController: self) setTheme() collectionView.reloadData() } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "addPhotoButtonSegue" { guard let photoDetailVC = segue.destination as? PhotoDetailViewController else { return } photoDetailVC.themeHelper = themeHelper } else if segue.identifier == "collectionViewCellToPhotoDetailVCSegue" { guard let photoDetatilCell = segue.destination as? PhotoDetailViewController else { return } photoDetatilCell.themeHelper = themeHelper } else if segue.identifier == "selectThemeButtonSegue" { guard let selectThemeVC = segue.destination as? ThemeSelectionViewController else { return } selectThemeVC.themeHelper = themeHelper } } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photoController.photos.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as? PhotosCollectionViewCell else { return UICollectionViewCell()} let photo = photoController.photos[indexPath.row] cell.photo = photo // Configure the cell cell.backgroundColor = .red return cell } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return false } override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { } */ }
true
3cf379cb069d0c60b12fe15e815f5dd3f094abab
Swift
smallMas/TestCHGAdapterSwift
/TestCHGAdapterSwift/Classes/RXOther/TCOtherViewController.swift
UTF-8
5,144
2.703125
3
[]
no_license
// // TCOtherViewController.swift // TestCHGAdapterSwift // // Created by 燕来秋 on 2021/1/18. // import UIKit import RxCocoa import RxSwift enum YiHuo : UInt8{ case a = 0x0 case b = 0x1 case c = 0x2 } enum VNodeFlags : UInt32 { case Delete = 0x00000001 case Write = 0x00000002 case Extended = 0x00000004 case Attrib = 0x00000008 case Link = 0x00000010 case Rename = 0x00000020 case Revoke = 0x00000040 case None = 0x00000080 } class TCOtherViewController: TCBaseViewController { let disposedBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() self.rx.viewWillAppear.subscribe(onNext: {event in print("event : \(event)") }).disposed(by: disposedBag) var p = Person() p.progressOb.subscribe(onNext: { event in print("xx : \(event)") }).disposed(by: disposedBag) p.progress = 0.4; p.progress = 0.42; p.progress = 0.43; p.progress = 0.45; print("p.progress : \(p.progress)") // Do any additional setup after loading the view. // func swap( a: inout Int, b: inout Int) { // let temp = a // a = b // b = temp // } // var a = 1 // var b = 2 // print(a, b)// 1 2 // swap(a: &a, b: &b) // print(a, b)// 2 1 // let a = [2,3,4].map{ a in // a*2 // } // print("a : \(a)") // fun a * b a + b // let a1 = YiHuo.b | YiHuo.c // print("a1 : \(a1)") // if a1.HashFlag(YiHuo.b) { // print("ddddd") // } // let firstBit: UInt8 = 0b10000000 // let lastBit: UInt8 = 0b00000001 // let invertedBits = ~lastBit // 等于 0b11111110 // let noneBit = firstBit & lastBit // 等于 0b00000000 // let twoSideBits = firstBit | lastBit //等于 0b10000001 // let a1 = VNodeFlags.Link | VNodeFlags.Delete // print("a1 : \(a1)") // UIViewAutoresizingFlexibleWidth // NSCalendarUnitYear // let a = NSCalendar.Unit.year | NSCalendar.Unit.month // print("a : \(a)") // UIViewAnimationOptionAllowUserInteraction } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } } open class Person : NSObject { var progress : Float = 0.0 { didSet { rx_progress.onNext(progress) } } private var rx_progress = PublishSubject<Float>() var progressOb : Observable<Float> { return rx_progress.asObservable() } var value : String? } extension Reactive where Base : Person { // public var progress : ControlProperty<Float> { //// let source = Observable.deferred { [weak p = self.base]() -> Observable<Float> in //// return Observable.of(p?.progress ?? 0).startWith((p?.progress)!) //// } // let source = Observable.of(self.progress) // //// let observer = Binder(self.base) { (person , value : Float?) in //// person.progress = value ?? 0 //// } // // let observer = Binder(self.base){p, value in // p.progress = value // } // ControlProperty(values: source, valueSink: observer) // return ControlProperty(values: source, valueSink: observer.asObserver()) // } // public var value : ControlProperty<String> { //// let source = self.rx.mapObserver() // let source = Observable.of(self.value) // let observer = Binder(self.base){p, value in // value as? String ?? "" // p.value = value // } // return ControlProperty(values: source, valueSink: observer) // } } //extension Reactive where Base: NSTextField { // // /// Reactive wrapper for `delegate`. // /// // /// For more information take a look at `DelegateProxyType` protocol documentation. // public var delegate: DelegateProxy<NSTextField, NSTextFieldDelegate> { // RxTextFieldDelegateProxy.proxy(for: self.base) // } // // /// Reactive wrapper for `text` property. // public var text: ControlProperty<String?> { // let delegate = RxTextFieldDelegateProxy.proxy(for: self.base) // // let source = Observable.deferred { [weak textField = self.base] in // delegate.textSubject.startWith(textField?.stringValue) // }.take(until: self.deallocated) // // let observer = Binder(self.base) { (control, value: String?) in // control.stringValue = value ?? "" // } // // return ControlProperty(values: source, valueSink: observer.asObserver()) // } // //} public extension Reactive where Base:UIViewController { public var viewWillAppear: ControlEvent<Bool> { let source = self.methodInvoked(#selector(Base.viewWillAppear(_:))).map{ $0.first as? Bool ?? false } return ControlEvent(events: source) } }
true
4d99a670a9ad6afc1af5db0c44d425a747c673d7
Swift
trickstersio/envapp-sdk-ios
/EnvApp/PublicKey.swift
UTF-8
4,309
2.765625
3
[ "MIT" ]
permissive
// // File.swift // // // Created by Alexandr Gaidukov on 13.02.2020. // import Foundation private extension SecKey { static func key(withData keyData: Data, isPublic: Bool) throws -> SecKey { let keyClass = isPublic ? kSecAttrKeyClassPublic : kSecAttrKeyClassPrivate let sizeInBits = keyData.count * 8 let keyDict: [CFString: Any] = [ kSecAttrKeyType: kSecAttrKeyTypeRSA, kSecAttrKeyClass: keyClass, kSecAttrKeySizeInBits: NSNumber(value: sizeInBits), kSecReturnPersistentRef: true ] var error: Unmanaged<CFError>? guard let key = SecKeyCreateWithData(keyData as CFData, keyDict as CFDictionary, &error) else { throw EnvAppError.keyCreateFailed(error?.takeRetainedValue()) } return key } func isValid(forClass requiredClass: CFString) -> Bool { let attributes = SecKeyCopyAttributes(self) as? [CFString: Any] guard let keyType = attributes?[kSecAttrKeyType] as? String, let keyClass = attributes?[kSecAttrKeyClass] as? String else { return false } let isRSA = keyType == (kSecAttrKeyTypeRSA as String) let isValidClass = keyClass == (requiredClass as String) return isRSA && isValidClass } } private extension Data { func stripKeyHeader() throws -> Data { let node: Asn1Parser.Node do { node = try Asn1Parser.parse(data: self) } catch { throw EnvAppError.asn1ParsingFailed } guard case .sequence(let nodes) = node else { throw EnvAppError.asn1ParsingFailed } let onlyHasIntegers = nodes.filter { node -> Bool in if case .integer = node { return false } return true }.isEmpty if onlyHasIntegers { return self } if let last = nodes.last, case .bitString(let data) = last { return data } if let last = nodes.last, case .octetString(let data) = last { return data } throw EnvAppError.asn1ParsingFailed } } public struct PublicKey { let reference: SecKey public init(data: Data) throws { let dataWithoutHeader = try data.stripKeyHeader() reference = try SecKey.key(withData: dataWithoutHeader, isPublic: true) } public init(reference: SecKey) throws { guard reference.isValid(forClass: kSecAttrKeyClassPublic) else { throw EnvAppError.wrongPublicKey } self.reference = reference } public init(base64Encoded base64String: String) throws { guard let data = Data(base64Encoded: base64String, options: [.ignoreUnknownCharacters]) else { throw EnvAppError.invalidBase64String } try self.init(data: data) } public init(pemEncoded pemString: String) throws { let base64String = try PublicKey.base64String(pemEncoded: pemString) try self.init(base64Encoded: base64String) } public init(pemNamed pemName: String, in bundle: Bundle) throws { guard let path = bundle.path(forResource: pemName, ofType: "pem") else { throw EnvAppError.pemFileNotFound(pemName) } let keyString = try String(contentsOf: URL(fileURLWithPath: path), encoding: .utf8) try self.init(pemEncoded: keyString) } public init(derNamed derName: String, in bundle: Bundle) throws { guard let path = bundle.path(forResource: derName, ofType: "der") else { throw EnvAppError.derFileNotFound(derName) } let data = try Data(contentsOf: URL(fileURLWithPath: path)) try self.init(data: data) } private static func base64String(pemEncoded pemString: String) throws -> String { let lines = pemString.components(separatedBy: "\n").filter { line in return !line.hasPrefix("-----BEGIN") && !line.hasPrefix("-----END") } guard lines.count != 0 else { throw EnvAppError.pemDoesNotContainKey } return lines.joined(separator: "") } }
true
a74d9b6132f7313540da02b5d516b82ae8eb31d1
Swift
Jay-Hong/Calculendar
/Calculendar/Controller/MoneyUnitViewController.swift
UTF-8
1,540
2.71875
3
[]
no_license
import UIKit class MoneyUnitViewController: UITableViewController { var moneyUnit = Int() override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { moneyUnitsDataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MoneyUnitCell", for: indexPath) cell.textLabel?.text = moneyUnitsDataSource[indexPath.row] cell.accessoryType = indexPath.row == moneyUnit ? .checkmark : .none return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 이전 체크 제거 let preIndexPath = IndexPath(row: moneyUnit, section: indexPath.section) let preCell = tableView.cellForRow(at: preIndexPath) preCell?.accessoryType = .none // 새로 선택된 화폐단위 체크 let newCell = tableView.cellForRow(at: indexPath) newCell?.accessoryType = .checkmark moneyUnit = indexPath.row performSegue(withIdentifier: "unwindFromMoneyUnitVC", sender: newCell) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "unwindFromMoneyUnitVC" { if let setting2VC = segue.destination as? Setting2ViewController { setting2VC.moneyUnit = moneyUnit } } } }
true
f58089222980211b1dd2481ba8b9a95cd1a3b53c
Swift
ram4ik/AlertsInDetails
/AlertsInDetails/ContentView.swift
UTF-8
1,209
3.140625
3
[]
no_license
// // ContentView.swift // AlertsInDetails // // Created by ramil on 25.02.2020. // Copyright © 2020 com.ri. All rights reserved. // import SwiftUI struct ContentView: View { @State private var showAlert = false var body: some View { Button(action: { self.showAlert.toggle() }) { Text("Hello, World!") } .alert(isPresented: $showAlert) { let cancelButton = Alert.Button.cancel() let defaultButton = Alert.Button.default(Text("Print")) { print("Default") } let destructiveButton = Alert.Button.destructive(Text("Destructive")) return Alert(title: Text("Alert"), message: Text("My alert message!"), primaryButton: cancelButton, secondaryButton: destructiveButton) // return Alert(title: Text("Alert"), // message: Text("My alert message!"), // dismissButton: defaultButton) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
true
b24c6e28c033ae1be9513c069c298bd29eefc838
Swift
hd170998/LessWasteiOS
/LessWaste/Controller/Login/LoginVC.swift
UTF-8
5,669
2.515625
3
[]
no_license
// // LoginVC.swift // LessWaste // // Created by Héctor David Hernández Rodríguez on 14/05/20. // Copyright © 2020 Héctor David Hernández Rodríguez. All rights reserved. // import UIKit import Firebase class LoginVC: UIViewController { let logoContainerView: UIView = { let view = UIView() let logoImageVIew = UIImageView(image: #imageLiteral(resourceName: "logo_white")) logoImageVIew.contentMode = .scaleAspectFill view.addSubview(logoImageVIew) logoImageVIew.anchor(top: nil, left: nil, bottom: nil, right: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 200, height: 50) logoImageVIew.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true logoImageVIew.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true view.backgroundColor = UIColor(red: 0/255, green: 120/255, blue: 175/255, alpha: 1) return view }() let emailTextField: UITextField = { let tf = UITextField() tf.placeholder = "Email" tf.backgroundColor = UIColor(white: 0, alpha: 0.03) tf.borderStyle = .roundedRect tf.font = UIFont.systemFont(ofSize: 14) tf.autocapitalizationType = .none return tf }() let passwordTextField: UITextField = { let tf = UITextField() tf.placeholder = "Password" tf.backgroundColor = UIColor(white: 0, alpha: 0.03) tf.borderStyle = .roundedRect tf.font = UIFont.systemFont(ofSize: 14) tf.isSecureTextEntry = true return tf }() let logInButton: UIButton={ let button = UIButton(type: .system) button.setTitle("Login", for: .normal) button.setTitleColor(.white, for: .normal) button.backgroundColor = UIColor(red: 149/255, green: 204/255, blue: 244/255, alpha: 1) button.addTarget(self, action: #selector(handleLogin), for: .touchUpInside) return button }() let dontHaveAccountButton: UIButton = { let button = UIButton(type: .system) let attributedTitle = NSMutableAttributedString(string: "¿No tienes cuenta? ", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor: UIColor.lightGray]) attributedTitle.append(NSAttributedString(string: "Registarte",attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor(red: 17/255, green: 154/255, blue: 237/255, alpha: 1)])) button.setAttributedTitle(attributedTitle, for: .normal) button.addTarget(self, action: #selector(handleShowSingUp), for: .touchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white //hide Nav Bar navigationController?.navigationBar.isHidden = true view.addSubview(logoContainerView) logoContainerView.anchor(top: view.topAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 150) confugureViewComponents() view.addSubview(dontHaveAccountButton) dontHaveAccountButton.anchor(top: nil, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 60) } @objc func handleShowSingUp(){ let signUpVC = SignUpVC() navigationController?.pushViewController(signUpVC, animated: true) } @objc func handleLogin(){ guard let email = emailTextField.text, let password = passwordTextField.text else { return } Auth.auth().signIn(withEmail: email, password: password) { (user, error) in if let e = error{ let alert = UIAlertController(title: "Something happened", message: e.localizedDescription.description, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil)) self.present(alert, animated: true, completion: nil) return } guard let mainTabVC = UIApplication.shared.keyWindow?.rootViewController as? MainTabVC else { return } mainTabVC.confugureViewControllers() self.dismiss(animated: true, completion: nil) } } func confugureViewComponents() { let stackView = UIStackView(arrangedSubviews: [emailTextField, passwordTextField, logInButton]) stackView.axis = .vertical stackView.spacing = 10 stackView.distribution = .fillEqually view.addSubview(stackView) stackView.anchor(top: logoContainerView.bottomAnchor, left: view.leftAnchor, bottom: nil, right: view.rightAnchor, paddingTop: 40, paddingLeft: 40, paddingBottom: 0, paddingRight: 40, width: 0, height: 140) } @objc func formValidation() { // ensures that email and password text fields have text guard emailTextField.hasText, passwordTextField.hasText else { // handle case for above conditions not met logInButton.isEnabled = false logInButton.backgroundColor = UIColor(red: 149/255, green: 204/255, blue: 244/255, alpha: 1) return } // handle case for conditions were met logInButton.backgroundColor = UIColor(red: 17/255, green: 154/255, blue: 237/255, alpha: 1) logInButton.isEnabled = true } }
true
2a198f38e26a084378fa71961e15a446566e36aa
Swift
STMicroelectronics/BlueSTSDK_iOS
/Sources/STBlueSDK/Features/NEAIClassification/NEAIClassificationData.swift
UTF-8
15,135
2.59375
3
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "GPL-1.0-or-later", "Apache-2.0", "MIT", "EPL-1.0", "LicenseRef-scancode-stmicroelectronics-centrallabs" ]
permissive
// // NEAIClassificationData.swift // // Copyright (c) 2022 STMicroelectronics. // All rights reserved. // // This software is licensed under terms that can be found in the LICENSE file in // the root directory of this software component. // If no LICENSE file comes with this software, it is provided AS-IS. // import Foundation public struct NEAIClassificationData { public let mode: FeatureField<NEAIClassModeType> public var phase: FeatureField<NEAIClassPhaseType>? = nil public var state: FeatureField<NEAIClassStateType>? = nil public var classMajorProbability: FeatureField<UInt8>? = nil public var classesNumber: FeatureField<UInt8>? = nil public var class1Probability: FeatureField<UInt8>? = nil public var class2Probability: FeatureField<UInt8>? = nil public var class3Probability: FeatureField<UInt8>? = nil public var class4Probability: FeatureField<UInt8>? = nil public var class5Probability: FeatureField<UInt8>? = nil public var class6Probability: FeatureField<UInt8>? = nil public var class7Probability: FeatureField<UInt8>? = nil public var class8Probability: FeatureField<UInt8>? = nil init(with data: Data, offset: Int) { let mode = NEAIClassModeType(rawValue: data.extractUInt8(fromOffset: offset + 2)) var phase: NEAIClassPhaseType? = nil var state: NEAIClassStateType? = nil var classMajorProbability: UInt8? = nil var classesNumber: UInt8? = nil var class1Probability: UInt8? = nil var class2Probability: UInt8? = nil var class3Probability: UInt8? = nil var class4Probability: UInt8? = nil var class5Probability: UInt8? = nil var class6Probability: UInt8? = nil var class7Probability: UInt8? = nil var class8Probability: UInt8? = nil if data.count - offset == 4 { phase = NEAIClassPhaseType(rawValue: data.extractUInt8(fromOffset: offset + 2 + 1)) } else { switch mode { case .ONE_CLASS: if ((data.count-offset) != 6){ NSException( name: NSExceptionName(rawValue: "Invalid data"), reason: "Wrong number of bytes \(data.count-offset) for 1-Class", userInfo: nil ).raise() } phase = NEAIClassPhaseType(rawValue: data.extractUInt8(fromOffset: offset + 2 + 1)) state = NEAIClassStateType(rawValue: data.extractUInt8(fromOffset: offset + 2 + 2)) classMajorProbability = UInt8(1) classesNumber = UInt8(1) class1Probability = data.extractUInt8(fromOffset: offset + 2 + 3) case .N_CLASS: if ((data.count-offset) == 6){ phase = NEAIClassPhaseType(rawValue: data.extractUInt8(fromOffset: offset + 2 + 1)) state = NEAIClassStateType(rawValue: data.extractUInt8(fromOffset: offset + 2 + 2)) classMajorProbability = data.extractUInt8(fromOffset: offset + 2 + 3) if(classMajorProbability != 0) { NSException( name: NSExceptionName(rawValue: "Invalid data"), reason: "Unknown case not valid classMajorProbability != 0", userInfo: nil ).raise() } classesNumber = UInt8(1) } else { let classesNumber = data.count - offset - 6 if(classesNumber > 8) { NSException( name: NSExceptionName(rawValue: "Invalid data"), reason: "Too many classes \(classesNumber)", userInfo: nil ).raise() } phase = NEAIClassPhaseType(rawValue: data.extractUInt8(fromOffset: offset + 2 + 1)) state = NEAIClassStateType(rawValue: data.extractUInt8(fromOffset: offset + 2 + 2)) classMajorProbability = data.extractUInt8(fromOffset: offset + 2 + 3) if(classesNumber == 1) { class1Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 0) } else if (classesNumber == 2) { class1Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 0) class2Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 1) } else if (classesNumber == 3) { class1Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 0) class2Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 1) class3Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 2) } else if (classesNumber == 4) { class1Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 0) class2Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 1) class3Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 2) class4Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 3) } else if (classesNumber == 5) { class1Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 0) class2Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 1) class3Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 2) class4Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 3) class5Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 4) } else if (classesNumber == 6) { class1Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 0) class2Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 1) class3Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 2) class4Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 3) class5Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 4) class6Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 5) } else if (classesNumber == 7) { class1Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 0) class2Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 1) class3Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 2) class4Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 3) class5Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 4) class6Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 5) class7Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 6) } else if (classesNumber == 8) { class1Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 0) class2Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 1) class3Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 2) class4Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 3) class5Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 4) class6Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 5) class7Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 6) class8Probability = data.extractUInt8(fromOffset: offset + 2 + 4 + 7) } } default: print("Default CASE") } } self.mode = FeatureField<NEAIClassModeType>(name: "Mode", uom: nil, min: .ONE_CLASS, max: .NULL, value: mode) self.phase = FeatureField<NEAIClassPhaseType>(name: "Phase", uom: nil, min: .IDLE, max: .NULL, value: phase) self.state = FeatureField<NEAIClassStateType>(name: "State", uom: nil, min: .OK, max: .NULL, value: state) self.classMajorProbability = FeatureField<UInt8>(name: "Class Major Prob", uom: nil, min: 0, max: 8, value: classMajorProbability) self.classesNumber = FeatureField<UInt8>(name: "ClassesNumber", uom: nil, min: 2, max: 8, value: classesNumber) self.class1Probability = FeatureField<UInt8>(name: "Class 1 Probability", uom: "%", min: 0, max: 100, value: class1Probability) self.class2Probability = FeatureField<UInt8>(name: "Class 2 Probability", uom: "%", min: 0, max: 100, value: class2Probability) self.class3Probability = FeatureField<UInt8>(name: "Class 3 Probability", uom: "%", min: 0, max: 100, value: class3Probability) self.class4Probability = FeatureField<UInt8>(name: "Class 4 Probability", uom: "%", min: 0, max: 100, value: class4Probability) self.class5Probability = FeatureField<UInt8>(name: "Class 5 Probability", uom: "%", min: 0, max: 100, value: class5Probability) self.class6Probability = FeatureField<UInt8>(name: "Class 6 Probability", uom: "%", min: 0, max: 100, value: class6Probability) self.class7Probability = FeatureField<UInt8>(name: "Class 7 Probability", uom: "%", min: 0, max: 100, value: class7Probability) self.class8Probability = FeatureField<UInt8>(name: "Class 8 Probability", uom: "%", min: 0, max: 100, value: class8Probability) } } extension NEAIClassificationData: CustomStringConvertible { public var description: String { let mode = mode.value let phase = phase?.value let state = state?.value let classMajorProbability = classMajorProbability?.value let classesNumber = classesNumber?.value let class1Probability = class1Probability?.value let class2Probability = class2Probability?.value let class3Probability = class3Probability?.value let class4Probability = class4Probability?.value let class5Probability = class5Probability?.value let class6Probability = class6Probability?.value let class7Probability = class7Probability?.value let class8Probability = class8Probability?.value return String(format: "Mode: %@, Phase: %@, State: %@, Class Major Probability: %@, Classes Number: %@, Class 1 Probability: %@, Class 2 Probability: %@, Class 3 Probability: %@, Class 4 Probability: %@, Class 5 Probability: %@, Class 6 Probability: %@, Class 7 Probability: %@, Class 8 Probability: %@,", mode?.description ?? "", phase?.description ?? "", state?.description ?? "", classMajorProbability?.description ?? "", classesNumber?.description ?? "", class1Probability?.description ?? "", class2Probability?.description ?? "", class3Probability?.description ?? "", class4Probability?.description ?? "", class5Probability?.description ?? "", class6Probability?.description ?? "", class7Probability?.description ?? "", class8Probability?.description ?? "") } } extension NEAIClassificationData: Loggable { public var logHeader: String { "\(mode.logHeader),\(phase?.logHeader ?? ""),\(state?.logHeader ?? ""),\(classMajorProbability?.logHeader ?? ""),\(classesNumber?.logHeader ?? ""),\(class1Probability?.logHeader ?? ""),\(class2Probability?.logHeader ?? ""),\(class3Probability?.logHeader ?? ""),\(class4Probability?.logHeader ?? ""),\(class5Probability?.logHeader ?? ""),\(class6Probability?.logHeader ?? ""),\(class7Probability?.logHeader ?? ""),\(class8Probability?.logHeader ?? "")" } public var logValue: String { "\(mode.logValue),\(phase?.logValue ?? ""),\(state?.logValue ?? ""),\(classMajorProbability?.logValue ?? ""),\(classesNumber?.logValue ?? ""),\(class1Probability?.logValue ?? ""),\(class2Probability?.logValue ?? ""),\(class3Probability?.logValue ?? ""),\(class4Probability?.logValue ?? ""),\(class5Probability?.logValue ?? ""),\(class6Probability?.logValue ?? ""),\(class7Probability?.logValue ?? ""),\(class8Probability?.logValue ?? "")" } }
true
35206c6f03bf10b22a8a9d9d8ebe47764313dcfe
Swift
pratulpatwari/swift-practice
/Open Other App/Open Other App/Authentication/LoginController.swift
UTF-8
5,239
2.609375
3
[]
no_license
// // LoginController.swift // Open Other App // // Created by pratul patwari on 6/14/18. // Copyright © 2018 pratul patwari. All rights reserved. // import UIKit func storeKeys(accessObject: AccessObject){ let now = Date() let expirationTime = now.addingTimeInterval(TimeInterval(accessObject.expires_in)) UserDefaults.standard.set(accessObject.refresh_token, forKey: "refresh_token") UserDefaults.standard.set(expirationTime, forKey: "expiration_time") UserDefaults.standard.set(accessObject.access_token, forKey: "access_token") } let clientID = "22CZXG" let clientSecret = "b12eb897edd9c61073700eb1c14e0d8f" let baseAuthUrlString = "https://www.fitbit.com/oauth2/authorize?" let baseTokenUrlString = "https://api.fitbit.com/oauth2/token?" let deviceUrl = "https://api.fitbit.com/1/user/-/devices.json" let baseURL = URL(string: baseAuthUrlString) let redirectURI = "myapp://" let defaultScope = "heartrate+activity+settings" class LoginController: UIViewController, AuthenticationProtocol { var authenticationController: AuthenticationController? let loginButton: UIButton = { let l = UIButton(type: .system) l.setTitleColor(.black, for: .normal) l.setTitle("Fitbit", for: .normal) l.layer.cornerRadius = 10 l.addTarget(self, action: #selector(loginAction), for: .touchUpInside) return l }() override func viewDidLoad() { super.viewDidLoad() setupLoginButton() authenticationController = AuthenticationController(delegate: self) } @objc func loginAction(_ sender: Any) { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ" //let dateTime = dateFormatter.date(from: String(expire_time)) if let access = UserDefaults.standard.object(forKey: "access_token") as? String{ if let expire_time = UserDefaults.standard.object(forKey: "expiration_time") as? Date { let now = Date() if now < expire_time { print("Current Time: ", now) print() print("Token expiration time: ", expire_time) print() print("Access Token: ", access) print() print("Token is valid. Calling the Fitbit server using the access token to fetch the data") callFitbitServerData(accessToken: access) } else { print("Last recevied access token has expired. Call for new access token using refresh token") if let refresh = UserDefaults.standard.object(forKey: "refresh_token") as? String { getAccessToken(token: nil, grantType: "refresh_token", refreshToken: refresh) { (accessObject) in storeKeys(accessObject: accessObject) self.callFitbitServerData(accessToken: accessObject.access_token) } } } } } else{ authenticationController?.login(fromParentViewController: self) } } fileprivate func setupLoginButton() { view.addSubview(loginButton) view.backgroundColor = .white loginButton.translatesAutoresizingMaskIntoConstraints = false //loginButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 50).isActive = true loginButton.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true loginButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true } @IBAction func buttonPressed(_ sender: Any) { if let appURL = URL(string: "fitbit://"){ let canOpen = UIApplication.shared.canOpenURL(appURL) print("\(canOpen)") let appName = "Fitbit" let appScheme = "\(appName)://" let appSchemeURL = URL(string: appScheme) if UIApplication.shared.canOpenURL(appSchemeURL! as URL) { UIApplication.shared.open(appSchemeURL!, options: [:], completionHandler: nil) } else { let alert = UIAlertController(title: "\(appName)", message: "The app named \(appName) is not installed. Please install the app from appstore", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(alert,animated: true,completion: nil) } } } func authorizationDidFinish(_ success: Bool) { FitbitAPI.sharedInstance.authorize(with: accessToken) let dataSyncController = DataSyncController() navigationController?.pushViewController(dataSyncController, animated: true) } func callFitbitServerData(accessToken: String){ FitbitAPI.sharedInstance.authorize(with: accessToken) let dataSyncController = DataSyncController() navigationController?.pushViewController(dataSyncController, animated: true) } }
true
6972bc1e3f5b3ce8d1e694b9bd54bcc26c959932
Swift
Liberate99/book-Trading
/BookTrading/module/baseUserClass.swift
UTF-8
874
2.734375
3
[]
no_license
// // baseUserClass.swift // BookTrading // // Created by apple on 2018/5/19. // Copyright © 2018年 Liberate. All rights reserved. // import UIKit class baseUserClass: NSObject { //string func cacheSetString(key: String, value: String) { let userInfo = UserDefaults() userInfo.setValue(value, forKey: key) } func cacheGetString(key: String) -> String { let userInfo = UserDefaults() let tmpSign = userInfo.string(forKey: key) return tmpSign! } // //float // func cacheSetFloat(key: String, value: Float) { // let userInfo = UserDefaults() // userInfo.setValue(value, forKey: key) // } // // func cacheGetFloat(key: String) -> Float { // let userInfo = UserDefaults() // let tmpSign = userInfo.float(forKey: key) // return tmpSign // } }
true
80677d022fc66f7a4fedb79f34878ee1a5eb4310
Swift
skelpo/CSV
/Sources/CSV/Coder/Encoder/AsyncSingleValueEncoder.swift
UTF-8
1,600
2.9375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
import Foundation final class AsyncSingleValueEncoder: SingleValueEncodingContainer { let codingPath: [CodingKey] let encoder: AsyncEncoder init(path: [CodingKey], encoder: AsyncEncoder) { self.codingPath = path self.encoder = encoder } var delimiter: UInt8? { return self.encoder.configuration.cellDelimiter } func encodeNil() throws { let value = self.encoder.encodingOptions.nilCodingStrategy.bytes().escaping(self.delimiter) self.encoder.container.cells.append(value) } func encode(_ value: Bool) throws { let value = self.encoder.encodingOptions.boolCodingStrategy.bytes(from: value).escaping(self.delimiter) self.encoder.container.cells.append(value) } func encode(_ value: String) throws { self.encoder.container.cells.append(value.bytes.escaping(self.delimiter)) } func encode(_ value: Double) throws { self.encoder.container.cells.append(value.bytes.escaping(self.delimiter)) } func encode(_ value: Float) throws { self.encoder.container.cells.append(value.bytes.escaping(self.delimiter)) } func encode(_ value: Int) throws { self.encoder.container.cells.append(value.bytes.escaping(self.delimiter)) } func encode<T>(_ value: T) throws where T : Encodable { let column = self.codingPath.map { $0.stringValue }.joined(separator: ".") throw EncodingError.invalidValue(value, EncodingError.Context( codingPath: self.codingPath, debugDescription: "Cannot encode nested data into cell in column '\(column)'" )) } }
true
b1200d815140e6cf9208421dc89afa58a33d29f7
Swift
katolefebvre/cheriebistro_order_app
/GlacoOrderApp/GlacoOrderApp/Model/OrderItem.swift
UTF-8
527
2.625
3
[]
no_license
// // OrderItem.swift // GlacoOrderApp // // Created by Kato Lefebvre on 2020-10-12. // Copyright © 2020 GLAC Co. All rights reserved. // import Foundation class OrderItem { var orderId: Int var quantity: Int var itemModification: String var menuItem: MenuItem init(orderId: Int, quantity: Int, itemModification: String, menuItem: MenuItem) { self.orderId = orderId self.quantity = quantity self.itemModification = itemModification self.menuItem = menuItem } }
true
502d7879dc0afa1f97be5f20c7eba9923c0d2041
Swift
ruby780/Twitter
/twitter_alamofire_demo/LikeAndRetweetTableViewCell.swift
UTF-8
1,494
2.71875
3
[ "Apache-2.0" ]
permissive
// // LikeAndRetweetTableViewCell.swift // twitter_alamofire_demo // // Created by Ruben A Gonzalez on 3/12/18. // Copyright © 2018 Charles Hieger. All rights reserved. // import UIKit class LikeAndRetweetTableViewCell: UITableViewCell { @IBOutlet weak var retweetLabel: UILabel! @IBOutlet weak var likeLabel: UILabel! var tweet: Tweet! { didSet { refreshData() } } func refreshData() { let retweets = NSMutableAttributedString(string: " Retweets") let retweetCount = String(describing: tweet.retweetCount) let attrs = [NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 17)] let retweetCountandLabel = NSMutableAttributedString(string:retweetCount, attributes:attrs) retweetCountandLabel.append(retweets) retweetLabel.attributedText = retweetCountandLabel let likes = NSMutableAttributedString(string: " Likes") let favoriteCount = String(describing: tweet.favoriteCount!) let likeCountandLabel = NSMutableAttributedString(string: favoriteCount, attributes: attrs) likeCountandLabel.append(likes) likeLabel.attributedText = likeCountandLabel } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
true
fdc8e9d116511adcc49f8d15a4231c59bac4d866
Swift
Migyabut147566/MovieAPI.Fetch
/moce2/ViewController.swift
UTF-8
3,265
2.625
3
[]
no_license
// // ViewController.swift // moce2 // // Created by Jose Miguel Agustin Yabut on 3/23/21. // import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UISearchBarDelegate { struct APIresponse: Codable { let Search: [Search] } struct Search: Codable { let Title: String let Poster: String } private var collectionView: UICollectionView? var Search: [Search] = [] let searchBar = UISearchBar() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.itemSize = CGSize(width: view.frame.size.width/3, height: view.frame.size.width/2) let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.register(MovieCell.self, forCellWithReuseIdentifier: MovieCell.identifier) collectionView.dataSource = self searchBar.delegate = self view.addSubview(searchBar) view.addSubview(collectionView) self.collectionView = collectionView } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() searchBar.frame = CGRect(x: 10, y: view.safeAreaInsets.top, width: view.frame.size.width-20, height: 50) collectionView?.frame = CGRect(x: 0, y: view.safeAreaInsets.top+55, width: view.frame.size.width, height: view.frame.size.height-55) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { self.searchBar.resignFirstResponder() if let text = self.searchBar.text { self.Search = [] collectionView?.reloadData() fetchPhotos(query: text) } } func fetchPhotos(query: String) { let urlString = "https://www.omdbapi.com/?s=(\(query))&page=2&apikey=e55825d3" //Swap test to \(query) later guard let url = URL(string: urlString) else { return } let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in guard let data = data, error == nil else { return } do { let jsonResult = try JSONDecoder().decode(APIresponse.self, from: data) DispatchQueue.main.async { self?.Search = jsonResult.Search self?.collectionView?.reloadData() } } catch { print(error) } } task.resume() } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.Search.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let imgURLString = self.Search[indexPath.row].Poster guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MovieCell.identifier, for: indexPath) as? MovieCell else { return UICollectionViewCell() } cell.configure(with: imgURLString) return cell } }
true
85971b7c72357d33b32dc3d391eb37179899923c
Swift
victorpere/NewsReader
/NewsReader/Requester.swift
UTF-8
1,203
2.9375
3
[]
no_license
// // Requester.swift // NewsReader // // Created by Victor on 2017-03-21. // Copyright © 2017 Victorius Software Inc. All rights reserved. // import Foundation class Requester : NSObject { var delegate: RequesterDelegate! var data = Data() // MARK: - Public methods func getData(from url: String) { let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil) let request = URLRequest(url: URL(string: url)!) let task = session.dataTask(with: request) task.resume() } } // MARK: - URLSessionDataDelegate extension Requester : URLSessionDataDelegate { func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { self.data.append(data) } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { task.suspend() session.invalidateAndCancel() self.delegate.receivedData(data: data) } } // MARK: - Protocol RequesterDelegate protocol RequesterDelegate { func receivedData(data: Data) }
true
ea711643735b24a99b00d7fbdcc17c7ca5df8de1
Swift
Joeyippel/RelaxApp
/RelaxApp/ViewController.swift
UTF-8
1,868
2.625
3
[]
no_license
// // ViewController.swift // RelaxApp // // Created by Joey Ippel on 04/10/2016. // Copyright © 2016 Joey Ippel. All rights reserved. // import UIKit import MapKit class ViewController: UIViewController, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let distanceSpan:CLLocationDegrees = 2000 let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 51.813298, longitude: 4.690093) mapView.setRegion(MKCoordinateRegionMakeWithDistance(CLLocationCoordinate2DMake(51.813298, 4.690093), distanceSpan, distanceSpan), animated: true) let annotation = MKPointAnnotation() annotation.coordinate = location annotation.title = "Relax plek 1" annotation.subtitle = "Leuke plek om te relaxen" mapView.addAnnotation(annotation) let longPress = UILongPressGestureRecognizer(target: self, action: Selector(("action:"))) longPress.minimumPressDuration = 1.0 mapView.addGestureRecognizer(longPress) } func action(gestureRecognizer:UIGestureRecognizer) { let touchPoint = gestureRecognizer.location(in: self.mapView) let newCoord:CLLocationCoordinate2D = mapView.convert(touchPoint, toCoordinateFrom: self.mapView) let newAnnotation = MKPointAnnotation() newAnnotation.coordinate = newCoord newAnnotation.title = "New Location" newAnnotation.subtitle = "New Subtitle" mapView.addAnnotation(newAnnotation) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
a9e4d4d9f023d0b7bd91f9a381145adbc07d6de1
Swift
Mizuki015/LaybearProject
/LaybearProject/Controller/HomeViewController.swift
UTF-8
5,192
2.65625
3
[]
no_license
// // HomeViewController.swift // LaybearProject // // Created by 城間海月 on 2019/12/20. // Copyright © 2019 Mizuki. All rights reserved. // import UIKit import FirebaseAuth import Firebase class HomeViewController: UIViewController { @IBOutlet weak var tableView: UITableView! // 投稿部屋を全件をもつ配列 var posts: [Post] = [] { didSet{ tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self // Firestoreに接続 let db = Firestore.firestore() db.collection("posts").addSnapshotListener { (querySnapshot, error) in // 最新のpostsコレクションの中身を取得 guard let documents = querySnapshot?.documents else { // postsコレクションの中身がnilの場合、処理を中断 // 中身がある場合は、変数documentsに中身を全て入れる return } // 結果を入れる配列 var results: [Post] = [] // ドキュメントをfor文を使ってループする for document in documents { let text = document.get("text") as! String let posts = Post(text: text, userId: document.documentID) results.append(posts) } print(results) // 表示する変数postsを全結果の入ったresultsで上書き self.posts = results } } @IBAction func didClickMyPageButton(_ sender: UIButton) { // MyPageに画面遷移する performSegue(withIdentifier: "toMyPage", sender: nil) } @IBAction func doAnonymousLogin(_ sender: UIButton) { //匿名ユーザーとしてログイン Auth.auth().signInAnonymously { (result, error) in if (result?.user) != nil{ //次の画面へ遷移 self.performSegue(withIdentifier: "toMyPage", sender: nil) } } } } extension HomeViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return posts.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // セルを名前と行番号で取得 let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) // 配列から表示する部屋情報を1件取得 let post = posts[indexPath.row] // cell内のアイコン画像を設定 let image = cell.viewWithTag(1) as! UIImageView // 画像の大きさを設定 image.frame = CGRect(x: 9, y: 103, width: 80, height: 80) // 画像を設定 // image.image = UIImage.ini // 角を丸くする image.layer.cornerRadius = 80 * 0.5 image.clipsToBounds = true // cell内のlabelを設定 let label = cell.viewWithTag(2) as! UILabel label.text = post.text // cell内の「解」ボタンを設定 let didClickUSButton = cell.viewWithTag(3) as! IndexButton didClickUSButton.addTarget(self, action: #selector(tapUSButton(_:)), for: .touchUpInside) didClickUSButton.index = indexPath.row // cell内の「幸」ボタンを設定 let didClickHopeButton = cell.viewWithTag(4) as! IndexButton2 didClickHopeButton.addTarget(self, action: #selector(tapHopeButton(_:)), for: .touchUpInside) didClickHopeButton.index2 = indexPath.row // セルを返す return cell } // 解ボタンの設定 @objc func tapUSButton(_ sender: IndexButton) { sender.isSelected = !sender.isSelected if sender.isSelected { sender.tintColor = UIColor.systemRed sender.backgroundColor = .systemRed sender.setTitleColor(UIColor.white, for: UIControl.State.normal) } else { sender.backgroundColor = .white sender.setTitleColor(UIColor.systemBlue, for: .normal) } } // 幸ボタンにの設定 @objc func tapHopeButton(_ sender: IndexButton2) { sender.isSelected = !sender.isSelected if sender.isSelected { sender.tintColor = UIColor.systemYellow sender.backgroundColor = .systemYellow sender.setTitleColor(UIColor.white, for: UIControl.State.normal) } else { sender.backgroundColor = .white sender.setTitleColor(UIColor.systemBlue, for: .normal) } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 150 } @objc private func pushButton(_ sender:UIButton) { } }
true
9b2009b47cd9d4a1c62994421c79f58050a2cfdb
Swift
leeyoulee/RxMoyaNetworking
/rxMoya_SchoolNews/Network/NetworkService.swift
UTF-8
7,533
2.765625
3
[]
no_license
// // NetworkService.swift // rxMoya_SchoolNews // // Created by 이유리 on 04/02/2020. // Copyright © 2020 이유리. All rights reserved. // import UIKit import Moya import RxSwift import RxCocoa struct NetworkService{ static let provider = MoyaProvider<SchoolProvider>(plugins:[NetworkLoggerPlugin(verbose: true, responseDataFormatter: JSONResponseDataFormatter)]) static func JSONResponseDataFormatter(_ data: Data) -> Data { do { let dataAsJSON = try JSONSerialization.jsonObject(with: data) let prettyData = try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted) return prettyData } catch { return data } } } extension NetworkService{ struct SchoolGet { static func getSchool(schoolName: String) -> Single<[School]> { return requestArray(.schoolGet(schoolName: schoolName), silent: true) } static func getSchoolFood(educationCode: String, schoolCode: String, startDate: String, endDate: String) -> Single<[SchoolFood]> { return requestArray(.schoolFoodGet(educationCode: educationCode, schoolCode: schoolCode, startDate: startDate, endDate: endDate)) } } } extension NetworkService{ static func requestArray<T: Codable>(_ api: SchoolProvider, silent: Bool = false) -> Single<[T]> { let request = Single<[T]>.create { single in let observable = NetworkService.provider.rx .request(api) .subscribe{ event in switch event { case .success(let response): do { print("network response : \(String(describing:response.response))") guard let responseData = try? response.data else { single(.error(SchoolProvider.Error.failureResponse(api: api, code: .sc_000))) return } if let json = try? JSONSerialization.jsonObject(with: responseData, options: []) as? [String : Any] { // 검색한 결과가 없거나 기타 에러일 때 내려오는 JSON을 Error로 방출 if let result = json?["RESULT"] as? [String : Any] { if let code = result["CODE"] as? String { let resultCode = SchoolProvider.ResultCode(rawValue: code) ?? .sc_000 single(.error(SchoolProvider.Error.failureResponse(api: api, code: resultCode))) } } // 검색한 결과가 있을 때 내려오는 JSON은 Success로 방출 else { if let info = json?[api.path] as? [[String : Any]] { let row = info[1] let data = row["row"] guard let jsonData = try? JSONSerialization.data(withJSONObject: data) else { single(.error(SchoolProvider.Error.failureResponse(api: api, code: .sc_000))) return } guard let datas = try? JSONDecoder().decode([T].self, from: jsonData) else { single(.error(SchoolProvider.Error.failureResponse(api: api, code: .sc_000))) return } single(.success(datas)) } } } } catch let error { print("network error :\(error.localizedDescription)") single(.error(error)) } case .error(let error): print("network error response :\(error.localizedDescription)") single(.error(error)) } } return Disposables.create{ observable.dispose() } }.observeOn(MainScheduler.instance) return silent ? request : request.retryWhen{ $0.flatMap { _retry(api: api, error: $0)}} } static func _retry(api: SchoolProvider, error: Error) -> Single<()> { return Single.create { single in var resultCode: SchoolProvider.ResultCode = .sc_000 if let apiServerError = error as? SchoolProvider.Error, case .failureResponse(let api, let code) = apiServerError { if let errors = api.errors, errors.contains(code) { single(.error(error)) return Disposables.create() } resultCode = code } DispatchQueue.main.async { let title = "안내" let message = "에러코드 : \(resultCode)\n다시 시도하겠습니까?" let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "취소", style: .cancel)) alert.addAction(UIAlertAction(title: "재시도", style: .default) { _ in single(.success(())) }) UIApplication.topViewController()?.present(alert, animated: false, completion: nil) } return Disposables.create() } } } extension PrimitiveSequenceType where TraitType == SingleTrait { @discardableResult func on() -> Disposable { return on(success: { _ in }, error: nil) } @discardableResult func on(success: @escaping (Self.ElementType) -> Void) -> Disposable { return on(success: success, error: nil) } @discardableResult func on(success: @escaping (Self.ElementType) -> Void, error errorHandler: ((SchoolProvider.ResultCode) -> Void)? = nil) -> Disposable { return subscribe( onSuccess: success, onError: { error in if let apiServerError = error as? SchoolProvider.Error, case .failureResponse(let api, let code) = apiServerError { if let errors = api.errors, errors.contains(code) { errorHandler?(code) } } }) } } // 상단에 띄워진 뷰컨트롤러를 가져옴 extension UIApplication { class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(base: nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(base: selected) } } if let presented = base?.presentedViewController { return topViewController(base: presented) } return base } }
true
cddf7f4ded17daa8f8f2f95c75bc90f4e435bfce
Swift
rhit-yinz1/Photo-Bucket
/Photo Bucket/PB.swift
UTF-8
545
2.75
3
[]
no_license
// // PB.swift // Photo Bucket // // Created by Theo Yin on 8/8/21. // import Foundation import Firebase class PB { var url: String var caption: String var id: String? init(url: String, caption: String){ self.url = url self.caption = caption } init(documentSnapshot: DocumentSnapshot) { self.id = documentSnapshot.documentID let data = documentSnapshot.data()! self.url = data["imgUrl"] as! String self.caption = data["imgCaption"] as! String } }
true
a201a976b7e57e01e45dfb213b81c87e642bdd12
Swift
svanimpe/around-the-table
/Sources/AroundTheTable/Forms/ActivityForm.swift
UTF-8
2,981
3.40625
3
[ "BSD-2-Clause" ]
permissive
import Foundation /** Form for submitting a new activity. */ struct ActivityForm: Codable { let game: Int let name: String let playerCount: Int let minPlayerCount: Int let prereservedSeats: Int let day: Int let month: Int let year: Int let hour: Int let minute: Int /// The activity's date. /// Returns `nil` if the form's fields do not represent a valid date. var date: Date? { var components = DateComponents() components.calendar = Settings.calendar components.day = day components.month = month components.year = year components.hour = hour components.minute = minute components.timeZone = Settings.timeZone guard components.isValidDate, let date = components.date else { return nil } return date } let deadlineType: String /// The activity's deadline. /// Returns `nil` if either the deadline type or date is invalid. var deadline: Date? { guard let date = date else { return nil } switch deadlineType { case "one hour": return Settings.calendar.date(byAdding: .hour, value: -1, to: date)! case "one day": return Settings.calendar.date(byAdding: .day, value: -1, to: date)! case "two days": return Settings.calendar.date(byAdding: .day, value: -2, to: date)! case "one week": return Settings.calendar.date(byAdding: .weekOfYear, value: -1, to: date)! default: return nil } } let address: String let city: String let country: String let latitude: Double let longitude: Double /// The activity's location. var location: Location { return Location(coordinates: Coordinates(latitude: latitude, longitude: longitude), address: address, city: city, country: country) } let info: String /// Whether the form's fields are valid. Checks: /// - if the form does not contain an empty string for a required field, /// - if the player count is at least 1, /// - if the minimum player count is between 1 and the player count, /// - if the number of prereserved seats is at least 0 and less than the player count, /// - if the date is valid and in the future, /// - if the deadline is valid and in the future. var isValid: Bool { let checks = [ ![name, address, city, country].contains { $0.isEmpty }, playerCount >= 1, minPlayerCount >= 1 && minPlayerCount <= playerCount, prereservedSeats >= 0 && prereservedSeats < playerCount, date?.compare(Date()) == .orderedDescending, deadline?.compare(Date()) == .orderedDescending ] return !checks.contains(false) } }
true
a8fa9f25c5b27c5e8f085758ca8a0e33630f268f
Swift
yklishevich/mindvalley
/Project/MindvalleyTrial/Utils/KeyedDecodingContainer+Utils.swift
UTF-8
1,177
2.953125
3
[]
no_license
// // Decoder+Utils.swift // MindvalleyTrial // // Created by Yauheni Klishevich on 27.06.2020. // Copyright © 2020 Yauheni Klishevich. All rights reserved. // import Foundation extension KeyedDecodingContainer { /// - Parameter limit: max number of elements that should be decoded /// - Parameter keypathToSetPosition: position of element in json will be set to the property indicated by this keypath func decodeArray<Element: Decodable>( _ elementType: Element.Type, forKey key: KeyedDecodingContainer<K>.Key, keypathToSetPosition: ReferenceWritableKeyPath<Element, Int?>? = nil, limit: Int = Int.max ) throws -> [Element] { var arrayContainer = try nestedUnkeyedContainer(forKey: key) var elements: [Element] = [] var counter = 0 while !arrayContainer.isAtEnd && counter < limit { let element = try arrayContainer.decode(elementType.self) if let positionKeypath = keypathToSetPosition { element[keyPath: positionKeypath] = counter } elements.append(element) counter += 1 } return elements } }
true
df5a31c1b955edad9aea6cab98f44673785423ff
Swift
EgeKaanGurkan/crypto-toolkit
/CryptoToolkit/Beta/PortfolioCardView.swift
UTF-8
3,492
2.875
3
[]
no_license
// // PortfolioCardView.swift // CryptoToolkit // // Created by Ege Kaan Gürkan on 29.04.2021. // import SwiftUI struct PortfolioCardView: View { @State var hover = false @State var fave = true var coinDetail: CoinDetail func getFont(size: CGFloat) -> Font { return Font.custom("RecoletaAlt-Regular", size: size) } var body: some View { VStack (alignment: .leading, spacing: 0) { HStack () { Image(nsImage: NSImage(named: coinDetail.name.lowercased())!) .resizable() .frame(width: 18, height: 18) .shadow(color: .black, radius: self.hover ? 5 : 0) .animation(.easeInOut(duration: 0.1)) Text(coinDetail.symbol) .font(getFont(size: 15)) .fontWeight(.medium) .foregroundColor(.white) Spacer() Button(action: {self.fave.toggle()}) { if (fave) { Image(systemName: "star.fill") } else { Image(systemName: "star") } } .buttonStyle(PlainButtonStyle()) Button(action: {print("add to portfolio")}) { Image(systemName: "pencil") } .buttonStyle(PlainButtonStyle()) } .padding(.horizontal, 10) .padding(.top, 5) .padding(.bottom, 5) .background(Color(NSColor(named: coinDetail.name)!)) .cornerRadius(3) .shadow(color: .black, radius: 5) HStack (alignment: .lastTextBaseline, spacing: 3){ VStack (alignment: .leading, spacing: -7){ Text("Price") .font(.caption) .fontWeight(.bold) Text("54680") .padding(.top, 9) } Text("x") VStack (alignment: .leading, spacing: -7){ Text("Portfolio") .font(.caption) .fontWeight(.bold) Text("0.00058") .padding(.top, 9) } // Spacer() } .foregroundColor(.black) .font(.system(size: 12, weight: .medium, design: .monospaced)) .padding(10) .zIndex(-1) .offset(y: -3) HStack { Text("=") .foregroundColor(.black) .font(.title2) Text("31.7144") .foregroundColor(.black) .font(.system(size: 20, weight: .medium, design: .monospaced)) } .padding(.leading, 10) .padding(.bottom, 10) } .onHover(perform: { hovering in self.hover = hovering }) .background(Color.white) .cornerRadius(3.0, antialiased: true) } } struct PortfolioCardView_Previews: PreviewProvider { static var previews: some View { PortfolioCardView(coinDetail: CoinDetail(name: "Bitcoin", symbol: "BTC", price: "123123", id: 0, iconUrl: "asd")) } }
true
d70fc184bd7a78c995baa28bd2a01499afc9cc6b
Swift
jbossiere/TweetTweet
/TwitterClient/ProfileViewController.swift
UTF-8
3,700
2.625
3
[ "Apache-2.0" ]
permissive
// // ProfileViewController.swift // TwitterClient // // Created by Julian Test on 2/15/17. // Copyright © 2017 Julian Bossiere. All rights reserved. // import UIKit class ProfileViewController: UIViewController { var tweet: Tweet! var user: User! var userId: String? @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var screennameLabel: UILabel! @IBOutlet weak var taglineLabel: UILabel! @IBOutlet weak var followingNumLabel: UILabel! @IBOutlet weak var followersNumLabel: UILabel! @IBOutlet weak var bgImageView: UIImageView! @IBOutlet weak var userColorBannerView: UIView! override func viewDidLoad() { super.viewDidLoad() //MAKES NAVBAR TRANSPARENT self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.isTranslucent = true userImageView.setImageWith(user.profileUrl!) userImageView.layer.cornerRadius = 5 userImageView.layer.borderWidth = 4 let white = UIColor(red: 1, green: 1, blue: 1, alpha: 1) userImageView.layer.borderColor = white.cgColor userImageView.clipsToBounds = true userNameLabel.text = user.name screennameLabel.text = "@\(user.screenname!)" taglineLabel.text = user.tagline followingNumLabel.text = user.followingCountString! followersNumLabel.text = user.followersCountString! userId = user.userIdString TwitterClient.sharedInstance?.getUserBanner(success: { (bannerDictionary: NSDictionary) in let images = bannerDictionary["sizes"] as? NSDictionary let mobileRetina = images?["600x200"] as? NSDictionary let bgImgUrlString = mobileRetina?["url"] as? String let bgImgUrl = URL(string: bgImgUrlString!) self.userColorBannerView.backgroundColor = nil self.bgImageView.setImageWith(bgImgUrl!) }, failure: { (error: Error) in let hexStarter = "0x" let hexString = hexStarter + self.user.userColor! let bgColor = hexString.hexColor self.userColorBannerView.backgroundColor = bgColor }, userId: userId!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension String { var hexColor: UIColor { let hex = trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int = UInt32() Scanner(string: hex).scanHexInt32(&int) let a, r, g, b: UInt32 switch hex.characters.count { case 3: // RGB (12-bit) (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: return .clear } return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: 255 / 255) } }
true
922a89cc50090a77e2ac851006b97a9af847511f
Swift
griotspeak/2016-11-Examples
/Types/MyPlayground.playground/Pages/Untitled Page.xcplaygroundpage/Contents.swift
UTF-8
234
3.46875
3
[]
no_license
func greet(name: String = "friend") { print("Hello, \(name)!") } func greeting(name: String) -> String { return "Hello, \(name)!" } greet() greet(name: "Jane") let greetIkenna = greeting(name: "Ikenna") print(greetIkenna)
true
1058fc8e9013c396940eeefc99870c422f02623d
Swift
inahuelzapata/iOS-Architectures
/iOS-Architectures/Cross/RequestManager/RequestManager.swift
UTF-8
1,973
2.671875
3
[]
no_license
// // RequestManager.swift // iOS-Architectures // // Created by Nahuel Zapata on 25/12/2017. // Copyright © 2017 Nahuel Zapata. All rights reserved. // import Foundation import BoltsSwift import Alamofire class RequestManager: Requestable, HttpRequestHandler { static let shared = RequestManager() typealias Dictionary = [String: Any] typealias ReturnTask = Task<Any> typealias Endpoint = String typealias Headers = [String: String] typealias Encoding = JSONEncoding private var urlPath: String! private var defaultEncoding: Encoding! private init() { urlPath = "https://jsonplaceholder.typicode.com" defaultEncoding = Encoding.default } func get(endpoint: String, params: [String: Any], headers: [String: String]) -> Task<Any> { return self.request(urlPath + endpoint, parameters: params, headers: headers) } func post(endpoint: String, params: [String: Any], headers: [String: String]) -> Task<Any> { return self.request(urlPath + endpoint, method: .post, parameters: params, encoding: defaultEncoding, headers: headers) } func put(endpoint: String, params: [String: Any], headers: [String: String]) -> Task<Any> { return self.request(urlPath + endpoint, method: .put, parameters: params, encoding: defaultEncoding, headers: headers) } func delete(endpoint: String, params: [String: Any], headers: [String: String]) -> Task<Any> { return self.request(urlPath + endpoint, method: .delete, parameters: params, encoding: defaultEncoding, headers: headers) } }
true
c551e7e794cea99fd9dadba748252936acda2dd8
Swift
abhandary/Flicks
/Flicks/Flicks/DetailViewController.swift
UTF-8
3,443
2.6875
3
[ "Apache-2.0" ]
permissive
// // DetailViewController.swift // Flicks // // Created by Akshay Bhandary on 3/28/17. // Copyright © 2017 AkshayBhandary. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var imageView: UIImageView! let monthMap = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] public var imagePath : String = ""; public var text : String = ""; public var movieTitle : String = "" public var releaseDate : String = "" public var voteAverage : Double = 0.0 public var backdropImage : UIImage! override func viewDidLoad() { super.viewDidLoad() // set content size on the scroll view let contentWidth = scrollView.bounds.width var contentHeight = scrollView.bounds.height * 1.2 scrollView.contentSize = CGSize(width: contentWidth, height: contentHeight); // set the scrollable view let grayView = UIView(frame: CGRect(x: 50, y: 300, width: scrollView.contentSize.width - 100, height: 350)); grayView.backgroundColor = UIColor.black; grayView.alpha = 0.8; scrollView.addSubview(grayView) scrollView.showsVerticalScrollIndicator = false; // format the date let dateParts = releaseDate.components(separatedBy: "-"); let month = Int(dateParts[1]) var dateString = ""; if let month = month { dateString = "\(monthMap[month - 1]) \(dateParts[2]), \(dateParts[0])" } let voteAvgInt = Int(self.voteAverage * 10); let label = UILabel(frame: CGRect(x: 5, y: 10, width: scrollView.contentSize.width - 100, height: 350)); label.numberOfLines = 0; label.lineBreakMode = NSLineBreakMode.byWordWrapping; label.text = "\(movieTitle)\n\n\(dateString)\n👑 \(voteAvgInt)%\n\n\(text)" ; label.font = UIFont(name: "Arial-BoldMT", size: 16); //adjust the label the the new height. label.textColor = UIColor.white; label.sizeToFit(); // adjust the gray view's frame per the label's adjusted frame grayView.frame = CGRect(x: (UIScreen.main.bounds.width - label.frame.width) / 2, y:scrollView.bounds.height - label.frame.height, width: label.frame.width + 10, height: label.frame.height + 20); grayView.addSubview(label); // set to new content height based on label height contentHeight = grayView.frame.height + scrollView.bounds.height - 300; // set image view to low res image until high res loads self.imageView.image = self.backdropImage; } override func viewWillAppear(_ animated: Bool) { self.imageView.setImageWith(URL(string: imagePath)!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
0facc52abc91009ddfc4215827160c4c1311d929
Swift
RinatAbidullin/FirebaseDashboardReport
/FirebaseDashboardReport/FirebaseDashboardReportParser+OsVersions.swift
UTF-8
5,678
2.765625
3
[]
no_license
// // FirebaseDashboardReportParser+OsVersions.swift // FirebaseDashboardReport // // Created by Rinat Abidullin on 06.08.2021. // import Foundation extension FirebaseDashboardReportParser { func osVersions(dateFormatter: DateFormatter? = nil) -> OsVersions { // Выделяем строки с версиями OS var osVersionsRawWithTitles = [String]() let contentLines = csvRawContent.components(separatedBy: "\n") var startFound = false for (index, line) in contentLines.enumerated() { let line = line.trimmingCharacters(in: .newlines) if line.hasPrefix(FirebaseDashboardReportConstants.rowOSWithVersionUsers) { osVersionsRawWithTitles.append( contentLines[index - 2].trimmingCharacters(in: .newlines) ) osVersionsRawWithTitles.append( contentLines[index - 1].trimmingCharacters(in: .newlines) ) startFound = true } if startFound && !line.isEmpty { osVersionsRawWithTitles.append( line.trimmingCharacters(in: .newlines) ) } else if startFound && line.isEmpty { break } } // Диапазон дат let startDate = osVersionsRawWithTitles[0].components(separatedBy: ":")[1].trimmingCharacters(in: .whitespaces) let endDate = osVersionsRawWithTitles[1].components(separatedBy: ":")[1].trimmingCharacters(in: .whitespaces) let osVersionsRaw = osVersionsRawWithTitles[3...].joined(separator: "\n") let dateFormatterForReadCSV = DateFormatter() dateFormatterForReadCSV.dateFormat = "yyyyMMdd" let dateFormatterPrint = DateFormatter() dateFormatterPrint.dateFormat = "dd.MM.yyyy" let startDateString = dateFormatterPrint.string(from: dateFormatterForReadCSV.date(from: startDate)!) let endDateString = dateFormatterPrint.string(from: dateFormatterForReadCSV.date(from: endDate)!) // Строки с версиями OS var osVersions = [OsVersion]() let lines = osVersionsRaw.components(separatedBy: "\n") for line in lines { // iOS 12.3.2, 1 // Android 4.2.2, 1 let osComponents = line.components(separatedBy: ",") // iOS 12.3.2, 1 let osNameWithVersion = osComponents[0].trimmingCharacters(in: .whitespacesAndNewlines) // iOS 12.3.2 let userCount = Int(osComponents[1].trimmingCharacters(in: .whitespacesAndNewlines))! // 1 let osNameWithVersionComponents = osNameWithVersion.components(separatedBy: " ") // iOS 12.3.2 let osName = osNameWithVersionComponents[0].trimmingCharacters(in: .whitespacesAndNewlines) // iOS let osVersion = osNameWithVersionComponents[1].trimmingCharacters(in: .whitespacesAndNewlines) // 12.3.2 let osVersionComponents = osVersion.components(separatedBy: ".") // 12.3.2 let osVersionMajor = Int(osVersionComponents[0].trimmingCharacters(in: .whitespacesAndNewlines))! // 12 if let existedOsVersion = osVersions.filter( { $0.platform == osName && $0.majorVersion == osVersionMajor } ).first { existedOsVersion.userCount += userCount } else { osVersions.append(OsVersion(platform: osName, majorVersion: osVersionMajor, userCount: userCount)) } } let allUsersCount = osVersions .map { $0.userCount }.reduce(0, +) let iosUsersCount = osVersions .filter({ $0.platform == "iOS" }) .map { $0.userCount }.reduce(0, +) let androidUsersCount = osVersions .filter({ $0.platform == "Android" }) .map { $0.userCount }.reduce(0, +) let sortedOsVersions = osVersions.sorted { if $0.platform != $1.platform { return $0.platform > $1.platform } else { return $0.majorVersion > $1.majorVersion } } let resultVersions = OsVersions( versions: sortedOsVersions, allUsersCount: allUsersCount, iOSUsersCount: iosUsersCount, androidUsersCount: androidUsersCount, startDate: startDateString, endDate: endDateString ) return resultVersions } } struct OsVersions { let versions: [OsVersion] let allUsersCount: Int let iOSUsersCount: Int let androidUsersCount: Int let startDate: String let endDate: String var iOSUsersPersent: Double { Double(iOSUsersCount) / Double(allUsersCount) * 100 } var androidUsersPersent: Double { Double(androidUsersCount) / Double(allUsersCount) * 100 } func iOSUsersPersent(accuracy: Int) -> Double { (iOSUsersPersent * pow(10, Double(accuracy))).rounded() / pow(10, Double(accuracy)) } func androidUsersPersent(accuracy: Int) -> Double { (androidUsersPersent * pow(10, Double(accuracy))).rounded() / pow(10, Double(accuracy)) } } class OsVersion { let platform: String let majorVersion: Int var userCount: Int init(platform: String, majorVersion: Int, userCount: Int) { self.platform = platform self.majorVersion = majorVersion self.userCount = userCount } } enum OSPlatform: String { case iOS = "iOS" case Android = "Android" }
true
35c6ad946035c027c406091fb4a970d850852b2b
Swift
mail4karthickr/SpoonacularApi
/SpoonacularApi/Common/LogInfo.swift
UTF-8
1,752
2.53125
3
[]
no_license
// // LogInfo.swift // SpoonacularApi // // Created by Karthick Ramasamy on 4/20/20. // Copyright © 2020 Karthick Ramasamy. All rights reserved. // import Foundation protocol Loggable { func toAnyObject() -> Any } enum UseCaseType: String { case login case depositCheck case billPay case filterRecipe } struct UseCase: Loggable { var type: UseCaseType var id: String func toAnyObject() -> Any { return [ "type": type.rawValue, "id": id, ] } } enum Loglevel: String { case error case warning case info case verbose } protocol LogNameType { var logName: String { get } } struct LogInfo: Loggable { var useCase: UseCase var loglevel: Loglevel var logNameType: LogNameType var userInfo: [String: String] func toAnyObject() -> Any { return [ "logName": logNameType.logName, "useCase": useCase.toAnyObject(), "loglevel": loglevel.rawValue, "userInfo": userInfo ] } } //struct DepositCheckLogger { // var useCase: UseCase! // // func startCheckDeposit() { // let useCase = UseCase(type: .depositCheck, id: UUID().uuidString) // let logInfo = LogInfo(useCase: useCase, loglevel: .info, userInfo: [:]) // // send to tracking client // } // // func accountSelected() { // guard let useCase = self.useCase else { // fatalError("startCheckDeposit must be called") // } // let logInfo = LogInfo(useCase: useCase, loglevel: .info, userInfo: [:]) // } // // func amountEntered() { // // } // // func makeCheckDepositTapped() { // // } // // func checkDepositCompleted() { // // } //}
true
e76ca096e0fd71c744875f495e895b120b28290e
Swift
ZuoLuFei/BaseFramework
/BaseFramework/BaseFramework/UIModule/PageList/KCPageListViewController.swift
UTF-8
2,415
2.609375
3
[]
no_license
/******************************************************************************* # File : KCPageListViewController.swift # Project : &&&& # Author : &&&& # Created : 2018/9/6 # Corporation : **** # Description : 列表页面基类,封装的tableView,以及空数据占位视图 ******************************************************************************/ import UIKit protocol KCPageListViewControllerDelegate: NSObjectProtocol { func pageListViewControllerDidScroll(_ scrollView: UIScrollView) } class KCPageListViewController: KCBaseViewController { weak var tableView: UITableView! weak var emptyView: KCEmptyView? weak var pageListDelegate: KCPageListViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() _configUI() _configData() } } // MARK: - 初始化UI extension KCPageListViewController { private func _configUI() { _initTableView() _initEmptyView() } private func _initTableView() { let tableView = UITableView(frame: CGRect.zero) view.addSubview(tableView) self.tableView = tableView tableView.snp.makeConstraints { (make) in make.edges.equalTo(0) } tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none } private func _initEmptyView() { let emptyView = KCEmptyView() self.emptyView = emptyView view.addSubview(emptyView) emptyView.snp.makeConstraints { (make) in make.centerX.equalTo(view.snp.centerX) make.centerY.equalTo(view.snp.centerY) } emptyView.isHidden = true } } extension KCPageListViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 0 } func scrollViewDidScroll(_ scrollView: UIScrollView) { pageListDelegate?.pageListViewControllerDidScroll(scrollView) } } // MARK: - 初始化Data extension KCPageListViewController { private func _configData() { } }
true
51168dd7c6690a2e26068ce38a4495619dbc68c4
Swift
Mister-Jam/FootballFixtures
/FootballFixtures/Networking/NetworkManager.swift
UTF-8
962
2.875
3
[]
no_license
// // NetworkManager.swift // FootballFixtures // // Created by King Bileygr on 8/27/21. // import Foundation class NetworkManager: NetworkLoader { static let shared = NetworkManager() private init () { } public func loadRequest<T: Decodable>(path: String, model: T.Type, completion: @escaping ((Result<T, Error>)->Void)) { guard let url = URL(string: Constants.URLConstants.baseURL+path) else { return } var request = URLRequest(url: url) request.httpMethod = "GET" request.setValue(Constants.URLConstants.apiToken, forHTTPHeaderField: Constants.URLConstants.httpHeader) URLSession.shared.decodeData(from: request, type: T.self) { result in switch result { case .success(let data): completion(.success(data)) case .failure(let error): completion(.failure(error)) } } } }
true
300669480b50a03f2367f991431c7fd9025a620c
Swift
DanielXinYi8023/UGFAFAFA
/apple/macOS/Pages/Home/Page/SettingView.swift
UTF-8
5,014
2.640625
3
[]
no_license
// // SettingView.swift // apple (macOS) // // Created by admin on 2021/3/26. // import SwiftUI struct SettingView: View { @State var host = "127.0.0.1" @State var port = "8888" @State var httpPort = "8181" @State var dbfile = UserDefaults.standard.string(forKey: "dbfile") var body: some View { VStack(alignment: .leading){ socketSetting httpSetting dbSetting test } .padding(.all) .frame(width: 400, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) .navigationTitle("设置") } var socketSetting:some View{ Group (){ Text("socket设置") .font(.subheadline) .fontWeight(.medium) .opacity(0.4) VStack(alignment: .trailing){ VStack { HStack(){ Text("ip地址") TextField("请输入ip地址", text: $host) .font(.title3) .padding(8) .background(Color("Background 1")) .mask(RoundedRectangle(cornerRadius: 8, style: .continuous)) .padding(.vertical, 8) } HStack{ Text("端口号") TextField("请输入端口号", text: $port) .font(.title3) .padding(8) .background(Color("Background 1")) .mask(RoundedRectangle(cornerRadius: 8, style: .continuous)) .padding(.vertical, 8) } } } } .padding(.trailing) } var httpSetting:some View{ Group (){ Text("http设置") .font(.subheadline) .fontWeight(.medium) .opacity(0.4) VStack(alignment: .trailing){ VStack { HStack{ Text("端口号") TextField("请输入端口号", text: $httpPort) .font(.title3) .padding(8) .background(Color("Background 1")) .mask(RoundedRectangle(cornerRadius: 8, style: .continuous)) .padding(.vertical, 8) } } } } .padding(.trailing) } var dbSetting:some View{ Group{ Text("db设置") .font(.subheadline) .fontWeight(.medium) .opacity(0.4) HStack{ Text(dbfile ?? "") .font(.subheadline) .padding(8) .background(Color("Background 1")) .mask(RoundedRectangle(cornerRadius: 8, style: .continuous)) .padding(.vertical, 8) Button(action: findFile) { Text("选择文件") } } } } var test:some View{ Group{ Text("测试按钮") .font(.subheadline) .fontWeight(.medium) .opacity(0.4) HStack{ Button(action: dotest) { Text("测试按钮") } } } } func start() { } func stop() { } func httpStart(){ } private func findFile(){ let openPanel = NSOpenPanel() openPanel.allowsMultipleSelection = false openPanel.canChooseDirectories = true openPanel.canCreateDirectories = false openPanel.canChooseFiles = false // openPanel.allowedFileTypes = ["db"] openPanel.begin { (result) -> Void in if result.rawValue == NSApplication.ModalResponse.OK.rawValue { let defaults = UserDefaults.standard defaults.set(openPanel.url?.absoluteString, forKey: "dbfile") dbfile = openPanel.url?.absoluteString SQLiteManage.updatefile() print(defaults.string(forKey: "dbfile")!) } } } private func dotest(){ // pythonManageTest1() } } struct SettingView_Previews: PreviewProvider { static var previews: some View { SettingView() } }
true
3f399c7827db275868e726c30942ab006a6d268c
Swift
charlesmartinreed/WeatherEye
/WeatherEye/PreferencesWindow.swift
UTF-8
1,477
3.015625
3
[]
no_license
// // PreferencesWindow.swift // WeatherEye // // Created by Charles Martin Reed on 11/27/18. // Copyright © 2018 Charles Martin Reed. All rights reserved. // import Cocoa //we'll use the delegate method to let the view controller's know that data has been updated protocol PreferencesWindowDelegate { func preferencesDidUpdate() } class PreferencesWindow: NSWindowController, NSWindowDelegate { var delegate: PreferencesWindowDelegate? //MARK:- @IBOutlets @IBOutlet weak var cityTextField: NSTextField! //link to our custom xib override var windowNibName: String! { return "PreferencesWindow" } override func windowDidLoad() { super.windowDidLoad() //load the default city let defaults = UserDefaults.standard let city = defaults.string(forKey: "city") ?? defaultCity cityTextField.stringValue = city //position the window, move it to the front of the window stack, make ours the active app self.window?.center() self.window?.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) } //MARK:- Delegate method func windowWillClose(_ notification: Notification) { //save to the user defaults area when we close out let defaults = UserDefaults.standard defaults.set(cityTextField.stringValue, forKey: "city") //call the delegate delegate?.preferencesDidUpdate() } }
true
c07f25c30fd2bd1ef544f59af1eccbf8a50161ea
Swift
davidyedeewhy/quiz
/Quiz/Module/Quiz/Controller/LandingViewController.swift
UTF-8
1,632
2.828125
3
[]
no_license
// // LandingViewController.swift // Quiz // // Created by David Ye on 11/5/19. // Copyright © 2019 David Ye. All rights reserved. // import UIKit class LandingViewController: UIViewController { // MARK: - variables @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var playButton: UIButton! private var score: Int = 0 private var progress: (answered: Int, total: Int) = (0, 0) // MARK: - view life cycle override func viewDidLoad() { super.viewDidLoad() scoreLabel.text = "\(score) (\(progress.answered)/\(progress.total))" } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) playButton.setTitle(progress.total == 0 ? "Play" : "Continue", for: .normal) } // MARK: - segue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == "showQuestion" else { return } if let questionViewController = (segue.destination as? UINavigationController)?.viewControllers.first as? QuestionViewController { questionViewController.delegate = self questionViewController.questionIndex = progress.total } } } // MARK: - protocol protocol ResultDelegate: class { func updateScore(_ isRight: Bool) } extension LandingViewController: ResultDelegate { func updateScore(_ isRight: Bool) { progress.total += 1 if isRight { progress.answered += 1 score += 20 scoreLabel.text = "\(score) (\(progress.answered)/\(progress.total))" } } }
true
e64c53e9de5a1999f34d35694252e7feba2912c2
Swift
roman85ph/jewishMusic
/JewishMusic.fm/Cell/PullDataTableViewCell.swift
UTF-8
1,010
2.53125
3
[]
no_license
// // PullDataTableViewCell.swift // JewishMusic.fm // // Created by Admin on 27/04/2018. // Copyright © 2018 JewishMusic.fm. All rights reserved. // import UIKit import Foundation class PullDataTableViewCell: UITableViewCell { @IBOutlet weak var progressView : UIActivityIndicatorView! @IBOutlet weak var progressLabel : UILabel! override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func startStopLoading(_ isStart : Bool) { if(isStart) { progressView.isHidden = false progressView.startAnimating() progressLabel.text = "Fetching Data..." } else { progressView.isHidden = true progressView.stopAnimating() progressLabel.text = "Pull to load more Data" } } }
true
7b1840692883d675cf8bcc2f784214b0ddb54cc4
Swift
pmwheatley/project-euler
/Swift/Tools/Sequences/CentralBinomialCoefficientsSequence.swift
UTF-8
839
3.234375
3
[]
no_license
// // CentralBinomialCoefficientsSequence.swift // ProjectEuler // // Created by convict7421 on 17/12/2015. // Copyright © 2015 convict7421. All rights reserved. // import Foundation // Central Binomial Coefficients - A000984 class CentralBinomialCoefficients : SequenceType { typealias GeneratorType = CentralBinomialCoefficientsGenerator func generate() -> CentralBinomialCoefficientsGenerator { return CentralBinomialCoefficientsGenerator() } } class CentralBinomialCoefficientsGenerator : GeneratorType { var current = 1 typealias Element = Int func next() -> Int? { return 0 } } func getNthBinomialCoefficient(n: Double) -> Double { return (2*n).factorial() / pow(n.factorial(), 2) } let CentralBinomialCoefficientsSequence = CentralBinomialCoefficients.init()
true
a35d1a983a0118915a2117d8c8b1fdd5427f580d
Swift
carlosmdarribas/Cerveceria_DAA
/La Cervecería de Pepe/Libraries/CSVParser.swift
UTF-8
1,581
3.109375
3
[]
no_license
// // CSVParser.swift // La Cervecería de Pepe // // Created by Carlos on 15/01/2021. // import Foundation class CSVParser { // https://gist.github.com/algal/ceb17773bbc01e9b6bb1 actualizado. static func JSONObjectFromTSV(tsvInputString:String, columnNames optionalColumnNames:[String]? = nil) -> Data? { let lines = tsvInputString.components(separatedBy: "\n") guard lines.isEmpty == false else { return nil } let columnNames = optionalColumnNames ?? lines[0].components(separatedBy: "\t") var lineIndex = (optionalColumnNames != nil) ? 0 : 1 let columnCount = columnNames.count var result = Array<NSDictionary>() for inline in lines[lineIndex ..< lines.count] { let line = inline.replacingOccurrences(of: "\n", with: "") let fieldValues = line.components(separatedBy: "\t") if fieldValues.count != columnCount { // NSLog("WARNING: header has %u columns but line %u has %u columns. Ignoring this line", columnCount, lineIndex,fieldValues.count) } else { result.append(NSDictionary(objects: fieldValues, forKeys: columnNames as [NSCopying])) } lineIndex = lineIndex + 1 } do { let jsonObject = try JSONSerialization.data(withJSONObject: result, options: .sortedKeys) return jsonObject } catch { print(error.localizedDescription) return nil } } }
true
46a572200da5a41cdf809295004d1fc0bd05871c
Swift
xiaozhenyangCode/ProjectBaseFramework
/ProjectBaseFramework/Classes/Main/XzyBaseViewController.swift
UTF-8
2,776
2.59375
3
[]
no_license
// // XzyBaseViewController.swift // // // Created by 一天 on 2017/3/1. // Copyright © 2017年 肖振阳. All rights reserved. // import UIKit /// OC 没有多继承 可以使用协议代替 //class XzyBaseViewController: UIViewController : UITableViewDelegate,UITableViewDataSource class XzyBaseViewController: UIViewController { /// UITableView var tableView : UITableView? let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 64)) let navItem = UINavigationItem() override func viewDidLoad() { super.viewDidLoad() setUpUI() } deinit { print("deinit\(self)") // 注销通知 NotificationCenter.default.removeObserver(self) } override var title: String?{ didSet{ navItem.title = title } } } // MARK: - 隔离代码 extension XzyBaseViewController{ func scrollViewDidScrollToTop(_ scrollView: UIScrollView) { } func setUpUI() { /// 取消自动缩进 如果隐藏nav 会缩进20个点 automaticallyAdjustsScrollViewInsets = false setUpNavBar() setUpTableView() } func setUpTableView(){ tableView = UITableView(frame: view.bounds, style: .plain) tableView?.delegate = self tableView?.dataSource = self view.insertSubview(tableView!, belowSubview: navigationBar) /// 设置内容缩进 tableView?.contentInset = UIEdgeInsetsMake(navigationBar.bounds.height, 0, tabBarController?.tabBar.bounds.height ?? 49, 0) // 修改指示器的缩进 - 强行解包是为了拿到一个必有的 inset tableView?.scrollIndicatorInsets = tableView!.contentInset } private func setUpNavBar(){ navigationBar.barTintColor = UIColor.white navigationBar.tintColor = UIColor.orange view.addSubview(navigationBar) navigationBar.items = [navItem] /// 设置navBar的字体颜色 navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray] } } // MARK: - UITableViewDelegate,UITableViewDataSource extension XzyBaseViewController : UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 10 } }
true
2dcc55082ed37d13594273e94615d65e62f23558
Swift
ohlsont/puls
/Puls/pulseDayCell.swift
UTF-8
741
2.75
3
[]
no_license
// // pulseDayCell.swift // Puls // // Created by Tomas Ohlson on 2016-12-18. // Copyright © 2016 Tomas Ohlson. All rights reserved. // import Foundation import UIKit import Charts class PulseDayCell: UITableViewCell { @IBOutlet weak var date: UILabel! @IBOutlet weak var chart: LineChartView! var chartManager: ChartManager? = nil func configure(pulseData: [PulseData]) { chartManager = ChartManager(chart: chart) chartManager?.fill(points: pulseData) let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(secondsFromGMT: 3600) dateFormatter.dateFormat = "dd MMMM" date.text = dateFormatter.string(from: pulseData.first?.start ?? Date()) } }
true
051c3c6854fee41d92db0ae8417955759e525b4c
Swift
olejiksa/eventpad
/Eventpad/Views/Event/ScheduleViewController.swift
UTF-8
6,624
2.53125
3
[]
no_license
// // ScheduleViewController.swift // Eventpad // // Created by Oleg Samoylov on 05.05.2020. // Copyright © 2020 Oleg Samoylov. All rights reserved. // import UIKit final class ScheduleViewController: UIViewController { private let cellID = "\(SubtitleCell.self)" private var titles: [String] = [] private var items: [[Event]] = [] private var spinner = UIActivityIndicatorView(style: .medium) private let alertService = AlertService() private let requestSender = RequestSender() @IBOutlet private weak var noDataLabel: UILabel! @IBOutlet private weak var tableView: UITableView! private let parentID: Int private let isManager: Bool init(parentID: Int, isManager: Bool) { self.parentID = parentID self.isManager = isManager super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupNavigation() setupTableView() setupSpinner() loadData() } private func setupNavigation() { navigationItem.title = "Расписание" if isManager { let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addDidTap)) navigationItem.rightBarButtonItem = addButton } } private func setupSpinner() { spinner.translatesAutoresizingMaskIntoConstraints = false spinner.startAnimating() view.addSubview(spinner) spinner.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true spinner.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } private func setupTableView() { tableView.register(SubtitleCell.self, forCellReuseIdentifier: cellID) } private func loadData() { let config = RequestFactory.events(conferenceID: parentID, limit: 20, offset: 0) requestSender.send(config: config) { [weak self] result in guard let self = self else { return } switch result { case .success(let events): self.spinner.stopAnimating() self.noDataLabel.isHidden = !events.isEmpty self.tableView.separatorStyle = events.isEmpty ? .none : .singleLine let groupSorted = events.groupSort(byDate: { $0.dateStart }) self.items = groupSorted self.titles = events.sorted { $0.dateStart > $1.dateStart }.map { $0.dateStartFormatted }.uniques self.tableView.reloadData() case .failure(let error): let alert = self.alertService.alert(error.localizedDescription) self.present(alert, animated: true) } } } @objc private func addDidTap() { let vc = NewEventViewController(conferenceID: parentID, mode: .new) let nvc = UINavigationController(rootViewController: vc) present(nvc, animated: true) } } // MARK: - UITableViewDataSource extension ScheduleViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return items.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items[section].count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard section < titles.count else { return nil } return titles[section] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let item = items[indexPath.section][indexPath.row] let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .short let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) let dateString = dateFormatter.string(from: item.dateStart) cell.textLabel?.text = item.title cell.detailTextLabel?.text = dateString cell.accessoryType = .disclosureIndicator return cell } } // MARK: - UITableViewDelegate extension ScheduleViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let event = items[indexPath.section][indexPath.row] let vc = EventViewController(event: event, isManager: isManager, fromFavorites: false) if let splitVc = splitViewController, !splitVc.isCollapsed { (splitVc.viewControllers.last as? UINavigationController)?.pushViewController(vc, animated: true) } else { navigationController?.pushViewController(vc, animated: true) } tableView.deselectRow(at: indexPath, animated: true) } } extension Sequence { func groupSort(ascending: Bool = false, byDate dateKey: (Iterator.Element) -> Date) -> [[Iterator.Element]] { var categories: [[Iterator.Element]] = [] for element in self { let key = dateKey(element) guard let dayIndex = categories.firstIndex(where: { $0.contains(where: { Calendar.current.isDate(dateKey($0), inSameDayAs: key) }) }) else { guard let nextIndex = categories.firstIndex(where: { $0.contains(where: { dateKey($0).compare(key) == (ascending ? .orderedDescending : .orderedAscending) }) }) else { categories.append([element]) continue } categories.insert([element], at: nextIndex) continue } guard let nextIndex = categories[dayIndex].firstIndex(where: { dateKey($0).compare(key) == (ascending ? .orderedDescending : .orderedAscending) }) else { categories[dayIndex].append(element) continue } categories[dayIndex].insert(element, at: nextIndex) } return categories } } extension Array where Element: Hashable { var uniques: Array { var buffer = Array() var added = Set<Element>() for elem in self { if !added.contains(elem) { buffer.append(elem) added.insert(elem) } } return buffer } }
true
093351e654f09e572ab615f8b3c310dc765a7023
Swift
KanjiKan/KanjiKit
/Sources/Kanji.swift
UTF-8
645
3.03125
3
[]
no_license
// // Kanji.swift // KanjiKit // // Created by Sikhapol Saijit on 1/5/17. // Copyright © 2017 KanjiKan. All rights reserved. // public struct Kanji { public var codepoint: Int public init(codepoint: Int) { self.codepoint = codepoint } } extension Kanji { public var unicodeScalar: UnicodeScalar { guard let unicodeScalar = UnicodeScalar(codepoint) else { fatalError() } return unicodeScalar } public var character: Character { return Character(unicodeScalar) } } extension Kanji: CustomStringConvertible { public var description: String { return String(character) } }
true
76cd75e1f92136bc7cc9eba78b4e7c4335452c30
Swift
tesch/Bookmarks
/Sources/Bookmarks/Types/Resolve.swift
UTF-8
476
3.046875
3
[ "MIT" ]
permissive
// // Resolve.swift // // Created by Marcel Tesch on 2020-06-11. // Think different. // import Foundation import ArgumentParser struct Resolve: ParsableCommand { static let configuration = CommandConfiguration(abstract: "Resolve a bookmark.") @Argument(help: "The to-be-resolved bookmark.", transform: URL.init(fileURLWithPath:)) var target: URL func run() throws { let source = try URL.resolveBookmark(at: target) print(source.path) } }
true
e3e245c73de87f7f75c6cfd7884472b01a48fdbc
Swift
mohsinalimat/grpc-swift
/Sources/SwiftGRPCNIO/HTTP1ToRawGRPCServerCodec.swift
UTF-8
11,323
2.5625
3
[ "Apache-2.0" ]
permissive
import Foundation import NIO import NIOHTTP1 import NIOFoundationCompat /// Incoming gRPC package with an unknown message type (represented by a byte buffer). public enum RawGRPCServerRequestPart { case head(HTTPRequestHead) case message(ByteBuffer) case end } /// Outgoing gRPC package with an unknown message type (represented by `Data`). public enum RawGRPCServerResponsePart { case headers(HTTPHeaders) case message(Data) case status(GRPCStatus) } /// A simple channel handler that translates HTTP1 data types into gRPC packets, and vice versa. /// /// This codec allows us to use the "raw" gRPC protocol on a low level, with further handlers operationg the protocol /// on a "higher" level. /// /// We use HTTP1 (instead of HTTP2) primitives, as these are easier to work with than raw HTTP2 /// primitives while providing all the functionality we need. In addition, this should make implementing gRPC-over-HTTP1 /// (sometimes also called pPRC) easier in the future. /// /// The translation from HTTP2 to HTTP1 is done by `HTTP2ToHTTP1ServerCodec`. public final class HTTP1ToRawGRPCServerCodec { // 1-byte for compression flag, 4-bytes for message length. private let protobufMetadataSize = 5 private var contentType: ContentType? // The following buffers use force unwrapping explicitly. With optionals, developers // are encouraged to unwrap them using guard-else statements. These don't work cleanly // with structs, since the guard-else would create a new copy of the struct, which // would then have to be re-assigned into the class variable for the changes to take effect. // By force unwrapping, we avoid those reassignments, and the code is a bit cleaner. // Buffer to store binary encoded protos as they're being received if the proto is split across // multiple buffers. private var binaryRequestBuffer: NIO.ByteBuffer! // Buffers to store text encoded protos. Only used when content-type is application/grpc-web-text. // TODO(kaipi): Extract all gRPC Web processing logic into an independent handler only added on // the HTTP1.1 pipeline, as it's starting to get in the way of readability. private var requestTextBuffer: NIO.ByteBuffer! private var responseTextBuffer: NIO.ByteBuffer! var inboundState = InboundState.expectingHeaders var outboundState = OutboundState.expectingHeaders var messageWriter = LengthPrefixedMessageWriter() var messageReader = LengthPrefixedMessageReader(mode: .server, compressionMechanism: .none) } extension HTTP1ToRawGRPCServerCodec { /// Expected content types for incoming requests. private enum ContentType: String { /// Binary encoded gRPC request. case binary = "application/grpc" /// Base64 encoded gRPC-Web request. case text = "application/grpc-web-text" /// Binary encoded gRPC-Web request. case web = "application/grpc-web" } enum InboundState { case expectingHeaders case expectingBody // ignore any additional messages; e.g. we've seen .end or we've sent an error and are waiting for the stream to close. case ignore } enum OutboundState { case expectingHeaders case expectingBodyOrStatus case ignore } } extension HTTP1ToRawGRPCServerCodec: ChannelInboundHandler { public typealias InboundIn = HTTPServerRequestPart public typealias InboundOut = RawGRPCServerRequestPart public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { if case .ignore = inboundState { return } do { switch self.unwrapInboundIn(data) { case .head(let requestHead): inboundState = try processHead(ctx: ctx, requestHead: requestHead) case .body(var body): inboundState = try processBody(ctx: ctx, body: &body) case .end(let trailers): inboundState = try processEnd(ctx: ctx, trailers: trailers) } } catch { ctx.fireErrorCaught(error) inboundState = .ignore } } func processHead(ctx: ChannelHandlerContext, requestHead: HTTPRequestHead) throws -> InboundState { guard case .expectingHeaders = inboundState else { throw GRPCError.server(.invalidState("expecteded state .expectingHeaders, got \(inboundState)")) } if let contentTypeHeader = requestHead.headers["content-type"].first { contentType = ContentType(rawValue: contentTypeHeader) } else { // If the Content-Type is not present, assume the request is binary encoded gRPC. contentType = .binary } if contentType == .text { requestTextBuffer = ctx.channel.allocator.buffer(capacity: 0) } ctx.fireChannelRead(self.wrapInboundOut(.head(requestHead))) return .expectingBody } func processBody(ctx: ChannelHandlerContext, body: inout ByteBuffer) throws -> InboundState { guard case .expectingBody = inboundState else { throw GRPCError.server(.invalidState("expecteded state .expectingBody, got \(inboundState)")) } // If the contentType is text, then decode the incoming bytes as base64 encoded, and append // it to the binary buffer. If the request is chunked, this section will process the text // in the biggest chunk that is multiple of 4, leaving the unread bytes in the textBuffer // where it will expect a new incoming chunk. if contentType == .text { precondition(requestTextBuffer != nil) requestTextBuffer.write(buffer: &body) // Read in chunks of 4 bytes as base64 encoded strings will always be multiples of 4. let readyBytes = requestTextBuffer.readableBytes - (requestTextBuffer.readableBytes % 4) guard let base64Encoded = requestTextBuffer.readString(length: readyBytes), let decodedData = Data(base64Encoded: base64Encoded) else { throw GRPCError.server(.base64DecodeError) } body.write(bytes: decodedData) } self.messageReader.append(buffer: &body) while let message = try self.messageReader.nextMessage() { ctx.fireChannelRead(self.wrapInboundOut(.message(message))) } return .expectingBody } private func processEnd(ctx: ChannelHandlerContext, trailers: HTTPHeaders?) throws -> InboundState { if let trailers = trailers { throw GRPCError.server(.invalidState("unexpected trailers received \(trailers)")) } ctx.fireChannelRead(self.wrapInboundOut(.end)) return .ignore } } extension HTTP1ToRawGRPCServerCodec: ChannelOutboundHandler { public typealias OutboundIn = RawGRPCServerResponsePart public typealias OutboundOut = HTTPServerResponsePart public func write(ctx: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { if case .ignore = outboundState { return } switch self.unwrapOutboundIn(data) { case .headers(var headers): guard case .expectingHeaders = outboundState else { return } var version = HTTPVersion(major: 2, minor: 0) if let contentType = contentType { headers.add(name: "content-type", value: contentType.rawValue) if contentType != .binary { version = .init(major: 1, minor: 1) } } if contentType == .text { responseTextBuffer = ctx.channel.allocator.buffer(capacity: 0) } ctx.write(self.wrapOutboundOut(.head(HTTPResponseHead(version: version, status: .ok, headers: headers))), promise: promise) outboundState = .expectingBodyOrStatus case .message(let messageBytes): guard case .expectingBodyOrStatus = outboundState else { return } if contentType == .text { precondition(self.responseTextBuffer != nil) // Store the response into an independent buffer. We can't return the message directly as // it needs to be aggregated with all the responses plus the trailers, in order to have // the base64 response properly encoded in a single byte stream. #if swift(>=4.2) messageWriter.write(messageBytes, into: &self.responseTextBuffer, usingCompression: .none) #else // Write into a temporary buffer to avoid: "error: cannot pass immutable value as inout argument: 'self' is immutable" var responseBuffer = ctx.channel.allocator.buffer(capacity: LengthPrefixedMessageWriter.metadataLength) messageWriter.write(messageBytes, into: &responseBuffer, usingCompression: .none) responseTextBuffer.write(buffer: &responseBuffer) #endif // Since we stored the written data, mark the write promise as successful so that the // ServerStreaming provider continues sending the data. promise?.succeed(result: Void()) } else { var responseBuffer = ctx.channel.allocator.buffer(capacity: LengthPrefixedMessageWriter.metadataLength) messageWriter.write(messageBytes, into: &responseBuffer, usingCompression: .none) ctx.write(self.wrapOutboundOut(.body(.byteBuffer(responseBuffer))), promise: promise) } outboundState = .expectingBodyOrStatus case .status(let status): // If we error before sending the initial headers (e.g. unimplemented method) then we won't have sent the request head. // NIOHTTP2 doesn't support sending a single frame as a "Trailers-Only" response so we still need to loop back and // send the request head first. if case .expectingHeaders = outboundState { self.write(ctx: ctx, data: NIOAny(RawGRPCServerResponsePart.headers(HTTPHeaders())), promise: nil) } var trailers = status.trailingMetadata trailers.add(name: "grpc-status", value: String(describing: status.code.rawValue)) if let message = status.message { trailers.add(name: "grpc-message", value: message) } if contentType == .text { precondition(responseTextBuffer != nil) // Encode the trailers into the response byte stream as a length delimited message, as per // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-WEB.md let textTrailers = trailers.map { name, value in "\(name): \(value)" }.joined(separator: "\r\n") responseTextBuffer.write(integer: UInt8(0x80)) responseTextBuffer.write(integer: UInt32(textTrailers.utf8.count)) responseTextBuffer.write(string: textTrailers) // TODO: Binary responses that are non multiples of 3 will end = or == when encoded in // base64. Investigate whether this might have any effect on the transport mechanism and // client decoding. Initial results say that they are inocuous, but we might have to keep // an eye on this in case something trips up. if let binaryData = responseTextBuffer.readData(length: responseTextBuffer.readableBytes) { let encodedData = binaryData.base64EncodedString() responseTextBuffer.clear() responseTextBuffer.reserveCapacity(encodedData.utf8.count) responseTextBuffer.write(string: encodedData) } // After collecting all response for gRPC Web connections, send one final aggregated // response. ctx.write(self.wrapOutboundOut(.body(.byteBuffer(responseTextBuffer))), promise: promise) ctx.write(self.wrapOutboundOut(.end(nil)), promise: promise) } else { ctx.write(self.wrapOutboundOut(.end(trailers)), promise: promise) } outboundState = .ignore inboundState = .ignore } } }
true
c911520d167f84db115e5dc3cfce6950a323e794
Swift
achimk/swift-kata
/CoreKit/CoreKitTests/Primitives/ResultTests.swift
UTF-8
5,275
2.90625
3
[ "MIT" ]
permissive
// // Created by Joachim Kret on 12/03/2020. // Copyright © 2020 Joachim Kret. All rights reserved. // import XCTest import CoreKit final class ResultTests: XCTestCase { struct StringError: Swift.Error, Equatable { var value: String init(_ value: String) { self.value = value } } struct IntError: Swift.Error, Equatable { var value: Int init(_ value: Int) { self.value = value } } struct FakeError: Swift.Error { } func testInitializeSuccess() { let result = Result<Int, StringError>(1) let value = retrieveValue(from: result, otherwise: 0) XCTAssertEqual(value, 1) } func testInitializeFailure() { let result = Result<Int, StringError>(StringError("a")) let errorReason = retrieveErrorReason(from: result, otherwise: StringError("b")) XCTAssertEqual(errorReason, StringError("a")) } func testValueProperty() { let result = Result<Int, StringError>(1) XCTAssertEqual(result.value, 1) } func testErrorReasonProperty() { let result = Result<Int, StringError>(StringError("a")) XCTAssertEqual(result.error, StringError("a")) } func testCheckIsSuccess() { let result = Result<Int, StringError>(1) XCTAssertTrue(result.isSuccess) } func testCheckIsFailure() { let result = Result<Int, StringError>(StringError("a")) XCTAssertTrue(result.isFailure) } func testOnSuccessClosure() { var value: Int = 0 let result = Result<Int, StringError>(1) result.onSuccess { value = $0 } XCTAssertEqual(value, 1) } func testOnFailureClosure() { var errorReason = StringError("b") let result = Result<Int, StringError>(StringError("a")) result.onFailure { errorReason = $0 } XCTAssertEqual(errorReason, StringError("a")) } func testMap() { let result = Result<Int, StringError>(1).map { String("-\($0)-") } let value = retrieveValue(from: result, otherwise: "") XCTAssertEqual(value, "-1-") } func testFlatMap() { let result = Result<Int, StringError>(1) .flatMap { _ in Result.success("1") } let value = retrieveValue(from: result, otherwise: "") XCTAssertEqual(value, "1") } func testMapError() { let result = Result<Int, StringError>(StringError("1")).mapError { _ in IntError(1) } let errorReason = retrieveErrorReason(from: result, otherwise: IntError(0)) XCTAssertEqual(errorReason, IntError(1)) } func testFlatMapError() { let result = Result<Int, StringError>(StringError("1")) .flatMapError { _ in Result.failure(IntError(1)) } let value = retrieveErrorReason(from: result, otherwise: IntError(0)) XCTAssertEqual(value, IntError(1)) } func testAnalyze() { let success: (Int) -> Int = { _ in 1 } let failure: (StringError) -> Int = { _ in 2 } let outputValue = Result<Int, StringError>(0).analyze(ifSuccess: success, ifFailure: failure) let outputErrorReason = Result<Int, StringError>(StringError("a")).analyze(ifSuccess: success, ifFailure: failure) XCTAssertEqual(outputValue, 1) XCTAssertEqual(outputErrorReason, 2) } func testAnalyzeWithoutInput() { let success: () -> Int = { 1 } let failure: () -> Int = { 2 } let outputValue = Result<Int, StringError>(0).analyze(ifSuccess: success, ifFailure: failure) let outputErrorReason = Result<Int, StringError>(StringError("a")).analyze(ifSuccess: success, ifFailure: failure) XCTAssertEqual(outputValue, 1) XCTAssertEqual(outputErrorReason, 2) } func testConvenienceSuccessVoidValue() { let result = Result<Void, StringError>.success() XCTAssertTrue(result.isSuccess) } func testDetermineValue() { let value = try? Result<Int, FakeError>(1).get() XCTAssertEqual(value, 1) } func testThrowIfFailure() { do { try Result<Int, FakeError>(FakeError()).throwsIfFailure() XCTFail("Should never happen!") } catch { XCTAssertTrue(error as? FakeError != nil) } } private func retrieveValue<T, U>(from result: Result<T, U>, otherwise: T) -> T { switch result { case .success(let value): return value case .failure: return otherwise } } private func retrieveErrorReason<T, U>(from result: Result<T, U>, otherwise: U) -> U { switch result { case .success: return otherwise case .failure(let errorReason): return errorReason } } }
true
09cd11f9ad1f157b8cbd276fdf12abcceee579a5
Swift
gkrat17/CovidApp
/CovidApp/Scenes/Details/DetailsPresenter.swift
UTF-8
2,521
2.796875
3
[]
no_license
// // DetailsPresenter.swift // CovidApp // // Created by Giorgi Kratsashvili on 10/15/20. // import Foundation protocol DetailsPresenter { func handleViewDidLoad() func numberOfItems(in section: Int) -> Int func viewModel(at indexPath: IndexPath) -> ConfirmedViewModel func handleNotificationsTapped() } class DetailsPresenterImplementation: DetailsPresenter { weak var view: DetailsView? let detailsFetchingUseCase: DetailsFetchingUseCase let notificationsStateUpdaterUseCase: NotificationsStateUpdaterUseCase var details: CovidDetailsEntity init ( view: DetailsView, identifier: CountryIdentifier, detailsFetchingUseCase: DetailsFetchingUseCase, notificationsStateUpdaterUseCase: NotificationsStateUpdaterUseCase ) { self.view = view self.detailsFetchingUseCase = detailsFetchingUseCase self.notificationsStateUpdaterUseCase = notificationsStateUpdaterUseCase self.details = .init(identifier: identifier, hasNotifications: false, confirmed: []) } func handleViewDidLoad() { detailsFetchingUseCase.fetchDetails { [weak self] (result) in guard let self = self else { return } switch result { case .success(let details): self.details = details self.view?.set(notifications: details.hasNotifications) self.view?.reloadData() case .failure(let error): self.view?.show(error: error.localizedDescription) } } } func numberOfItems(in section: Int) -> Int { details.confirmed.count } func viewModel(at indexPath: IndexPath) -> ConfirmedViewModel { details.confirmed[indexPath.row].toConfirmedViewModel() } func handleNotificationsTapped() { notificationsStateUpdaterUseCase.updateNotificationsState(with: !details.hasNotifications) { [weak self] (result) in guard let self = self else { return } switch result { case .success: self.details.hasNotifications.toggle() self.view?.set(notifications: self.details.hasNotifications) case .failure(let error): self.view?.show(error: error.localizedDescription) } } } } fileprivate extension ConfirmedEntity { func toConfirmedViewModel() -> ConfirmedViewModel { return ConfirmedViewModel(count: String(count), date: date.toLocalizedString()) } }
true
2d469ab16322679746e4f6c59b2f2de9320476f9
Swift
ignotusverum/token-ios
/consumer/Utilities/Layout Engine/Layout.swift
UTF-8
332
2.734375
3
[]
no_license
// // Layout.swift // consumer // // Created by Gregory Sapienza on 2/15/17. // Copyright © 2017 Human Ventures Co. All rights reserved. // import Foundation protocol Layout { /// Lays out object within a specified rect. /// /// - Parameter rect: Rect to layout within. mutating func layout(in rect: CGRect) }
true
55b5336a244a40844fadc095178fb9755813a1f9
Swift
binwei/Twitter
/Twitter/TweetCountsCell.swift
UTF-8
1,230
2.578125
3
[ "Apache-2.0" ]
permissive
// // TweetCountsCell.swift // Twitter // // Created by Binwei Yang on 7/30/16. // Copyright © 2016 Binwei Yang. All rights reserved. // import UIKit enum TweetAction { case Reply, Retweet, Favor } protocol TweetCountsCellDelete { func tweetCountsCell(tweetCountsCell: TweetCountsCell, didTweetAction tweetAction: TweetAction) } class TweetCountsCell: UITableViewCell { @IBOutlet weak var retweetCountLabel: UILabel! @IBOutlet weak var favoriteCountLabel: UILabel! var delegate: TweetCountsCellDelete? @IBAction func onReplyButton(sender: UIButton) { delegate?.tweetCountsCell(self, didTweetAction: .Reply) } @IBAction func onFavorButton(sender: UIButton) { delegate?.tweetCountsCell(self, didTweetAction: .Favor) } @IBAction func onRetweetButton(sender: UIButton) { delegate?.tweetCountsCell(self, didTweetAction: .Retweet) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
true
2e026e2599f4ae464cdf8e6481c78885be731e12
Swift
fuwamaki/sample-mvvm-ios
/SampleMVVM/Network/Request/ItemRequest.swift
UTF-8
1,449
2.625
3
[ "MIT" ]
permissive
// // ItemRequest.swift // SampleMVVM // // Created by yusaku maki on 2019/09/23. // Copyright © 2019 yusaku maki. All rights reserved. // import Alamofire struct ItemsFetchRequest: RequestProtocol { typealias Response = ItemsFetchResponse var url: String = Url.getItemsURL var method: HTTPMethod = .get } struct ItemPostRequest: RequestProtocol { typealias Response = ItemPostResponse var url: String = Url.postItemURL var method: HTTPMethod = .post // memo: postのparametersをbody化するのに重要な設定 var encoding: ParameterEncoding = JSONEncoding.default var parameters: [String: Any]? var headers: [String: String]? = ["Content-Type": "application/json"] } struct ItemDeleteRequest: RequestProtocol { typealias Response = ItemDeleteResponse var id: Int var url: String { var urlComponents = URLComponents(string: Url.deleteItemURL)! urlComponents.queryItems = [URLQueryItem(name: "id", value: String(id))] return (urlComponents.url?.absoluteString)! } var method: HTTPMethod = .delete } struct ItemPutRequest: RequestProtocol { typealias Response = ItemPutResponse var id: Int var url: String { var urlComponents = URLComponents(string: Url.putItemURL)! urlComponents.queryItems = [URLQueryItem(name: "id", value: String(id))] return (urlComponents.url?.absoluteString)! } var method: HTTPMethod = .put }
true
71f3db326f7e78b7fc43eb69a61ace531c6cd560
Swift
BenShutt/FontManager
/Example/FontsTableViewController.swift
UTF-8
1,432
2.8125
3
[ "MIT" ]
permissive
// // FontsTableViewController.swift // Example // // Created by Ben Shutt on 22/02/2020. // import UIKit import FontManager // MARK: - FontsTableViewController class FontsTableViewController: UITableViewController { private lazy var textStyles = UIFont.TextStyle.allCases override func viewDidLoad() { super.viewDidLoad() tableView.allowsSelection = false tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 44 tableView.tableFooterView = UIView() let identifier = "\(UITableViewCell.self)" tableView.register(UITableViewCell.self, forCellReuseIdentifier: identifier) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return textStyles.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = "\(UITableViewCell.self)" let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) let textStyle = textStyles[indexPath.row] cell.textLabel?.text = textStyle.description cell.textLabel?.font = Font.font(forTextStyle: textStyle) return cell } }
true
47a637c75110cbb48bc1c954c456b107a10f3852
Swift
ErickHdzProleit/Test
/Test/MeijiSwiftUIView.swift
UTF-8
440
2.578125
3
[]
no_license
// // MeijiSwiftUIView.swift // Test // // Created by erick eduardo on 14/07/21. // import SwiftUI struct MeijiSwiftUIView: View { var body: some View { Image("meiji") .clipShape(Circle()) .overlay(Circle().stroke(Color.white, lineWidth: 4)) .shadow(radius: 7) } } struct MeijiSwiftUIView_Previews: PreviewProvider { static var previews: some View { MeijiSwiftUIView() } }
true
c0b6a8e80117123ca58ea6c31a692ddd001a8ede
Swift
ijl0322/Backend-For-Mobile-Application
/AddressBook/Sources/App/main.swift
UTF-8
3,261
2.828125
3
[ "MIT" ]
permissive
import Vapor import VaporPostgreSQL let drop = Droplet() do { try drop.addProvider(VaporPostgreSQL.Provider.self) drop.preparations = [Addr.self] } catch { assertionFailure("Error adding provider: \(error)") } drop.get("version") { req in if let db = drop.database?.driver as? PostgreSQLDriver { let version = try db.raw("SELECT version()") return try JSON(node: version) } else { return "No database connection" } } drop.get("hello") { req in return "Hello!" } drop.get("model") { request in let address = Addr(firstName: "Isabel", lastName: "Lee", phone: "6261231234", address: "test") return try address.makeJSON() } // Add new data to database drop.post("new") { request in let name = request.data["firstname"]?.string guard let firstname = name else { return "Please specify a first name" } let lastname = request.data["lastname"]?.string ?? "No Data for Last Name" let phone = request.data["phone"]?.string ?? "No Phone Number Specified" let addr = request.data["address"]?.string ?? "No Address Specified" var address = Addr(firstName: firstname, lastName: lastname, phone: phone, address: addr) try address.save() return try JSON(node: Addr.all().makeNode()) } // Search for data drop.get("all") { request in return try JSON(node: Addr.all().makeNode()) } drop.get("search", "firstName", String.self) { request, param in return try JSON(node: Addr.query().filter("firstname", param).all().makeNode()) } drop.get("search", "lastName", String.self) { request, param in return try JSON(node: Addr.query().filter("lastname", param).all().makeNode()) } drop.get("search", "phone", String.self) { request, param in return try JSON(node: Addr.query().filter("phone", param).all().makeNode()) } drop.get("search", "address", String.self) { request, param in return try JSON(node: Addr.query().filter("address", param).all().makeNode()) } drop.get("search", "id", Int.self) { request, param in return try JSON(node: Addr.query().filter("id", param).all().makeNode()) } // Updating data drop.patch("update", "id", Int.self) { request, param in var addressToUpdate = try Addr.query().filter("id", param).first() guard var newAddress = addressToUpdate else { return "Cannot find this entry" } let firstname = request.data["firstname"]?.string let lastname = request.data["lastname"]?.string let phone = request.data["phone"]?.string let addr = request.data["address"]?.string if let firstname = firstname { newAddress.firstname = firstname } if let lastname = lastname { newAddress.lastname = lastname } if let phone = phone { newAddress.phone = phone } if let addr = addr { newAddress.address = addr } try newAddress.save() return newAddress } // Deleting data using id drop.delete("delete", "id", Int.self) { request, param in var addressToDelete = try Addr.query().filter("id", param).first() guard var address = addressToDelete else { return "Cannot find this entry" } try address.delete() return try JSON(node: Addr.all().makeNode()) } drop.run()
true
a268efbad461ca9bebeb2fc31271db4e48aae75c
Swift
smileszhang/TechStepApp
/TechStepApp/ContactViewController.swift
UTF-8
1,784
2.65625
3
[]
no_license
// // ContactViewController.swift // TechStepApp // // Created by smile on 2018/3/13. // Copyright © 2018年 smile. All rights reserved. // import UIKit import ContactsUI class ContactViewController: UIViewController,CNContactPickerDelegate { @IBOutlet weak var send_button: UIButton! var count = Int() override func viewDidLoad() { super.viewDidLoad() send_button.isEnabled = false // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func click_contacts(_ sender: Any) { let cnPicker = CNContactPickerViewController() cnPicker.delegate = self self.present(cnPicker,animated: true,completion: nil) } func contactPicker(_ picker:CNContactPickerViewController, didSelect contacts: [CNContact]){ count = contacts.count contacts.forEach{ contact in for number in contact.phoneNumbers{ let phoneNumber = number.value print("number is = \(phoneNumber)") } } if (count>=5){ send_button.isEnabled = true } } func contactPickerDidCancel(_ picker: CNContactPickerViewController){ print("Cancel contact Picker") } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
0e6bcb5b51627899bc7a9c66e3017210e631727a
Swift
yong076/PinCodeField
/Example/PinCodeField/ViewController.swift
UTF-8
990
2.8125
3
[ "MIT" ]
permissive
// // ViewController.swift // PinCodeField // // Created by nestorpopko on 11/25/2017. // Copyright (c) 2017 nestorpopko. All rights reserved. // import UIKit import PinCodeField class ViewController: UIViewController { @IBOutlet var pinCodeField: PinCodeField! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(patternImage: UIImage(named: "pattern")!) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) pinCodeField.becomeFirstResponder() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) pinCodeField.resignFirstResponder() } @IBAction func pinCodeChanged(_ sender: PinCodeField) { print("Pin code changed: " + sender.text) if sender.isFilled { sender.resignFirstResponder() print("Pin code entered.") } } }
true
33d93b64cd8c4fa2906a88c914d8ac9d3a6f43ac
Swift
nishiths23/SwiftUIDownloadView
/Example/SwiftUIDownloadViewDemo/FilesViewModel.swift
UTF-8
1,822
2.84375
3
[]
no_license
// // FilesViewModel.swift // SwiftUIDownloadViewDemo // // Created by Nishith on 16/06/2019. // Copyright © 2019 Nishith. All rights reserved. // import Combine import SwiftUI class FilesViewModel: BindableObject { let didChange = PassthroughSubject<FilesViewModel, Never>() private(set) var files: [DownloadableFile] { didSet { initiateDummyDownload() didChange.send(self) } } init(_ files:[DownloadableFile]) { self.files = files initiateDummyDownload() } func cancelDownload(_ file: DownloadableFile) { if let index = files.firstIndex(of: file){ files[index].progress = 1 files[index].isDownloading = false didChange.send(self) } } func addNewFile() { files.append(DownloadableFile(id: "00\(files.count)", title: "File #\(files.count)", progress: 0)) } func initiateDummyDownload() { for file in files { if file.progress < 1{ file.isDownloading = true file.downloadTimer?.invalidate() file.downloadTimer = nil file.downloadTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak file, weak self] _ in file?.progress += Float(0.1) file?.isDownloading = true if let progress = file?.progress, progress >= 1 { file?.downloadTimer?.invalidate() file?.downloadTimer = nil file?.isDownloading = false } if let selfRef = self { selfRef.didChange.send(selfRef) } }) } } } }
true
fb0d6878b36dff85d077358e8366c9457e221b5c
Swift
bekadeveloper/leetcode
/daily-swift-challenges/day-2.swift
UTF-8
857
3.375
3
[ "MIT" ]
permissive
import Foundation /* * Complete the 'solve' function below. * * The function accepts following parameters: * 1. DOUBLE meal_cost * 2. INTEGER tip_percent * 3. INTEGER tax_percent */ func solve(_ meal_cost: Double, _ tip_percent: Int, _ tax_percent: Int) -> Void { let tip = meal_cost/100 * Double(tip_percent) let tax = meal_cost/100 * Double(tax_percent) print("\(Int((meal_cost + tip + tax).rounded()))") } guard let meal_cost = Double((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!) else { fatalError("Bad input") } guard let tip_percent = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!) else { fatalError("Bad input") } guard let tax_percent = Int((readLine()?.trimmingCharacters(in: .whitespacesAndNewlines))!) else { fatalError("Bad input") } solve(meal_cost, tip_percent, tax_percent)
true
30afa0c34cf3a74ad862fa4c12a76a78bf3bd543
Swift
EKrkmz/To-DoWithPromodoro
/To-DoWithPromodoro/CompViewController.swift
UTF-8
2,424
2.671875
3
[]
no_license
// // CompViewController.swift // To-DoWithPromodoro // // Created by MYMACBOOK on 1.03.2021. // Copyright © 2021 ElifKorkmaz. All rights reserved. // import UIKit import CoreData class CompViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! var managedObjectContext: NSManagedObjectContext! var taskList = [Task]() var task: Task! override func viewDidLoad() { super.viewDidLoad() fetchTasks() collectionView.delegate = self collectionView.dataSource = self let tasarim : UICollectionViewFlowLayout = UICollectionViewFlowLayout() let genislik = self.collectionView.frame.size.width tasarim.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) let hucreGenislik = (genislik-30)/2 tasarim.itemSize = CGSize(width: hucreGenislik, height: hucreGenislik) tasarim.minimumInteritemSpacing = 10 tasarim.minimumLineSpacing = 10 collectionView.collectionViewLayout = tasarim } func fetchTasks() { do { let fetchReq: NSFetchRequest<Task> = Task.fetchRequest() fetchReq.predicate = NSPredicate(format: "task_done == %@ ", NSNumber(value: true)) taskList = try managedObjectContext.fetch(fetchReq) } catch { print(error.localizedDescription) } } func saveContext() { do { try managedObjectContext.save() } catch { print(error.localizedDescription) } } } extension CompViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { taskList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let task = taskList[indexPath.row] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "compCell", for: indexPath) as! CompCollectionViewCell cell.labelCategory.text = task.category?.category_name cell.labelTask.text = task.task_name cell.layer.borderColor = UIColor.lightGray.cgColor cell.layer.borderWidth = 1 cell.layer.cornerRadius = 20 return cell } }
true
68e7f8b64b1650f4679c122eddef3c40b0b09754
Swift
fumiyasac/ios_ui_recipe_showcase
/03_LikeTinder/LikeTinderExample/LikeTinderExample/ViewController/MainViewController.swift
UTF-8
7,918
2.640625
3
[]
no_license
// // MainViewController.swift // LikeTinderExample // // Created by 酒井文也 on 2018/08/18. // Copyright © 2018年 酒井文也. All rights reserved. // import UIKit class MainViewController: UIViewController { // カード表示用のViewを格納するための配列 private var itemCardViewList: [ItemCardView] = [] // TravelPresenterに設定したプロトコルを適用するための変数 private var presenter: TravelPresenter! override func viewDidLoad() { super.viewDidLoad() setupNavigationController() setupTravelPresenter() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Private Function // カードの内容をボタン押下時に実行されるアクションに関する設定を行う @objc private func refreshButtonTapped() { presenter.getTravelModels() } private func setupNavigationController() { setupNavigationBarTitle("気になる旅行") var attributes = [NSAttributedString.Key : Any]() attributes[NSAttributedString.Key.font] = UIFont(name: "HiraKakuProN-W3", size: 13.0) attributes[NSAttributedString.Key.foregroundColor] = UIColor.white let rightButton = UIBarButtonItem(title: "✨再追加✨", style: .done, target: self, action: #selector(self.refreshButtonTapped)) rightButton.setTitleTextAttributes(attributes, for: .normal) rightButton.setTitleTextAttributes(attributes, for: .highlighted) self.navigationItem.rightBarButtonItem = rightButton } // Presenterとの接続に関する設定を行う private func setupTravelPresenter() { presenter = TravelPresenter(presenter: self) presenter.getTravelModels() } // UIAlertViewControllerのポップアップ共通化を行う private func showAlertControllerWith(title: String, message: String) { let singleAlert = UIAlertController(title: title, message: message, preferredStyle: .alert) singleAlert.addAction( UIAlertAction(title: "OK", style: .default, handler: nil) ) self.present(singleAlert, animated: true, completion: nil) } // 画面上にカード表示用のViewを追加 & 付随した処理を行う private func addItemCardViews(_ travelModels: [TravelModel]) { for index in 0..<travelModels.count { // Debug. //print(travelModels[index]) // ItemCardViewのインスタンスを作成してプロトコル宣言やタッチイベント等の初期設定を行う let itemCardView = ItemCardView() itemCardView.delegate = self itemCardView.setModelData(travelModels[index]) itemCardView.largeImageButtonTappedHandler = { // 画像の拡大縮小が可能な画面へ遷移する let storyboard = UIStoryboard(name: "Photo", bundle: nil) let controller = storyboard.instantiateInitialViewController() as! PhotoViewController controller.setTargetTravelModel(travelModels[index]) controller.modalPresentationStyle = .overFullScreen controller.modalTransitionStyle = .crossDissolve self.present(controller, animated: true, completion: nil) } itemCardView.isUserInteractionEnabled = false // カード表示用のViewを格納するための配列に追加する itemCardViewList.append(itemCardView) // 現在表示されているカードの背面へ新たに作成したカードを追加する view.addSubview(itemCardView) view.sendSubviewToBack(itemCardView) } // MEMO: 配列(itemCardViewList)に格納されているViewのうち、先頭にあるViewのみを操作可能にする enableUserInteractionToFirstItemCardView() // 画面上にあるカードの山の拡大縮小比を調節する changeScaleToItemCardViews(skipSelectedView: false) } // 画面上にあるカードの山のうち、一番上にあるViewのみを操作できるようにする private func enableUserInteractionToFirstItemCardView() { if !itemCardViewList.isEmpty { if let firstItemCardView = itemCardViewList.first { firstItemCardView.isUserInteractionEnabled = true } } } // 現在配列に格納されている(画面上にカードの山として表示されている)Viewの拡大縮小を調節する private func changeScaleToItemCardViews(skipSelectedView: Bool = false) { // アニメーション関連の定数値 let duration: TimeInterval = 0.26 let reduceRatio: CGFloat = 0.03 var itemCount: CGFloat = 0 for (itemIndex, itemCardView) in itemCardViewList.enumerated() { // 現在操作中のViewの縮小比を変更しない場合は、以降の処理をスキップする if skipSelectedView && itemIndex == 0 { continue } // 後ろに配置されているViewほど小さく見えるように縮小比を調節する let itemScale: CGFloat = 1 - reduceRatio * itemCount UIView.animate(withDuration: duration, animations: { itemCardView.transform = CGAffineTransform(scaleX: itemScale, y: itemScale) }) itemCount += 1 } } } // MARK: - TravelPresenterProtocol extension MainViewController: TravelPresenterProtocol { // Presenterでデータ取得処理を実行した際に行われる処理 func bindTravelModels(_ travelModels: [TravelModel]) { // 表示用のViewを格納するための配列「itemCardViewList」が空なら追加する if itemCardViewList.count > 0 { showAlertControllerWith(title: "まだカードが残っています", message: "画面からカードがなくなったら、\n再度追加をお願いします。\n※サンプルデータ計8件") return } else { addItemCardViews(travelModels) } } } // MARK: - ItemCardDelegate extension MainViewController: ItemCardDelegate { // ドラッグ処理が開始された際にViewController側で実行する処理 func beganDragging() { // Debug. //print("ドラッグ処理が開始されました。") changeScaleToItemCardViews(skipSelectedView: true) } // ドラッグ処理中に位置情報が更新された際にViewController側で実行する処理 func updatePosition(_ itemCardView: ItemCardView, centerX: CGFloat, centerY: CGFloat) { // Debug. //print("該当View: \(itemCardView) 移動した座標点(X,Y): (\(centerX),\(centerY))") } // 左方向へのスワイプが完了した際にViewController側で実行する処理 func swipedLeftPosition() { // Debug. //print("左方向へのスワイプ完了しました。") itemCardViewList.removeFirst() enableUserInteractionToFirstItemCardView() changeScaleToItemCardViews(skipSelectedView: false) } // 右方向へのスワイプが完了した際にViewController側で実行する処理 func swipedRightPosition() { // Debug. //print("右方向へのスワイプ完了しました。") itemCardViewList.removeFirst() enableUserInteractionToFirstItemCardView() changeScaleToItemCardViews(skipSelectedView: false) } // 元の位置へ戻った際にViewController側で実行する処理 func returnToOriginalPosition() { // Debug. //print("元の位置へ戻りました。") changeScaleToItemCardViews(skipSelectedView: false) } }
true
23c088411640e12b10e1890667409e0a3d631814
Swift
Torsph/DynamicLayout
/Carthage/Checkouts/Spots/Sources/iOS/Library/ViewRegistry.swift
UTF-8
408
3.0625
3
[ "MIT" ]
permissive
import UIKit import Brick public struct ViewRegistry { var storage = [String : UIView.Type]() /** A subscripting method for getting a value from storage using a StringConvertible key - Returns: An optional UIView type */ public subscript(key: StringConvertible) -> UIView.Type? { get { return storage[key.string] } set(value) { storage[key.string] = value } } }
true
4c9e185ce83b98801fecf7b7612a7f2c6771d60c
Swift
buffsldr/AdventOfCode2018
/AdventOfCode/Library/Day.swift
UTF-8
1,725
3.265625
3
[]
no_license
// // Day.swift // test // // Created by Dave DeLong on 12/22/17. // Copyright © 2017 Dave DeLong. All rights reserved. // protocol Year { var days: Array<Day> { get } } protocol Day { init() func run() -> (String, String) func part1() -> String func part2() -> String } extension Day { static func rawInput(_ callingFrom: StaticString = #file) -> String { var components = ("\(callingFrom)" as NSString).pathComponents _ = components.removeLast() components.append("input.txt") let path = NSString.path(withComponents: components) return try! String(contentsOf: URL(fileURLWithPath: path)) } static func trimmedInput(_ callingFrom: StaticString = #file) -> String { return rawInput(callingFrom).trimmingCharacters(in: .whitespacesAndNewlines) } static func inputLines(trimming: Bool = true, _ callingFrom: StaticString = #file) -> Array<String> { let i = trimming ? trimmedInput(callingFrom) : rawInput(callingFrom) return i.components(separatedBy: .newlines) } static func inputIntegers(trimming: Bool = true, radix: Int = 10, _ callingFrom: StaticString = #file) -> Array<Int> { return inputLines(trimming: trimming, callingFrom).compactMap { Int($0, radix: radix) } } static func inputCharacters(trimming: Bool = true, _ callingFrom: StaticString = #file) -> Array<Array<Character>> { return inputLines(trimming: trimming, callingFrom).map { Array($0) } } func run() -> (String, String) { return (part1(), part2()) } func part1() -> String { return "implement me!" } func part2() -> String { return "implement me!" } }
true
fb8919d49c330fdd5b62003503019497017cddda
Swift
lucabelezal/swift-foundation-lib
/Sources/FoundationLib/Collections/Stack.swift
UTF-8
1,445
3.390625
3
[ "MIT" ]
permissive
// // Stack.swift // // // Created by lonnie on 2020/9/20. // import Foundation public class Stack<T>: Sequence, Countable { public typealias Element = T public typealias Iterator = ListNode<T>.Iterater fileprivate(set) public var first: ListNode<T> = .leaf fileprivate(set) public var count: Int = 0 public func push(_ item: T) { first = .value(item, first) count += 1 } @discardableResult public func pop() throws -> T { guard case .value(let val, let next) = first else { throw FoundationError.nilValue } first = next count -= 1 return val } public __consuming func makeIterator() -> ListNode<T>.Iterater { ListNode.Iterater(node: first) } public func peek() throws -> T { guard case .value(let val, _) = first else { throw FoundationError.nilValue } return val } deinit { var flag = true while flag { switch first { case .leaf: first = .leaf flag = false case .value(_, let node): first = node } } } } public extension Stack { func push(@ArrayBuilder _ builder: () -> [T]) { let items = builder() for item in items { self.push(item) } } }
true
4e218c7d84eb8cfb32b3c9eb78f008a9ade6a6ef
Swift
Trithep/WeatherForecast
/WeatherForecast/Parents/ViewController/LandingBaseViewController.swift
UTF-8
1,058
2.625
3
[]
no_license
import UIKit class LandingBaseViewController: BaseViewController { // MARK: - Object Life Cycle required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "", style: .plain, target: nil, action: nil) } override func setupNavigationController(navigationController: UINavigationController, animated: Bool) { super.setupNavigationController(navigationController: navigationController, animated: animated) guard navigationController.children.count > 1 else { return } let backButton = UIButton() let backButtonImage = UIImage(named: "ic_back") backButton.setImage(backButtonImage, for: .normal) backButton.sizeToFit() backButton.addTarget(self, action: #selector(backButtonAction), for: .touchUpInside) let barButtonItem = UIBarButtonItem(customView: backButton) navigationItem.leftBarButtonItem = barButtonItem } @objc private func backButtonAction() { navigationController?.popViewController(animated: true) } }
true
e8e1f5e6a59c9332722fbbdb8f4e3388459dd46a
Swift
lepxx1991/TweetTiki
/TweetTest/Application/Constants.swift
UTF-8
563
2.625
3
[]
no_license
// // Constants.swift // TweetTest // // Created by Tien Phan on 6/6/18. // Copyright © 2018 Tien Phan. All rights reserved. // import Foundation import UIKit let kNumber = 50 enum ValidateError: Error { case overCharacter(String) case oneLine case empty } private var tickTimestamp: Date = Date() func TICK() { print("TICK.") tickTimestamp = Date() } func TOCK() { print("TOCK. Elapsed Time: \(Date().timeIntervalSince(tickTimestamp))") } struct ElertMessage { static let over50Chars = "Span of nonwhite space character > 50" }
true
690ee737d642b8446b5bfbe458bce35d6fc0e997
Swift
sshyran/Uniform
/Example/Tests/ConsistentObjects.swift
UTF-8
7,468
2.953125
3
[ "MIT" ]
permissive
// // ConsistentObjects.swift // Uniform_Example // // Created by King, Gavin on 1/3/18. // Copyright © 2018 CocoaPods. All rights reserved. // @testable import Uniform // MARK: Objects struct Object1: Model { var id: String var integer: Int } struct Object2: Model { var id: String var integer: Int var object1: Object1? var object1s: [Object1]? } struct Object3: Model { var id: String var integer: Int var object1: Object1? var object1s: [Object1]? var object2: Object2? var object2s: [Object2]? } // MARK: Extensions (Generated) extension Object1: ConsistentObject { var properties: [Property] { return [ (label: "id", value: self.id), (label: "integer", value: self.integer) ] } func setting(property: Property) -> Object1 { var builder = Object1Builder(object: self) do { try builder.set(property: property.label, with: property.value) } catch { assertionFailure() } return builder.build() } } extension Object2: ConsistentObject { var properties: [Property] { return [ (label: "id", value: self.id), (label: "integer", value: self.integer), (label: "object1", value: self.object1), (label: "object1s", value: self.object1s) ] } func setting(property: Property) -> Object2 { var builder = Object2Builder(object: self) do { try builder.set(property: property.label, with: property.value) } catch { assertionFailure() } return builder.build() } } extension Object3: ConsistentObject { var properties: [Property] { return [ (label: "id", value: self.id), (label: "integer", value: self.integer), (label: "object1", value: self.object1), (label: "object1s", value: self.object1s), (label: "object2", value: self.object2), (label: "object2s", value: self.object2s) ] } func setting(property: Property) -> Object3 { var builder = Object3Builder(object: self) do { try builder.set(property: property.label, with: property.value) } catch { assertionFailure() } return builder.build() } } // MARK: Builders (Generated) struct Object1Builder: Builder { var id: String var integer: Int init(object: Object1) { self.id = object.id self.integer = object.integer } func build() -> Object1 { return Object1(id: self.id, integer: self.integer) } mutating func set(property label: String, with value: Any?) throws { if label == "id" { if let id = value as? String { self.id = id return } else { throw BuilderError.invalidType } } if label == "integer" { if let integer = value as? Int { self.integer = integer return } else { throw BuilderError.invalidType } } } } struct Object2Builder: Builder { var id: String var integer: Int var object1: Object1? var object1s: [Object1]? init(object: Object2) { self.id = object.id self.integer = object.integer self.object1 = object.object1 self.object1s = object.object1s } func build() -> Object2 { return Object2(id: self.id, integer: self.integer, object1: self.object1, object1s: self.object1s) } mutating func set(property label: String, with value: Any?) throws { if label == "id" { if let id = value as? String { self.id = id return } else { throw BuilderError.invalidType } } if label == "integer" { if let integer = value as? Int { self.integer = integer return } else { throw BuilderError.invalidType } } if label == "object1" { if let object1 = value as? Object1? { self.object1 = object1 return } else { throw BuilderError.invalidType } } if label == "object1s" { if let object1s = value as? [Object1]? { self.object1s = object1s return } else { throw BuilderError.invalidType } } } } struct Object3Builder: Builder { var id: String var integer: Int var object1: Object1? var object1s: [Object1]? var object2: Object2? var object2s: [Object2]? init(object: Object3) { self.id = object.id self.integer = object.integer self.object1 = object.object1 self.object1s = object.object1s self.object2 = object.object2 self.object2s = object.object2s } func build() -> Object3 { return Object3(id: self.id, integer: self.integer, object1: self.object1, object1s: self.object1s, object2: self.object2, object2s: self.object2s) } mutating func set(property label: String, with value: Any?) throws { if label == "id" { if let id = value as? String { self.id = id return } else { throw BuilderError.invalidType } } if label == "integer" { if let integer = value as? Int { self.integer = integer return } else { throw BuilderError.invalidType } } if label == "object1" { if let object1 = value as? Object1? { self.object1 = object1 return } else { throw BuilderError.invalidType } } if label == "object1s" { if let object1s = value as? [Object1]? { self.object1s = object1s return } else { throw BuilderError.invalidType } } if label == "object2" { if let object2 = value as? Object2? { self.object2 = object2 return } else { throw BuilderError.invalidType } } if label == "object2s" { if let object2s = value as? [Object2]? { self.object2s = object2s return } else { throw BuilderError.invalidType } } } }
true
08a7cb796fcfbdba39d33c339522e6fc11f30b84
Swift
vadimtrifonov/CryptoSAK
/Sources/Ethereum/EthereumInternalTransaction.swift
UTF-8
452
2.703125
3
[ "Apache-2.0", "Swift-exception" ]
permissive
import Foundation public struct EthereumInternalTransaction { public let transaction: EthereumTransaction public let from: String public let to: String public let amount: Decimal public init( transaction: EthereumTransaction, from: String, to: String, amount: Decimal ) { self.from = from self.to = to self.amount = amount self.transaction = transaction } }
true
ce9afe46f0fe7be4a1aaea2cd56d8bb2c6ef0145
Swift
ArtemGrebenkin/myCoin
/myCoin/DataViewController.swift
UTF-8
3,370
2.53125
3
[]
no_license
// // DataViewController.swift // myCoin // // Created by Artem Grebenkin on 4/17/18. // Copyright © 2018 Artem Grebenkin. All rights reserved. // import UIKit import RealmSwift class DataViewController: UIViewController { var arrayRecords: Results<CoinRecord>! @IBOutlet weak var dataTable: UITableView! let visibleTime: Double = -16 //max time of visible mark "New" on a cell override func viewDidLoad() { super.viewDidLoad() arrayRecords = realm.objects(CoinRecord.self).sorted(byKeyPath: "datePickUp", ascending: false) let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPressed)) self.navigationItem.rightBarButtonItem = addButton } //override func viewWillAppear(_ animated: Bool) { // arrayRecords = realm.objects(CoinRecord.self).sorted(byKeyPath: "datePickUp", ascending: false) //} @objc func addPressed() { //go to ahead screen let storyboard = UIStoryboard(name: "Main", bundle: nil) let towardVC = storyboard.instantiateViewController(withIdentifier: "inputVC") as! InputViewController self.navigationController?.pushViewController(towardVC, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let indexPath = dataTable.indexPathForSelectedRow { let destinationController = segue.destination as! InputViewController if segue.identifier == "editRecord" { destinationController.uid = arrayRecords[indexPath.row].uid } else { //во всех остальных случаях будем считать что создаем новую запись destinationController.uid = UUID().uuidString //генерируем уникальный идентификатор новой монеты } } } } extension DataViewController: UITableViewDataSource, UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayRecords.isEmpty ? 0 : arrayRecords.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "dataCell", for: indexPath) as! DataTableViewCell //remove gray selected color let backgroundView = UIView() backgroundView.backgroundColor = UIColor(red: 254, green: 239, blue: 0, alpha: 0) cell.selectedBackgroundView = backgroundView if let recordDate = arrayRecords[indexPath.row].datePickUp { cell.datePickUpLabel?.text = extDateToString(date: recordDate as Date) cell.newCoinImage.isHidden = recordDate.timeIntervalSinceNow > visibleTime ? false:true //mark the cell as new (some seconds) } cell.coinNameLabel?.text = arrayRecords[indexPath.row].coin?.fullName return cell } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { StorageManager.deleteObject(arrayRecords[indexPath.row]) dataTable.deleteRows(at: [indexPath], with: .automatic) } } }
true
3c8da88b164ff7c881e6f511828ce51cb492f28e
Swift
hongPro-ios/100days-of-swift
/14day.playground/Pages/Enumerations.xcplaygroundpage/Contents.swift
UTF-8
511
3.25
3
[]
no_license
enum WeatherType { case sun case cloud case rain case wind(speed: Int) case snow } func getHaterStatus(weather: WeatherType) -> String? { switch weather { case .sun: return nil case .cloud: return "dislike" case .rain: return "dislike" case .wind(let speed) where speed < 10: return "wind speed \(speed)" case .snow: return "love" default: return "default" } } getHaterStatus(weather: .wind(speed: 9))
true
0058e7e3569635b0fe763123e219f79b95338586
Swift
fritza/SwiftGenerator
/SwiftGenerator/SwiftGenerator/DataModelFile.swift
UTF-8
2,752
3.046875
3
[]
no_license
// // DataModelFile.swift // SwiftGenerator // // Created by Fritz Anderson on 6/14/15. // Copyright (c) 2015 Fritz Anderson. All rights reserved. // import Foundation struct DataModelFile { let fileURL: NSURL var entities = [Entity]() init?(url: NSURL) { if let url = DataModelFile.modelFileFromModelPackage(url) { fileURL = url } else { fileURL = NSURL(fileURLWithPath: "/", isDirectory: true)! return nil } } mutating func fillEntities() -> Bool { var error: NSError? if let document = NSXMLDocument(contentsOfURL: fileURL, options: 0, error: &error), modelElement = document.rootElement() where modelElement.name! == "model" { let entityElements = modelElement.elementsForName("entity") as! [NSXMLElement] for entity in entityElements { if let entity = Entity(element: entity) { entities.append(entity) } else { break } // FIXME: Do something about broken <entity> } return true } return false } static func modelFileFromModelPackage(url: NSURL) -> NSURL? { if url.filePathURL == nil { return nil } if let components = url.pathComponents as? [String] where components.count >= 2 { var error: NSError? let fm = NSFileManager() // It’s the contents file of an .xcdatemodel package // return unchanged. if components.last! == "contents" && components[components.count - 2].hasSuffix(".xcdatamodel") { return url } if url.pathExtension == "xcdatamodel" { return DataModelFile.modelFileFromModelPackage(url.URLByAppendingPathComponent("contents")) } if url.pathExtension == "xcdatamodleld", let packageName = url.lastPathComponent?.stringByDeletingPathExtension { // FIXME: This is NOT going to find the right file in a versioned xcdatamodeld return DataModelFile.modelFileFromModelPackage(url.URLByAppendingPathComponent(packageName + ".xcdatamodel")) } } return nil } } // /Users/fritza/Dropbox/Swift/Beeswax/16-Measurement/Passer Rating/Passer_Rating.xcdatamodeld/Passer_Rating.xcdatamodel/contents extension DataModelFile : Printable { var description: String { let items = ", ".join(entities.map { $0.name }) return "\(fileURL.lastPathComponent!), \(entities.count) entities: " + items } }
true
e867728450a0b383c16b7223ae38efd7432b0eee
Swift
ericwidjaja/Swift-Fundamentals
/SwiftFundamentalsExercises.playground/Pages/2020-10-29_CollectionTypes_Dictionary.xcplaygroundpage/Contents.swift
UTF-8
5,984
4.625
5
[]
no_license
import UIKit // Dictionary - a collection of unordered pairs of key, value elements. The key (is required) to be unique. // the keys of a dictionary are required to conform to the (Hashable) protocol // Creating a Dictionary // - using generic initializer var usingGenericInitializerDictionary = Dictionary<String, Int>() usingGenericInitializerDictionary["Alex"] = 7 // years print(usingGenericInitializerDictionary) // - using subscript syntax var subscriptDictSyntax = [Int: Int]() subscriptDictSyntax[2020] = 11 print(subscriptDictSyntax) subscriptDictSyntax[2020] = 12 print(subscriptDictSyntax) // - dictionary literal var cities = ["Sweden": "Stockholm", "California": "Los Angeles", "Florida": "Miami"] print(cities) struct Car: Hashable { let brand: String let wheels: Int let color: UIColor } let nissan = Car(brand: "Nissan", wheels: 4, color: .black) let honda = Car(brand: "Honda", wheels: 4, color: .red) var carsDict = [nissan: 10, honda: 15] // Inspecting a Dictionary // - isEmpty if carsDict.isEmpty { print("No more cars in the parking lot") } else { print("There are still cars in the lot.") } // - count print("There are \(carsDict.count) brands of cars in the parking lot") // Accessing keys and values // - subscript [key] // accessing values from a dictionary is always optional because the key may not exist let numberOfNissans = carsDict[nissan] ?? 0 // returns an optional, we will use nil-coelescing to unwrap the optional print("There are \(numberOfNissans) nissans in the parking lot") if let numberOfHondas = carsDict[honda] { // optional binding print("There are \(numberOfHondas) hondas in the lot") } else { print("There a 0 honda's left.") } // - keys let allCars = carsDict.keys // 2 cars for car in allCars { print("Car brand is \(car.brand)") } // - values var gradesDict = ["Rachel": 90, "Alex": 85, "Kim": 95, "Tom": 92] let grades = gradesDict.values print(grades) // - first let firstStudent = gradesDict.first print(gradesDict) print(firstStudent) // - randomElement() let randomStudent = gradesDict.randomElement() print(randomStudent) // Adding Keys and Values // - updateValue() let oldGrade = gradesDict.updateValue(89, forKey: "Alex") print(oldGrade) print(gradesDict) let xaviersGrade = gradesDict.updateValue(100, forKey: "Xavier") print(xaviersGrade) print(gradesDict) // - subscript[key] gradesDict["Esther"] = 79 print(gradesDict) // Removing Keys and Values // - filter() let filteredStudents = gradesDict.filter { $0.value >= 92 } // trailing closure syntax, more coming up in a future lesson on closures print(filteredStudents.count) print(filteredStudents) // - removeValue() let removedValue = gradesDict.removeValue(forKey: "Xavier") print(removedValue) print(gradesDict) // - removeAll() gradesDict.removeAll() print(gradesDict) // Comparing Dictionaries // - using == var dict1 = [2010: 2] var dict2 = [2010: 2] if dict1 == dict2 { print("same dates") } // - using != var dict3 = [2010: 10] var dict4 = [2020: 10] if dict3 != dict4 { print("not equal dates") } // Iterating over Keys and Values // - forEach() gradesDict = ["Rachel": 90, "Alex": 85, "Kim": 95, "Tom": 92] var numbers = [1, 2,3, 4, 5] for num in numbers { print(num) } for (student, grade) in gradesDict { // (key, value) print("\(student) got a \(grade) on the exam.") } // - enumerated() for (index, studentGrade) in gradesDict.enumerated() { // (index, (key, value)) print("\(studentGrade.key) is at index \(index)") } // Finding Elements gradesDict = ["Rachel": 90, "Alex": 85, "Kim": 95, "Tom": 92] // - contains let studentExist = gradesDict.contains { (student, grade) -> Bool in return student == "Kim" } if studentExist { print("Kim's grade has been entered.") } else { print("Student needs to redo the exam.") } // - first // - firstIndex((key, value) -> Bool) -> Index? gradesDict = ["Rachel": 90, "Alex": 85, "Kim": 95, "Tom": 92] let index = gradesDict.firstIndex { $0.value == 95 } print(gradesDict) if let foundIndex = index { print(gradesDict[foundIndex]) } // - min(((key, value), (key, value)) -> Bool) -> (key, value)? // - max(((key, value), (key, value)) -> Bool) -> (key, value)? let maxElement = gradesDict.max { $0.value > $1.value } print(maxElement) // Transforming a Dictionary // - mapValues((Value) -> T) -> Dictionary<Key, T> let numbersDict = [1: 2, 2: 3, 3: 4] // [Int: Int] let valuesSquared = numbersDict.mapValues { $0 * $0 } print(valuesSquared) // - map((key, value) -> T) -> [T] struct Person { let name: String let age: Int } let personDict = ["Rachel": 34, "Henry": 29, "Gabriel": 45, "Tracy": 41] let people = personDict.map { Person(name: $0.key, age: $0.value) } people.forEach { print("\($0.name) is \($0.age) old.") } // - compactMapValues(() -> T?) -> Dictionary<Key, T> // - sorted(((key, value),(key, value)) -> Bool) -> [(key, value)] let sortedPeople = personDict.sorted { $0.value > $1.value } print(sortedPeople) for (name, age) in sortedPeople { print("\(name) is \(age) oid") } // - shuffled() -> [(key, value)] print(personDict) let shuffledElements = personDict.shuffled() print(shuffledElements) /* More resources: Apple documentation: https://developer.apple.com/documentation/swift/dictionary Swift Language Guide: https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html */ let languages = ["Javascript","Swift","Python","C++","Javascript","Python","C++","Javascript","C++","Python","Javascript","Swift","Javascript"] var freqDict = [String:Int]() for language in languages { if let count = freqDict[language] { freqDict[language] = count + 1 } else { freqDict[language] = 1 } } // using the frequency dictionary created earlier to return a new dictionary of [String: String] where the value show a language is "popular" or "not popular" based on the count. If the count is greater than 2 then the language is popular // Hint: use mapValues
true
ded3ba05cdf523703be2e972834c0f735f7e9606
Swift
AginSquash/100-Days-of-SwiftUI
/Days 77 - 78. Challenge/MeetupPeople/MeetupPeople/PersonView.swift
UTF-8
2,053
3.0625
3
[]
no_license
// // PersonView.swift // MeetupPeople // // Created by Vlad Vrublevsky on 01.05.2020. // Copyright © 2020 Vlad Vrublevsky. All rights reserved. // import SwiftUI import MapKit struct PersonView: View { @State private var annotation: MKPointAnnotation? = nil var person: person var body: some View { GeometryReader { geometry in ScrollView(.vertical) { VStack { Text(self.person.name) .font(.headline) Image(uiImage: self.person.image) .resizable() .frame(width: geometry.size.width, height: self.getHeight(frameWidth: geometry.size.width)) .scaledToFit() .clipShape(Rectangle().inset(by: 5)) .shadow(radius: 5) Spacer(minLength: 40) if self.annotation != nil { Text("Encountered \(self.person.date) at:") .font(.headline) MapView(annotation: self.annotation! ) .frame(height: 300) } } } } .onAppear(perform: loadAnotation) } func loadAnotation() { let annotation = MKPointAnnotation() annotation.title = person.name annotation.subtitle = "Meeting with" + person.name annotation.coordinate = CLLocationCoordinate2DMake(person.latitude, person.longtitude) self.annotation = annotation } func getHeight(frameWidth: CGFloat) -> CGFloat { let ratio = frameWidth / person.image.size.width return ratio * person.image.size.height } } struct PersonView_Previews: PreviewProvider { static var previews: some View { PersonView(person: person(image: UIImage(named: "3")! , name: "Vlad", date: "12 03 2020", latitude: 0, longtitude: 0)) } }
true
e4d055bb18888da26fd2d30c8816e180f8b80ca0
Swift
Hepsiburada-mobil-iOS-Bootcamp/HW5_TarkanOzturk
/WeatherApplication/SceneModules/Splash/SplashViewModel.swift
UTF-8
544
2.609375
3
[]
no_license
// // SplashViewModel.swift // WeatherApplication // // Created by Erkut Bas on 16.10.2021. // import Foundation typealias VoidBlock = () -> Void class SplashViewModel { private var splashFinalizeListener: VoidBlock? init(completion: @escaping VoidBlock) { self.splashFinalizeListener = completion } func fireApplicationInitiateProcess() { DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in self?.splashFinalizeListener?() } } }
true
e81729ff3ae607938dbb9e444ecfc3f5c19d1787
Swift
ajdos/VIPERtoCRY
/VIPERtoCRY/DetailScreenModule/View/Cells/FullNameTableViewCell.swift
UTF-8
817
2.78125
3
[]
no_license
// // LabelTableViewCell.swift // VIPERtoCRY // // Created by Айдин Абдурахманов on 21.07.2020. // Copyright © 2020 Айдин Абдурахманов. All rights reserved. // import UIKit class FullNameCell: UITableViewCell { private var userFullNameLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) addSubview(userFullNameLabel) setupViews(with: userFullNameLabel) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension FullNameCell: ConfigurableCell { typealias DataType = User func configure(data: User) { self.userFullNameLabel.text = data.userFullName contentView.backgroundColor = .orange } }
true
63bb7cb6284eea5bcb257f57970fef1ab41483ee
Swift
tjlarson4/BadgerBytes
/BadgerBytes/Main/Models/MenuItem.swift
UTF-8
923
3
3
[]
no_license
// // MenuItem.swift // BadgerBytes // // Created by Thor Larson on 2/24/21. // import UIKit struct MenuItem { let imageURL: String let name: String let price: String let category: String let id: String let inStock: Bool init(name: String, price: String, category: String, imageURL: String, id: String, inStock: Bool) { self.name = name self.price = price self.category = category self.imageURL = imageURL self.id = id self.inStock = inStock } init(id: String, dictionary: [String: Any]) { self.imageURL = dictionary["imageURL"] as? String ?? "" self.name = dictionary["name"] as? String ?? "" self.price = dictionary["price"] as? String ?? "" self.category = dictionary["category"] as? String ?? "" self.inStock = dictionary["inStock"] as? Bool ?? true self.id = id } }
true
b2ebaecf9fbdfe74e47199c78ee027d6ba12b2fc
Swift
sebastianstrus/SideMenuDemo2
/SideMenuDemo2/Controller/ContainerController.swift
UTF-8
7,764
2.765625
3
[]
no_license
// // ViewController.swift // SideMenuDemo2 // // Created by Sebastian Strus on 2019-06-02. // Copyright © 2019 Sebastian Strus. All rights reserved. // import UIKit class ContainerController: UIViewController { var menuView: MenuView! var menuShowing = false var sideMenuXAnchor: NSLayoutConstraint? override func viewDidLoad() { super.viewDidLoad() setupNavBar() setupView() } lazy var containerSideMenu: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.clipsToBounds = true return view }() lazy var waveContainerView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy var waveImageView: UIImageView = { let iv = UIImageView(image: UIImage(named: "wave_shape")?.withRenderingMode(.alwaysTemplate)) iv.tintColor = UIColor.white iv.contentMode = UIView.ContentMode.scaleToFill return iv }() func setupNavBar() { let menuBtn = UIBarButtonItem(image: UIImage(named: "menu_icon")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(toggleMenu)) navigationItem.leftBarButtonItem = menuBtn } func setupView() { menuView = MenuView() view.addSubview(menuView) menuView.pinToEdges(view: view) // add static container for side menu, initially hidden view.addSubview(containerSideMenu) containerSideMenu.topAnchor.constraint(equalTo: view.safeTopAnchor, constant: 0).isActive = true containerSideMenu.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true containerSideMenu.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: -160).isActive = true containerSideMenu.trailingAnchor.constraint(equalTo: view.leadingAnchor, constant: 80).isActive = true //add wave view shape containerSideMenu.addSubview(waveContainerView) waveContainerView.topAnchor.constraint(equalTo: containerSideMenu.topAnchor, constant: 0).isActive = true waveContainerView.bottomAnchor.constraint(equalTo: containerSideMenu.bottomAnchor, constant: 0).isActive = true waveContainerView.widthAnchor.constraint(equalToConstant: 160).isActive = true sideMenuXAnchor = waveContainerView.centerXAnchor.constraint(equalTo: view.leadingAnchor, constant: -80) sideMenuXAnchor?.isActive = true waveContainerView.addSubview(waveImageView) waveImageView.setAnchor(top: waveContainerView.topAnchor, leading: waveContainerView.leadingAnchor, bottom: waveContainerView.bottomAnchor, trailing: waveContainerView.trailingAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0) } @objc func toggleMenu() { if menuShowing { UIView.animate(withDuration: 0.7) { self.sideMenuXAnchor?.isActive = false self.sideMenuXAnchor = self.waveContainerView.centerXAnchor.constraint(equalTo: self.view.leadingAnchor, constant: -80) self.sideMenuXAnchor?.isActive = true self.view.layoutIfNeeded() } } else { UIView.animate(withDuration: 0.7) { self.sideMenuXAnchor?.isActive = false self.sideMenuXAnchor = self.waveContainerView.centerXAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 80) self.sideMenuXAnchor?.isActive = true self.view.layoutIfNeeded() } } menuShowing = !menuShowing } } extension UIView { func createStackView(views: [UIView]) -> UIStackView { let stackView = UIStackView(arrangedSubviews: views) stackView.axis = .vertical stackView.distribution = .fillProportionally stackView.spacing = 10 return stackView } func setAnchor(width: CGFloat, height: CGFloat) { self.setAnchor(top: nil, leading: nil, bottom: nil, trailing: nil, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: width, height: height) } func setAnchor(top: NSLayoutYAxisAnchor?, leading: NSLayoutXAxisAnchor?, bottom: NSLayoutYAxisAnchor?, trailing: NSLayoutXAxisAnchor?, paddingTop: CGFloat, paddingLeft: CGFloat, paddingBottom: CGFloat, paddingRight: CGFloat, width: CGFloat = 0, height: CGFloat = 0) { self.translatesAutoresizingMaskIntoConstraints = false if let top = top { self.topAnchor.constraint(equalTo: top, constant: paddingTop).isActive = true } if let leading = leading { self.leadingAnchor.constraint(equalTo: leading, constant: paddingLeft).isActive = true } if let bottom = bottom { self.bottomAnchor.constraint(equalTo: bottom, constant: -paddingBottom).isActive = true } if let trailing = trailing { self.trailingAnchor.constraint(equalTo: trailing, constant: -paddingRight).isActive = true } if width != 0 { self.widthAnchor.constraint(equalToConstant: width).isActive = true } if height != 0 { self.heightAnchor.constraint(equalToConstant: height).isActive = true } } var safeTopAnchor: NSLayoutYAxisAnchor { if #available(iOS 11.0, *) { return safeAreaLayoutGuide.topAnchor } return topAnchor } var safeLeadingAnchor: NSLayoutXAxisAnchor { if #available(iOS 11.0, *) { return safeAreaLayoutGuide.leadingAnchor } return leadingAnchor } var safeBottomAnchor: NSLayoutYAxisAnchor { if #available(iOS 11.0, *) { return safeAreaLayoutGuide.bottomAnchor } return bottomAnchor } var safeTrailingAnchor: NSLayoutXAxisAnchor { if #available(iOS 11.0, *) { return safeAreaLayoutGuide.trailingAnchor } return trailingAnchor } func setCellShadow() { self.backgroundColor = UIColor.white self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 3, height: 3) self.layer.shadowOpacity = 0.4 self.layer.shadowRadius = 4.0 self.layer.masksToBounds = false self.clipsToBounds = false self.layer.cornerRadius = 4 } func pinToEdges(view: UIView) { setAnchor(top: view.topAnchor, leading: view.leadingAnchor, bottom: view.bottomAnchor, trailing: view.trailingAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0) } func pinToSafeEdges(view: UIView) { setAnchor(top: view.safeTopAnchor, leading: view.safeLeadingAnchor, bottom: view.safeBottomAnchor, trailing: view.safeTrailingAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0) } }
true
ab35fec8ce85af817b6d50e91dba1806d85e9176
Swift
Schwenger/SwiftUtil
/Sources/SwiftUtil/Datastructures/CyclicBuffer.swift
UTF-8
1,205
3.296875
3
[ "MIT" ]
permissive
// // CyclicBuffer.swift // SwiftUtil // // Created by Maximilian Schwenger on 14.07.17. // // TODO: This is a BidirectionalCollection /* A collection storing a fixed number of values. */ public struct CyclicBuffer<Element> { public let size: Int private var values: [Element] private var nextFree: Int public var last: Element { get { return self.getRelative(withOffset: 0) } } init(size: Int, empty: Element) { self.size = size self.values = [Element](repeating: empty, count: size) self.nextFree = 0 } private func getIx(_ offset: Int) -> Int { return mod(nextFree - 1 + offset, self.size) } public func getRelative(withOffset offset: Int) -> Element { return values[getIx(offset)] } public mutating func replaceLast(by val: Element) { self.values[getIx(0)] = val } public static func +=(buffer: inout CyclicBuffer<Element>, elem: Element) { buffer.values[buffer.getIx(1)] = elem buffer.nextFree += 1 } } public extension CyclicBuffer where Element: Emptiable { init(size: Int) { self.init(size: size, empty: Element.empty) } }
true
d56f1764162c46544c54d2b7fa1db33ef11c43e8
Swift
oliviaeg2/InSync
/Old Proj/Interaction/User.swift
UTF-8
5,352
3
3
[]
no_license
// // User.swift // Interaction // // Created by Pedro Sandoval Segura on 7/5/16. // Copyright © 2016 FBU Team Interaction. All rights reserved. // import Foundation import Parse import ParseUI class User: NSObject { //The current logged in user public static var CURRENT_USER: PFUser! //Default profile image name, located in Assets.xcassets public static var DEFAULT_PROFILE_IMAGE_NAME = "default" //Constants for use in resizing current user profile image public static let PROFILE_VIEW_WIDTH = 40 public static let PROFILE_VIEW_HEIGHT = 40 /* Method to create a new user and upload to Parse Fields below must be configured in sign up process -username, password, email -Ex. newUser.username = usernameField.text - parameter newUser: a new PFUser object created on sign-up */ static func createUser(newUser: PFUser) { //Add relevant fields to the PFUser object newUser["author"] = PFUser.currentUser() // Pointer column type that points to PFUser newUser["email"] = newUser["author"].email!! newUser["username"] = newUser["author"].username!! //newUser["last_known_longitude"] = //newUser["last_known_latitude"] = newUser["last_active_time"] = String(NSDate()) newUser["active"] = true newUser["friendships"] = [Friendship]() newUser["profilePicture"] = loadDefaultProfileImageFile() newUser.saveInBackgroundWithBlock { (success: Bool, error: NSError?) in if success { print("New user successfully created") CURRENT_USER = newUser } else { print("error: \(error?.localizedDescription)") } } } /* Method to update user data, as used in Create Profile view. */ static func updateData(name: String, education: String, work: String, location: String) { CURRENT_USER["name"] = name CURRENT_USER["education"] = education CURRENT_USER["work"] = work CURRENT_USER["location"] = location } /* Method to load a user that is already signed in. - parameter user: a new PFUser object that is persisted. */ static func loadUser(user: PFUser) { CURRENT_USER = user } /* Method to load a user's default profile picture on sign up - returns: PFFile for the data in the image */ static func loadDefaultProfileImageFile() -> PFFile? { let defaultImage = UIImage(named: DEFAULT_PROFILE_IMAGE_NAME) let file = Friendship.getPFFileFromImage(defaultImage) return file } /* Method to change a user's profile image - parameter newProfileImage: a new UIImage to set as profile picture */ static func updateProfilePicture(newProfileImage: UIImage) { //Resize image in preparation for upload let resizedImage = resize(newProfileImage, newSize: CGSize(width: PROFILE_VIEW_WIDTH, height: PROFILE_VIEW_HEIGHT)) //Update the profile picture CURRENT_USER["profilePicture"] = Friendship.getPFFileFromImage(resizedImage) //Save CURRENT_USER.saveInBackground() } /* Method to resize an Image - parameter image: image to be resized - parameter newSize: size the picture will be changed to */ class func resize(image: UIImage, newSize: CGSize) -> UIImage { let resizeImageView = UIImageView(frame: CGRectMake(0, 0, newSize.width, newSize.height)) resizeImageView.contentMode = UIViewContentMode.ScaleAspectFill resizeImageView.image = image UIGraphicsBeginImageContext(resizeImageView.frame.size) resizeImageView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } /* Method to change a user's active state on logout/app close */ static func goInactive() { CURRENT_USER["active"] = false CURRENT_USER.saveInBackgroundWithBlock { (success: Bool, error: NSError?) in if success { print("User's active field set to false.") } else { print("error: \(error?.localizedDescription)") } } } /* Method to update the current user's location */ static func updateLocation() { //CURRENT_USER["last_known_longitude"] = //CURRENT_USER["last_known_latitude"] = CURRENT_USER.saveInBackgroundWithBlock { (success: Bool, error: NSError?) in if success { print("User's location fields updated.") } else { print("error: \(error?.localizedDescription)") } } } /* Method for user to log in with username and password - parameter username - parameter password */ static func login(username: String, password: String, withCompletion completion: PFUserResultBlock) { let username = username let password = password PFUser.logInWithUsernameInBackground(username, password: password, block: completion) } }
true
23efb627273a7efab1b133c2e8e2b38e172d4af3
Swift
alexstergiou/SpaceX-coding-demo
/SpaceX/Source/Data/Defaults/Defaults.swift
UTF-8
1,560
3.046875
3
[]
no_license
// // Defaults.swift // SpaceX // // Created by Alex Stergiou on 30/04/2021. // import Foundation let Defaults = UserDefaults.standard //Protocol wrapper around UserDefaults, for the required functionality of this excercise protocol DefaultsType: AnyObject { subscript<T: DefaultsValueType>(key: DefaultsKey<T>) -> T? { get set } func data<T>(_ key: DefaultsKey<T>) -> Data? func hasKey<T>(_ key: DefaultsKey<T>) -> Bool } extension UserDefaults: DefaultsType { public subscript<T: DefaultsValueType>(key: DefaultsKey<T>) -> T? { get { return object(forKey: key.key) as? T } set { set(newValue, forKey: key.key) } } func data<T>(_ key: DefaultsKey<T>) -> Data? { return data(forKey: key.key) } public func hasKey<T>(_ key: DefaultsKey<T>) -> Bool { return object(forKey: key.key) != nil } } public protocol DefaultsValueType { } extension URL: DefaultsValueType { } extension Array: DefaultsValueType { } extension Dictionary: DefaultsValueType { } extension String: DefaultsValueType { } extension Data: DefaultsValueType { } extension Bool: DefaultsValueType { } extension Int: DefaultsValueType { } extension Float: DefaultsValueType { } extension Double: DefaultsValueType { } extension Date: DefaultsValueType { } extension Set: DefaultsValueType { } open class DefaultsKeys { fileprivate init() {} } open class DefaultsKey<T: DefaultsValueType>: DefaultsKeys { public let key: String public init(_ key: String) { self.key = key super.init() } }
true
bf41ba116175291f0ccf89e1bc7c33a76824dbf3
Swift
JiSeobKim/Practice_RxSwift
/Practice_RxSwift/VC/Single/SingleRepository.swift
UTF-8
1,068
3
3
[]
no_license
// // SingleRepository.swift // Practice_RxSwift // // Created by 김지섭 on 2022/02/02. // Copyright © 2022 kimjiseob. All rights reserved. // import RxSwift import RxRelay struct SingleStruct { let title: String } protocol SingleRepository { var dataSources: BehaviorRelay<[SingleStruct]> { get } func fetch() -> Single<Void> } class SingleRepositoryImp: SingleRepository { var dataSources: BehaviorRelay<[SingleStruct]> = .init(value: []) func fetch() -> Single<Void> { let single = Single<Void>.create { single -> Disposable in DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + 0.5) { var previousList = self.dataSources.value let data = SingleStruct(title: "No. \(previousList.count)") previousList.append(data) self.dataSources.accept(previousList) single(.success(())) } return Disposables.create() } return single } }
true
cc4e938485d8e113e4f9a50df6ec88e3b4062a1b
Swift
LiumingGithub/LMFloatingKeeper
/TransitionKit/Animations/AppleAniTransitionProducer.swift
UTF-8
2,828
2.984375
3
[ "MIT" ]
permissive
// // AppleAnimatedTransitioning.swift // LMAnimatedTransition // // Created by 刘明 on 2019/3/16. // Copyright © 2019 com.ming. All rights reserved. // import UIKit public enum AniTransitionTimeFuncion: Int { case easeInOut = 0, easeIn, easeOut, linear public var asAnimationOptions: UIView.AnimationOptions { switch self { case .easeIn: return [.curveEaseIn] case .easeOut: return [.curveEaseOut] case .linear: return [.curveEaseOut] default: return [.curveEaseInOut] } } } // 生成系统自带Transition动画的工厂类 public final class AppleAniTransitionProducer: AniTransitionProducerType { public enum AnimationType: Int { case curl = 0, flipVertical, flipHorizontal,crossDissolve } public var animationType: AnimationType = .flipVertical public var timeFunction: AniTransitionTimeFuncion = .easeInOut public func animation(from fromVC: UIViewController, to toVC: UIViewController, For operation: AniTransitionOperation) -> UIViewControllerAnimatedTransitioning? { if case .unknown = operation { return nil } let appearingView: UIView = toVC.view // animation options from configuration var options = animationType.appleAnimation(for: operation) options.formUnion(timeFunction.asAnimationOptions) let animation = BlockAnimatedTransitioning(animate: { (during, context) in UIView.transition(with: context.containerView, duration: during, options: options, animations: { context.containerView.addSubview(appearingView) }) { (_) in let wasCancelled = context.transitionWasCancelled context.completeTransition(!wasCancelled) } }) return animation } } extension AppleAniTransitionProducer.AnimationType { fileprivate func appleAnimation(for operation: AniTransitionOperation) -> UIView.AnimationOptions { switch (operation, self) { case (.forward, .curl): return [.transitionCurlUp] case (.forward, .flipVertical): return [.transitionFlipFromTop] case (.forward, .flipHorizontal): return [.transitionFlipFromLeft] case (.forward, .crossDissolve): return [.transitionCrossDissolve] case (.backward, .curl): return [.transitionCurlDown] case (.backward, .flipVertical): return [.transitionFlipFromBottom] case (.backward, .flipHorizontal): return [.transitionFlipFromRight] case (.backward, .crossDissolve): return [.transitionCrossDissolve] default: return [] } } }
true
433d7663278386952bf71366f574f9364f6ac22d
Swift
abdulbasit18/WordPuzzle
/WordPuzzle/Features/MainGame/Models/WordModel.swift
UTF-8
380
2.890625
3
[]
no_license
// // WordModel.swift // WordPuzzle // // Created by Abdul Basit on 23/08/2020. // Copyright © 2020 Abdul Basit. All rights reserved. // import Foundation struct WordModel { let english: String let spanish: String } extension WordModel: Codable { enum CodingKeys: String, CodingKey { case english = "text_eng" case spanish = "text_spa" } }
true
3ae92ede975736505e00b7fb473ad4469de3266d
Swift
pqhuy87it/MonthlyReport
/IBDesignableAndIBInspectable/IBDesignableAndIBInspectable/CTLabel.swift
UTF-8
488
2.53125
3
[]
no_license
// // CTLabel.swift // IBDesignableAndIBInspectable // // Created by Exlinct on 1/22/17. // Copyright © 2017 Framgia, Inc. All rights reserved. // import UIKit @IBDesignable class CTLabel: UILabel { @IBInspectable var increaseH: CGFloat = 0 { didSet { self.setNeedsDisplay() } } override func intrinsicContentSize() -> CGSize { var size = super.intrinsicContentSize() size.height += increaseH return size } }
true
875fa882581b37974f3cadab4b401a374dca3ddf
Swift
AsmaHero/TheMovieManagerUpdate
/TheMovieManager/Controller/MovieDetailViewController.swift
UTF-8
4,138
2.8125
3
[]
no_license
// // MovieDetailViewController.swift // TheMovieManager // // Created by Owen LaRosa on 8/13/18. // Copyright © 2018 Udacity. All rights reserved. // import UIKit class MovieDetailViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var watchlistBarButtonItem: UIBarButtonItem! @IBOutlet weak var favoriteBarButtonItem: UIBarButtonItem! var movie: Movie! var isWatchlist: Bool { return MovieModel.watchlist.contains(movie) } var isFavorite: Bool { return MovieModel.favorites.contains(movie) } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = movie.title toggleBarButton(watchlistBarButtonItem, enabled: isWatchlist) toggleBarButton(favoriteBarButtonItem, enabled: isFavorite) //not every movie has a poster that is why we write below code // if it has a posterpathimage , the parameter we passed in struct client //Use [weak self] when loading image in detail view //This ensures the image view is not retained after the detail view (and therefore the image view) no longer exists. to safe memory if let posterpath = movie.posterPath{ TMDBClient.downloadpoasterImage(path: posterpath){ [weak self] (data, error) in guard let data = data else{ return } let image = UIImage(data: data) // once we have image downloaded we just have image in imageview self?.imageView.image = image } } } @IBAction func watchlistButtonTapped(_ sender: UIBarButtonItem) { TMDBClient.markWatchlist(media_id: movie.id, watchlist: !isWatchlist, completion: handleRequestMarkWitchlist(success:error:)) } @IBAction func favoriteButtonTapped(_ sender: UIBarButtonItem) { TMDBClient.markFavorites(media_id: movie.id, favorite: !isFavorite, completion: handleRequestMarkFavorites(success:error:)) } func toggleBarButton(_ button: UIBarButtonItem, enabled: Bool) { if enabled { button.tintColor = UIColor.primaryDark } else { button.tintColor = UIColor.gray } } func handleRequestMarkWitchlist(success: Bool, error: Error?) { if success { if isWatchlist{ //here we filter the item, if it is exist we just delete it , the movie contains the movie id in the array // when we handle we just waiting for a response then completed the steps if not return with something MovieModel.watchlist = MovieModel.watchlist.filter() { $0 != movie.self} } else { // if it is not in watchlist , we just adding that mpvie item to watchlist MovieModel.watchlist.append(movie) } // to highligh or not highligh the button depend on status , such as in the like button toggleBarButton(watchlistBarButtonItem, enabled: isWatchlist) } } func handleRequestMarkFavorites(success: Bool, error: Error?) { if success { if isFavorite{ //here we filter the item, if it is exist we just delete it , the movie contains the movie id in the array // when we handle we just waiting for a response then completed the steps if not return with something MovieModel.favorites = MovieModel.favorites.filter() { $0 != movie.self} } else { // if it is not in watchlist , we just adding that mpvie item to watchlist MovieModel.favorites.append(movie) } // to highligh or not highligh the button depend on status , such as in the like button toggleBarButton(favoriteBarButtonItem, enabled: isFavorite) } } }
true
9302a4f06d85c5765d328590df7e1926456ceb93
Swift
Hsieh-1989/ConnectFour
/ConnectFour/Utility/UIView+constraint.swift
UTF-8
1,105
2.84375
3
[ "MIT" ]
permissive
// // UIView+constraint.swift // ConnectFour // // Created by Hsieh on 2017/11/18. // Copyright © 2017年 Hsieh. All rights reserved. // import UIKit extension UIView { func constraintEqual(to other: UIView, margin: CGFloat = 0) { self.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.leadingAnchor.constraint(equalTo: other.leadingAnchor, constant: margin), self.trailingAnchor.constraint(equalTo: other.trailingAnchor, constant: margin), self.topAnchor.constraint(equalTo: other.topAnchor, constant: margin), self.bottomAnchor.constraint(equalTo: other.bottomAnchor, constant: margin), ]) } } extension CGRect { func shrink(ratio: CGFloat) -> CGRect { let diffWidth = self.width - self.width * ratio let diffHeight = self.height - self.height * ratio return CGRect( x: self.origin.x + diffWidth / 2.0, y: self.origin.y + diffHeight / 2.0, width: self.width * ratio, height: self.height * ratio) } }
true
c28221bf466fc652b12a9ea72a4c10201e716ee7
Swift
DavidWrightOS/Resfeber-labspt13
/Resfeber/Model Controller/ProfileController.swift
UTF-8
7,298
2.59375
3
[ "MIT" ]
permissive
// // ProfileController.swift // LabsScaffolding // // Created by Spencer Curtis on 7/23/20. // Copyright © 2020 Spencer Curtis. All rights reserved. // import OktaAuth import UIKit fileprivate let baseURL = URL(string: "https://resfeber-web-be.herokuapp.com/")! class ProfileController { static let shared = ProfileController() typealias CompletionHandler<T: Decodable> = (Result<T, NetworkError>) -> Void // MARK: - Properties let oktaAuth = OktaAuth(baseURL: URL(string: "https://auth.lambdalabs.dev/")!, clientID: "0oalwkxvqtKeHBmLI4x6", redirectURI: "labs://scaffolding/implicit/callback") private(set) var authenticatedUserProfile: Profile? private var oktaCredentials: OktaCredentials? { try? oktaAuth.credentialsIfAvailable() } private var bearer: Bearer? { guard let credentials = oktaCredentials else { return nil } return Bearer(token: credentials.idToken) } private let router = Router() // MARK: - Init private init() {} // MARK: - API Requests func getAuthenticatedUserProfile(completion: @escaping () -> Void = {}) { getAuthenticatedUserProfile { _ in completion() } } private func getAuthenticatedUserProfile(completion: @escaping CompletionHandler<Profile>) { guard let oktaCredentials = oktaCredentials else { NSLog("Credentials do not exist. Unable to get authenticated user profile from API") completion(.failure(.noAuth)) return } guard let userID = oktaCredentials.userID else { NSLog("User ID is missing.") completion(.failure(.noAuth)) return } getProfile(userID) { result in switch result { case .success(let profile): self.authenticatedUserProfile = profile case .failure(let error): NSLog("Error getting authenticated user profile: \(error)") } completion(result) } } func checkForExistingAuthenticatedUserProfile(completion: @escaping (Bool) -> Void) { getAuthenticatedUserProfile { completion(self.authenticatedUserProfile != nil) } } func updateAuthenticatedUserProfile(_ profile: Profile, with name: String, email: String, avatarURL: URL, completion: @escaping (Profile) -> Void) { let userID = profile.id let updatedProfile = Profile(id: userID, email: email, name: name, avatarURL: avatarURL) guard var request = router.makeURLRequest(method: .put, endpointURL: Endpoints.profiles.url, bearer: bearer), let encodedProfile = encode(updatedProfile) else { completion(profile) return } request.httpBody = encodedProfile router.send(request) { error in if let error = error { NSLog("Error putting updated profile: \(error)") completion(profile) return } self.authenticatedUserProfile = updatedProfile completion(updatedProfile) } } // NOTE: This method is unused, but left as an example for creating a profile. func createProfile(with email: String, name: String, avatarURL: URL) -> Profile? { guard let oktaCredentials = oktaCredentials else { NSLog("Credentials do not exist. Unable to create a profile for the authenticated user") return nil } guard let userID = oktaCredentials.userID else { NSLog("User ID is missing.") return nil } return Profile(id: userID, email: email, name: name, avatarURL: avatarURL) } // NOTE: This method is unused, but left as an example for creating a profile on the scaffolding backend. func addProfile(_ profile: Profile, completion: @escaping () -> Void) { guard var request = router.makeURLRequest(method: .post, endpointURL: Endpoints.profiles.url, bearer: bearer), let encodedProfile = encode(profile) else { completion() return } request.httpBody = encodedProfile router.send(request) { error in if let error = error { NSLog("Error adding profile: \(error)") completion() return } completion() } } func image(for url: URL, completion: @escaping (UIImage?) -> Void) { let dataTask = URLSession.shared.dataTask(with: url) { data, _, error in var fetchedImage: UIImage? defer { DispatchQueue.main.async { completion(fetchedImage) } } if let error = error { NSLog("Error fetching image for url: \(url.absoluteString), error: \(error)") return } guard let data = data, let image = UIImage(data: data) else { return } fetchedImage = image } dataTask.resume() } } //MARK: - Profile API extension ProfileController { func getProfile(_ userID: String, completion: @escaping CompletionHandler<Profile>) { guard let request = router.makeURLRequest(method: .get, endpointURL: Endpoints.profileByUserId(userID).url, bearer: bearer) else { NSLog("Failed retrieving user ID from authenticated user profile.") completion(.failure(.badRequest)) return } router.send(request) { result in completion(result) } } func getAllProfiles(completion: @escaping CompletionHandler<[Profile]>) { guard let request = router.makeURLRequest(method: .get, endpointURL: Endpoints.profiles.url, bearer: bearer) else { NSLog("Failed to GET all profiles from server: badRequest") completion(.failure(.badRequest)) return } router.send(request) { (result: Result<[Profile], NetworkError>) in completion(result) } } } // MARK: - Private extension ProfileController { private func encode<T: Encodable>(_ object: T) -> Data? { do { return try JSONEncoder().encode(object) } catch { NSLog("Error encoding JSON: \(error)") return nil } } } //MARK: - Endpoints extension ProfileController { /// The endpoints used to connect to the Resfeber backend API private enum Endpoints { case profileByUserId(String) case profiles var url: URL { switch self { case .profileByUserId(let userID): return baseURL.appendingPathComponent("profiles/\(userID)/") case .profiles: return baseURL.appendingPathComponent("profiles/") } } } } // MARK: - Notifications extension ProfileController { private func postAuthenticationExpiredNotification() { NotificationCenter.default.post(name: .oktaAuthenticationExpired, object: nil) } }
true
7029f54aca33e719314b21dd6c8faa9b86bf05ee
Swift
jobernas/GymBoard
/GymBoard/Entry.swift
UTF-8
2,577
2.953125
3
[]
no_license
// // Entry.swift // GymBoard // // Created by João Luís on 08/03/17. // Copyright © 2017 JoBernas. All rights reserved. // import Foundation import RealmSwift class Entry : Object { static let TYPE_UNKNOWN = -1 static let TYPE_WEIGHT = 0 static let TYPE_BMI = 1 static let TYPE_FAT_MASS = 2 static let TYPE_WATER = 3 static let TYPE_PHYSICAL_EVAL = 4 static let TYPE_BONE_MASS = 5 static let TYPE_BMR = 6 static let TYPE_IDDMET = 7 static let TYPE_VIS_FAT = 8 static let TYPE_LEAN_MASS = 9 dynamic var id = NSUUID().uuidString dynamic var type: Int = Entry.TYPE_UNKNOWN dynamic var unit: String = "Unknown" dynamic var value: Double = 0.0 dynamic var date: String = "DD-MM-YYYY" /// Primary Key So it Can be updated /// /// - Returns: String ID override class func primaryKey() -> String? { return "id" } /// Get Label for Entry type /// /// - Returns: String with label func getLabel() -> String { switch self.type { case Entry.TYPE_WEIGHT: return "Weight:" case Entry.TYPE_BMI: return "BMI:" case Entry.TYPE_FAT_MASS: return "Fat Mass:" case Entry.TYPE_WATER: return "Water:" case Entry.TYPE_PHYSICAL_EVAL: return "Physical Evaluation:" case Entry.TYPE_BONE_MASS: return "Bone Mass:" case Entry.TYPE_BMR: return "BMR:" case Entry.TYPE_IDDMET: return "IDD Met:" case Entry.TYPE_VIS_FAT: return "Visceral Fat:" case Entry.TYPE_LEAN_MASS: return "Lean Mass:" default: return "Unknown" } } /// save into DB func save() { do { let realm = try Realm() try realm.write { realm.add(self) } } catch let error as NSError { fatalError(error.localizedDescription) } } // Update into DB func update(key: Int?, date:String?, value:Double?, unit:String?) { do { let realm = try Realm() try realm.write { self.type = key ?? self.type self.date = date ?? self.date self.value = value ?? self.value self.unit = unit ?? self.unit realm.add(self, update: true) } } catch let error as NSError { fatalError(error.localizedDescription) } } }
true
0b4de0ce33aa92e412e2959f08bed00d6f10d68a
Swift
v57/Some
/Sources/SomeUI/Screen/Device.swift
UTF-8
2,871
2.703125
3
[]
no_license
#if os(iOS) // // Device.swift // Some // // Created by Димасик on 11/2/17. // Copyright © 2017 Dmitry Kozlov. All rights reserved. // import UIKit import Some extension SomeSettings { public static var lowPowerMode = LowPowerMode() public struct LowPowerMode { public var disableAnimations = true } } public var device = DeviceType(resolution: UIScreen.main.bounds.size) public class Device { public static var isInBackground = false public static var lowPowerMode = _lowPowerMode public static var isSimulator: Bool { return TARGET_OS_SIMULATOR != 0 } private static var _lowPowerMode: Bool { if #available(iOS 9.0, *) { return ProcessInfo.processInfo.isLowPowerModeEnabled } else { return false } } @discardableResult static func updateLowPowerMode() -> Bool { guard !isInBackground else { return false } let newValue = _lowPowerMode guard lowPowerMode != newValue else { return false } lowPowerMode = newValue return true } static func updateType() { device = DeviceType(resolution: UIScreen.main.bounds.size) } } extension DeviceType: Comparable { public static func <(lhs: DeviceType, rhs: DeviceType) -> Bool { return lhs.rawValue < rhs.rawValue } public static func <=(lhs: DeviceType, rhs: DeviceType) -> Bool { return lhs.rawValue <= rhs.rawValue } public static func >=(lhs: DeviceType, rhs: DeviceType) -> Bool { return lhs.rawValue >= rhs.rawValue } public static func >(lhs: DeviceType, rhs: DeviceType) -> Bool { return lhs.rawValue > rhs.rawValue } // public static func <(lhs: DeviceType, rhs: DeviceType) -> Bool { // return lhs.rawValue < rhs.rawValue // } } public enum DeviceType: Int { case iphone4, iphone5, iphone6, iphoneX, iphone6plus, ipad, ipadpro init(resolution: CGSize) { var size = resolution if size.width > size.height { size.rotate() } if size <= DeviceType.iphone4.size { self = .iphone4 } else if size <= DeviceType.iphone5.size { self = .iphone5 } else if size <= DeviceType.iphone6.size { self = .iphone6 } else if size <= DeviceType.iphoneX.size { self = .iphoneX } else if size <= DeviceType.iphone6plus.size { self = .iphone6plus } else if size <= DeviceType.ipad.size { self = .ipad } else { self = .ipadpro } } var size: CGSize { switch self { case .iphone4: return CGSize(320,480) case .iphone5: return CGSize(320,568) case .iphone6: return CGSize(375,667) case .iphoneX: return CGSize(375,812) case .iphone6plus: return CGSize(414,736) case .ipad: return CGSize(768,1024) case .ipadpro: return CGSize(1024,1366) } } public var cornerRadius: CGFloat { switch self { case .iphoneX: return 40 default: return 0 } } } #endif
true
23bf78fd1846401dafbcc3b543d88f958bff9339
Swift
jaarce/MQBoilerplateSwift
/MQBoilerplateSwift/Objects/MQDispatcher.swift
UTF-8
1,162
2.828125
3
[ "Apache-2.0" ]
permissive
// // MQDispatcher.swift // MQBoilerplateSwift // // Created by Matt Quiros on 4/23/15. // Copyright (c) 2015 Matt Quiros. All rights reserved. // import Foundation open class MQDispatcher { /** Executes the specified block in the main thread and waits until it returns. The function guarantees that no deadlocks will occur. If the current thread is the main thread, it executes there. If it isn't, the block is dispatched to the main thread. */ open class func syncRunInMainThread(_ block: () -> Void) { if Thread.isMainThread { block() } else { DispatchQueue.main.sync { block() } } } open class func asyncRunInMainThread(_ block: @escaping () -> Void) { if Thread.isMainThread { DispatchQueue.global().async { block() } } else { DispatchQueue.main.async { block() } } } open class func asyncRunInBackgroundThread(_ block: @escaping () -> Void) { DispatchQueue.global().async { block() } } }
true
661b74ca1691dabbea7f51f5089b46efdaa014a2
Swift
v-mobile/ios_challenge_levon
/iOS Coding Challenge/Extensions/Date.swift
UTF-8
431
2.921875
3
[]
no_license
// // Date.swift // iOS Coding Challenge // // Created by Levon Hovsepyan on 9/18/17. // Copyright © 2017 VOLO. All rights reserved. // import Foundation extension Date { static func from(string: String) -> Date? { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" formatter.timeZone = TimeZone.current return formatter.date(from: string) } }
true
60c75f6640a31a055e7a53397de3f7889aab7637
Swift
perintyler/arch-app
/arch_mobile/arch_mobile/models/Action.swift
UTF-8
931
3.15625
3
[]
no_license
import Foundation struct Action: Decodable { var user: User var venueName: String var eventDate: String static func get_all(callback: @escaping ([Action])->()) { rest.get(path: "action/") { (data, response) in let decoder = JSONDecoder() print(data) print(response) let actions = try! decoder.decode([Action].self, from: data) callback(actions) } } func get_message() -> String { // parse python datetime string to swift Date object let date_from_string = self.eventDate.parseAsDate() // format the date object into a readable string let formatted_date = date_from_string.formatted() return " is going to \(self.venueName) on \(formatted_date)" //return "\(self.user.name) is going to \(self.venueName) on \(formatted_date)" } }
true
bc0f31dd2cb57a0c576b07d23724fe53383efb8e
Swift
voidref/Jackson
/Jackson/Playlist.swift
UTF-8
4,615
2.90625
3
[]
no_license
// // Playlist.swift // Jackson // // Created by Alan Westbrook on 7/15/18. // Copyright © 2018 rockwood. All rights reserved. // import Cocoa protocol PlaylistDelegate: class { func didUpdate(playlist: Playlist, position: Double) func didUpdate(playlist: Playlist, index: Int) func didUpdate(playlist: Playlist) } class Playlist: NSObject, NSTableViewDataSource { struct Keys { static let lastLoaded = "LastFolder" // Remove inna while. static let currentPlaylist = "Current" static let lastIndex = "LastIndex" static let lastProgress = "LastProgress" } weak var delegate: PlaylistDelegate? var lastIndex = 0 var lastProgress = 0.0 var songs: [Song] = [] var index: Int = 0 { didSet { UserDefaults.standard.set(index, forKey: Keys.lastIndex) delegate?.didUpdate(playlist: self, index: index) } } var nextIndex: Int { if songs.count > index + 1 { return index + 1 } else { return 0 } } var position: Double = 0 { didSet { UserDefaults.standard.set(position, forKey: Keys.lastProgress) delegate?.didUpdate(playlist: self, position: position) } } override init() { super.init() loadSongs() } func add(urls: [URL]) { let data = urls.map { Song(url: $0) } let songSet = Set(songs) songs = Array<Song>(songSet.union(data)) sortSongs() songsUpdated() } func addFrom(folder url: URL) { loadSongsIn(folder: url) } func delete(at index: Int) { songs.remove(at: index) songsUpdated() if songs.count > 0 { if index == songs.count { self.index = index - 1 } else { self.index = index } } } func deleteAll() { songs.removeAll() songsUpdated() self.index = 0 } func loadSongs() { let defaults = UserDefaults.standard // Tech debt, remove this when our userbase has pretty much all // updated to the new version if let lastLoaded = defaults.url(forKey: Keys.lastLoaded) { loadSongsIn(folder: lastLoaded) defaults.removeObject(forKey: Keys.lastLoaded) } else { loadPlaylist() } index = defaults.integer(forKey: Keys.lastIndex) position = defaults.double(forKey: Keys.lastProgress) } func advance() { index = nextIndex } // MARK: - Private private func loadSongsIn(folder url: URL) { guard let urls = FileManager.default.suburls(at: url) else { return } let supported = ["m4a", "mp3", "aac", "flac", "wav"] let songURLs = urls.compactMap { url -> URL? in return supported.contains(url.pathExtension.lowercased()) ? url : nil } add(urls: songURLs) } private func sortSongs() { songs.sort { (lhs, rhs) -> Bool in return lhs < rhs } } private func songsUpdated() { delegate?.didUpdate(playlist: self) savePlaylist() } private func loadPlaylist() { let decoder = JSONDecoder() let defaults = UserDefaults.standard if let songsData = defaults.object(forKey: Keys.currentPlaylist) as? Data, let songsActual = try? decoder.decode([Song].self, from: songsData) { songs = songsActual } } private func savePlaylist() { let encoder = JSONEncoder() if let coded = try? encoder.encode(songs) { UserDefaults.standard.set(coded, forKey: Keys.currentPlaylist) } // Remove as above when we don't think anyone will have the 'old' version of the app. UserDefaults.standard.removeObject(forKey: Keys.lastLoaded) } // MARK: - TableView Datasource @objc func numberOfRows(in tableView: NSTableView) -> Int { return songs.count } } extension FileManager { func suburls(at url: URL) -> [URL]? { let urls = enumerator(atPath: url.path)?.compactMap { e -> URL? in guard let s = e as? String else { return nil } let relativeURL = URL(fileURLWithPath: s, relativeTo: url) return relativeURL.absoluteURL } return urls } }
true
036dac20835efe467023babf21ab5c25cf40e5d2
Swift
xuvw/HKAnimation
/HKAnimation/Classes/HKAnimation.swift
UTF-8
522
2.625
3
[ "MIT" ]
permissive
// // HKAnimation.swift // HKAnimation // // Created by heke on 16/7/1. // Copyright © 2016年 mhk. All rights reserved. // import Foundation import UIKit class HKAnimation { var animations = [String : CAAnimation]() var animation: CAAnimation? //real Animation[s] var animationKey = "" func installTo(layer: CALayer) { if animation != nil { layer .addAnimation(animation!, forKey: animationKey) }else { print("animation not exist!!!"); } } }
true