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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
63f172d662e0c47bceae9abb220f832c4e86040e
|
Swift
|
tomasanda/assignment-gis
|
/FIIT-PDT-Project/FIIT-PDT-Project/Generic/Networking/NetworkServiceManager.swift
|
UTF-8
| 8,873
| 2.515625
| 3
|
[] |
no_license
|
//
// NetworkServiceManager.swift
// Mealur
//
// Created by Tomáš Anda on 04/01/2018.
// Copyright © 2018 FIIT-PDT. All rights reserved.
//
import Alamofire
import SwiftyJSON
public class NetworkServiceManager: NSObject {
static let sharedInstance = NetworkServiceManager()
var header = ["Content-type": "application/json", "Accept": "application/json", "Accept-Language": "en-US", "Cache-Control" : "no-cache"]
var headerMultipart = ["Content-Type": "multipart/form-data", "Accept": "application/json", "Accept-Language": "en-US", "Cache-Control" : "no-cache"]
func makeRequest(_ serviceCall: ServiceCall, processedErrorCodes: Set<Int> = [401,403], vc: UIViewController? = nil, completion: @escaping (_ responseCode: ResponseStatusCode, _ result: JSON?) -> Void) {
var processedErrorCodes = processedErrorCodes + [401,403]
if Environment.current.type == .production {
processedErrorCodes = processedErrorCodes + [500]
}
let requestUrl = Environment.current.host.url + serviceCall.requestUrl!
Alamofire
.request(requestUrl,
method: serviceCall.requestMethod,
parameters: serviceCall.requestParams,
encoding: serviceCall.encoding,
headers: header)
.responseJSON { response in
var statusCode: Int
if response.response != nil {
statusCode = response.response!.statusCode
} else {
statusCode = 501
}
if statusCode == 403, let data = response.data {
let json = JSON(data)
if json["message"].stringValue == "Error" {
statusCode = 422
}
}
if statusCode > 399, let data = response.data, !processedErrorCodes.contains(statusCode) {
self.getErrorMessage(json: JSON(data), vc: vc)
}
switch statusCode {
case 200...204:
if let json = try? JSON(data: response.data!) {
completion(.responseStatusOk, json)
} else {
completion(.responseStatusOk, nil)
}
case 400,402:
completion(.responseStatusAuthError(statusCode), nil)
case 401:
completion(.responseStatusAuthError(statusCode), nil)
case 403:
completion(.responseStatusAuthError(statusCode), nil)
case 404:
completion(.responseStatusApplicationError(statusCode), nil)
case 405:
completion(.responseStatusApplicationError(statusCode), nil)
case 422:
completion(.responseStatusApplicationError(statusCode), nil)
case 500:
completion(.responseStatusBusinessError, nil)
default:
completion(.responseStatusCommunicationError(statusCode), nil)
}
}
}
func getErrorMessage(json: JSON, vc: UIViewController? = nil) {
if let title = json["message"].string, !title.isEmpty {
var message = json["errors"].string
if message == nil, let dictionary = json["errors"].dictionary {
for (_, val) in dictionary {
if val.array != nil {
let errors = val.array!.map {$0.stringValue}
message = errors.joined(separator: "\n")
}
}
}
// ErrorHandleController.shared.error(vc: vc, title: title.localized, message: message)
}
}
func downloadImage(imageUrl: String?, completion: @escaping (_ result: UIImage?, _ url: String?) -> Void) {
if imageUrl == nil {
return completion(nil, nil)
}
if let url = URL(string: imageUrl!) {
let session = URLSession(configuration: URLSessionConfiguration.default)
session.dataTask(with: url, completionHandler: { data, response, error in
guard let data = data, error == nil else {
return completion(nil, imageUrl!)
}
DispatchQueue.main.async {
completion(UIImage(data: data), imageUrl!)
}
}).resume()
} else {
completion(nil, imageUrl!)
}
}
fileprivate func showErrorHUD(title:String, subtitle:String) {
//showe only if online (if app is offline - do not spam user with error messages)
// if ReachabilityManager.shared.isReachable {
// HUDPlayer.shared.showErrorHUD(title: title, subTitle: subtitle)
// }
}
func makeRequestMultipart(_ serviceCall: ServiceCall, processedErrorCodes: Set<Int> = [401,403], mimeType: String = "image/jpeg", filename: String = "avatar.jpg", completion: @escaping (_ responseCode: ResponseStatusCode, _ result: JSON?) -> Void) {
var processedErrorCodes = processedErrorCodes + [401,403]
if Environment.current.type == .production {
processedErrorCodes = processedErrorCodes + [500]
}
let requestUrl = Environment.current.host.url + serviceCall.requestUrl
Alamofire.upload(
multipartFormData: { MultipartFormData in
for (key, value) in serviceCall.requestParams! {
switch key {
case "avatar", "image":
if value as? UIImage != nil {
MultipartFormData.append((value as! UIImage).jpegData(compressionQuality: 0.8)!, withName: key, fileName: filename, mimeType: mimeType)
}
default:
if value is Double {
MultipartFormData.append(("\(value)").data(using: String.Encoding.utf8)!, withName: key)
} else {
MultipartFormData.append((value as? String ?? "").data(using: String.Encoding.utf8)!, withName: key)
}
}
}
}, to: requestUrl,
method: serviceCall.requestMethod,
headers: headerMultipart,
encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress { (progress) in
DispatchQueue.main.async() {
NotificationCenter.default.post(name: Notification.Name("uploadProgress"), object: (serviceCall.info ?? "", Float(progress.fractionCompleted)))
}
}
upload.responseJSON { (response) in
print(response.result.value ?? "nil")
var statusCode: Int
if response.response != nil {
statusCode = response.response!.statusCode
} else {
statusCode = 501
}
if statusCode > 399 && response.data != nil && !processedErrorCodes.contains(statusCode) {
self.getErrorMessage(json: JSON(response.data!))
}
switch statusCode {
case 200...204:
if let json = try? JSON(data: response.data!) {
completion(.responseStatusOk, json)
} else {
completion(.responseStatusOk, nil)
}
case 401:
completion(.responseStatusAuthError(statusCode), nil)
case 403:
completion(.responseStatusAuthError(statusCode), nil)
case 400,402:
completion(.responseStatusAuthError(statusCode), nil)
case 404,405,422:
completion(.responseStatusApplicationError(statusCode), nil)
case 500:
completion(.responseStatusBusinessError, nil)
default:
completion(.responseStatusCommunicationError(statusCode), nil)
}
}
case .failure(let encodingError):
print(encodingError)
completion(.responseStatusNoData, nil)
}
})
}
}
| true
|
08dc84affc6c1449e861e32f1ac4a150c14c12de
|
Swift
|
ddgold/CardRef
|
/CardRef/Enums/Legality.swift
|
UTF-8
| 853
| 3.484375
| 3
|
[] |
no_license
|
//
// Legality.swift
// CardRef
//
// Created by Doug Goldstein on 6/11/19.
// Copyright © 2019 Doug Goldstein. All rights reserved.
//
import Foundation
enum Legality: String, Codable {
case legal = "legal"
case notLegal = "not_legal"
case restricted = "restricted"
case banned = "banned"
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let raw = try container.decode(String.self)
if let legality = Legality(rawValue: raw) {
self = legality
}
else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid legality value: '\(raw)'")
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
| true
|
f523ca9817c3398816e6aa371fbb989d850194af
|
Swift
|
mayurmori/UIButtonWithShadow
|
/UIButtonWithShadow/ViewController.swift
|
UTF-8
| 712
| 2.71875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// UIButtonWithShadow
//
// Created by Mayur Mori on 10/09/19.
// Copyright © 2019 Mayur Mori. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// MARK: - IBOUTLET -
@IBOutlet weak var btnWithShadow: UIButton!
// MARK: - VIEW LIFE CYCLE METHODS -
override func viewDidLoad() {
super.viewDidLoad()
self.setupUI()
}
// MARK: - FUNCTIONS -
private func setupUI() {
btnWithShadow.layer.shadowColor = UIColor.black.cgColor
btnWithShadow.layer.shadowOffset = CGSize(width: 5, height: 5)
btnWithShadow.layer.shadowRadius = 5
btnWithShadow.layer.shadowOpacity = 1.0
}
}
| true
|
a03708fd4a8719045dff3faacfddee76b06cb1d9
|
Swift
|
butcallmeJo/holbertonschool-higher_level_programming
|
/silicon_valley_is_too_small_for_everybody/TechCompanies/TechCompanies/TechCompaniesListViewController.swift
|
UTF-8
| 4,013
| 2.640625
| 3
|
[] |
no_license
|
//
// TechCompaniesListViewController.swift
// TechCompanies
//
// Created by Josquin Gaillard on 6/8/16.
// Copyright © 2016 Josquin Gaillard. All rights reserved.
//
import UIKit
class TechCompaniesListViewController: UITableViewController {
var schoolList: [Entity]!
var techCompanyList: [Entity]!
let techDetailSegue = "techDetailSg"
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Silicon Valley Entities"
techCompanyList = EntitiesHelper.getTechCompanies()
schoolList = EntitiesHelper.getSchools()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
if section == 0 {
// return # of companies as # of rows
return techCompanyList.count
}
else {
// return # of schools as # of rows
return schoolList.count
}
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
// return title for section
if section == 0 {
return "Tech Companies"
}
else {
return "Schools"
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("techCell", forIndexPath: indexPath)
// Configure the cell...
if indexPath.section == 0 {
cell.textLabel?.text = techCompanyList[indexPath.row].name
cell.detailTextLabel?.text = "I love working"
}
else if indexPath.section == 1 {
cell.textLabel?.text = schoolList[indexPath.row].name
cell.detailTextLabel?.text = "I love studying"
}
return cell
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
print ("TESSSTTT")
if segue.identifier == "techDetailSegue" {
print ("segue works test")
let indexPath = self.tableView.indexPathForCell(sender as! UITableViewCell)
if let destinationViewController = segue.destinationViewController as? TechCompanyDetailViewController { // set destination vc to detail view controller
print ("destinationViewController thingy test")
// if cast was successful,
// pass appropriate entity to represent to new view controller, according to section and row.
if indexPath!.section == 0 {
destinationViewController.entity = techCompanyList[indexPath!.row]
print (techCompanyList[indexPath!.row])
print ("test")
}
else if indexPath!.section == 1 {
destinationViewController.entity = schoolList[indexPath!.row]
}
}
}
}
}
| true
|
3d9f862cbcfd5eced284642c83b491d80dd65c32
|
Swift
|
hakkabon/BNF-Parser
|
/Sources/ebnf/main.swift
|
UTF-8
| 557
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
import ArgumentParser
import Files
import Tokenizer
import BNF
struct EBNF: ParsableCommand {
@Argument(help: "Input file name to lexer") var input: String
@Flag(help: "Pretty printed BNF parse tree") var tree: Bool = false
mutating func run() throws {
var level: Parser.TraceOptions = [Parser.TraceOptions.bnf]
if tree {
level.remove(Parser.TraceOptions.bnf)
level.insert(Parser.TraceOptions.bnftree)
}
let _ = try Parser(grammar: File(path: input), level: level)
}
}
EBNF.main()
| true
|
6a1aadd946e524b44052cc924dae9974b8ef90d7
|
Swift
|
Ram-cs/Outside-College-Projects-Swift-Firebase
|
/ForTesting/ForTesting/ViewController.swift
|
UTF-8
| 1,327
| 2.984375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// ForTesting
//
// Created by Ram Yadav on 7/27/17.
// Copyright © 2017 Ram Yadav. All rights reserved.
//
import UIKit
import Firebase
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var zipCodeText: UITextField!
@IBOutlet weak var amountText: UITextField!
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
zipCodeText.delegate = self
amountText.delegate = self
}
@IBAction func switchButton(_ sender: UISwitch) {
if sender.isOn {
textField.isUserInteractionEnabled = true
} else {
textField.isUserInteractionEnabled = false
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let text = zipCodeText.text else {
return true
}
//write only and 5 characters
let newLength = text.characters.count + string.characters.count - range.length
//give only digits
let allowcharacterSet = CharacterSet.decimalDigits
let characterSet = CharacterSet(charactersIn: string)
return allowcharacterSet.isSuperset(of: characterSet) && newLength <= 5
}
}
| true
|
7d51d397260522a431401d58b926a6b7ffd2590d
|
Swift
|
VRGsoftUA/mygoal-viper-ios
|
/MyGoal/Modules/GoalCategories/Interactor/SMGoalCategoriesInteractor.swift
|
UTF-8
| 528
| 2.53125
| 3
|
[] |
no_license
|
//
// SMGoalCategoriesInteractor.swift
// Project: MyGoal
//
// Module: GoalCategories
//
// By OLEKSANDR SEMENIUK 7/26/17
// VRG Soft 2017
//
import Foundation
final class SMGoalCategoriesInteractor {
weak var output: SMGoalCategoriesInteractorOutput!
}
extension SMGoalCategoriesInteractor: SMGoalCategoriesInteractorInput {
func obtainTitle() {
output.didObtainTitle(text: "GoalCategories")
}
func obtainCategories() {
output.didObtainCategories(categories: SMCategoryType().getCategoties())
}
}
| true
|
1bf67e7608cb2fe73a219bb82eb132211780dfd1
|
Swift
|
yyokii/QuizApp
|
/quizApp/ViewController.swift
|
UTF-8
| 4,559
| 2.96875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// quizApp
//
// Created by 東原与生 on 2017/04/23.
// Copyright © 2017年 yoki. All rights reserved.
//
import UIKit
//テーブルビューに関係する定数 ??ここでやんなくてもよくね
struct GuidanceTableStruct {
static let cellCount: Int = 5
static let cellSectionCount: Int = 1
}
class ViewController: UIViewController,UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource {
//Outlet接続をした部品
@IBOutlet var guideTableView: UITableView!
//テーブルビューに表示する文言の内容を入れておくメンバ変数
var guidanceArray: NSMutableArray = []
//画面出現のタイミングに読み込まれる処理
override func viewWillAppear(_ animated: Bool) {
//ガイダンス用のテーブルビューに表示するテキストを(CSV形式で準備)読み込む
let csvBundle = Bundle.main.path(forResource: "guidance", ofType: "csv")
//CSVデータの解析処理
do {
//CSVデータを読み込む、改行があるので\rが含まれている
var csvData: String = try String(contentsOfFile: csvBundle!, encoding: String.Encoding.utf8)
csvData = csvData.replacingOccurrences(of: "\r", with: "")
//改行を基準にしてデータを分割する読み込む
let csvArray = csvData.components(separatedBy: "\n")
//print(csvArray)
//CSVデータの行数分ループさせる
for line in csvArray {
//カンマ区切りの1行を["aaa", "bbb", ... , "zzz"]形式に変換して代入する
let parts = line.components(separatedBy: ",")
self.guidanceArray.add(parts)
}
//print(self.guidanceArray)
} catch let error as NSError {
print(error.localizedDescription)
}
}
override func viewDidLoad() {
super.viewDidLoad()
//ナビゲーションのデリゲート設定
self.navigationController?.delegate = self
self.navigationItem.title = "食べ合わせクイズ"
//テーブルビューのデリゲート設定
self.guideTableView.delegate = self
self.guideTableView.dataSource = self
//自動計算の場合は必要
//self.guideTableView.estimatedRowHeight = 100
//self.guideTableView.rowHeight = UITableViewAutomaticDimension
//Xibのクラスを読み込む、nibname はファイル名を入力
let nibDefault:UINib = UINib(nibName: "guidanceCell", bundle: nil)
self.guideTableView.register(nibDefault, forCellReuseIdentifier: "guidanceCell")
}
func numberOfSections(in tableView: UITableView) -> Int {
return GuidanceTableStruct.cellSectionCount
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return GuidanceTableStruct.cellCount
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//Xibファイルを元にデータを作成する
let cell = tableView.dequeueReusableCell(withIdentifier: "guidanceCell") as? guidanceCell
//取得したデータを読み込ませる
//配列 → 0番目:タイトル, 1番目:説明文,
let guidanceData: NSArray = self.guidanceArray[indexPath.row] as! NSArray
cell!.guidanceTitle.text = guidanceData[0] as? String
cell!.guidanceDescription.text = guidanceData[1] as? String
//セルのアクセサリタイプと背景の設定
cell!.accessoryType = UITableViewCellAccessoryType.none
cell!.selectionStyle = UITableViewCellSelectionStyle.none
return cell!
}
//データをリロードした際に読み込まれるメソッド、使ってる??
func reloadData() {
self.guideTableView.reloadData()
}
//クイズ画面に遷移するアクション
@IBAction func goQuizAction(_ sender: AnyObject) {
self.performSegue(withIdentifier: "goQuiz", sender: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| true
|
b44c745238663ce1d8294c094b6a62b8f9ee8e0a
|
Swift
|
FeifanZhang/IOS-Projects
|
/Assign4/Assign4/ColorPatchView.swift
|
UTF-8
| 963
| 2.890625
| 3
|
[] |
no_license
|
//
// ColorPatchView.swift
// Assign4
//
// Created by 张非凡 on 10/12/18.
// Copyright © 2018 Steven Senger. All rights reserved.
//
import UIKit
class ColorPatchView: UIView {
var color = UIColor.white
@IBOutlet var redSlider: UISlider!
@IBOutlet var greenSlider: UISlider!
@IBOutlet var blueSlider: UISlider!
@IBAction func updateColor() {
self.setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let red = CGFloat(self.redSlider.value)
let green = CGFloat(self.greenSlider.value)
let blue = CGFloat(self.blueSlider.value)
self.color = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
context?.setFillColor(self.color.cgColor)
context?.fill(rect)
context?.setStrokeColor(red: 0, green: 0, blue: 0, alpha: 1)
context?.setLineWidth(3.0)
context?.stroke(rect)
}
}
| true
|
33180bc815c526286ef06453dc6ac42b832b63eb
|
Swift
|
joshlong95/Todooey
|
/Todooey/ToDoViewController.swift
|
UTF-8
| 1,437
| 2.890625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Todooey
//
// Created by Joshua Long on 14/08/2019.
// Copyright © 2019 Joshua Long. All rights reserved.
//
import UIKit
class ToDoViewController: UITableViewController {
let itemArray = ["Live", "Laugh", "Love"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath)
cell.textLabel?.text = itemArray[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(itemArray[indexPath.row])
if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCell.AccessoryType.checkmark{
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCell.AccessoryType.none
}
else {
tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCell.AccessoryType.checkmark
}
}
}
| true
|
e2907bf7c16de37f6789d7ed72d675a7e6d85666
|
Swift
|
keshk26/weatherSwift
|
/WeatherSwift/Forecast.swift
|
UTF-8
| 2,084
| 2.96875
| 3
|
[] |
no_license
|
//
// Forecast.swift
// WeatherSwift
//
// Created by Keshav on 8/20/17.
// Copyright © 2017 Keshav. All rights reserved.
//
import Foundation
import CoreLocation
let kAPI_KEY:String = "7e16895662d3dc898860576f62722a97"
class Forecast: NSObject, CLLocationManagerDelegate {
var locationManager : CLLocationManager?
// This initalizer starts updating location to get the temperature data
override init() {
super.init()
locationManager = CLLocationManager()
locationManager?.delegate = self
locationManager?.desiredAccuracy = kCLLocationAccuracyBest
locationManager?.requestWhenInUseAuthorization()
locationManager?.startUpdatingLocation()
}
func getTemperateForLocation(_ newLocation: CLLocation, completion: @escaping (Temperature)->Void) {
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(newLocation) { (placemarks, error) in
guard let placemark = placemarks?.first else {
return
}
let forcastURL = URL(string: "https://api.darksky.net/forecast/\(kAPI_KEY)/\(newLocation.coordinate.latitude),\(newLocation.coordinate.longitude)")
let request = URLRequest(url: forcastURL!)
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
guard let data = data else { return }
let parsedData = JSON(data: data)
let tempData = Temperature(json: parsedData, city: placemark.locality!)
completion(tempData)
})
task.resume()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManager?.stopUpdatingLocation()
locationManager?.delegate = nil
NotificationCenter.default.post(name:Notification.Name("DID_UPDATE_LOCATION"), object: nil, userInfo: ["location": locations[0]])
}
}
| true
|
8734329e6f2399bdbf1ebc9da4e74fb76ed371e8
|
Swift
|
wei800919/Hahago
|
/Hahago_Practice/Hahago_Practice/Hahago_Practice/Hahago_Practice/ViewController.swift
|
UTF-8
| 5,373
| 2.765625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Hahago_Practice
//
// Created by honeywld on 2019/5/20.
// Copyright © 2019 honeywld. All rights reserved.
//
import UIKit
import HealthKit
import CoreMotion
class ViewController: UIViewController {
let pedonmeter:CMPedometer = CMPedometer()
var healthStore = HKHealthStore()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func authoriztion(){
// 判读是否支持‘健康’
if HKHealthStore.isHealthDataAvailable() {
healthStore.requestAuthorization(toShare: nil, read: dataTypesRead()) { (isAuthorize, error) in
print(isAuthorize)
print(error)
}
} else {
print("can't support!")
}
}
private func dataTypesRead() -> Set<HKObjectType>? {
guard let stepCount = HKObjectType.quantityType(forIdentifier: .stepCount),
let distance = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning) else { return nil }
var set = Set<HKObjectType>()
set.insert(stepCount)
set.insert(distance)
return set
}
func getStepCount(){
if CMPedometer.isStepCountingAvailable(){
//開始時間
let startTime = getStartTime()
//結束時間
let endTime = getEndTime()
//第一種
//獲取一個時間範圍內的資料最大7天 引數 開始時間,結束時間, 一個閉包
pedonmeter.queryPedometerData(from: startTime, to: endTime) { (pedometerData, error) in
if error != nil{
print("error:\(error)")
}
else{
print("開始時間:\(startTime)")
print("結束時間:\(endTime)")
print("步數===\(pedometerData!.numberOfSteps)")
print("距離===\(pedometerData!.distance)")
}
}
}
}
func getStepCountFromAPP(){
let healthStore: HKHealthStore? = {
if HKHealthStore.isHealthDataAvailable() {
return HKHealthStore()
} else {
return nil
}
}()
let stepsCount = HKQuantityType.quantityType(
forIdentifier: HKQuantityTypeIdentifier.stepCount)
let dataTypesToWrite = NSSet(object: stepsCount)
let dataTypesToRead = NSSet(object: stepsCount)
healthStore?.requestAuthorization(toShare: nil ,
read: dataTypesToRead as! Set<HKObjectType>,
completion: { [unowned self] (success, error) in
if success {
print("success")
} else {
print(error.debugDescription)
}
})
let now = Date()
let exactlySevenDaysAgo = Calendar.current.date(byAdding: DateComponents(day: 0), to: now)!
let startOfSevenDaysAgo = Calendar.current.startOfDay(for: exactlySevenDaysAgo)
let predicate = HKQuery.predicateForSamples(withStart: startOfSevenDaysAgo, end: now, options: .strictStartDate)
let query = HKStatisticsCollectionQuery.init(quantityType: stepsCount!,
quantitySamplePredicate: predicate,
options: .cumulativeSum,
anchorDate: startOfSevenDaysAgo,
intervalComponents: DateComponents(day: 1))
query.initialResultsHandler = { query, results, error in
guard let statsCollection = results else {
// Perform proper error handling here...
return
}
statsCollection.enumerateStatistics(from: startOfSevenDaysAgo, to: now) { statistics, stop in
if let quantity = statistics.sumQuantity() {
let stepValue = quantity.doubleValue(for: HKUnit.count())
print(stepValue)
}
}
}
// Don't forget to execute the Query!
healthStore?.execute(query)
}
func getStartTime() -> Date {
let datef = DateFormatter()
datef.dateFormat = "yyyy-MM-dd"
let stringdate = datef.string(from: getEndTime())
print("當天日期:\(stringdate)")
let tdate = datef.date(from: stringdate)
let zone = TimeZone.current
let interval = zone.secondsFromGMT(for: tdate!)
let nowday = tdate!.addingTimeInterval(TimeInterval(interval))
return nowday
}
func getEndTime() -> Date {
let date = Date()
let zone = TimeZone.current
let interval = zone.secondsFromGMT(for: date)
let nowDate = date.addingTimeInterval(TimeInterval(interval))
return nowDate
}
}
| true
|
023daa3019d5e1e6e4d1be4aa491fbc9e4c3538e
|
Swift
|
skelpo/serversideswift
|
/Sources/App/Routes.swift
|
UTF-8
| 1,479
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
import Vapor
final class Routes: RouteCollection {
let view: ViewRenderer
init(_ view: ViewRenderer) {
self.view = view
}
func build(_ builder: RouteBuilder) throws {
builder.get("/") { req in
return try self.view.make("pages/home", ["home": true])
}
builder.get("/about") { req in
return try self.view.make("pages/about", ["about": true])
}
builder.get("/speakers") { req in
return try self.view.make(
"pages/speakers",
["speakers": Speaker.allSpeaker()]
)
}
builder.get("/speakers", Speaker.parameter) { req in
let speaker = try req.parameters.next(Speaker.self)
return try self.view.make(
"pages/speaker-profile",
["speakers": true, "speaker": speaker]
)
}
builder.get("/location") { req in
return try self.view.make("pages/location", ["location": true])
}
builder.get("/sponsors") { req in
return try self.view.make("pages/sponsors", ["sponsors": true])
}
builder.get("thank-you") { req in
return try self.view.make("pages/thank-you")
}
builder.get("tickets") { req in
return try self.view.make("pages/tickets")
}
builder.get("/code-of-conduct") { req in
return try self.view.make("pages/code-of-conduct", ["code-of-conduct": true])
}
builder.get("/faq") { req in
return try self.view.make("pages/faq", ["faq": true])
}
}
}
| true
|
7763cb93c20619d930f145689390fa32b8921ba3
|
Swift
|
Mukul444/Neostore-IOS-Swift4.2-
|
/Neostore/Models/Entities/Response/GetUserData/Datum.swift
|
UTF-8
| 1,010
| 2.953125
| 3
|
[] |
no_license
|
//
// Datum.swift
// Neostore
//
// Created by webwerks1 on 12/04/21.
// Copyright © 2021 webwerks. All rights reserved.
//
import Foundation
struct Datum : Codable {
let productCategories : [ProductCategory]?
let totalCarts : Int?
let totalOrders : Int?
let userData : UserDatum?
enum CodingKeys: String, CodingKey {
case productCategories = "product_categories"
case totalCarts = "total_carts"
case totalOrders = "total_orders"
case userData = "user_data"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
productCategories = try values.decodeIfPresent([ProductCategory].self, forKey: .productCategories)
totalCarts = try values.decodeIfPresent(Int.self, forKey: .totalCarts)
totalOrders = try values.decodeIfPresent(Int.self, forKey: .totalOrders)
userData = try values.decodeIfPresent(UserDatum.self, forKey: .userData)
}
}
| true
|
374167756e05f5101ab20c7691ee2b39e0b74bf5
|
Swift
|
paxos/LifeCycleBug
|
/LifeCycleBug/ContentView.swift
|
UTF-8
| 567
| 2.890625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// LifeCycleBug
//
// Created by Patrick Dinger on 2/22/21.
//
import SwiftUI
struct ContentView: View {
@State var toggle = false
var body: some View {
VStack {
Button("Toggle") {
self.toggle = !self.toggle
}
Spacer()
if toggle {
MyViewControllerRepresentable()
}
}
.frame(width: 600, height: 600)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
241bfddfdac02455c635fe0730f81bdcc8438159
|
Swift
|
YuryRadchenko/CodeExample
|
/AppCodeExample/Extension/UITableView.swift
|
UTF-8
| 2,266
| 2.734375
| 3
|
[] |
no_license
|
//
// UITableView.swift
// AppCodeExample
//
// Created Yury Radchenko on 4/9/19.
// Copyright © 2019 iPadchenko. All rights reserved.
//
import UIKit
struct TableOption {
var separatorStyle: UITableViewCell.SeparatorStyle = .singleLine
var separatorInset: UIEdgeInsets = .zero
var separatorColor: UIColor = .gray
var contentInset: UIEdgeInsets = UIEdgeInsets(top: 0, bottom: 0)
var tableFooterView: UIView? = UIView()
var isUserInteractionEnabled = true
var isScrollEnabled = true
var showsVerticalScrollIndicator = true
var showsHorizontalScrollIndicator = false
var estimatedRowHeight: CGFloat = 44.0
var rowHeight: CGFloat = UITableView.automaticDimension
var keyboardDismissMode: UIScrollView.KeyboardDismissMode = .interactive
}
extension UITableView {
func config(options: TableOption) {
self.separatorStyle = options.separatorStyle
self.separatorColor = options.separatorColor
self.separatorInset = options.separatorInset
self.contentInset = options.contentInset
self.tableFooterView = options.tableFooterView
self.isUserInteractionEnabled = options.isUserInteractionEnabled
self.isScrollEnabled = options.isScrollEnabled
self.showsVerticalScrollIndicator = options.showsVerticalScrollIndicator
self.showsHorizontalScrollIndicator = options.showsHorizontalScrollIndicator
self.estimatedRowHeight = options.estimatedRowHeight
self.rowHeight = options.rowHeight
self.keyboardDismissMode = options.keyboardDismissMode
}
}
extension UITableView {
func reloadData(completion: @escaping () -> Void) {
UIView.animate(withDuration: 0, animations: {
self.reloadData()
}) { (complited) in
completion()
}
}
func selectRow(at indexPath: IndexPath, animated: Bool, scrollPosition: UITableView.ScrollPosition, completion: @escaping () -> Void) {
UIView.animate(withDuration: 0, animations: {
self.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}) { (complited) in
completion()
}
}
}
| true
|
5e123235281b572989d0da82c9f969d5e4403a21
|
Swift
|
gb4iosdev/TTH_TechDegree_Unit-10
|
/NASA/Extension/VisualEffectView.swift
|
UTF-8
| 896
| 2.75
| 3
|
[] |
no_license
|
//
// VisualEffectView.swift
// NASA
//
// Created by Gavin Butler on 30-12-2019.
// Copyright © 2019 Gavin Butler. All rights reserved.
//
import UIKit
extension UIView {
//Add blurr effect to the view. Used in Eye in the Sky component when user is resetting location search
func addBlurrEffect() {
let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.regular)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = self.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
blurEffectView.alpha = 0.6
self.addSubview(blurEffectView)
}
//Remove all blurr effects from the view.
func removeBlurrEffect() {
for subView in self.subviews {
if subView is UIVisualEffectView {
subView.removeFromSuperview()
}
}
}
}
| true
|
c86a55332470663bdd6f2aa5335fa87faf716c4c
|
Swift
|
nhatduy129/ios-core
|
/Project/1.LifeCycle/1.LifeCycle/ChildPageVC.swift
|
UTF-8
| 2,281
| 3.109375
| 3
|
[] |
no_license
|
//
// ChildPageVC.swift
// 1.LifeCycle
//
// Created by Duy Nguyen on 3/4/19.
// Copyright © 2019 Duy Nguyen. All rights reserved.
//
import UIKit
class ChildPageVC: UIViewController {
@IBOutlet private weak var timerLabel: UILabel!
var cnt: Int = 0
var myTimer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
print("ChildPageVC: viewDidLoad")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("ChildPageVC: viewWillAppear")
//Nếu dùng [unowned self] thì về cơ bản có thể gỡ được strong reference và deinit sẽ được gọi, tuy nhiên sẽ bị crash vì closure vẫn tiếp tục được gọi, do đó crash ở dòng "self.cnt += 1" vì self lúc này là nil
//Nếu dùng [weak self], bên trong dùng self?, cách này OK, gỡ được strong reference và ko bị crash, tuy nhiên, closure vẫn bị gọi đi gọi lại
//Chính vì vậy phải code như bên dưới, sử dụng guard let là best practice.
// Timer.scheduledTimer(withTimeInterval: 3, repeats: true, block: {[weak self] timer in
// guard let `self` = self else {
// timer.invalidate()
// return
// }
// self.cnt += 1
// self.timerLabel.text = "\(String(describing: self.cnt))"
// })
weak var weakSelf = self
myTimer = Timer.scheduledTimer(timeInterval: 3, target: weakSelf!, selector: #selector(timeCount), userInfo: nil, repeats: true)
}
@objc func timeCount() {
self.cnt += 1
self.timerLabel.text = "\(String(describing: self.cnt))"
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("ChildPageVC: viewDidAppear")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
print("ChildPageVC: viewWillDisappear")
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
//myTimer?.invalidate()
print("ChildPageVC: viewDidDisappear")
}
deinit {
print("ChildPageVC: deinit")
}
}
| true
|
4f362e44f2639dedeb0fd015975f63853e99116d
|
Swift
|
stripe/stripe-ios
|
/StripePaymentSheet/StripePaymentSheet/Source/Helpers/IntentStatusPoller.swift
|
UTF-8
| 3,021
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
//
// IntentStatusPoller.swift
// StripePaymentSheet
//
// Created by Nick Porter on 9/6/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
import StripeCore
import StripePayments
protocol IntentStatusPollerDelegate: AnyObject {
func didUpdate(paymentIntent: STPPaymentIntent)
}
class IntentStatusPoller {
let apiClient: STPAPIClient
let clientSecret: String
let maxRetries: Int
private var lastStatus: STPPaymentIntentStatus = .unknown
private var retryCount = 0
private let pollingQueue = DispatchQueue(label: "com.stripe.intent.status.queue")
private var nextPollWorkItem: DispatchWorkItem?
weak var delegate: IntentStatusPollerDelegate?
var isPolling: Bool = false {
didSet {
// Start polling if we weren't already polling
if !oldValue && isPolling {
forcePoll()
} else if !isPolling {
nextPollWorkItem?.cancel()
}
}
}
init(apiClient: STPAPIClient, clientSecret: String, maxRetries: Int) {
self.apiClient = apiClient
self.clientSecret = clientSecret
self.maxRetries = maxRetries
}
// MARK: Public APIs
public func beginPolling() {
isPolling = true
}
public func suspendPolling() {
isPolling = false
}
public func forcePoll() {
fetchStatus(forcePoll: true)
}
// MARK: Private functions
private func fetchStatus(forcePoll: Bool = false) {
guard forcePoll || (isPolling && retryCount < maxRetries) else { return }
retryCount += 1
apiClient.retrievePaymentIntent(withClientSecret: clientSecret) { [weak self] paymentIntent, _ in
guard let isPolling = self?.isPolling else {
return
}
// If latest status is different than last known status notify our delegate
if let paymentIntent = paymentIntent,
paymentIntent.status != self?.lastStatus,
isPolling {
self?.lastStatus = paymentIntent.status
self?.delegate?.didUpdate(paymentIntent: paymentIntent)
}
// If we are polling and have retries left, schedule a status fetch
if isPolling, let maxRetries = self?.maxRetries, let retryCount = self?.retryCount {
self?.retryWithExponentialDelay(retryCount: maxRetries - retryCount) {
self?.fetchStatus()
}
}
}
}
private func retryWithExponentialDelay(retryCount: Int, block: @escaping () -> Void) {
// Add some backoff time
let delayTime = TimeInterval(
pow(Double(1 + maxRetries - retryCount), Double(2))
)
nextPollWorkItem = DispatchWorkItem {
block()
}
guard let nextPollWorkItem = nextPollWorkItem else { return }
pollingQueue.asyncAfter(deadline: .now() + delayTime, execute: nextPollWorkItem)
}
}
| true
|
e26a8bd3452e70ed6e696b32f7a8d8caf5d2676d
|
Swift
|
Nikita2933/AvitoInternship
|
/avitoTest/View/CollectionViewCell.swift
|
UTF-8
| 5,198
| 2.578125
| 3
|
[] |
no_license
|
import UIKit
class CollectionViewCell: UICollectionViewCell {
var titleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = .max
label.textAlignment = .left
label.font = UIFont.boldSystemFont(ofSize: 22)
return label
}()
var descriptionTitleLabel: UILabel = {
let label = UILabel()
label.numberOfLines = .max
label.textAlignment = .left
label.font = UIFont.systemFont(ofSize: 17)
return label
}()
var priceLabel: UILabel = {
let label = UILabel()
label.font = UIFont.boldSystemFont(ofSize: 16)
return label
}()
var selectImage: UIImageView = {
let imageView = UIImageView()
imageView.isHidden = true
imageView.image = UIImage(named: "checmark")
return imageView
}()
var imageCell = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
setupCell()
contentView.bottomAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 10).isActive = true
contentView.widthAnchor.constraint(equalToConstant: UIScreen.main.bounds.width - 20).isActive = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func iSelected() {
if (!isSelected) {
self.selectImage.isHidden = true
} else {
self.selectImage.isHidden = false
}
}
private func setupCell() {
setupImageView()
setupSelectView()
setupTitleLabel()
setupDescriptionTitile()
setupPriceLabel()
self.backgroundColor = #colorLiteral(red: 0.972464025, green: 0.9726034999, blue: 0.9724335074, alpha: 1)
}
func setupCell(withData: List) {
titleLabel.text = withData.title
descriptionTitleLabel.text = withData.listDescription
priceLabel.text = withData.price
iSelected()
LoadImage.loadImage(imgString: withData.icon.icon) { [self] (result) in
switch result {
case .success(let image):
DispatchQueue.main.async {
imageCell.image = UIImage(data: image)
}
case .failure(let error):
print(error)
DispatchQueue.main.async {
imageCell.image = UIImage(named: "cancel" )
}
}
}
}
private func setupImageView() {
contentView.addSubview(imageCell)
imageCell.translatesAutoresizingMaskIntoConstraints = false
imageCell.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
imageCell.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 15).isActive = true
imageCell.widthAnchor.constraint(equalToConstant: 55).isActive = true
imageCell.heightAnchor.constraint(equalToConstant: 55).isActive = true
}
private func setupSelectView() {
contentView.addSubview(selectImage)
selectImage.translatesAutoresizingMaskIntoConstraints = false
selectImage.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 25).isActive = true
selectImage.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -20).isActive = true
selectImage.widthAnchor.constraint(equalToConstant: 25).isActive = true
selectImage.heightAnchor.constraint(equalToConstant: 25).isActive = true
}
private func setupTitleLabel() {
contentView.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20).isActive = true
titleLabel.leftAnchor.constraint(equalTo: self.imageCell.rightAnchor, constant: 10).isActive = true
titleLabel.rightAnchor.constraint(equalTo: self.selectImage.leftAnchor, constant: -10).isActive = true
}
private func setupDescriptionTitile() {
contentView.addSubview(descriptionTitleLabel)
descriptionTitleLabel.translatesAutoresizingMaskIntoConstraints = false
descriptionTitleLabel.topAnchor.constraint(equalTo: self.titleLabel.bottomAnchor, constant: 5).isActive = true
descriptionTitleLabel.leftAnchor.constraint(equalTo: self.titleLabel.leftAnchor, constant: 0).isActive = true
descriptionTitleLabel.rightAnchor.constraint(equalTo: self.selectImage.leftAnchor, constant: 0).isActive = true
}
private func setupPriceLabel() {
contentView.addSubview(priceLabel)
priceLabel.translatesAutoresizingMaskIntoConstraints = false
priceLabel.topAnchor.constraint(equalTo: self.descriptionTitleLabel.bottomAnchor, constant: 5).isActive = true
priceLabel.leftAnchor.constraint(equalTo: self.descriptionTitleLabel.leftAnchor, constant: 0).isActive = true
priceLabel.rightAnchor.constraint(equalTo: self.selectImage.leftAnchor, constant: 0).isActive = true
}
}
| true
|
b86501512431129382765acc38e9858c2a3dcd6a
|
Swift
|
waqassultancheema/MindValley-Demo
|
/MindValleyTest/MindValley_iOS_Demo/MindValley_iOS_Demo/Models/UrlsBo.swift
|
UTF-8
| 1,409
| 3.140625
| 3
|
[] |
no_license
|
//
// UrlBo.swift
// MindValley_iOS_Demo
//
// Created by Waqas Sultan on 3/17/19.
// Copyright © 2019 Waqas Sultan. All rights reserved.
//
import UIKit
struct UrlsBo: Codable {
let raw, full, regular, small: String
let thumb: String
}
extension UrlsBo {
init(data: Data) throws {
self = try newJSONDecoder().decode(UrlsBo.self, from: data)
}
init(_ json: String, using encoding: String.Encoding = .utf8) throws {
guard let data = json.data(using: encoding) else {
throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
}
try self.init(data: data)
}
init(fromURL url: URL) throws {
try self.init(data: try Data(contentsOf: url))
}
func with(
raw: String? = nil,
full: String? = nil,
regular: String? = nil,
small: String? = nil,
thumb: String? = nil
) -> UrlsBo {
return UrlsBo(
raw: raw ?? self.raw,
full: full ?? self.full,
regular: regular ?? self.regular,
small: small ?? self.small,
thumb: thumb ?? self.thumb
)
}
func jsonData() throws -> Data {
return try newJSONEncoder().encode(self)
}
func jsonString(encoding: String.Encoding = .utf8) throws -> String? {
return String(data: try self.jsonData(), encoding: encoding)
}
}
| true
|
b189c7402d4282d93474ad57e8b0cec763c05577
|
Swift
|
malctreacy/tip_calculator_app
|
/tipster/ViewController.swift
|
UTF-8
| 1,400
| 2.765625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// tipster
//
// Created by Malcolm Treacy on 3/31/19.
// Copyright © 2019 Malcolm Treacy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var billTotalLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func onTap(_ sender: Any) {
// Closes the digit pad on tap of any area in the view.
// print("hello")
view.endEditing(true)
}
@IBAction func calculate_tip(_ sender: Any) {
// 1. Get the bill amounts
// let = const
// ?? everything to the left of the symbols, if it is not
// valid just change it to zero (eg. pasted text)
let bill = Double(billField.text!) ?? 0
// 2. Calculate the tip and total
let tipPercentages = [0.15, 0.18, 0.2]
let tip = bill * tipPercentages[tipControl.selectedSegmentIndex]
let total = bill + tip
// 3. Update the tip and totals
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
}
}
| true
|
2e1e133fc555ea5bfca01e601b7663479be513fc
|
Swift
|
hirosyrup/comet
|
/comet/Model/api/callApi/CallShowPullRequest.swift
|
UTF-8
| 1,321
| 2.75
| 3
|
[
"CC-BY-4.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// CallShowPullRequest.swift
// comet
//
// Created by 岩井 宏晃 on 2020/06/06.
// Copyright © 2020 koalab. All rights reserved.
//
import Foundation
import Moya
class CallShowPullRequest {
private let id: Int
private let repositoryOwner: String
private let repositorySlug: String
private let userName: String
private let password: String
init(id: Int, repositoryOwner: String, repositorySlug: String, userName: String, password: String) {
self.id = id
self.repositoryOwner = repositoryOwner
self.repositorySlug = repositorySlug
self.userName = userName
self.password = password
}
func execute() throws -> ShowPullRequestResponse {
let semaphore = DispatchSemaphore(value: 0)
var result: Result<Moya.Response, Moya.MoyaError>!
let requestHeader = RequestHeader(userName: userName, password: password)
let provider = MoyaProvider<ShowPullRequest>()
provider.request(ShowPullRequest(id: id, repositoryOwner: repositoryOwner, repositorySlug: repositorySlug, requestHeader: requestHeader)) { _result in
result = _result
semaphore.signal()
}
semaphore.wait()
return try DecodeJson<ShowPullRequestResponse>(result: result).decode()
}
}
| true
|
18dc436a169aeea384354cbef1e0a0cb0625210f
|
Swift
|
ethan510010/SceneChangeWithNavigation
|
/SceneChangeWithNavigation/SecondViewController.swift
|
UTF-8
| 1,225
| 2.65625
| 3
|
[] |
no_license
|
//
// SecondViewController.swift
// SceneChangeWithNavigation
//
// Created by EthanLin on 2017/12/26.
// Copyright © 2017年 EthanLin. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
var infoFromViewOne:Int?
var sceneArray = ["scene1","scene2","scene3","scene4","scene5","scene6","scene7","scene8","scene9","scene10"]
@IBOutlet weak var myImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
if let okInfo = infoFromViewOne{
myImageView.image = UIImage(named: sceneArray[okInfo-1])
}
// Do any additional setup after loading the view.
}
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
|
94e4dd24b01199e4bbad42aa0e7ad7f5ca2d6ab0
|
Swift
|
simonboots/json2codable
|
/Sources/json2codable/Merge.swift
|
UTF-8
| 4,353
| 3.734375
| 4
|
[
"MIT"
] |
permissive
|
/// Merge two types if possible
///
/// During the parsing phase, it is often not clear what the type of a value exactly is. For example, parsing this array:
/// ```
/// [null, 123]
/// ```
/// Looking at the first value (`null`) it is not clear what the type of the array should be and it is stored as a `.optional(.unknown)` type.
/// Only after the parser sees the second value(`123`), it can attempt to merge the two types (`.optional(.unknown)` and `int`). The final
/// value for the array content is `.optional(.int)`.
///
/// - Parameters:
/// - type1: A `JSONType`
/// - type2: Another `JSONType`
func merge(_ type1: JSONType, _ type2: JSONType) -> Result<JSONType, J2CError> {
guard type1 != type2 else { return .success(type1) }
switch (type1, type2) {
// Int + Bool = Int
case (.int, .bool),
(.bool, .int):
return .success(.int)
// Double + Bool = Double
case (.double, .bool),
(.bool, .double):
return .success(.double)
// Double + Int = Double
case (.double, .int),
(.int, .double):
return .success(.double)
// unknown + T = T
case (.unknown, let other),
(let other, .unknown):
return .success(other)
// optional(T) + optional(S) = optional(merge(T,S))
case (.optional(let optionalType1), .optional(let optionalType2)):
return merge(optionalType1, optionalType2).map(JSONType.optional)
// optional(T) + S = optional(merge(T,S))
case (.optional(let optionalType), let type),
(let type, .optional(let optionalType)):
return merge(type, optionalType).map(JSONType.optional)
// dict1 + dict2 = mergeDicts(dict1, dict2)
case (.dict(let content1), .dict(let content2)):
return mergeDicts(content1, content2)
// array1(T) + array2(S) = array(merge(T, S))
case (.array(let content1), .array(let content2)):
return merge(content1, content2).map(JSONType.array)
default:
return .failure(.unableToMergeTypes("Unable to merge type \(type1) with \(type2)"))
}
}
/// Merge dictionaries
///
/// The keys and their types of two dictionaries can be merged together into a single dictionary. This is neccessary if the content type of an array
/// are dictionaries and we need to find a common dictionary type that can store any of the dictionaries in the array. For example:
/// ```
/// [
/// {
/// "commonKey1": true,
/// "commonKey2": 123,
/// "uniqueKey": "someValue",
/// },
/// {
/// "commonKey1": false,
/// "commonKey2": null,
/// }
/// ]
/// ```
/// Here, we have two dictionaries with some overlap. The types of overlapping keys are merged using the `merge` function. Types for unique keys that only
/// exist in some of the dictionaries are automatically changed to `.optional`.
/// - Parameters:
/// - d1: Contents of a `JSONType.dict`
/// - d2: Contents of another `JSONType.dict`
private func mergeDicts(_ d1: [String: JSONType], _ d2: [String: JSONType]) -> Result<JSONType, J2CError> {
let d1Keys = Set(d1.keys)
let d2Keys = Set(d2.keys)
var resultDict: [String: JSONType] = [:]
// Common keys that exist in both dictionaries must have same type or be mergeable
let commonKeys = d1Keys.intersection(d2Keys)
for key in commonKeys {
guard let d1Type = d1[key], let d2Type = d2[key] else {
return .failure(.internalInconsistencyError)
}
let result = merge(d1Type, d2Type)
guard case .success(let mergedType) = result else {
return result
}
resultDict[key] = mergedType
}
// Types for unique keys that exist in only one dictionary are changed to `.optional(T)`
let uniqueKeys = d1Keys.union(d2Keys).subtracting(commonKeys)
for key in uniqueKeys {
guard let type = d1[key] ?? d2[key] else {
return .failure(.internalInconsistencyError)
}
let result = merge(.optional(.unknown), type)
guard case .success(let mergedType) = result else {
return result
}
resultDict[key] = mergedType
}
return .success(.dict(resultDict))
}
| true
|
d72343fdf8f0a2fd9584e4f663e22eaac80169a2
|
Swift
|
ArchyVan/LearniOS
|
/SwiftLearn/LearnSwift/LearnSwift/main.swift
|
UTF-8
| 1,337
| 3.8125
| 4
|
[] |
no_license
|
//
// main.swift
// LearnSwift
//
// Created by Archy on 15/6/15.
// Copyright (c) 2015年 Van. All rights reserved.
//
import Foundation
print("Hello, World!")
func sum(num1: Int, num2: Int) ->Int
{
return num1 + num2
}
func minus(num1: Int, num2: Int) ->Int
{
return num1 - num2
}
func divide(num1: Int, num2: Int) ->Int
{
return num1 / num2
}
var c = sum(10, num2: 20)
print(c)
func printResult(fn:(Int, Int)->Int,num1:Int,num2:Int)
{
print(fn(num1,num2))
}
printResult(sum, num1: 10, num2: 22)
func printLine()
{
print("-------")
}
printLine()
func howToDo(day:Int) ->Void ->Void
{
func goToWork(){
print("上班去。。。。")
}
func haveFun(){
print("踢足球。。。。")
}
if day == 6 || day == 7 {
return haveFun
} else {
return goToWork
}
}
var fn = howToDo(5)
fn()
func addStudent(name:String, age:NSInteger){
// assert(age > 0, "年龄参数不正确")
print("添加了一个学生:姓名=\(name),年龄=\(age)")
}
addStudent("Jack", age: 20)
addStudent("Jake", age: -10)
addStudent("Rose", age: 22)
func sum(num1: Int,num2:Int,num3:Int)->Int
{
return num1 + num2 + num3
}
var a:Int = sum(10, num2: 20, num3: 30)
print(a)
var 国家 = "中国"
print("国家是\(国家)")
testFunction()
| true
|
5b1dcf93a6e4481d61127e1a02f04a44c7be4ea0
|
Swift
|
hvgmbdmg/Mobile-App-Programming-NCCU-2017S
|
/HW/HW1-Bookstore/Book Store.playground/Pages/Practice - Functions.xcplaygroundpage/Contents.swift
|
UTF-8
| 4,206
| 4.25
| 4
|
[] |
no_license
|
/*:
# Your shopping cart
Now, it's your turn to create your shopping list.
Assume that you want to buy following books:
* "Digital Fortress" by "Dan Brown", $9.99
* "Angels & Demons" by "Dan Brown", $17.00
* "The Da Vinci Code" by "Dan Brown", $9.99
* "Deception Point" by "Dan Brown", $17.00
* "Harry Potter and the Goblet of Fire" by "J.K. Rowling", $12.99
* "Harry Potter and the Half-Blood Prince" by "J.K. Rowling", $12.99
* "Harry Potter and the Deathly Hallows" by "J.K. Rowling", $14.99
* "旅行與讀書" by "詹宏志", $12.00
* "國宴與家宴" by "王宣一", $7.99
Then, let's create a book store first:
*/
var bookStore = BookStore()
/*:
Now start to feed data to the book store.
You have to prepare following functions:
1. A function which returns the name of authors in a set or a list.
_Note, you have to remove duplicated authors._
2. A function which returns the totoal price of books to purchase
3. A function which returns the number of books to buy
4. A function which returns a book with its title, author, and price by a given index.
If the index is out of bound, return `nil`.
*/
/*
same name will be ignore.
*/
let books: [[String: String]] = [
["author": "Dan Brown", "title": "Digital Fortress", "price": "9.99"],
["author": "Dan Brown", "title": "Angels & Demons", "price": "17.00"],
["author": "Dan Brown", "title": "The Da Vinci Code", "price": "9.99"],
["author": "Dan Brown", "title": "Deception Point", "price": "17.00"],
["author": "J.K. Rowling", "title": "Harry Potter and the Goblet of Fire", "price": "12.99"],
["author": "J.K. Rowling", "title": "Harry Potter and the Half-Blood Prince", "price": "12.99"],
["author": "J.K. Rowling", "title": "Harry Potter and the Deathly Hallows", "price": "14.99"],
["author": "詹宏志", "title": "旅行與讀書", "price": "12.00"],
["author": "王宣一", "title": "國宴與家宴", "price": "7.99"]
]
//books.count
/*
books.count
books.description
books.capacity
books.customMirror
books.endIndex
books.first
books.endIndex
Double(books[1]["price"]!)
*/
//.author
//books[1].index()
//books[2].
//books[1].values("price");
//let booktest = Set(books[1..5].value);
//var authorName = [String]();
//var smallEvenNumbers: Set<String>;
/*for bookItem in 0 ..< books.count {
authorName.append((books[bookItem].first?.value)!)
}
var set3 = Set(authorName)
*/
//books[1].first?.value
//Test
//bookStore = BookStore.from(books)
// Use this
func distinctAuthors() -> Set<String> {
var authorsList = [String]();
for bookItem in 0 ..< books.count {
authorsList.append((books[bookItem].first?.value)!)
}
return Set(authorsList);
}
// or this
distinctAuthors().sorted();
/*
func distinctAuthors() -> [String] {
var authorsList = [String]();
for bookItem in 0 ..< books.count {
authorsList.append((books[bookItem].first?.value)!)
}
let distinctAuthorsList = Set(authorsList);
return [String](distinctAuthorsList);
//return authorsList;
}*/
//distinctAuthors();
// then
bookStore.setDataSource(authorsGetter: distinctAuthors);
func totalBookPrice() -> Double {
var allPrice: Double = 0.0;
for bookItem in 0 ..< books.count {
allPrice += Double(books[bookItem]["price"]!)!;
}
return allPrice;
}
totalBookPrice();
bookStore.setDataSource(priceCalculator: totalBookPrice);
func getBook(at index: Int) -> (title: String, author: String, price: Double)? {
if index > books.count-1 || index < 0 {
return nil;
}
let title: String = books[index]["title"]!;
let author: String = books[index]["author"]!;
let price: Double = Double(books[index]["price"]!)!;
//return (title: books[index]["title"]!, author: books[index]["author"]!, price: Double(books[index]["price"]!)!);
return (title, author, price);
}
//getBook(at: 1)
//getBook(at: 9)
bookStore.setDataSource(bookGetter: getBook(at:))
//Double(books[1]["price"]!);
//books[1]["author"];
//books[1]["title"];
/*:
Finally, let's show the book store shopping cart:
*/
bookStore.showInPlayground()
//: ---
//: [<- Previous](@previous) | [Next ->](@next)
| true
|
c38aa8e1c2845eb5997d11e5ff99c4cfd7e9a424
|
Swift
|
RichAppz/Cuvva-Theme
|
/Theme/Components/CuvvaUIButton.swift
|
UTF-8
| 2,110
| 2.59375
| 3
|
[] |
no_license
|
//
// CuvvaUIButton.swift
// swift-theme-demo
//
// Created by Rich Mucha on 10/04/2019.
// Copyright © 2019 Cuvva. All rights reserved.
//
import Foundation
import UIKit
class CuvvaUIButton: UIButton, CuvvaUIComponentProtocol {
//================================================================================
// MARK: - Properties
//================================================================================
var theme: CuvvaTheme?
@IBInspectable var themeFont: String? {
didSet {
guard let font = themeFont?.font else { return }
titleLabel?.font = font
}
}
@IBInspectable var themeColor: String? {
didSet {
setTitleColor(themeColor?.color, for: .normal)
}
}
@IBInspectable var themeBackgroundColor: String? {
didSet {
backgroundColor = themeBackgroundColor?.color
}
}
//================================================================================
// MARK: - Initialization
//================================================================================
init() {
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
//================================================================================
// MARK: - CuvvaUIComponent Protocol
//================================================================================
func handleThemeChangedNotification(notification: Notification) { }
func loadTheme(_ theme: CuvvaTheme) {
setTitleColor(themeColor?.color, for: .normal)
backgroundColor = themeBackgroundColor?.color
if let shadow = themeFont?.shadow {
layer.shadowColor = shadow.color?.cgColor
layer.shadowOffset = shadow.offset
layer.shadowRadius = shadow.blurRadius
layer.shadowOpacity = 1
}
guard let font = themeFont?.font else { return }
titleLabel?.font = font
}
}
| true
|
b8dca4f522a6fc334566d39b63992080fc8d7cb4
|
Swift
|
sagayathri/MoviesExercise
|
/CurveExercise/CurveExercise/Helper/Persistance.swift
|
UTF-8
| 4,714
| 3.015625
| 3
|
[] |
no_license
|
//
// Persistance.swift
// CurveExercise
//
import Foundation
import CoreData
class Persistance {
static let sharedInstance = Persistance()
var movieFetched: Movie?
var context: NSManagedObjectContext? = nil
init() {
movieFetched = nil
context = persistentContainer.viewContext
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "CurveExercise")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
if context!.hasChanges {
do {
try context!.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
//MARK:- Saves all movies to coredata
func saveToCoreData(moviesToStore: [CoreMovies]) {
let entity = NSEntityDescription.entity(forEntityName: "MoviesStored", in: context!)
for item in moviesToStore {
let movie = NSManagedObject(entity: entity!, insertInto: context)
movie.setValue(item.id, forKey: "id")
movie.setValue(item.name, forKey: "name")
movie.setValue(item.date, forKey: "date")
movie.setValue("\(item.voteAvg)", forKey: "voteAvg")
movie.setValue(item.isFav, forKey: "isFav")
do {
try context?.save()
} catch {
print("Failed to saved your message")
}
}
}
//MARK:- Fetches all movies from coredata
func fetchMoviesFromCoreData() -> [CoreMovies]? {
var movies: [CoreMovies] = []
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MoviesStored")
request.returnsObjectsAsFaults = false
do {
let result = try context!.fetch(request)
for data in result as! [NSManagedObject] {
let movieFetched = CoreMovies(id: data.value(forKey: "id") as! Int,
voteAvg: Double(data.value(forKey: "voteAvg") as! String)!,
name: data.value(forKey: "name") as! String,
isFav: data.value(forKey: "isFav") as! Bool,
date: data.value(forKey: "date") as! String)
movies.append(movieFetched)
}
} catch {
print("Failed")
}
return movies
}
//MARK:- Clears saved Movies From CoreData
func clearAllMovies() {
do {
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "MoviesStored")
let deleteALL = NSBatchDeleteRequest(fetchRequest: deleteFetch)
try self.context?.execute(deleteALL)
try self.context?.save()
} catch {
let errmsg = error as NSError
print("Deleting movies, error = ", errmsg)
}
}
//MARK:- Saves imageData to coredata
func saveImage(imageData: NSData) {
let entity = NSEntityDescription.entity(forEntityName: "Image", in: context!)
let image = NSManagedObject(entity: entity!, insertInto: context)
image.setValue(imageData, forKey: "imageData")
do {
try context?.save()
} catch {
print("Failed to save image")
}
}
//MARK:- Fetches imageData from coredata
func fetchImage() -> [NSData]? {
var imageData: [NSData] = []
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Image")
do {
let result = try context!.fetch(request)
for data in result as! [NSManagedObject] {
imageData.append((data.value(forKey: "imageData") as? NSData)!)
}
} catch {
print("Failed")
}
return imageData
}
//MARK:- Clears saved images From CoreData
func clearAllImages() {
do {
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Image")
let deleteALL = NSBatchDeleteRequest(fetchRequest: deleteFetch)
try self.context?.execute(deleteALL)
try self.context?.save()
} catch {
let errmsg = error as NSError
print("Deleting images, error = ", errmsg)
}
}
}
| true
|
da0d47bcd83720269acc7fb9df5da7e707616637
|
Swift
|
dennovc/WhatToWatch
|
/WhatToWatch/Data/Repositories/DefaultImageRepository.swift
|
UTF-8
| 1,267
| 3.09375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// DefaultImageRepository.swift
// WhatToWatch
//
// Created by Denis Novitsky on 23.04.2021.
//
import Foundation
final class DefaultImageRepository {
private let dataTransferService: DataTransferService
private var cacheService: AnyCacheService<String, Data>
init<T: CacheService>(dataTransferService: DataTransferService,
cacheService: T) where T.Key == String,
T.Value == Data {
self.dataTransferService = dataTransferService
self.cacheService = AnyCacheService(cacheService)
}
}
// MARK: - Image Repository
extension DefaultImageRepository: ImageRepository {
func fetchImage(path: String, width: Int, completion: @escaping CompletionHandler) -> Cancellable? {
if let imageData = cacheService[path] {
completion(.success(imageData))
return nil
}
let endpoint = APIEndpoints.fetchMediaImage(path: path, width: width)
return dataTransferService.request(with: endpoint) { [weak self] result in
if case .success(let imageData) = result {
self?.cacheService[path] = imageData
}
completion(result.mapError { $0 as Error })
}
}
}
| true
|
f3023eb673a8e71d5e07678f89d4ccbc2ed85105
|
Swift
|
utsav475908/CodeFights
|
/Arcade/Intro/absoluteValuesSumMinimization.swift
|
UTF-8
| 438
| 3.140625
| 3
|
[] |
no_license
|
// https://codefights.com/arcade/intro/level-7/ZFnQkq9RmMiyE6qtq
func absoluteValuesSumMinimization(A: [Int]) -> Int {
let c = A.count
//prove?
if c % 2 < 1 {
// try A[c/2-1] and A[c/2]
var m1 = 0, m2 = 0
for i in 0..<c {
m1 += abs(A[i] - A[c/2-1])
m2 += abs(A[i] - A[c/2])
}
return m1 <= m2 ? A[c/2-1] : A[c/2]
} else {
return A[c/2]
}
}
| true
|
7a10132cd1f442a157d57802d5f900ef304e0c05
|
Swift
|
shivakumar8484/Badge
|
/Demo_badgeCount/ViewController.swift
|
UTF-8
| 2,592
| 2.6875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Demo_badgeCount
//
//
//
import UIKit
class ViewController: UIViewController {
var notificationBadge : MJBadgeBarButton!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Badge"
let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
navigationController?.navigationBar.titleTextAttributes = textAttributes
let menuImage = UIImage(named: "Menu")!
let cartImage = UIImage(named: "Group 2568")!
let MenuBarButton = UIBarButtonItem (image: menuImage, style: .plain, target: self, action: #selector(self.menuBarBtnTap(sender:)))
let CartButton = UIBarButtonItem (image: cartImage, style: .plain, target: self, action: #selector(self.addToCartBarBtnTap(sender:)))
MenuBarButton.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
CartButton.tintColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
navigationItem.leftBarButtonItem = MenuBarButton
let customButton = UIButton(type: .custom)
customButton.frame = CGRect(x: 0, y: 0, width: 35.0, height: 35.0)
customButton.addTarget(self, action: #selector(self.notificationBtn), for: .touchUpInside)
customButton.setImage(UIImage(named: "Group 411"), for: .normal) //Group 535
self.notificationBadge = MJBadgeBarButton()
self.notificationBadge.setup(customButton: customButton)
self.notificationBadge.badgeValue = "0"
self.notificationBadge.badgeOriginX = 20.0
self.notificationBadge.badgeOriginY = -4
navigationItem.rightBarButtonItems = [CartButton,notificationBadge]
}
//MENU BTN Action
@objc func menuBarBtnTap(sender: AnyObject){
print("Menu button Tap")
}
//MARK:- addToCartBarBtnTap
@objc func addToCartBarBtnTap(sender: AnyObject){
print("cart button Tap")
// self.notificationBadge.badgeValue = "0"
}
@objc func notificationBtn() {
print("Notification")
// self.notificationBadge.badgeValue = "4"
}
@IBAction func addBadgeCountNotificationCountBtnTap(_ sender: UIButton) {
self.notificationBadge.badgeValue = "10"
}
@IBAction func removeNotifiBadgeCount(_ sender: UIButton) {
self.notificationBadge.badgeValue = "0"
}
}
| true
|
f4d97e9ce261ac697974816b6f910ff9bebb4560
|
Swift
|
CameronRivera/KVOLab
|
/KVOLab/Models/User.swift
|
UTF-8
| 564
| 2.71875
| 3
|
[] |
no_license
|
//
// User.swift
// KVOLab
//
// Created by Cameron Rivera on 4/7/20.
// Copyright © 2020 Cameron Rivera. All rights reserved.
//
import Foundation
@objc class User: NSObject{
private let name: String
@objc dynamic private var currentBalance: Account
init(_ name: String, _ startingBalance: Double){
self.name = name
currentBalance = Account(startingBalance)
}
public func getUserName() -> String {
return self.name
}
public func getCurrentBalance() -> Account {
return self.currentBalance
}
}
| true
|
e64ad1a13eb88a2f1f0d2fca4794beffcb426a47
|
Swift
|
alanscarpa/Count-Out
|
/QuickCount/Bluetooth/BTService.swift
|
UTF-8
| 3,736
| 2.625
| 3
|
[] |
no_license
|
//
// Service.swift
// Counted
//
// Created by Alan Scarpa on 5/15/16.
// Copyright © 2016 Counted. All rights reserved.
//
import Foundation
import CoreBluetooth
class BTService: NSObject, CBPeripheralDelegate {
var peripheral: CBPeripheral?
let weightServiceCBUUID = CBUUID(string: "FFF0")
init(initWithPeripheral peripheral: CBPeripheral) {
super.init()
self.peripheral = peripheral
self.peripheral?.delegate = self
startDiscoveringServices()
}
deinit {
reset()
}
func startDiscoveringServices() {
peripheral?.discoverServices(nil)
}
// MARK: CBPeripheralDelegate
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
if let error = errorForPeripheral(peripheral, error: error) {
NSNotificationCenter.defaultCenter().postNotificationName(kBluetoothError, object: self, userInfo: [kBluetoothError: error])
print(error)
} else {
guard let services = peripheral.services where peripheral.services?.count > 0 else { return }
for service in services {
let thisService = service as CBService
if thisService.UUID == weightServiceCBUUID {
peripheral.discoverCharacteristics(nil, forService: thisService)
}
}
}
}
func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
if let error = errorForPeripheral(peripheral, error: error) {
NSNotificationCenter.defaultCenter().postNotificationName(kBluetoothError, object: self, userInfo: [kBluetoothError: error])
print(error)
} else {
if let characteristics = service.characteristics {
for characteristic in characteristics {
peripheral.setNotifyValue(true, forCharacteristic: characteristic)
}
}
}
}
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
guard let data = characteristic.value else {
if let error = errorForPeripheral(peripheral, error: error) {
NSNotificationCenter.defaultCenter().postNotificationName(kBluetoothError, object: self, userInfo: [kBluetoothError: error])
print(error)
}
return
}
// the number of elements:
let count = data.length / sizeof(UInt32)
// create array of appropriate length:
var array = [UInt32](count: count, repeatedValue: 0)
// copy bytes into array
data.getBytes(&array, length:count * sizeof(UInt32))
// 206 means scale has final weight
if array[0] == 206 {
let weightInPounds = Double(CFSwapInt32BigToHost(array[1])) * 0.00000336223
NSNotificationCenter.defaultCenter().postNotificationName(kDidGetWeightReading, object: nil, userInfo: ["weight": weightInPounds])
}
}
// MARK: Helpers
private func reset() {
if peripheral != nil {
peripheral = nil
}
}
private func errorForPeripheral(peripheral: CBPeripheral, error: NSError?) -> NSError? {
if peripheral != peripheral {
return NSError(domain: Errors.Domain.kPeripheral, code: Errors.Code.kDiscoveredWrongPeripheral, userInfo: [NSLocalizedDescriptionKey: Errors.Description.kDiscoveredWrongPeripheral])
} else if let error = error {
return error
} else {
return nil
}
}
}
| true
|
d4bc4e63b2d7a2ffbe2f1dfa6947cb2b22d111d3
|
Swift
|
SparrowTek/LittleManComputer
|
/LittleManComputerTests/LittleManComputerTests.swift
|
UTF-8
| 4,455
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// LittleManComputerTests.swift
// LittleManComputerTests
//
// Created by Thomas J. Rademaker on 8/13/19.
// Copyright © 2019 SparrowTek LLC. All rights reserved.
//
import XCTest
@testable import LittleManComputer
class LittleManComputerTests: XCTestCase {
override func setUp() {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func createTestState() -> ProgramState {
let registers = [506, 107, 902, 108, 902, 000, 001, 010, 003, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000,
000, 000, 000, 000, 000, 000, 000, 000, 000, 000]
return ProgramState(registers: registers)
}
// MARK: Compiler Tests
func testCompile() {
do {
let code = """
LDA ONE
ADD TEN
OUT
ADD THREE
OUT
HLT
ONE DAT 001
TEN DAT 010
THREE DAT 003
"""
let testState = createTestState()
let compiler = Compiler()
let state = try compiler.compile(code)
XCTAssert(state.registers == testState.registers, "STATE: \(state)")
} catch let error {
XCTAssert(false, "Error: \(error)")
}
}
// MARK: Virtual Machine Tests
func testVirtualMachineStep() {
let state = createTestState()
let vm = VirtualMachine(state: state)
let expectation = XCTestExpectation(description: "expect State to change from the Virtual Machine \"Step\"")
let cancelable = vm.state.sink(receiveCompletion: { completion in
expectation.fulfill()
}, receiveValue: { state in
expectation.fulfill()
})
vm.step()
wait(for: [expectation], timeout: 3)
XCTAssert(vm.state.value.programCounter == 1, "Program counter should have incremented to 1. \n program counter: \(vm.state.value.programCounter)")
#warning("figure out how to test Localized string")
// let printStatement = "Load the value in register 6 (1) into the accumulator"
// let vmPrintStatement: String = "\(vm.state.value.printStatement)"
// XCTAssert(vmPrintStatement == printStatement, "wrong print statement: \n \(vm.state.value.printStatement)")
XCTAssertNotNil(cancelable, "The subscription should not be nil")
}
func testVirtualMachineRun() {
let state = createTestState()
let vm = VirtualMachine(state: state)
var count = 0
let expectation = XCTestExpectation(description: "program complete")
let cancelable = vm.state.sink(receiveCompletion: { _ in },
receiveValue: { state in
count += 1
if count >= 13 {
expectation.fulfill()
}
})
vm.run(speed: 0.1)
wait(for: [expectation], timeout: 2)
let executedState = vm.state.value
XCTAssertNotNil(cancelable, "The subscription should not be nil")
XCTAssertEqual(executedState.programCounter, 5, "Program Counter: \(executedState.programCounter)")
XCTAssertEqual(executedState.printStatement, "Program Complete", "Print Statement: \(executedState.printStatement)")
XCTAssertEqual(executedState.outbox, [11, 14], "Outbox: \(executedState.outbox)")
XCTAssertEqual(executedState.accumulator, 14, "Accumulator: \(executedState.accumulator)")
XCTAssertNil(executedState.inbox, "Inbox should be nil but is \(String(describing: executedState.inbox))")
}
}
| true
|
66a8b85b93f0d4d11eae23323ac45129a7597657
|
Swift
|
aballari9/GuessTheNumber
|
/Guess The Number/ViewController.swift
|
UTF-8
| 2,226
| 3.421875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Guess The Number
//
// Created by Akhila Ballari on 9/5/17.
// Copyright © 2017 Akhila Ballari. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var guessLabel: UILabel!
@IBOutlet weak var guessTextField: UITextField!
@IBOutlet weak var guessButton: UIButton!
let lowerBound = 1
let upperBound = 100
var numberToGuess: Int!
var numberofGuesses = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
numberToGuess = generateRandomNumber()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func generateRandomNumber() -> Int {
return Int(arc4random_uniform(UInt32(upperBound))) + lowerBound
}
@IBAction func buttonPressed(_ sender: Any) {
if let guess = guessTextField.text {
if let numberGuess = Int(guess) {
numberofGuesses += 1
print(guess)
validateGuess(numberGuess)
}
}
guessTextField.text = ""
}
func validateGuess(_ guess: Int) {
if guess < lowerBound || guess > upperBound {
guessLabel.text = "Guess out of range"
} else if guess < numberToGuess {
guessLabel.text = "Guess higher! ⬆️"
} else if guess > numberToGuess {
guessLabel.text = "Guess lower! ⬇️"
} else {
showWinAlert()
}
}
func showWinAlert() {
let alert = UIAlertController(title: "CONGRATS! 😁", message: "You won after only \(numberofGuesses) guesses.", preferredStyle: .alert)
let action = UIAlertAction(title: "Play again", style: .default, handler: { _ in
self.guessLabel.text = "Guess the number"
self.numberofGuesses = 0
self.numberToGuess = self.generateRandomNumber()
})
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
| true
|
f1f00ea848f1f97386616e6219deb892c4642e42
|
Swift
|
Lauriane75/RecipleaseP10
|
/RecipleaseTests/Creations/Creations List/CreationsListViewModelTests.swift
|
UTF-8
| 3,323
| 2.78125
| 3
|
[] |
no_license
|
//
// CreationsListViewModelTests.swift
// RecipleaseTests
//
// Created by Lauriane Haydari on 25/01/2020.
// Copyright © 2020 Lauriane Haydari. All rights reserved.
//
import XCTest
@ testable import Reciplease
final class MockCreationsListViewModelDelegate: CreationsListViewModelDelegate {
var alert: AlertType? = nil
var creation: CreationItem? = nil
func selectCreation(creation: CreationItem) {
self.creation = creation
}
func displayAlert(for type: AlertType) {
self.alert = type
}
}
class MockCreationRepository: CreationRepositoryType {
var creationItem: [CreationItem]?
func didPressSaveCreation(creation: CreationItem) {
}
func getCreations(callback: @escaping ([CreationItem]) -> Void) {
if let creationItem = creationItem {
callback(creationItem)
} else {
callback([])
}
}
func didPressRemoveCreation(titleCreation: String) {
}
}
class CreationsListViewModelTests: XCTestCase {
let delegate = MockCreationsListViewModelDelegate()
let repository = MockCreationRepository()
let expectedResult = CreationItem(image: "11314165".data(using: .utf8), name: "Mushroom risotto", ingredient: "rice", method: "boil the rice into water", time: "30", category: "Veggie", yield: "4")
func test_Given_ViewModel_When_viewDidLoad_Then_ReactivePropertiesAreDisplayed() {
let viewModel = CreationsListViewModel(repository: repository, delegate: delegate)
viewModel.viewDidLoad()
repository.creationItem = [expectedResult]
viewModel.creationItem = { creation in
XCTAssertEqual(creation, [self.expectedResult])
}
}
func test_Given_ViewModel_When_didSelectCreation_Then_expectedResult() {
let viewModel = CreationsListViewModel(repository: repository, delegate: delegate)
viewModel.viewDidLoad()
repository.creationItem = [expectedResult]
viewModel.didSelectCreation(creation: expectedResult)
XCTAssertEqual(delegate.creation, expectedResult)
}
func test_Given_ViewModel_When_didPressDeleteCreation_Then_creationItemIsNil() {
let viewModel = CreationsListViewModel(repository: repository, delegate: delegate)
viewModel.viewDidLoad()
repository.creationItem = [expectedResult]
repository.didPressRemoveCreation(titleCreation: expectedResult.name)
viewModel.creationItem = { creation in
XCTAssertEqual(creation, [])
}
}
func test_Given_When_Then() {
let viewModel = CreationsListViewModel(repository: repository, delegate: delegate)
viewModel.viewDidLoad()
viewModel.didSelectCreation(creation: expectedResult)
XCTAssertEqual(delegate.creation, expectedResult)
}
func test_Given_ViewModel_When_NoCreation_Then_Alert() {
let viewModel = CreationsListViewModel(repository: repository, delegate: delegate)
viewModel.viewDidLoad()
repository.didPressSaveCreation(creation: expectedResult)
repository.didPressRemoveCreation(titleCreation: expectedResult.name)
repository.getCreations(callback: { items in
XCTAssertEqual(items, Optional([]))
})
XCTAssertEqual(delegate.alert, .noCreation)
}
}
| true
|
6b188651c7da68727a9ebb206837cf35e821b211
|
Swift
|
ibaibhavsingh/Unsplash_Clone
|
/Unsplah_Clone/ReusableComponent/Color/StringColor.swift
|
UTF-8
| 410
| 2.578125
| 3
|
[] |
no_license
|
//
// StringColor.swift
// Unsplah_Clone
//
// Created by JungpyoHong on 5/7/21.
//
import UIKit
enum StringColor {
static func changeColor(textField: UITextField, text: String, color: UIColor) {
textField.attributedPlaceholder = NSAttributedString(string: text,
attributes: [NSAttributedString.Key.foregroundColor: color])
}
}
| true
|
fa581c89d42430effb48fa0f9aef515e14568317
|
Swift
|
cb-prabu/chargebee-ios
|
/Chargebee/Classes/CBEnvironment.swift
|
UTF-8
| 554
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
//
// Created by Mac Book on 9/7/20.
//
import Foundation
class CBEnvironment {
static var site: String = ""
static var apiKey: String = ""
static var encodedApiKey: String = ""
static var baseUrl: String = ""
static func configure(site: String, apiKey: String) {
CBEnvironment.site = site
CBEnvironment.apiKey = apiKey
CBEnvironment.encodedApiKey = CBEnvironment.apiKey.data(using: .utf8)?.base64EncodedString() ?? ""
CBEnvironment.baseUrl = "https://\(CBEnvironment.site).chargebee.com/api"
}
}
| true
|
eb398fbec58c0746bf5ef29140e0c1d4362c6980
|
Swift
|
eunmyun/iQuiz
|
/iQuiz/iQuiz/QuestionVC.swift
|
UTF-8
| 3,923
| 2.578125
| 3
|
[] |
no_license
|
//
// QuestionVC.swift
// iQuiz
//
// Created by MyungJin Eun on 5/14/16.
// Copyright © 2016 MyungJin Eun. All rights reserved.
//
import UIKit
class QuestionVC: UIViewController {
var questionArray: [[String : AnyObject]] = []
var currQuestion:Int = -1
var correctAns = ""
var answerSelect = ""
var totalQuestion = 0
var totalScore = 0
@IBOutlet weak var question: UILabel!
@IBOutlet weak var answer1: UIButton!
@IBOutlet weak var answer2: UIButton!
@IBOutlet weak var answer3: UIButton!
@IBOutlet weak var answer4: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
currQuestion += 1
let quest: [String:AnyObject] = questionArray[currQuestion]
question.text = quest["text"] as? String
answer1.setTitle(quest["answers"]![0] as? String, forState: UIControlState.Normal)
answer2.setTitle(quest["answers"]![1] as? String, forState: UIControlState.Normal)
answer3.setTitle(quest["answers"]![2] as? String, forState: UIControlState.Normal)
answer4.setTitle(quest["answers"]![3] as? String, forState: UIControlState.Normal)
setColor()
let index: Int = Int((quest["answer"] as? String)!)! - 1
correctAns = (quest["answers"]![index] as? String)!
let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("swipeDetected:"))
let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("swipeDetected:"))
leftSwipe.direction = .Left
rightSwipe.direction = .Right
view.addGestureRecognizer(leftSwipe)
view.addGestureRecognizer(rightSwipe)
}
func swipeDetected(sender:UISwipeGestureRecognizer) {
if (sender.direction == .Left) {
helperFunc()
} else if (sender.direction == .Right) {
let listView = self.storyboard?.instantiateViewControllerWithIdentifier("ViewController") as! ViewController
self.presentViewController(listView, animated: true, completion: nil)
}
}
func setColor() {
answer1.backgroundColor = UIColor(red: 0, green: 0.898, blue: 0.898, alpha: 1.0)
answer2.backgroundColor = UIColor(red: 0, green: 0.898, blue: 0.898, alpha: 1.0)
answer3.backgroundColor = UIColor(red: 0, green: 0.898, blue: 0.898, alpha: 1.0)
answer4.backgroundColor = UIColor(red: 0, green: 0.898, blue: 0.898, alpha: 1.0)
}
@IBAction func answerPress(sender: UIButton) {
answerSelect = sender.currentTitle!
if sender.backgroundColor == UIColor(red: 0, green: 0.898, blue: 0.898, alpha: 1.0) {
setColor()
sender.backgroundColor = UIColor(red: 0.8471, green: 0.9569, blue: 0, alpha: 1.0)
}
else if sender.backgroundColor == UIColor(red: 0.8471, green: 0.9569, blue: 0, alpha: 1.0) {
sender.backgroundColor = UIColor(red: 0, green: 0.898, blue: 0.898, alpha: 1.0)
}
}
@IBAction func submit(sender: AnyObject) {
helperFunc()
}
func helperFunc() {
let aVC = self.storyboard?.instantiateViewControllerWithIdentifier("AnswerVC") as! AnswerVC
aVC.questionArray = self.questionArray
aVC.currQuestion = self.currQuestion
aVC.correctAns = self.correctAns
aVC.answerSelect = self.answerSelect
aVC.totalQuestion = self.totalQuestion
aVC.totalScore = self.totalScore
self.presentViewController(aVC, animated: true, completion: nil)
}
}
/*
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let qVC = self.storyboard?.instantiateViewControllerWithIdentifier("QuestionVC") as! QuestionVC
qVC.questionArray = json.questions[indexPath.row]
self.presentViewController(qVC, animated: true, completion: nil)
}
*/
| true
|
304f0e037ccc25a8598275cee8349d11f2a06148
|
Swift
|
XIgorX/Anonym
|
/AnonimTest/NetworkManager.swift
|
UTF-8
| 2,605
| 2.828125
| 3
|
[] |
no_license
|
//
// NetworkManager.swift
// AnonimTest
//
// Created by Igor Danilchenko on 10.05.2020.
// Copyright © 2020 Igor Danilchenko. All rights reserved.
//
import UIKit
struct Response: Codable {
var data: Data
}
struct Data: Codable {
var items: [Item]
var cursor: String
}
struct Item: Codable {
var id: String
var replyOnPostId: String?
var type: String
var thankedComment: String?
var status: String
var hidingReason: String?
// var coordinates: Coordinates
var isCommentable: Bool
var hasAdultContent: Bool
var isAuthorHidden: Bool
var isHidden: Bool
var contents: [Content]
var language: String
var createdAt: Int
var updatedAt: Int
var page: Int?
//var author: Author
//var stats: Stats
var isMyFavorite: Bool
}
struct Coordinates: Codable {
var latitude: Double
var longitude: Double
var zoom: Int?
}
struct Content: Codable {
var type: String
var data: ContentData
}
struct ContentData: Codable {
var value: String?
var extraSmall: Picture?
var small: Picture?
}
struct Picture: Codable {
var url: String
var size : Size
}
struct Size: Codable {
var width: Int
var height : Int
}
class NetworkManager: NSObject {
func getPosts(first : Int = 20, after : String? = nil, completion: @escaping ([Item]?, String) -> ())
{
var urlString = ""
if let after = after
{
urlString = "\(baseUrl)?first=\(first)&after=\(after)"
}
else
{
urlString = "\(baseUrl)?first=\(first)"
}
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url) { data, response, error in
if let data = data {
let jsonString = String(data: data, encoding: .utf8)
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
// we have good data – go back to the main thread
DispatchQueue.main.async {
// update our UI
completion(decodedResponse.data.items, decodedResponse.data.cursor)
}
// everything is good, so we can exit
return
}
else
{
//fatalError(error?.localizedDescription ?? jsonString ?? "")
print(error?.localizedDescription ?? jsonString ?? "nil")
}
}
}.resume()
}
}
}
| true
|
1732c1c881ea81421023687ecd50d7e5fb5e2a44
|
Swift
|
zvoneiOS/scheduler
|
/MeetingScheduler/IntroModul/presenters/RegisterScreenPresenter.swift
|
UTF-8
| 773
| 2.546875
| 3
|
[] |
no_license
|
//
// RegisterScreenPresenter.swift
// MeetingScheduler
//
import Foundation
class RegisterScreenPresenter: RegisterPresenterProtocol {
weak var view: RegisterViewProtocol?
var interactor: RegisterInteractorInputProtocol?
var wireFrame: RegisterWireFrameProtocol?
func viewDidLoad() {
}
func registerClicked(username: String, email: String, password: String) {
self.interactor?.register(username: username, email: email, password: password)
}
}
extension RegisterScreenPresenter: RegisterInteractorOutputProtocol{
func error(message: String) {
view?.showError(message: message)
}
func success() {
wireFrame?.switchToMainModule(from: view!)
}
}
| true
|
049314816fde7ee1d1565b37eaaaaf0f247c1e60
|
Swift
|
pavangandhi/iOS-8-Swift-Programming
|
/chapter-health/Retrieving User’s Date of Birth/Retrieving User’s Date of Birth/ViewController.swift
|
UTF-8
| 2,481
| 3.171875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Retrieving User’s Date of Birth
//
// Created by vandad on 237//14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at vandad.np@gmail.com
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
import HealthKit
class ViewController: UIViewController {
let dateOfBirthCharacteristicType =
HKCharacteristicType.characteristicTypeForIdentifier(
HKCharacteristicTypeIdentifierDateOfBirth)!
lazy var types: Set<HKObjectType> = {
return [self.dateOfBirthCharacteristicType]
}()
lazy var healthStore = HKHealthStore()
func readDateOfBirthInformation(){
do{
let birthDate = try healthStore.dateOfBirthWithError()
let now = NSDate()
let components = NSCalendar.currentCalendar().components(
.NSYearCalendarUnit,
fromDate: birthDate,
toDate: now,
options: .WrapComponents)
let age = components.year
print("The user is \(age) years old")
} catch {
print("Could not read user's date of birth")
}
}
/* Ask for permission to access the health store */
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if HKHealthStore.isHealthDataAvailable(){
healthStore.requestAuthorizationToShareTypes(nil,
readTypes: types,
completion: {succeeded, error in
if succeeded && error == nil{
dispatch_async(dispatch_get_main_queue(),
self.readDateOfBirthInformation)
} else {
if let theError = error{
print("Error occurred = \(theError)")
}
}
})
} else {
print("Health data is not available")
}
}
}
| true
|
b748a6554e92932e2ce0b12adc5340481df78573
|
Swift
|
fadyyecob/adidas
|
/adidas/ProductList/ProductListItemViewModel.swift
|
UTF-8
| 963
| 3.1875
| 3
|
[] |
no_license
|
//
// ProductListItemViewModel.swift
// adidas
//
// Created by Fady Yecob on 01/05/2021.
//
import Foundation
struct ProductListItemViewModel: Hashable {
private let uuid = UUID()
let id: String
let name: String
let imageURL: URL
let description: String
let currencyAndPrice: String
var descriptionAndPrice: String {
[description, currencyAndPrice]
.joined(separator: "\n")
}
init(product: Product) {
id = product.id
name = product.name
imageURL = product.imageURL
description = product.description
currencyAndPrice = Self.makeCurrencyAndPriceString(currency: product.currency, price: product.price)
}
private static func makeCurrencyAndPriceString(currency: String, price: Decimal) -> String {
let formatter = CurrencyFormatter(currency: currency)
return formatter.string(from: NSDecimalNumber(decimal: price)) ?? ""
}
}
| true
|
d4b333f0aadc37cc6aeb2cbd9c07ddb58650ebd5
|
Swift
|
almazrafi/Fugen
|
/Sources/FugenTools/HTTPService/HTTPService.swift
|
UTF-8
| 1,786
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
public final class HTTPService {
// MARK: - Instance Properties
private let session: URLSession
// MARK: -
public var sessionConfiguration: URLSessionConfiguration {
session.configuration
}
public var activityIndicator: HTTPActivityIndicator?
// MARK: - Initializers
public init(
sessionConfiguration: URLSessionConfiguration = .httpServiceDefault,
activityIndicator: HTTPActivityIndicator? = nil
) {
self.session = URLSession(configuration: sessionConfiguration)
self.activityIndicator = activityIndicator
}
// MARK: - Instance Methods
public func request(route: HTTPRoute) -> HTTPTask {
DispatchQueue.main.async {
self.activityIndicator?.incrementActivityCount()
}
return HTTPServiceTask<URLSessionDataTask>(session: session, route: route)
.launch()
.response { _ in
DispatchQueue.main.async {
self.activityIndicator?.decrementActivityCount()
}
}
}
}
extension URLSessionConfiguration {
// MARK: - Type Properties
public static var httpServiceDefault: URLSessionConfiguration {
let configuration = URLSessionConfiguration.default
let headers = [
HTTPHeader.defaultAcceptLanguage(),
HTTPHeader.defaultAcceptEncoding(),
HTTPHeader.defaultUserAgent()
]
let rawHeaders = Dictionary(uniqueKeysWithValues: headers.map { ($0.name, $0.value) })
configuration.httpAdditionalHeaders = rawHeaders
configuration.timeoutIntervalForRequest = 45
return configuration
}
}
| true
|
6c4c8ef4d2f10d860074476d4f1b05a3f2fc7e71
|
Swift
|
xorum-io/codeforces_watcher
|
/ios/algois-me/Application/components/labels/HeadingLabel.swift
|
UTF-8
| 420
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import UIKit
class HeadingLabel: UILabel {
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
numberOfLines = 1
textColor = Palette.black
font = Font.textHeading
}
}
| true
|
6ae277f8a8b1a0c52bff764e8b838fa9bf557a4a
|
Swift
|
Bushra-Oudah-Alatwi/SW-Lab-U02_W05_D23_25-WorldTrotter-iter4
|
/WorldTrotter- Programmatically- “Bushra_Oudah”- iter03 new Brounce+ Silver/WorldTrotter- Programmatically- “Bushra_Oudah”-iter1/Quiz.swift
|
UTF-8
| 2,531
| 2.921875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Trivial Single Choice
//
// Created by Bushra alatwi on 12/03/1443 AH.
//
import UIKit
class Quiz: UIViewController {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var trueButton: UIButton!
@IBOutlet weak var falseButton: UIButton!
@IBOutlet weak var progressView: UIProgressView!
var quizManager = QuizManager()
var change = 0
override func viewDidLoad() {
super.viewDidLoad()
configureButtons()
updateUI()
progressView.progress = 0.0
}
@IBAction func buttonPressed(_ sender: UIButton) {
let userAnswer = sender.currentTitle!
let check = quizManager.checkAnswer(userAnswer)
if check {
sender.backgroundColor = .systemGreen
}
else {
sender.backgroundColor = .systemRed
}
if quizManager.nextQuestion(){ Timer.scheduledTimer(timeInterval:1.2,
target: self,
selector: #selector(updateUI),
userInfo: nil,
repeats: false
)
}
else{
showGameOverAlertMessage()
}
}
@objc func updateUI(){
questionLabel.text = quizManager.getQuestion()
progressView.progress = quizManager.getProgress()
scoreLabel.text = "Score: \(quizManager.getScore())"
trueButton.backgroundColor = UIColor.clear
falseButton.backgroundColor = UIColor.clear
//true_Button.setTitle(quizManager.getChoices), for: .normal)
// fulse_button.setTitle(quizManager.getChoices), for: .normal)
}
func startGame(action : UIAlertAction! = nil) {
print(#function)
quizManager.startGame()
updateUI()
}
func showGameOverAlertMessage(){
let ac = UIAlertController(title: "GAME OVER",
message: "Your scores is\(quizManager.getScore ())",
preferredStyle: .alert )
ac.addAction(UIAlertAction(title:"Play Again", style:.default, handler:startGame))
present(ac, animated: true)
}
func configureButtons() {
trueButton.layer.cornerRadius = 15
trueButton.layer.masksToBounds = true
trueButton.layer.borderWidth = 2
trueButton.layer.borderColor = UIColor.black.cgColor
falseButton.layer.cornerRadius = 15
falseButton.layer.masksToBounds = true
falseButton.layer.borderWidth = 2
falseButton.layer.borderColor = UIColor.black.cgColor
}
}
| true
|
4d7b1bde5a3b696834ce2a10ed64d945c3e6eb8b
|
Swift
|
CoderDqZhang/LiangPiao
|
/LiangPiao/LiangPiao/Views/Order/OrderManagerTableViewCell.swift
|
UTF-8
| 9,882
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// OrderManagerTableViewCell.swift
// LiangPiao
//
// Created by Zhang on 05/12/2016.
// Copyright © 2016 Zhang. All rights reserved.
//
import UIKit
enum TicketImageViewsType {
case oneImage
case twoOrMore
}
class TicketImageViews: UIView {
var imageView:UIImageView = UIImageView()
var imageViewSplash1:UIImageView = UIImageView()
var imageViewSplash2:UIImageView = UIImageView()
init(imageUrl:String?, frame:CGRect, type:TicketImageViewsType?) {
super.init(frame: frame)
imageView.frame = CGRect.init(x: 0, y: 8, width: frame.size.width, height: frame.size.height - 8)
imageViewSplash1.frame = CGRect.init(x: 8, y: 0, width: frame.size.width - 16, height: (frame.size.width - 16) * frame.size.height / frame.size.width)
imageViewSplash2.frame = CGRect.init(x: 4, y: 4, width: frame.size.width - 8, height: (frame.size.width - 8) * frame.size.height / frame.size.width)
self.addSubview(imageViewSplash1)
self.addSubview(imageViewSplash2)
self.addSubview(imageView)
self.setImage(imageView)
self.setImage(imageViewSplash1)
self.setImage(imageViewSplash2)
if imageUrl != nil {
imageView.sd_setImage(with: URL.init(string: imageUrl!), placeholderImage: UIImage.init(named: "Feeds_Default_Cover"), options: .retryFailed, progress: { (start, end, rul) in
}, completed: { (image, error, cacheType, url) in
if type == nil || type == .oneImage {
self.imageViewSplash1.isHidden = true
self.imageViewSplash2.isHidden = true
}
if type == .twoOrMore {
self.imageViewSplash1.isHidden = false
self.imageViewSplash2.isHidden = false
self.imageViewSplash1.image = image
self.imageViewSplash1.alpha = 0.2
self.imageViewSplash2.image = image
self.imageViewSplash2.alpha = 0.4
}
})
}else{
let image = UIImage.init(named: "Feeds_Default_Cover")
imageView.image = image
self.imageViewSplash1.image = image
self.imageViewSplash1.alpha = 0.2
self.imageViewSplash2.image = image
self.imageViewSplash2.alpha = 0.4
if type == nil || type == .oneImage {
self.imageViewSplash1.isHidden = true
self.imageViewSplash2.isHidden = true
}
if type == .twoOrMore {
self.imageViewSplash1.isHidden = false
self.imageViewSplash2.isHidden = false
}
}
}
func setImageType(_ imageUrl:String,type:TicketImageViewsType?){
imageView.sd_setImage(with: URL.init(string: imageUrl), placeholderImage: UIImage.init(named: "Feeds_Default_Cover"), options: .retryFailed, progress: { (start, end, rul) in
}, completed: { (image, error, cacheType, url) in
if type == nil || type == .oneImage {
self.imageViewSplash1.isHidden = true
self.imageViewSplash2.isHidden = true
}
if type == .twoOrMore {
self.imageViewSplash1.isHidden = false
self.imageViewSplash2.isHidden = false
self.imageViewSplash1.image = image
self.imageViewSplash1.alpha = 0.2
self.imageViewSplash2.image = image
self.imageViewSplash2.alpha = 0.4
}
})
}
func setImage(_ image:UIImageView){
image.layer.cornerRadius = 3.0
image.layer.masksToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class OrderManagerTableViewCell: UITableViewCell {
var ticketPhoto:TicketImageViews!
var ticketTitle:UILabel!
var ticketRow:UILabel!
var ticketTime:UILabel!
var ticketMuch:UILabel!
var ticketSelledNumber:UILabel!
var tickType:OrderType = .orderWaitPay
var didMakeConstraints:Bool = false
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = UIColor.white
self.setUpView()
}
func setUpView() {
ticketPhoto = TicketImageViews(imageUrl: nil, frame: CGRect.init(x: 15, y: 22, width: 82, height: 118), type: .oneImage)
self.contentView.addSubview(ticketPhoto)
ticketTitle = UILabel()
ticketTitle.text = "刘若英“Renext”世界巡回演唱会北京站预售"
UILabel.changeLineSpace(for: ticketTitle, withSpace: TitleLineSpace)
ticketTitle.textColor = UIColor.init(hexString: App_Theme_384249_Color)
ticketTitle.font = App_Theme_PinFan_R_15_Font
ticketTitle.numberOfLines = 0
self.contentView.addSubview(ticketTitle)
ticketTime = UILabel()
ticketTime.text = "场次:2016.12.18-2016.12.20"
ticketTime.textColor = UIColor.init(hexString: App_Theme_8A96A2_Color)
ticketTime.font = App_Theme_PinFan_R_12_Font
self.contentView.addSubview(ticketTime)
ticketMuch = UILabel()
ticketMuch.text = "票面:380、580(290x2上下本联票)、68…"
ticketMuch.textColor = UIColor.init(hexString: App_Theme_8A96A2_Color)
ticketMuch.font = App_Theme_PinFan_R_12_Font
self.contentView.addSubview(ticketMuch)
ticketRow = UILabel()
ticketRow.text = "座位:2016.12.18-2016.12.20"
ticketRow.textColor = UIColor.init(hexString: App_Theme_8A96A2_Color)
ticketRow.font = App_Theme_PinFan_R_12_Font
self.contentView.addSubview(ticketRow)
ticketSelledNumber = UILabel()
ticketSelledNumber.text = "已售:0"
ticketSelledNumber.textColor = UIColor.init(hexString: App_Theme_8A96A2_Color)
ticketSelledNumber.font = App_Theme_PinFan_R_12_Font
self.contentView.addSubview(ticketSelledNumber)
self.updateConstraintsIfNeeded()
}
func setData(_ title:String, cover:String, session:String, much:String, remainCount:String, soldCount:String, isMoreTicket:Bool){
ticketTitle.text = title
UILabel.changeLineSpace(for: ticketTitle, withSpace: TitleLineSpace)
ticketTime.text = "场次:\(session)"
ticketMuch.text = "票面:\(much)"
ticketSelledNumber.text = "在售:\(remainCount) 已售:\(soldCount)"
if isMoreTicket {
ticketRow.isHidden = true
ticketMuch.snp.remakeConstraints({ (make) in
make.bottom.equalTo(self.ticketSelledNumber.snp.top).offset(-2)
make.left.equalTo(self.ticketPhoto.snp.right).offset(12)
make.right.equalTo(self.contentView.snp.right).offset(-15)
})
ticketPhoto.setImageType(cover, type: .twoOrMore)
}else{
ticketRow.isHidden = false
ticketMuch.snp.remakeConstraints({ (make) in
make.bottom.equalTo(self.ticketRow.snp.top).offset(-2)
make.left.equalTo(self.ticketPhoto.snp.right).offset(12)
make.right.equalTo(self.contentView.snp.right).offset(-15)
})
ticketPhoto.setImageType(cover, type: .oneImage)
}
}
override func updateConstraints() {
if !self.didMakeConstraints {
ticketPhoto.snp.makeConstraints({ (make) in
make.top.equalTo(self.contentView.snp.top).offset(22)
make.left.equalTo(self.contentView.snp.left).offset(15)
make.size.equalTo(CGSize.init(width: 82, height: 118))
})
ticketTitle.snp.makeConstraints({ (make) in
make.top.equalTo(self.contentView.snp.top).offset(27)
make.left.equalTo(self.ticketPhoto.snp.right).offset(12)
make.right.equalTo(self.contentView.snp.right).offset(-15)
})
ticketTime.snp.makeConstraints({ (make) in
make.bottom.equalTo(self.ticketMuch.snp.top).offset(-2)
make.left.equalTo(self.ticketPhoto.snp.right).offset(12)
make.right.equalTo(self.contentView.snp.right).offset(-15)
})
ticketMuch.snp.makeConstraints({ (make) in
make.bottom.equalTo(self.ticketRow.snp.top).offset(-2)
make.left.equalTo(self.ticketPhoto.snp.right).offset(12)
make.right.equalTo(self.contentView.snp.right).offset(-15)
})
ticketRow.snp.makeConstraints({ (make) in
make.bottom.equalTo(self.ticketSelledNumber.snp.top).offset(-2)
make.left.equalTo(self.ticketPhoto.snp.right).offset(12)
make.right.equalTo(self.contentView.snp.right).offset(-15)
})
ticketSelledNumber.snp.makeConstraints({ (make) in
make.bottom.equalTo(self.contentView.snp.bottom).offset(-20)
make.left.equalTo(self.ticketPhoto.snp.right).offset(12)
})
self.didMakeConstraints = true
}
super.updateConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
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
|
bcafc0bc843d10bad39690106ea0b071d1aecf63
|
Swift
|
PhanithNY/ChatLayout
|
/Example/ChatLayout/Chat/Controller/Keyboard/KeyboardInfo.swift
|
UTF-8
| 1,594
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
//
// ChatLayout
// KeyboardInfo.swift
// https://github.com/ekazaev/ChatLayout
//
// Created by Eugene Kazaev in 2020-2021.
// Distributed under the MIT license.
//
import Foundation
import UIKit
struct KeyboardInfo: Equatable {
let animationDuration: Double
let animationCurve: UIView.AnimationCurve
let frameBegin: CGRect
let frameEnd: CGRect
let isLocal: Bool
init?(_ notification: Notification) {
guard let userInfo: NSDictionary = notification.userInfo as NSDictionary?,
let keyboardAnimationCurve = (userInfo.object(forKey: UIResponder.keyboardAnimationCurveUserInfoKey) as? NSValue) as? Int,
let keyboardAnimationDuration = (userInfo.object(forKey: UIResponder.keyboardAnimationDurationUserInfoKey) as? NSValue) as? Double,
let keyboardIsLocal = (userInfo.object(forKey: UIResponder.keyboardIsLocalUserInfoKey) as? NSValue) as? Bool,
let keyboardFrameBegin = (userInfo.object(forKey: UIResponder.keyboardFrameBeginUserInfoKey) as? NSValue)?.cgRectValue,
let keyboardFrameEnd = (userInfo.object(forKey: UIResponder.keyboardFrameEndUserInfoKey) as? NSValue)?.cgRectValue else {
return nil
}
self.animationDuration = keyboardAnimationDuration
var animationCurve = UIView.AnimationCurve.easeInOut
NSNumber(value: keyboardAnimationCurve).getValue(&animationCurve)
self.animationCurve = animationCurve
self.isLocal = keyboardIsLocal
self.frameBegin = keyboardFrameBegin
self.frameEnd = keyboardFrameEnd
}
}
| true
|
2671bf07b7ee40ba9be2d3a58e3440b2321ebae6
|
Swift
|
mengwang0301/MWWatermarkDemo
|
/CommonUtils.swift
|
UTF-8
| 1,363
| 3
| 3
|
[] |
no_license
|
//
// CommonUtils.swift
// MWCommonUtils
//
// Created by 王萌 on 2019/10/31.
// Copyright © 2019 MENGWANG. All rights reserved.
//
import UIKit
class CommonUtils {
/// 根据给定的文字生成对应的图片
///
/// - Parameter text: 要显示的文字
/// - Returns: 生成的图片
func getImageFromText(_ text: String) -> UIImage {
/**
这里之所以外面再放一个UIView,是因为直接用label画图的话,旋转就不起作用了
*/
let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.backgroundColor = .white
let label = UILabel(frame: view.bounds)
label.backgroundColor = .clear
//textColor暂时设置为隐形, 目前用作隐形水印用
label.textColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.01)
label.text = text
label.transform = CGAffineTransform(rotationAngle: CGFloat(-Double.pi/4))
view.addSubview(label)
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale);
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image=UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image!;
}
}
| true
|
a1dc0a3d942c3d53251ece93ce574a4fa92fd5ff
|
Swift
|
CodePath-iOS-bootcamp2017/Warble
|
/Warble/User.swift
|
UTF-8
| 3,219
| 3.015625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// User.swift
// Warble
//
// Created by Satyam Jaiswal on 2/26/17.
// Copyright © 2017 Satyam Jaiswal. All rights reserved.
//
import UIKit
class User: NSObject {
var name: String?
var handle: String?
var followersCount: Int?
var followingCount: Int?
var backgroundImageUrl: URL?
var statusesCount: Int?
var profileImageUrl: URL?
var id: String?
var bio: String?
var userDictionary: NSDictionary?
static var _currentUser: User?
class var currentUser: User?{
get{
if(_currentUser == nil){
let defaults = UserDefaults.standard
// defaults.removeObject(forKey: "currentUserData")
let data = defaults.object(forKey: "currentUserData") as? Data
if let data = data{
if let currentUserDictionary = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary{
let user = User(dictionary: currentUserDictionary)
self._currentUser = user
}
}
}
return _currentUser
}
set(user){
_currentUser = user
let defaults = UserDefaults.standard
if let user = user{
let data = try! JSONSerialization.data(withJSONObject: user.userDictionary!, options: [])
defaults.set(data, forKey: "currentUserData")
}else{
defaults.removeObject(forKey: "currentUserData")
}
defaults.synchronize()
}
}
init(dictionary: NSDictionary) {
self.userDictionary = dictionary
if let name = dictionary.value(forKey: "name") as? String{
self.name = name
}
if let handle = dictionary.value(forKey: "screen_name") as? String{
self.handle = handle
}
if let followersCount = dictionary.value(forKey: "followers_count") as? Int{
self.followersCount = followersCount
}
if let followingCount = dictionary.value(forKey: "friends_count") as? Int{
self.followingCount = followingCount
}
if let backgroundImageUrlString = dictionary.value(forKey: "profile_banner_url") as? String{
if let backgroundImageUrl = URL(string: backgroundImageUrlString){
self.backgroundImageUrl = backgroundImageUrl
}
}
if let statusesCount = dictionary.value(forKey: "statuses_count") as? Int{
self.statusesCount = statusesCount
}
if let profileImageUrlString = dictionary.value(forKey: "profile_image_url_https") as? String{
if let profileImageUrl = URL(string: profileImageUrlString){
self.profileImageUrl = profileImageUrl
}
}
if let id = dictionary.value(forKey: "id_str") as? String{
self.id = id
}
if let bio = dictionary.value(forKey: "description") as? String{
self.bio = bio
}
}
}
| true
|
09f43036064e0da291afb023d44bd1b7fe59d575
|
Swift
|
rakeshtripathy82/iOS-SDK
|
/Examples/swift/ProximityContent/ProximityContent/Estimote/ProximityContentManager.swift
|
UTF-8
| 1,731
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// Please report any problems with this app template to contact@estimote.com
//
protocol ProximityContentManagerDelegate: class {
func proximityContentManager(_ proximityContentManager: ProximityContentManager, didUpdateContent content: AnyObject?)
}
class ProximityContentManager: NearestBeaconManagerDelegate {
weak var delegate: ProximityContentManagerDelegate?
private let beaconContentFactory: BeaconContentFactory
private let nearestBeaconManager: NearestBeaconManager
init(beaconRegions: [CLBeaconRegion], beaconContentFactory: BeaconContentFactory) {
self.beaconContentFactory = beaconContentFactory
self.nearestBeaconManager = NearestBeaconManager(beaconRegions: beaconRegions)
self.nearestBeaconManager.delegate = self
}
convenience init(beaconIDs: [BeaconID], beaconContentFactory: BeaconContentFactory) {
let beaconRegions = beaconIDs.map { $0.asBeaconRegion }
self.init(beaconRegions: beaconRegions, beaconContentFactory: beaconContentFactory)
}
func startContentUpdates() {
self.nearestBeaconManager.startNearestBeaconUpdates()
}
func stopContentUpdates() {
self.nearestBeaconManager.stopNearestBeaconUpdates()
}
func nearestBeaconManager(_ nearestBeaconManager: NearestBeaconManager, didUpdateNearestBeacon nearestBeacon: CLBeacon?) {
if let nearestBeacon = nearestBeacon {
self.beaconContentFactory.requestContent(for: nearestBeacon) { (proximityContent) in
self.delegate?.proximityContentManager(self, didUpdateContent: proximityContent)
}
} else {
self.delegate?.proximityContentManager(self, didUpdateContent: nil)
}
}
}
| true
|
1379a706ff14f2a52b1be87ae29f05d458526edd
|
Swift
|
hakanyildizay/amplify-ios
|
/Amplify/Categories/API/Request/GraphQLRequest.swift
|
UTF-8
| 1,359
| 2.515625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Copyright 2018-2020 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
public struct GraphQLRequest<R: Decodable> {
/// The name of graphQL API being invoked, as specified in `amplifyconfiguration.json`.
/// Specify this parameter when more than one GraphQL API is configured.
public let apiName: String?
/// Query document
public let document: String
/// Query variables
public let variables: [String: Any]?
/// Type to decode the graphql response data object to
public let responseType: R.Type
/// The path to decode to the graphQL response data to `responseType`. Delimited by `.` The decode path
/// "listTodos.items" will traverse to the object at `listTodos`, and decode the object at `items` to `responseType`
/// The data at that decode path is a list of Todo objects so `responseType` should be `[Todo].self`
public let decodePath: String?
public init(apiName: String? = nil,
document: String,
variables: [String: Any]? = nil,
responseType: R.Type,
decodePath: String? = nil) {
self.apiName = apiName
self.document = document
self.variables = variables
self.responseType = responseType
self.decodePath = decodePath
}
}
| true
|
e6643c5c505380fe50f2ebcccd4f29a0ad4a2175
|
Swift
|
Jc-hammond/Sean-Allen-DubDubGrub
|
/DubDubGrub/DubDubGrub/Views/Screens/LocationMapView/LocationMapViewModel.swift
|
UTF-8
| 2,661
| 2.546875
| 3
|
[] |
no_license
|
//
// LocationMapViewModel.swift
// DubDubGrub
//
// Created by Connor Hammond on 9/30/21.
//
import MapKit
final class LocationMapViewModel: NSObject, ObservableObject {
@Published var isShowingOnboardView = false
@Published var alertItem: AlertItem?
@Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 37.331516,
longitude: -121.891054),
span: MKCoordinateSpan(latitudeDelta: 0.01,
longitudeDelta: 0.01))
var deviceLocationManager: CLLocationManager?
let kHasSeenOnboardView = "hasSeenOnboardView"
var hasSeenOnboardView: Bool {
return UserDefaults.standard.bool(forKey: kHasSeenOnboardView)
}
func runStartupChecks() {
if !hasSeenOnboardView {
isShowingOnboardView = true
UserDefaults.standard.set(true, forKey: kHasSeenOnboardView)
} else {
checkIfLocationServicesIsEnabled()
}
}
func checkIfLocationServicesIsEnabled() {
if CLLocationManager.locationServicesEnabled() {
deviceLocationManager = CLLocationManager()
deviceLocationManager!.delegate = self
} else {
alertItem = AlertContext.locationDisabled
}
}
private func checkLocationAuthorization() {
guard let deviceLocationManager = deviceLocationManager else {return}
switch deviceLocationManager.authorizationStatus {
case .notDetermined:
deviceLocationManager.requestWhenInUseAuthorization()
case .restricted:
alertItem = AlertContext.locationRestricted
case .denied:
alertItem = AlertContext.locationDenied
case .authorizedAlways, .authorizedWhenInUse:
break
@unknown default:
break
}
}
func getLocations(for locationManager: LocationManager) {
CLoudKitManager.getLocations { [self] result in
DispatchQueue.main.async {
switch result {
case .success(let locations):
locationManager.locations = locations
case .failure(_):
alertItem = AlertContext.unableToGetLocations
}
}
}
}
}
extension LocationMapViewModel: CLLocationManagerDelegate {
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
checkLocationAuthorization()
}
}
| true
|
266cc3022abe05088e92fec7af6e945a524bbbf1
|
Swift
|
filestack/filestack-swift
|
/Sources/FilestackSDK/Internal/Operations/StartUploadOperation.swift
|
UTF-8
| 3,824
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// StartUploadOperation.swift
// FilestackSDK
//
// Created by Ruben Nine on 7/19/17.
// Copyright © 2017 Filestack. All rights reserved.
//
import Foundation
class StartUploadOperation: BaseOperation<UploadDescriptor> {
// MARK: - Private Properties
private let config: Config
private let options: UploadOptions
private let reader: UploadableReader
private let filename: String
private let filesize: UInt64
private let mimeType: String
// MARK: - Lifecycle
required init(config: Config,
options: UploadOptions,
reader: UploadableReader,
filename: String,
filesize: UInt64,
mimeType: String) {
self.config = config
self.options = options
self.reader = reader
self.filename = filename
self.filesize = filesize
self.mimeType = mimeType
super.init()
}
}
// MARK: - Overrides
extension StartUploadOperation {
override func main() {
let uploadURL = URL(string: "multipart/start", relativeTo: Constants.uploadURL)!
let headers = ["Content-Type": "application/json"]
guard let payload = self.payload() else { return }
UploadService.shared.upload(data: payload, to: uploadURL, method: "POST", headers: headers) { (data, response, error) in
let jsonResponse = JSONResponse(response: response, data: data, error: error)
self.handleResponse(response: jsonResponse)
}
}
}
// MARK: - Private Functions
private extension StartUploadOperation {
func handleResponse(response: JSONResponse) {
// Ensure that there's a response and JSON payload or fail.
guard let json = response.json else {
finish(with: .failure(.custom("Unable to obtain JSON from /multipart/start response.")))
return
}
// Did the REST API return an error? Fail and send the error downstream.
if let apiErrorDescription = json["error"] as? String {
finish(with: .failure(.api(apiErrorDescription)))
return
}
// Ensure that there's an uri, region, and upload_id in the JSON payload or fail.
guard let uri = json["uri"] as? String,
let region = json["region"] as? String,
let uploadID = json["upload_id"] as? String
else {
finish(with: .failure(.custom("JSON payload is missing required parameters.")))
return
}
// Detect whether intelligent ingestion is available.
// The JSON payload should contain an "upload_type" field with value "intelligent_ingestion".
let canUseIntelligentIngestion = json["upload_type"] as? String == "intelligent_ingestion"
let descriptor = UploadDescriptor(
config: config,
options: options,
reader: reader,
filename: filename,
filesize: filesize,
mimeType: mimeType,
uri: uri,
region: region,
uploadID: uploadID,
useIntelligentIngestion: canUseIntelligentIngestion
)
finish(with: .success(descriptor))
}
func payload() -> Data? {
var payload: [String: Any] = [
"apikey": config.apiKey,
"filename": filename,
"mimetype": mimeType,
"size": filesize,
"store": options.storeOptions.asDictionary()
]
if let security = config.security {
payload["policy"] = security.encodedPolicy
payload["signature"] = security.signature
}
if options.preferIntelligentIngestion {
payload["fii"] = true
}
return try? JSONSerialization.data(withJSONObject: payload)
}
}
| true
|
c86db85e0fe823157f39d6ccc7fa782a4abd4eda
|
Swift
|
vkondrashkov/parylation
|
/ParylationDomain/ParylationDomain/Interactors/CalendarInteractor.swift
|
UTF-8
| 2,003
| 3.0625
| 3
|
[] |
no_license
|
//
// CalendarInteractor.swift
// ParylationDomain
//
// Created by Vladislav Kondrashkov on 27.01.21.
// Copyright © 2021 Vladislav Kondrashkov. All rights reserved.
//
import RxSwift
public enum CalendarInteractorError: Error {
case failed
}
public protocol CalendarInteractor {
func monthMetadata(date: Date) -> Single<MonthMetadata>
}
public final class CalendarInteractorImpl {
private let calendar: Calendar
public init(
calendar: Calendar
) {
self.calendar = calendar
}
}
// MARK: - CalendarInteractor implementation
extension CalendarInteractorImpl: CalendarInteractor {
public func monthMetadata(date: Date) -> Single<MonthMetadata> {
return .create { [weak self] single in
guard let self = self else {
single(.error(CalendarInteractorError.failed))
return Disposables.create()
}
let numberOfDaysInMonth = self.calendar.range(of: .day, in: .month, for: date)?.count
let firstDayOfMonth = self.calendar.date(from: self.calendar.dateComponents([.year, .month], from: date))
guard let numberOfDays = numberOfDaysInMonth, let firstDay = firstDayOfMonth else {
single(.error(CalendarInteractorError.failed))
return Disposables.create()
}
let lastDayInMonth = self.calendar.date(byAdding: DateComponents(month: 1, day: -1), to: firstDay)
let firstDayWeekday = self.calendar.component(.weekday, from: firstDay)
guard let lastDay = lastDayInMonth else {
single(.error(CalendarInteractorError.failed))
return Disposables.create()
}
let metadata = MonthMetadata(
numberOfDays: numberOfDays,
firstDay: firstDay,
lastDay: lastDay,
firstDayWeekday: firstDayWeekday
)
single(.success(metadata))
return Disposables.create()
}
}
}
| true
|
e574df7a52dec9ac0f3d3b2dfa6f296b4191d3f4
|
Swift
|
rubu/Pancake
|
/Pancake/RingBuffer.swift
|
UTF-8
| 4,184
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// RingBuffer.swift
// Pancake
//
// Created by mxa on 19.09.2017.
// Copyright © 2017 0bmxa. All rights reserved.
//
// From 10.15 the CoreAudioTypes from CoreAudio has been moved to CoreAudioTypes
#if canImport(CoreAudioTypes)
import CoreAudioTypes.CoreAudioBaseTypes
#else
import CoreAudio.CoreAudioTypes
#endif
final class RingBuffer {
private(set) var frames: UInt32
private var byteSize: UInt32
private var buffer: UnsafeMutableRawPointer
private let serialQueue: DispatchQueue
private var activeFormat: AudioStreamBasicDescription
init(frames: UInt32, format: AudioStreamBasicDescription) {
self.frames = frames
self.activeFormat = format
self.byteSize = frames * format.mBytesPerFrame
self.buffer = calloc(1, Int(self.byteSize))
let queueID = UUID().string
self.serialQueue = DispatchQueue(label: "Pancake.RingBuffer." + queueID)
}
deinit {
free(self.buffer)
}
private func reAllocateBuffer() {
self.byteSize = self.frames * self.activeFormat.mBytesPerFrame
self.buffer = realloc(self.buffer, Int(self.byteSize))
}
func fill(from srcBuffer: UnsafeMutableRawPointer, fromOffset frameOffset: UInt32, numberOfFrames frameCount: UInt32) {
// Translate frames to bytes
let bytesPerFrame = self.activeFormat.mBytesPerFrame
let startByte = Int(frameOffset * bytesPerFrame)
let bytesToCopy = Int(frameCount * bytesPerFrame)
guard bytesToCopy <= self.byteSize else { assertionFailure(); return }
self.serialQueue.sync {
// Copy directly, if we can.
// (If the segment to copy fits in the rest of the ringbuffer)
if (startByte + bytesToCopy) <= self.byteSize {
memcpy(self.buffer + startByte, srcBuffer, bytesToCopy)
return
}
// Otherwise, copy first half from [offset – ringbuffer end],
// then second half [ringbuffer start – requested lenght]
let sizeOfFirstHalf = Int(self.byteSize) - startByte
let sizeOfSecondHalf = bytesToCopy - sizeOfFirstHalf
memcpy(self.buffer + startByte, srcBuffer, sizeOfFirstHalf)
memcpy(self.buffer, srcBuffer + sizeOfFirstHalf, sizeOfSecondHalf)
}
}
func copy(to destBuffer: UnsafeMutableRawPointer, fromOffset frameOffset: UInt32, numberOfFrames frameCount: UInt32) {
// Translate frames to bytes
let bytesPerFrame = Int(self.activeFormat.mBytesPerFrame)
let startByte = Int(frameOffset) * bytesPerFrame
let bytesToCopy = Int(frameCount) * bytesPerFrame
guard bytesToCopy <= self.byteSize else { assertionFailure(); return }
self.serialQueue.sync {
// Copy directly, if we can
// (if the segment to copy can be taken from the rest of the ringbuffer)
if (startByte + bytesToCopy) <= self.byteSize {
memcpy(destBuffer, self.buffer + startByte, bytesToCopy)
return
}
// Otherwise, copy first half from [offset – ringbuffer end],
// then second half [ringbuffer start – requested lenght]
let sizeOfFirstHalf = Int(self.byteSize) - startByte
let sizeOfSecondHalf = bytesToCopy - sizeOfFirstHalf
memcpy(destBuffer, self.buffer + startByte, sizeOfFirstHalf)
memcpy(destBuffer + sizeOfFirstHalf, self.buffer, sizeOfSecondHalf)
}
}
/// Updates the format used in the ringbuffer.
/// **Caution:** this resets the buffer.
///
/// - Parameter format: The new audio format to be used.
func update(format: AudioStreamBasicDescription) {
self.activeFormat = format
self.reAllocateBuffer()
}
/// Updates the frame count used in the ringbuffer.
/// **Caution:** this resets the buffer.
///
/// - Parameter frames: The new number of frames to be used.
func update(frames: Int) {
self.frames = UInt32(frames)
self.reAllocateBuffer()
}
}
| true
|
d704ea8929cf34759032267843d60f9e3d4f32e0
|
Swift
|
Vietanh09876/swiftgit
|
/thigiua/thigiua/main.swift
|
UTF-8
| 8,318
| 3.1875
| 3
|
[] |
no_license
|
import Foundation
//Bài 1
func hcn() {
print("Chiều dài: ", terminator: "")
let x = readLine()
guard let x1 = x, let x2 = Int(x1) else {
print("Chiều dài không hợp lệ")
return
}
print("Chiều rộng: ", terminator: "")
let y = readLine()
guard let y1 = y, let y2 = Int(y1) else {
print("Chiều rộng không hợp lệ")
return
}
if x2 == 0 || y2 == 0 {
print("Chiều rộng hoặc chiều dài không hợp lệ")
} else {
for i in 1...y2 {
for u in 1...x2 {
if i == 1 || i == y2 {
print("*", terminator: "")
}
else {
if u == 1 || u == x2 {
print("*",terminator: "")
} else {
print(" ", terminator: "")
}
}
}
print()
}
}
}
//Bài 2
func lich() {
print("Ngày: ", terminator: "")
let n = readLine()
print("Tháng: ", terminator: "")
let t = readLine()
print("Năm: ", terminator: "")
let na = readLine()
guard let n1 = n, let n2 = Int(n1) else {
print("Ngày không hợp lệ")
return
}
guard let t1 = t, let t2 = Int(t1) else {
print("Tháng không hợp lệ")
return
}
guard let na1 = na, let na2 = Int(na1) else {
print("Năm không hợp lệ")
return
}
if t2 > 12 || t2 < 1 {
print("Tháng không hợp lệ")
return
}
else {
if [1,3,5,7,8,10,12].contains(t2) {
print("Tháng \(t2) có 31 ngày")
}
else if t2 == 2 {
if na2%4 == 0 && na2%100 != 0 || na2%400 == 0 {
print("Tháng \(t2) có 29 ngày")
}
else {
print("Tháng \(t2) có 28 ngày")
}
}
else {
print("Tháng \(t2) có 30 ngày")
}
}
if [1,3,5,7,8,10,12].contains(t2) {
if t2 == 1 {
if n2 < 31 && n2 > 1 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else if n2 == 31 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày 1 tháng \(t2+1)")
}
else if n2 == 1{
print("Ngày trước ngày \(n2) là ngày 31 tháng 12 năm \(na2-1) ")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else {
print("Ngày không hợp lệ")
}
}
else if t2 == 12 {
if n2 < 31 && n2 > 1 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else if n2 == 31 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày 1 tháng 1 năm \(na2+1)")
}
else if n2 == 1 {
print("Ngày trước ngày \(n2) là ngày 30 tháng \(t2-1) ")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else {
print("Ngày không hợp lệ")
}
}
else if t2 == 3 {
if na2%4 == 0 && na2%100 != 0 || na2%400 == 0 {
if n2 < 30 && n2 > 1 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else if n2 == 30 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày 1 tháng \(t2+1)")
}
else if n2 == 1 {
print("Ngày trước ngày \(n2) là ngày 29 tháng \(t2-1) ")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else {
print("Ngày không hợp lệ")
}
}
else {
if n2 < 30 && n2 > 1 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else if n2 == 30 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày 1 tháng \(t2+1)")
}
else if n2 == 1 {
print("Ngày trước ngày \(n2) là ngày 28 tháng \(t2-1) ")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else {
print("Ngày không hợp lệ")
}
}
}
else {
if n2 < 31 && n2 > 1 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else if n2 == 31 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày 1 tháng \(t2+1)")
}
else if n2 == 1 {
print("Ngày trước ngày \(n2) là ngày 30 tháng \(t2-1) ")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else {
print("Ngày không hợp lệ")
}
}
}
else if t2 == 2 {
if na2%4 == 0 && na2%100 != 0 || na2%400 == 0 {
if n2 < 29 && n2 > 1 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else if n2 == 29 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày 1 tháng \(t2+1)")
}
else if n2 == 1 {
print("Ngày trước ngày \(n2) là ngày 31 tháng \(t2-1) ")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else {
print("Ngày không hợp lệ")
}
}
else {
if n2 < 28 && n2 > 1 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else if n2 == 28 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày 1 tháng \(t2+1)")
}
else if n2 == 1 {
print("Ngày trước ngày \(n2) là ngày 31 tháng \(t2-1) ")
print("Ngày sau ngày \(n2) là ngày 1 \(n2+1)")
}
else {
print("Ngày không hợp lệ")
}
}
}
else {
if n2 < 30 && n2 > 1 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else if n2 == 30 {
print("Ngày trước ngày \(n2) là ngày \(n2-1)")
print("Ngày sau ngày \(n2) là ngày 1 tháng \(t2+1)")
}
else if n2 == 1 {
print("Ngày trước ngày \(n2) là ngày 31 tháng \(t2-1) ")
print("Ngày sau ngày \(n2) là ngày \(n2+1)")
}
else {
print("Ngày không hợp lệ")
}
}
}
//Bài 3
var o = 0
func doan() {
let x = Int.random(in: 1...100)
if o == 3 {
print("Bạn đã hết lượt thử")
}
else {
print("Hãy đoán 1 số bất kỳ từ 1-100: ", terminator: "")
let y = readLine()
guard let y1 = y, let y2 = Int(y1) else {
print("Không hợp lệ")
o += 1
doan()
return
}
if x == y2 {
print("Chúc mừng bạn đã đoán đúng")
}
else if y2 < x {
print("Bé quá")
}
else {
print("Lớn quá")
}
}
}
| true
|
f093bc692f36d53e272cc772462381a99d6871f8
|
Swift
|
cipriancaba/swiftintro
|
/TswiftDeck/TswiftDeck/ImageService.swift
|
UTF-8
| 606
| 2.8125
| 3
|
[] |
no_license
|
//
// ImageService.swift
// TswiftDeck
//
// Created by Ciprian Caba on 28/08/15.
// Copyright (c) 2015 Ciprian Caba. All rights reserved.
//
import Foundation
import UIKit
class ImageService {
static var cache: [String: UIImage] = [:]
class func getImage(url: String) -> UIImage? {
if let image = cache[url] {
return image
} else {
if let nsurl = NSURL(string: url) {
if let data = NSData(contentsOfURL: nsurl){
if let image = UIImage(data: data) {
cache[url] = image
return image
}
}
}
}
return nil
}
}
| true
|
bb08a716fff0d4d0f459f91db106f0136235eacf
|
Swift
|
noremac/Layout
|
/Tests/LayoutTests/BuilderTests.swift
|
UTF-8
| 7,704
| 2.890625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
import SwiftUI
import UIKit
import XCTest
@testable import Layout
enum TestEnum {
case one
case two
case three
}
extension UILabel {
convenience init(int: Int) {
self.init(frame: .zero)
text = "\(int)"
}
}
final class BadConstrainableItem: ConstrainableItem {
var parentView: UIView?
func setTranslatesAutoresizingMaskIntoConstraintsFalseIfNecessary() {}
}
final class StackBuilderTests: XCTestCase {
func testVerticalDefaultInitializers() {
let stack = UIStackView.vertical {}
XCTAssertEqual(stack.axis, .vertical)
XCTAssertEqual(stack.distribution, .fill)
XCTAssertEqual(stack.alignment, .fill)
XCTAssertEqual(stack.spacing, UIStackView.spacingUseDefault)
}
func testVerticalInitializerPassThrough() {
let stack = UIStackView.vertical(distribution: .fillEqually, alignment: .top, spacing: 100) {}
XCTAssertEqual(stack.axis, .vertical)
XCTAssertEqual(stack.distribution, .fillEqually)
XCTAssertEqual(stack.alignment, .top)
XCTAssertEqual(stack.spacing, 100)
}
func testHorizontalDefaultInitializers() {
let stack = UIStackView.horizontal {}
XCTAssertEqual(stack.axis, .horizontal)
XCTAssertEqual(stack.distribution, .fill)
XCTAssertEqual(stack.alignment, .fill)
XCTAssertEqual(stack.spacing, UIStackView.spacingUseDefault)
}
func testHorizontalInitializerPassThrough() {
let stack = UIStackView.horizontal(distribution: .fillEqually, alignment: .top, spacing: 100) {}
XCTAssertEqual(stack.axis, .horizontal)
XCTAssertEqual(stack.distribution, .fillEqually)
XCTAssertEqual(stack.alignment, .top)
XCTAssertEqual(stack.spacing, 100)
}
func testAddsSubviews() {
let label = UILabel()
let stack = UIStackView.vertical {
label
}
XCTAssertEqual(label.superview, stack)
XCTAssertEqual(stack.arrangedSubviews, [label])
}
func testCustomSpacing() {
let label = UILabel()
let stack = UIStackView.vertical {
label
.spacingAfter(10)
}
XCTAssertEqual(stack.customSpacing(after: label), 10)
}
func testIfTrue() {
let label1 = UILabel()
let label2 = UILabel()
let value = true
let stack = UIStackView.vertical {
if value {
label1
} else {
label2
}
}
XCTAssertEqual(stack.arrangedSubviews, [label1])
}
func testIfFalse() {
let label1 = UILabel()
let label2 = UILabel()
let value = false
let stack = UIStackView.vertical {
if value {
label1
} else {
label2
}
}
XCTAssertEqual(stack.arrangedSubviews, [label2])
}
func testIfTrueWithoutElse() {
let label1 = UILabel()
let value = true
let stack = UIStackView.vertical {
if value {
label1
}
}
XCTAssertEqual(stack.arrangedSubviews, [label1])
}
func testIfFalseWithoutElse() {
let label1 = UILabel()
let value = false
let stack = UIStackView.vertical {
if value {
label1
}
}
XCTAssertEqual(stack.arrangedSubviews, [])
}
func testSwitchOne() {
let label1 = UILabel()
let label2 = UILabel()
let label3 = UILabel()
let value = TestEnum.one
let stack = UIStackView.vertical {
switch value {
case .one:
label1
case .two:
label2
case .three:
label3
}
}
XCTAssertEqual(stack.arrangedSubviews, [label1])
}
func testSwitchTwo() {
let label1 = UILabel()
let label2 = UILabel()
let label3 = UILabel()
let value = TestEnum.two
let stack = UIStackView.vertical {
switch value {
case .one:
label1
case .two:
label2
case .three:
label3
}
}
XCTAssertEqual(stack.arrangedSubviews, [label2])
}
func testSwitchThree() {
let label1 = UILabel()
let label2 = UILabel()
let label3 = UILabel()
let value = TestEnum.three
let stack = UIStackView.vertical {
switch value {
case .one:
label1
case .two:
label2
case .three:
label3
}
}
XCTAssertEqual(stack.arrangedSubviews, [label3])
}
func testOptionalNil() {
let label: UILabel? = nil
let stack = UIStackView.vertical {
label
}
XCTAssertEqual(stack.arrangedSubviews, [])
}
func testOptionalNotNil() {
let label: UILabel? = UILabel()
let stack = UIStackView.vertical {
label
}
XCTAssertEqual(stack.arrangedSubviews, [label!])
}
func testUIViewBuilder() {
let label = UILabel()
let guide = UILayoutGuide()
let view = UIView.build {
label
guide
}
XCTAssertEqual(label.superview, view)
XCTAssertEqual(guide.owningView, view)
}
func testViewParent() {
let label = UILabel()
let view = UIView.build {
label.constraints {
AlignEdges()
}
}
let constraint = view.constraints.first
XCTAssertTrue(constraint?.secondItem === view)
}
func testGuideParent() {
let guide = UILayoutGuide()
let label = UILabel()
let view = UIView.build {
UILayoutGuide.build {
guide.constraints {
AlignEdges()
}
label.constraints {
AlignEdges()
}
}
}
XCTAssertEqual(guide.owningView, view)
XCTAssertEqual(label.superview, view)
XCTAssertEqual(view.constraints.count, 8)
XCTAssertTrue(view.constraints.allSatisfy({ $0.secondItem is UILayoutGuide }))
}
func testFatalErrorsIfYouPassSomethingWrong() {
let crashed = FatalError.withTestFatalError {
_ = UIView.build {
BadConstrainableItem()
}
}
XCTAssertTrue(crashed)
}
func testArray() {
let view = UIStackView.vertical {
(0..<100).map(UILabel.init(int:))
}
XCTAssertEqual(view.arrangedSubviews.count, 100)
}
func testForEach() {
let view = UIStackView.vertical {
for i in 0..<100 {
UILabel(int: i)
}
}
XCTAssertEqual(view.arrangedSubviews.count, 100)
}
func testAvailabilityAvailable() throws {
let view = UIStackView.vertical {
if #available(iOS 13, *) {
UILabel()
} else {
UITextField()
}
}
let item = try XCTUnwrap(view.arrangedSubviews.first)
XCTAssertTrue(item is UILabel)
}
func testAvailabilityNotAvailable() throws {
let view = UIStackView.vertical {
if #available(iOS 9999, *) {
UILabel()
} else {
UITextField()
}
}
let item = try XCTUnwrap(view.arrangedSubviews.first)
XCTAssertTrue(item is UITextField)
}
}
| true
|
0f460d62fb97b3d1f936bd11d8c89a0d052493e8
|
Swift
|
taigamatsuo/Messa-ji
|
/Messaji/Controller/ViewController.swift
|
UTF-8
| 8,793
| 2.875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Messaji
//
// Created by 松尾大雅 on 2020/10/08.
// Copyright © 2020 litech. All rights reserved.
//
import UIKit
import os
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate{
@IBOutlet weak var AddImage: UIImageView!
@IBOutlet weak var NameText: UITextField!
@IBOutlet weak var DateLabel: UILabel!
var saveData : UserDefaults = UserDefaults.standard
var Userimage : UIImage!
var request : UNNotificationRequest!
override func viewDidLoad() {
super.viewDidLoad()
UIset()
Dayset()
timerFiring()
updateColor()
}
//UI設定諸々
func UIset(){
AddImage.layer.cornerRadius = 75
AddImage.layer.shadowColor = UIColor.black.cgColor //影の色を決める
AddImage.layer.shadowOpacity = 1 //影の色の透明度
AddImage.layer.shadowRadius = 8 //影のぼかし
AddImage.layer.shadowOffset = CGSize(width: 4, height: 4)
if DateLabel.text != nil{
judgeDate()
}
self.AddImage.isUserInteractionEnabled = true
NameText.text = saveData.object(forKey: "key_NameText") as? String
if saveData.object(forKey: "key_AddImage") != nil {
let ImageData = saveData.data(forKey: "key_AddImage")
let Userimage2 = UIImage(data: ImageData!)
Userimage = Userimage2
AddImage.image = Userimage
}
}
// 日付フォーマット
func Dayset(){
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .medium
dateFormatter.dateStyle = .medium
dateFormatter.locale = Locale(identifier: "ja_JP")
// 現在時刻の1分後に設定
let date2 = Date(timeInterval: 5, since: date)
let targetDate = Calendar.current.dateComponents(
[.year, .month, .day, .hour, .minute],
from: date2)
let dateString = dateFormatter.string(from: date2)
print(dateString)
// トリガーの作成
let trigger = UNCalendarNotificationTrigger.init(dateMatching: targetDate, repeats: false)
// 通知コンテンツの作成
let content = UNMutableNotificationContent()
content.title = "Calendar Notification"
content.body = dateString
content.sound = UNNotificationSound.default
// 通知リクエストの作成
request = UNNotificationRequest.init(
identifier: "CalendarNotification",
content: content,
trigger: trigger)
}
func judgeDate(){
//現在のカレンダ情報を設定
let calender = Calendar.current
//日本時間を設定
let now_day = Date(timeIntervalSinceNow: 60 * 60 * 9)
//日付判定結果
var judge = Bool()
// 日時経過チェック
if saveData.object(forKey: "today") != nil {
let past_day = saveData.object(forKey: "today") as! Date
let now = calender.component(.minute, from: now_day)
let past = calender.component(.minute, from: past_day)
let diff = calender.dateComponents([.minute], from: past_day, to: now_day)
print(diff.minute!)
DateLabel.text = String("\(diff.minute!)分話していません")
//日にちが変わっていた場合
if now != past {
judge = true
}
else {
judge = false
}
}
//初回実行のみelse(nilならば、)
else {
judge = true
/* 今の日時を保存 */
saveData.set(now_day, forKey: "today")
}
/* 日付が変わった場合はtrueの処理 */
if judge == true {
judge = false
//日付が変わった時の処理
}
else {
//日付が変わっていない時の処理をここに書く
DateLabel.text = "初日です!"
}
}
//背景色変化
func timerFiring() {
let timer = Timer(timeInterval: 0.2,
target: self,
selector: #selector(updateColor),
userInfo: nil,
repeats: true)
RunLoop.main.add(timer, forMode: .default)
}
@objc func updateColor() {
//グラデーションの開始色(上下)
//タイマー処理でRGB値を少しずつ変化させてセット
let topColor = UIColor(red: 1.0, green: 0, blue: 0, alpha: 1.0)
let bottomColor = UIColor(red: 1.0, green: 0.5, blue: 0, alpha: 1.0)
//グラデーションの色を配列で管理
let gradientColors: [CGColor] = [topColor.cgColor, bottomColor.cgColor]
//グラデーションレイヤーを作成
var gradientLayer = CAGradientLayer()
gradientLayer.removeFromSuperlayer()
gradientLayer = CAGradientLayer()
//グラデーションの色をレイヤーに割り当てる
gradientLayer.colors = gradientColors
//グラデーションレイヤーをスクリーンサイズにする
gradientLayer.frame = self.view.bounds
//グラデーションレイヤーをビューの一番下に配置
self.view.layer.insertSublayer(gradientLayer, at: 0)
}
//登録ボタンで値をuserdefaultsへ保存する
@IBAction func save(_ sender: Any) {
os_log("setButton")
// saveData.set(EmailText.text, forKey: "key_EmailText")
saveData.set(NameText.text, forKey: "key_NameText")
// saveData.set(TextView.text, forKey: "key_TextView")
let data = Userimage.pngData()
saveData.set(data, forKey: "key_AddImage")
judgeDate()
// 通知リクエストの登録
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
print("alertrequest!")
let alert : UIAlertController = UIAlertController(title: "登録しました", message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction(title:"OK",style: .default, handler: nil))
present(alert,animated: true, completion: nil)
}
// タップされたときの処理
@IBAction func tapped(sender: UITapGestureRecognizer){
print("押されました")
//アラートを出す
let alert : UIAlertController = UIAlertController(title: "プロフィール写真を選択", message: "", preferredStyle: .alert)
//OKボタン
alert.addAction(UIAlertAction(title:"OK",style: .default, handler: { action in
//ボタンが押された時の動作
print("OKが押されました")
//フォトライブラリの画像を呼び出す
let imagePickerController : UIImagePickerController = UIImagePickerController()
imagePickerController.sourceType = UIImagePickerController.SourceType.photoLibrary
imagePickerController.allowsEditing = true
self.present(imagePickerController,animated: true , completion: nil)
imagePickerController.delegate = self
}
))
alert.addAction(UIAlertAction(title:"Cancel",style: .default, handler: nil))
present(alert,animated: true, completion: nil)
}
}
extension ViewController {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
//選択された画像を取得
guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage?
else {return}
Userimage = selectedImage
//画像を変更
self.AddImage.image = Userimage
print("画像が選択されました")
//imagepickerの削除
self.dismiss(animated: true, completion: nil)
}
}
| true
|
a1cd42a2833a0759f4381efc91a7656b68696d8e
|
Swift
|
jocate/ios-albums
|
/Albums/Albums/Album.swift
|
UTF-8
| 5,106
| 3.15625
| 3
|
[] |
no_license
|
//
// Album.swift
// Albums
//
// Created by Jocelyn Stuart on 2/18/19.
// Copyright © 2019 JS. All rights reserved.
//
import Foundation
struct Album: Codable, Equatable {
enum CodingKeys: String, CodingKey {
case artist
case name
case genres
case coverArt
case id
}
var artist: String
var name: String
var genres: [String]
var coverArt: [[String: String]]
var id: String?
init(artist: String, name: String, genres: [String], coverArt: [[String: String]], id: String? = UUID().uuidString) {
self.artist = artist
self.name = name
self.genres = genres
self.coverArt = coverArt
self.id = id
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let genres = try container.decode([String].self, forKey: .genres)
let artist = try container.decode(String.self, forKey: .artist)
let name = try container.decode(String.self, forKey: .name)
let id = try container.decodeIfPresent(String.self, forKey: .id)
//var coverArt: [[String: String]] = []
let coverArt = try container.decode([[String: String]].self, forKey: .coverArt)
//coverArt.append(coverArts)
self.artist = artist
self.name = name
self.genres = genres
self.coverArt = coverArt
self.id = id
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(artist, forKey: .artist)
try container.encode(name, forKey: .name)
var genresContainer = container.nestedUnkeyedContainer(forKey: .genres)
for genre in genres {
try genresContainer.encode(genre)
}
var coverArtContainer = container.nestedUnkeyedContainer(forKey: .coverArt)
for art in coverArt {
try coverArtContainer.encode(art)
}
}
}
struct Song: Codable {
enum CodingKeys: String, CodingKey {
case songs
enum SongsCodingKeys: String, CodingKey {
case duration
enum DurationCodingKeys: String, CodingKey {
case duration
}
case name
enum NameCodingKeys: String, CodingKey {
case title
}
}
}
var songs: [String: String] //ability - name // duration - duration and name - title
init(songs: [String: String]) {
self.songs = songs
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
var songsContainer = try container.nestedUnkeyedContainer(forKey: .songs)
var songs: [String: String] = [:]
while !songsContainer.isAtEnd {
let songContainer = try songsContainer.nestedContainer(keyedBy: CodingKeys.SongsCodingKeys.self)
let songTitleContainer = try songContainer.nestedContainer(keyedBy: CodingKeys.SongsCodingKeys.NameCodingKeys.self, forKey: .name)
let songTitle = try songTitleContainer.decode(String.self, forKey: .title)
let songDurationContainer = try songContainer.nestedContainer(keyedBy: CodingKeys.SongsCodingKeys.DurationCodingKeys.self, forKey: .duration)
let durationTime = try songDurationContainer.decode(String.self, forKey: .duration)
songs[songTitle] = durationTime
}
self.songs = songs
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
var songsContainer = container.nestedUnkeyedContainer(forKey: .songs)
for name in songs.keys {
var songContainer = songsContainer.nestedContainer(keyedBy: CodingKeys.SongsCodingKeys.self)
var songTitleContainer = songContainer.nestedContainer(keyedBy: CodingKeys.SongsCodingKeys.NameCodingKeys.self, forKey: .name)
try songTitleContainer.encode(name, forKey: .title)
}
for duration in songs.values {
var songContainer = songsContainer.nestedContainer(keyedBy: CodingKeys.SongsCodingKeys.self)
var songDurationContainer = songContainer.nestedContainer(keyedBy: CodingKeys.SongsCodingKeys.DurationCodingKeys.self, forKey: .duration)
try songDurationContainer.encode(duration, forKey: .duration)
}
}
}
/*struct CoverArt: Decodable {
enum CodingKeys: String, CodingKey {
case coverArt
enum ArtCodingKeys: String, CodingKey {
case url
}
}
var coverArt: [String: String]
}*/
| true
|
e518485311eefe23842e4343728da38246d5d3c3
|
Swift
|
syuyuusyu/iosJoyFish
|
/joyFish/spirt/BulletSpirt.swift
|
UTF-8
| 3,117
| 2.625
| 3
|
[] |
no_license
|
//
// BulletSpirt.swift
// joyFish
//
// Created by 沈渝 on 2018/10/23.
// Copyright © 2018 沈渝. All rights reserved.
//
import SpriteKit
import GameplayKit
class BulletSpirt :SKSpriteNode,AfterAddToGameScene{
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var level :Int
var direction :CGFloat
static private var textureMap:[String:SKTexture] = [
"bullet1" : SKTexture(imageNamed: "bullet1"),
"bullet2" : SKTexture(imageNamed: "bullet2"),
"bullet3" : SKTexture(imageNamed: "bullet3"),
"bullet4" : SKTexture(imageNamed: "bullet4"),
"bullet5" : SKTexture(imageNamed: "bullet5"),
"bullet6" : SKTexture(imageNamed: "bullet6"),
"bullet7" : SKTexture(imageNamed: "bullet7"),
"bullet8" : SKTexture(imageNamed: "bullet8"),
]
init(level:Int,direction:CGFloat,at point :CGPoint){
self.level = level
self.direction = direction
guard let texture = BulletSpirt.textureMap["bullet\(level)"] else {
fatalError("init() image bullet\(level) not exiset")
}
super.init(texture: texture, color: SKColor.clear, size: texture.size())
name = "bullet"
xScale = JoyFishConstant.Scale
yScale = JoyFishConstant.Scale
//anchorPoint = CGPoint(x:0,y:0.5)
position = point
zPosition = JoyFishConstant.bulletzPosition
zRotation = CGFloat.pi/2 - direction
speed = 2.0 + CGFloat(level)/2
physicsBody = SKPhysicsBody(circleOfRadius:min(self.size.width/2,self.size.height/2))
physicsBody?.isDynamic = true
physicsBody?.affectedByGravity = false
physicsBody?.categoryBitMask = JoyFishConstant.bulletCategoryBitMask
physicsBody?.collisionBitMask = 0
physicsBody?.contactTestBitMask = JoyFishConstant.fishCategoryBitMask
}
deinit {
//print("bullet collisionCount",collisionCount)
}
var collisionCount = 0
public func collide(){
let web = WebSpirt(level: level, at: position)
scene?.addChild(web)
removeAction(forKey: "move")
removeFromParent()
}
func afterAddToScene() {
let duration = TimeInterval(Int.max)
let moveAction = SKAction.customAction(withDuration:duration,actionBlock:{ (node,elapsedTime) in
if let node = node as? SKSpriteNode{
node.position.x += sin(self.direction) * self.speed
node.position.y += cos(self.direction) * self.speed
//node.zRotation = self.direction
if node.position.x > (node.scene?.view?.bounds.width)!+210
|| node.position.y > (node.scene?.view?.bounds.height)!+210
|| node.position.x < -210
|| node.position.y < -210 {
node.removeAction(forKey: "move")
node.removeFromParent()
}
}
})
run(moveAction,withKey:"move")
}
}
| true
|
47f7546146e0801956c983c9ab019e07fe01c241
|
Swift
|
ahspadafora/PWR
|
/PWR/PWR/Delegates/ParserDelegate.swift
|
UTF-8
| 1,557
| 2.578125
| 3
|
[] |
no_license
|
//
// ParserDelegate.swift
// PWR
//
// Created by Amber Spadafora on 10/3/17.
// Copyright © 2017 Amber Spadafora. All rights reserved.
//
import Foundation
class ParserDelegate: NSObject, XMLParserDelegate {
private var currentString = String()
private var currentElement = String()
private var object: [String: String] = [:]
private var objArray: [[String: String]] = []
var senators: [Senator] = []
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
if elementName != "member" {
self.currentElement = elementName
self.object[self.currentElement] = String()
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == "member" {
self.objArray.append(self.object)
self.object = [:]
}
if elementName == self.currentElement {
self.object[self.currentElement] = self.currentString.trimmingCharacters(in: .whitespacesAndNewlines)
self.currentString = ""
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
self.currentString += string
}
func parserDidEndDocument(_ parser: XMLParser) {
print("finished parsing documnet")
print(self.objArray.count)
self.senators = objArray.flatMap{Senator.init(dict: $0)}
}
}
| true
|
73b6077fb38caa0ec2a8f20fe0bf413c0d60686a
|
Swift
|
pkulcsarsz/VMA-IOS
|
/Foods/Foods/MealDetailViewController.swift
|
UTF-8
| 2,214
| 2.75
| 3
|
[] |
no_license
|
//
// MealDetailViewController.swift
// Foods
//
// Created by Péter Kulcsár Szabó on 10/11/2018.
// Copyright © 2018 Péter Kulcsár Szabó. All rights reserved.
//
import UIKit
class MealDetailViewController: UIViewController {
//MARK: Properties
var meal : Meal?
@IBOutlet var mealName: UILabel!
@IBOutlet var mealImage: UIImageView!
@IBOutlet var mealInfo: UILabel!
@IBOutlet var mealTime: UILabel!
@IBOutlet var mealNutrition: UILabel!
@IBOutlet var authorImage: UIImageView!
@IBOutlet var authorName: UILabel!
@IBOutlet var ratingController: UIStackView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
mealName.text = meal?.name
mealInfo.text = meal?.info
mealImage.image = meal?.photo
mealImage.layer.cornerRadius = 20
mealImage.clipsToBounds = true
authorName.text = meal?.authorName
authorImage.image = meal?.author
mealTime.text = meal?.time
mealNutrition.text = meal?.nutrition
self.title = meal?.name
let starEmpty = UIImage(named: "star")
let starFilled = UIImage(named: "starFilled")
for i in 1...5 {
let imageView = UIImageView()
if ((meal?.rating)! <= i)
{
imageView.image = starEmpty
}
else
{
imageView.image = starFilled
}
ratingController.addArrangedSubview(imageView)
}
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
guard let mealIngredientViewController = segue.destination as? MealIngredientsViewController
else {
fatalError("Unexpected destination: \(sender ?? "unknown")")
}
mealIngredientViewController.meal = self.meal
}
}
| true
|
272e07069c16cc6b4d533a729e3fdbcae2bf5775
|
Swift
|
lishten/ProgressViewDemo
|
/ProgressViewDemo/CircleProgressView/CircleShapeLayer.swift
|
UTF-8
| 3,380
| 2.796875
| 3
|
[] |
no_license
|
//
// CircleShapeLayer.swift
// ProgressViewDemo
//
// Created by Lishten on 15/12/4.
// Copyright © 2015年 Lishten. All rights reserved.
//
import UIKit
class CircleShapeLayer: CAShapeLayer {
var startValue:Double!
var endingValue:Double!
var status:String!
var percent:Double!
var progressLayer:CAShapeLayer!
var initialProgress:Double!
required override init() {
super.init()
self.setUpLayer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setUpLayer(){
self.path = self.drawPathWithArcCenter()
self.fillColor = UIColor.clearColor().CGColor
self.lineWidth = 16
self.progressLayer = CAShapeLayer()
self.progressLayer.path = self.drawPathWithArcCenter()
self.progressLayer.fillColor = UIColor.yellowColor().CGColor
self.progressLayer.lineWidth = 16
self.progressLayer.lineCap = kCALineCapRound
self.progressLayer.lineJoin = kCALineJoinRound
self.progressLayer.borderWidth = 0.5
self.progressLayer.borderColor = UIColor.yellowColor().CGColor
self.progressLayer.strokeColor = UIColor.redColor().CGColor
self.addSublayer(self.progressLayer)
}
override func layoutSublayers() {
self.path = self.drawPathWithArcCenter()
self.progressLayer.path = self.drawPathWithArcCenter()
super.layoutSublayers()
}
func drawPathWithArcCenter() -> CGPathRef{
let position_y = self.frame.size.height / 2
let position_x = self.frame.size.width / 2
let startAge = CGFloat(-M_PI / 2)
let endAge = CGFloat((3 * M_PI) / 2)
let path = UIBezierPath(arcCenter: CGPointMake(position_x, position_y), radius: position_y, startAngle:startAge, endAngle: endAge, clockwise: true).CGPath
return path
}
func getEndingValue(endingValue:Double){
self.initialProgress = self.calculatePercent(startValue, toValue: endingValue)
self.endingValue = endingValue
self.percent = self.getPercent()
if self.percent != 0 {
self.startAnimation(self.percent)
} else {
self.initialProgress = self.calculatePercent(0, toValue: 0)
self.startAnimation(self.percent)
}
}
func getPercent() -> Double{
self.percent = self.calculatePercent(startValue, toValue: endingValue)
return percent
}
func getStartValue(startValue:Double ){
self.startValue = startValue
}
func calculatePercent(fromValue:Double, toValue:Double) -> Double{
if toValue > 0 {
var percent:Double!
percent = Double(toValue) / 100.0
return percent
} else {
return 0
}
}
func startAnimation(strokeEnd:Double){
// self.progressLayer.strokeStart = 0.5
// self.progressLayer.strokeEnd = CGFloat(strokeEnd)
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
// pathAnimation.duration = 3
pathAnimation.fromValue = 0
pathAnimation.toValue = self.percent
print(self.percent)
pathAnimation.removedOnCompletion = false
self.progressLayer.addAnimation(pathAnimation, forKey: "strokeEnd")
}
}
| true
|
4973a144e5432bc985c7d161a15c57e389d5d31e
|
Swift
|
AuroraFramework/Aurora.swift
|
/Sources/Aurora/propertyWrappers/Aurora.Config.swift
|
UTF-8
| 4,361
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
// Aurora framework for Swift
//
// The **Aurora.framework** contains a base for your project.
//
// It has a lot of extensions built-in to make development easier.
//
// - Version: 1.0
// - Copyright: [Wesley de Groot](https://wesleydegroot.nl) ([WDGWV](https://wdgwv.com))\
// and [Contributors](https://github.com/AuroraFramework/Aurora.swift/graphs/contributors).
//
// Thanks for using!
//
// Licence: MIT
import Foundation
/// A type safe property wrapper to set and get values from UserDefaults with support for defaults values.
///
/// Usage:
/// ```
/// @AuroraConfig("isReady", default: false)
/// static var isReady: Bool
/// ```
///
/// [Apple documentation on UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults)
@propertyWrapper
public struct AuroraConfig<Value: AuroraConfigStoreValue> {
/// A key in the current user‘s defaults database.
let key: String
/// A default value for the key in the current user‘s defaults database.
let defaultValue: Value
/// Current user's defaults database
var userDefaults: UserDefaults
/// Returns/set the object associated with the specified key.
/// - Parameters:
/// - key: A key in the current user‘s defaults database.
/// - default: A default value for the key in the current user‘s defaults database.
public init(_ key: String, `default`: Value) {
self.key = "Aurora." + key
self.defaultValue = `default`
self.userDefaults = .standard
}
/// Wrapped userdefault
public var wrappedValue: Value {
get {
return userDefaults.object(forKey: key) as? Value ?? defaultValue
}
set {
userDefaults.set(newValue, forKey: key)
}
}
}
/// A type than can be stored in `UserDefaults`.
///
/// From UserDefaults;
/// The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray,
/// or NSDictionary.
/// For NSArray and NSDictionary objects, their contents must be property list objects. For more information,
/// see What is a Property List? in Property List Programming Guide.
public protocol AuroraConfigStoreValue {}
/// Make `Data` compliant to `AuroraConfigStoreValue`
extension Data: AuroraConfigStoreValue {}
/// Make `NSData` compliant to `AuroraConfigStoreValue`
extension NSData: AuroraConfigStoreValue {}
/// Make `String` compliant to `AuroraConfigStoreValue`
extension String: AuroraConfigStoreValue {}
/// Make `Date` compliant to `AuroraConfigStoreValue`
extension Date: AuroraConfigStoreValue {}
/// Make `NSDate` compliant to `AuroraConfigStoreValue`
extension NSDate: AuroraConfigStoreValue {}
/// Make `NSNumber` compliant to `AuroraConfigStoreValue`
extension NSNumber: AuroraConfigStoreValue {}
/// Make `Bool` compliant to `AuroraConfigStoreValue`
extension Bool: AuroraConfigStoreValue {}
/// Make `Int` compliant to `AuroraConfigStoreValue`
extension Int: AuroraConfigStoreValue {}
/// Make `Int8` compliant to `AuroraConfigStoreValue`
extension Int8: AuroraConfigStoreValue {}
/// Make `Int16` compliant to `AuroraConfigStoreValue`
extension Int16: AuroraConfigStoreValue {}
/// Make `Int32` compliant to `AuroraConfigStoreValue`
extension Int32: AuroraConfigStoreValue {}
/// Make `Int64` compliant to `AuroraConfigStoreValue`
extension Int64: AuroraConfigStoreValue {}
/// Make `UInt` compliant to `AuroraConfigStoreValue`
extension UInt: AuroraConfigStoreValue {}
/// Make `UInt8` compliant to `AuroraConfigStoreValue`
extension UInt8: AuroraConfigStoreValue {}
/// Make `UInt16` compliant to `AuroraConfigStoreValue`
extension UInt16: AuroraConfigStoreValue {}
/// Make `UInt32` compliant to `AuroraConfigStoreValue`
extension UInt32: AuroraConfigStoreValue {}
/// Make `UInt64` compliant to `AuroraConfigStoreValue`
extension UInt64: AuroraConfigStoreValue {}
/// Make `Double` compliant to `AuroraConfigStoreValue`
extension Double: AuroraConfigStoreValue {}
/// Make `Floar` compliant to `AuroraConfigStoreValue`
extension Float: AuroraConfigStoreValue {}
/// Make `Array` compliant to `AuroraConfigStoreValue`
extension Array: AuroraConfigStoreValue where Element: AuroraConfigStoreValue {}
/// Make `Dictionary` compliant to `AuroraConfigStoreValue`
extension Dictionary: AuroraConfigStoreValue where Key == String, Value: AuroraConfigStoreValue {}
| true
|
52c6dd1b523b3406ea838b8c9e160f7391e97c31
|
Swift
|
ashislaha/BabyPink
|
/BabyPink/BabyPink/Product Details/Controller/ProductDetailsVC+extensions.swift
|
UTF-8
| 1,484
| 2.578125
| 3
|
[] |
no_license
|
//
// ProductDetailsVC+extensions.swift
// BabyPink
//
// Created by Ashis Laha on 28/01/18
// Copyright © 2018 Ashis Laha. All rights reserved.
//
import UIKit
extension ProductDetailsViewController {
func updateOffer(stepCount: Int) {
guard let product = model, !product.productOffer.isEmpty else { return }
switch stepCount {
case 0: offerLabel.text = product.productOffer
case let x where x > 0 && x < product.buy: viewModel.showOfferAvailMessage(x: x,product: product)
case let x where x >= product.buy: viewModel.showCongratsMessage(x: x, product: product)
default: break
}
}
func updateImage(id: String) {
viewModel.updateImage(id: id)
}
@objc func addToCardViewTapped() {
viewModel.addCartTapped()
}
@objc func favouriteTapped() {
viewModel.favouriteTapped()
}
}
// MARK:- TopViewProtocol
extension ProductDetailsViewController: TopViewProtocol {
func leftImageTapped(type: LeftImageType) {
dismiss(animated: true, completion: nil)
}
}
// MARK:- Used for Unit testing
extension ProductDetailsViewController {
func getOfferLabelText() -> String? {
return offerLabel.text
}
func getDescriptionLabelText() -> String? {
return descriptionLabel.text
}
func getPriceLabelText() -> String? {
return priceLabel.text
}
func getStepperCount() -> String? {
return stepCountLabel.text
}
}
| true
|
e031ef8b84d60c5ea9990cb3a78ca062d0cda0d7
|
Swift
|
jmade/Ambilight-iOS
|
/Ambilight/AmbilightOptions.swift
|
UTF-8
| 2,549
| 2.828125
| 3
|
[] |
no_license
|
//
// AmbilightOptions.swift
// Ambilight
//
// Created by Justin Madewell on 7/3/18.
// Copyright © 2018 Jmade. All rights reserved.
//
import Foundation
struct AmbilightOption {
enum Catagory: String {
case cec = "CEC"
case neopixel = "Neopixel"
case volume = "Volume"
case atv = "ATV"
case ir = "IR"
case test = "TEST"
case exp = "EXPERIMENTAL"
case undefined = "-"
func displayValue() -> String {
switch self {
case .cec:
return "CEC"
case .neopixel:
return "Neopixel"
case .volume:
return "Volume"
case .atv:
return "tv"
case .ir:
return "IR"
case .test:
return "Test"
case .exp:
return "Experimental"
case .undefined:
return "-"
}
}
}
let catagory: Catagory
let title: String
let description: String
enum Keys: String {
case catagory = "catagory"
case title = "title"
case description = "description"
}
init(_ data:[String:Any] = [:]) {
let rawCatagoryValue = data[Keys.catagory.rawValue] as? String ?? "-"
if let catagory = Catagory(rawValue: rawCatagoryValue) {
self.catagory = catagory
} else {
self.catagory = .undefined
}
self.title = data[Keys.title.rawValue] as? String ?? ""
self.description = data[Keys.description.rawValue] as? String ?? ""
}
}
struct AmbilightResponse {
enum Status {
case active, inactive, undefined
}
let options: [AmbilightOption]
let status: Status
let processName:String
enum Keys: String {
case options = "options"
case light_reading = "light_reading"
}
init(_ data:[String:Any] = [:]){
self.options = (data[Keys.options.rawValue] as? [[String:Any]] ?? [[:]]).map({AmbilightOption($0)})
let lightStatus = (data[Keys.light_reading.rawValue] as? [String:Any] ?? [:])
self.processName = lightStatus["process"] as? String ?? "-"
let status = lightStatus["status"] as? String ?? "-"
switch status {
case "Y":
self.status = .active
case "N":
self.status = .inactive
default:
self.status = .undefined
}
}
}
| true
|
9ee2a3ddf8bd4ddd0d0e1eadc8b96a959cd0e1da
|
Swift
|
gamael/Lets-cook
|
/Lets cook/App/Extensions.swift
|
UTF-8
| 1,472
| 3.140625
| 3
|
[] |
no_license
|
//
// Extensions.swift
// Lets cook
//
// Created by Alejandro Agudelo on 29/03/21.
// Copyright © 2021 Alejandro Agudelo. All rights reserved.
//
import UIKit
extension Decodable {
static func decode(with decoder: JSONDecoder = JSONDecoder(), from data: Data) throws -> Self {
return try decoder.decode(Self.self, from: data)
}
}
extension Encodable {
func encode(with encoder: JSONEncoder = JSONEncoder()) throws -> Data {
return try encoder.encode(self)
}
}
extension UIImageView {
func loadImage(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
contentMode = mode
let activityView = UIActivityIndicatorView(style: .medium)
activityView.center = center
addSubview(activityView)
activityView.startAnimating()
activityView.hidesWhenStopped = true
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: url) {
if let image = UIImage(data: data) {
DispatchQueue.main.async {
self?.image = image
}
}
}
DispatchQueue.main.async {
activityView.stopAnimating()
}
}
}
func loadImage(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
loadImage(from: url, contentMode: mode)
}
}
| true
|
de56dc5c59d2f825f3639bab15f272b8eb665ec0
|
Swift
|
rvsantos/TwitterClone
|
/TwitterClone/View/UserCell.swift
|
UTF-8
| 2,014
| 2.78125
| 3
|
[] |
no_license
|
//
// UserCell.swift
// TwitterClone
//
// Created by Rafael V. dos Santos on 06/01/21.
//
import UIKit
class UserCell: UITableViewCell {
// MARK:- Properties
var user: User? {
didSet { self.configure() }
}
private lazy var profileImageView: UIImageView = {
let iv = UIImageView()
iv.contentMode = .scaleAspectFit
iv.clipsToBounds = true
iv.setDimensions(width: 32, height: 32)
iv.layer.cornerRadius = 32/2
iv.backgroundColor = .twitterBlue
return iv
}()
private let usernameLabel: UILabel = {
let lb = UILabel()
lb.font = UIFont.boldSystemFont(ofSize: 14)
lb.text = "Username"
return lb
}()
private let fullnameLabel: UILabel = {
let lb = UILabel()
lb.font = UIFont.systemFont(ofSize: 14)
lb.text = "Fullname"
return lb
}()
// MARK:- Lifecycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.configureUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- Private
private func configure() {
guard let user = self.user else { return }
self.profileImageView.sd_setImage(with: user.profileImageUrl)
self.usernameLabel.text = user.username
self.fullnameLabel.text = user.fullname
}
private func configureUI() {
self.addSubview(self.profileImageView)
self.profileImageView.centerY(inView: self, leftAnchor: leftAnchor, paddingLeft: 12)
let stack = UIStackView(arrangedSubviews: [self.usernameLabel, self.fullnameLabel])
stack.axis = .vertical
stack.spacing = 2
self.addSubview(stack)
stack.centerY(inView: self.profileImageView, leftAnchor: self.profileImageView.rightAnchor, paddingLeft: 12)
}
}
| true
|
c6b36a85a617c3f4a9433f73b064440f1c69478c
|
Swift
|
Ziangirov/CS193P.Assignment5.ImageGallery
|
/ImageGallery/GalleryCell.swift
|
UTF-8
| 2,444
| 2.859375
| 3
|
[] |
no_license
|
//
// GalleryCell.swift
// ImageGallery
//
// Created by Evgeniy Ziangirov on 23/07/2018.
// Copyright © 2018 Evgeniy Ziangirov. All rights reserved.
//
import UIKit
protocol GalleryCellDelegate {
func titleDidChange(_ title: String, in cell: UITableViewCell)
}
class GalleryCell: UITableViewCell, UITextFieldDelegate {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupViews()
textField.delegate = self
textField.clearsOnBeginEditing = false
textField.isUserInteractionEnabled = false
textField.addTarget(self, action: #selector(titleDidChange(_:)), for: .editingDidEnd)
textField.returnKeyType = .done
textField.keyboardType = .alphabet
let tap = UITapGestureRecognizer(target: self, action: #selector(editName(_:)))
tap.numberOfTapsRequired = 2
self.addGestureRecognizer(tap)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let textField: UITextField = {
let textField = UITextField()
textField.backgroundColor = .lead
textField.alpha = 0.90
textField.textColor = .white
return textField
}()
var delegate: GalleryCellDelegate?
private var title: String {
set {
textField.text = newValue
}
get {
return textField.text ?? ""
}
}
private func setupViews() {
backgroundColor = .lead
alpha = 0.90
contentView.addSubview(textField)
contentView.activateConstraints(withVisualFormat: "H:|-[v0]-|", for: textField)
contentView.activateConstraints(withVisualFormat: "V:|-[v0]-|", for: textField)
}
@objc private func editName(_ sender: UITapGestureRecognizer) {
if sender.state == .ended {
textField.isUserInteractionEnabled = true
textField.becomeFirstResponder()
}
}
@objc func titleDidChange(_ sender: UITextField) {
guard let title = sender.text, title != "" else { return }
delegate?.titleDidChange(sender.text ?? "", in: self)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
textField.isUserInteractionEnabled = false
return true
}
}
| true
|
9241d8a8a5a8f725bbc2f76524d5f4fa62e9562e
|
Swift
|
julianny-favinha/movile-next
|
/MovieList/MovieList/Controller/NotificationViewController.swift
|
UTF-8
| 4,165
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
//
// NotificationViewController.swift
// MovieList
//
// Created by Julianny Favinha on 11/16/18.
// Copyright © 2018 MovileNext. All rights reserved.
//
import UIKit
import UserNotifications
class NotificationViewController: UIViewController {
// MARK: - IBOutlets
@IBOutlet weak var datePicker: UIDatePicker!
// MARK: - Variables
var movie: Movie?
let center = UNUserNotificationCenter.current()
// MARK: - Super Methods
override func viewDidLoad() {
super.viewDidLoad()
datePicker.minimumDate = Date()
center.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
center.getNotificationSettings { (settings) in
print("Authorization status: \(settings.authorizationStatus.rawValue)")
}
let confirmAction = UNNotificationAction(identifier: "confirm", title: "OK", options: [.destructive])
let cancelAction = UNNotificationAction(identifier: "cancel", title: "Cancel", options: [])
let category = UNNotificationCategory(identifier: "reminder",
actions: [confirmAction, cancelAction],
intentIdentifiers: [],
hiddenPreviewsBodyPlaceholder: "",
options: [.customDismissAction])
center.setNotificationCategories([category])
center.requestAuthorization(options: [.alert, .badge, .sound]) { (success, error) in
if error != nil {
print(error!)
} else {
print(success)
}
}
}
// MARK: - IBActions
@IBAction func savePressed(_ sender: UIBarButtonItem) {
let idNotification = String(Date().timeIntervalSince1970)
let content = UNMutableNotificationContent()
content.title = L10n.watchNowTheMovie + " '\(movie?.title ?? "")'"
// content.body = "So much \(movie?.categories?.first ?? "")!"
content.body = L10n.soMuchFun
content.categoryIdentifier = "reminder"
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute],
from: datePicker.date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: idNotification, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if error != nil {
print(error!)
} else {
DispatchQueue.main.async {
print("Notification registered at \(self.datePicker.date)")
}
}
}
self.dismiss(animated: true, completion: nil)
}
@IBAction func cancelPressed(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
}
// MARK: - Extensions
extension NotificationViewController: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler:
@escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
switch response.actionIdentifier {
case "confirm":
break
case "cancel":
break
case UNNotificationDefaultActionIdentifier:
print("Touched in notification")
case UNNotificationDismissActionIdentifier:
print("Dismissed notification")
default:
break
}
completionHandler()
}
}
| true
|
33a55625878c8e555c5677dac3c7849c5d655825
|
Swift
|
realm/SwiftLint
|
/Source/SwiftLintCore/Reporters/JUnitReporter.swift
|
UTF-8
| 1,449
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
/// Reports violations as JUnit XML.
struct JUnitReporter: Reporter {
// MARK: - Reporter Conformance
static let identifier = "junit"
static let isRealtime = false
static let description = "Reports violations as JUnit XML."
static func generateReport(_ violations: [StyleViolation]) -> String {
let warningCount = violations.filter({ $0.severity == .warning }).count
let errorCount = violations.filter({ $0.severity == .error }).count
return """
<?xml version="1.0" encoding="utf-8"?>
<testsuites failures="\(warningCount)" errors="\(errorCount)">
\t<testsuite failures="\(warningCount)" errors="\(errorCount)">
\(violations.map(testCase(for:)).joined(separator: "\n"))
\t</testsuite>
</testsuites>
"""
}
private static func testCase(for violation: StyleViolation) -> String {
let fileName = (violation.location.file ?? "<nopath>").escapedForXML()
let reason = violation.reason.escapedForXML()
let severity = violation.severity.rawValue.capitalized
let lineNumber = String(violation.location.line ?? 0)
let message = severity + ":" + "Line:" + lineNumber
return """
\t\t<testcase classname='Formatting Test' name='\(fileName)'>
\t\t\t<failure message='\(reason)'>\(message)</failure>
\t\t</testcase>
"""
}
}
| true
|
5009bceb16dfc2cc41e53259eafeec5ff0f3ad2a
|
Swift
|
onglao1999/onglao1999.github.io
|
/BT_Tren_Mang/BT_LogicNC/BT_LogicNC/B5.swift
|
UTF-8
| 740
| 3.203125
| 3
|
[] |
no_license
|
//
// B5.swift
// BT_LogicNC
//
// Created by Ong_Lao_Ngao on 1/6/20.
// Copyright © 2020 Ong_Lao_Ngao. All rights reserved.
//
//B5: Đổi mỗi kí tự đầu tiên của mỗi từ thành chữ in hoa
import Foundation
func b5(){
print("Nhập chuỗi từ bàn phím: ", terminator: "")
var chuoi: String = readLine() ?? " "
var mang: [Character] = [" "]
for i in chuoi {
mang.append(i)
}
mang.remove(at: 0)
var c: String = String(mang[0])
mang[0] = Character(c.uppercased())
for i in 0..<mang.count - 1{
if mang[i] == " " {
c = String(mang[i + 1])
mang[i + 1] = Character(c.uppercased())
}
}
chuoi = String(mang)
print(chuoi)
}
| true
|
f58e491426a9d964c4a84e9961aeb9257a3e2ba5
|
Swift
|
barbosaMatheus/EasyEvents
|
/EasyEvents/SplashScreenViewController.swift
|
UTF-8
| 1,632
| 2.578125
| 3
|
[] |
no_license
|
//
// SplashScreenViewController.swift
// EasyEvents
//
// Created by Ryan Thomas McIver on 10/25/16.
// Copyright © 2016 Oklahoma State University. All rights reserved.
//
import UIKit
import QuartzCore
class SplashScreenViewController: UIViewController {
//db information
var dbUsername: String = ""
var dbPassword: String = ""
var user_id: Int = 0 //id attribute for the current user in the database
@IBOutlet weak var logo_image_view: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
logo_image_view.layer.cornerRadius = 90
logo_image_view.clipsToBounds = true
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor( patternImage: UIImage( named: "events_image2.jpg" )! )
self.navigationItem.setHidesBackButton( true, animated:true )
}
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.
guard let vc = segue.destination as? HomeScreenViewController else {
return
}
vc.user_id = self.user_id
vc.dbUsername = self.dbUsername
vc.dbPassword = self.dbPassword
}
}
| true
|
717fc47f5ab5991c9880eec6c71bae2a5bd84fd4
|
Swift
|
GrapeFruitJun/OVTimerLabel
|
/OVTimerLabel/Classes/OVTimerLabel.swift
|
UTF-8
| 3,243
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
//
// OVTimerLabel.swift
// OVTimerLabel
//
// Created by Onur Var on 12.04.2018.
//
import UIKit
@IBDesignable
open class OVTimerLabel: UILabel {
//MARK: open's
@IBInspectable open var isHoursEnabled : Bool = true
@IBInspectable open var resetOnStopTimer : Bool = false
@IBInspectable open var seperator : String = ":"
//MARK: Private's
fileprivate var initialInterval = Double(0)
fileprivate var timer : Timer!
fileprivate var date : Date!{
didSet{
setTimerLabel()
}
}
//MARK: View Life Cycle
deinit {
stopScheduledTimer()
}
//MARK: Public Methods
override open func awakeFromNib() {
super.awakeFromNib()
self.font = UIFont(name: "DBLCDTempBlack", size: 20.0)
resetTimer()
}
open func set(date: Date){
self.date = date
}
open func startTimer(){
if date == nil {
date = Date()
}
startScheduledTimer()
}
open func stopTimer(){
stopScheduledTimer()
}
open func resetTimer(){
self.text = isHoursEnabled ? String(format: "00%@00%@00", seperator,seperator) : String(format: "00%@00", seperator)
}
open func setInterval(interval: Double){
initialInterval = interval
setIntervalScreen(interval: 0)
}
open func set(font: UIFont){
self.font = font
}
open func set(fontSize: CGFloat){
self.font = self.font.withSize(fontSize)
}
//MARK: Private Methods
@objc fileprivate func didTimerTrigger(_ timer: Timer){
setTimerLabel()
}
fileprivate func stopScheduledTimer(){
if timer != nil {
timer.invalidate()
timer = nil
}
if resetOnStopTimer {
resetTimer()
}
}
fileprivate func startScheduledTimer(){
//Make sure you stop it first
stopScheduledTimer()
//Initialize Timer
DispatchQueue.main.async {
self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.didTimerTrigger(_:)), userInfo: nil, repeats: true)
self.timer.fire()
}
}
fileprivate func setTimerLabel(){
var checkDate : Date!
if let date = date {
checkDate = date
}
var interval = Double(Date().timeIntervalSince(checkDate))
if interval < 0 {
interval = interval * (-1)
}
interval = ceil(interval)
setIntervalScreen(interval: interval)
}
fileprivate func setIntervalScreen(interval: Double){
let totalInterval = interval + initialInterval
let hours = Int(totalInterval / 3600)
let minutes = Int((totalInterval - Double(hours * 3600)) / 60)
let seconds = Int(totalInterval - Double(minutes * 60) - Double(hours * 3600))
self.text = isHoursEnabled ? String(format: "%02d%@%02d%@%02d",hours,seperator,minutes,seperator,seconds) : String(format: "%02d%@%02d",minutes,seperator,seconds)
}
}
| true
|
03c42a4164b424f271086574dae3a2f2ba7eaf88
|
Swift
|
IamAScappy/TylerQuickMedia
|
/TylerQuickMedia/UI/Media/MediumViewModel.swift
|
UTF-8
| 954
| 2.609375
| 3
|
[] |
no_license
|
//
// MediumModel.swift
// TylerQuickMedia
//
// Created by tskim on 2018. 10. 21..
// Copyright © 2018년 tskim. All rights reserved.
//
import Foundation
protocol MediumConvetableModel {
func toMediumModel() -> MediumViewModel
}
struct MediumViewModel: Equatable, HasMedia {
let type: DataSourceType
let thumbnail: String
let origin: String
let title: String
let width: Int
let height: Int
let dateTime: Date
}
//extension MediumModel: IdentifiableType {
// var identity: String {
// return origin
// }
//}
//
//extension MediumModel: ListDiffable {
// func diffIdentifier() -> NSObjectProtocol {
// return medium_id as NSObjectProtocol
// }
//
// func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
// guard self !== object else { return true }
// guard let object = object as? MediumModel else { return false }
// return self == object
// }
//}
| true
|
2c451cb42358d7a6607f88435261a192d2ebae9c
|
Swift
|
cpascoli/WeatherHype
|
/WeatherHype/Classes/Utils/Utils.swift
|
UTF-8
| 1,106
| 3.265625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Utils.swift
// WeatherHype
//
// Created by Carlo Pascoli on 28/09/2016.
// Copyright © 2016 Carlo Pascoli. All rights reserved.
//
import UIKit
extension Date {
func dayOfWeek() -> String {
let weekdays = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Satudrday"
]
let comp:DateComponents = Calendar.current.dateComponents([.weekday], from: self)
return weekdays[comp.weekday!-1]
}
}
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(hex:Int) {
self.init(red:(hex >> 16) & 0xff, green:(hex >> 8) & 0xff, blue:hex & 0xff)
}
}
| true
|
f898a9a0ee69ba7e9c60659446803db9eb13a6f1
|
Swift
|
xpring-eng/XpringKit
|
/Tests/XRP/UtilsTest.swift
|
UTF-8
| 18,521
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
import XCTest
import XpringKit
class UtilsTest: XCTestCase {
// MARK: - isValid
func testIsValidAddressValidClassicAddress() {
XCTAssertTrue(Utils.isValid(address: "rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1"))
}
func testIsValidAddressValidXAddress() {
XCTAssertTrue(Utils.isValid(address: "XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHi"))
}
func testIsValidAddressInvalidAlphabet() {
XCTAssertFalse(Utils.isValid(address: "1EAG1MwmzkG6gRZcYqcRMfC17eMt8TDTit"))
}
func testIsValidAddressInvalidChecksumClassicAddress() {
XCTAssertFalse(Utils.isValid(address: "rU6K7V3Po4sBBBBBaU29sesqs2qTQJWDw1"))
}
func testIsvValidAddressInvalidChecksumXAddress() {
XCTAssertFalse(Utils.isValid(address: "XVLhHMPHU98es4dbozjVtdWzVrDjtV18pX8yuPT7y4xaEHI"))
}
func testIsValidAddressInvalidCharacters() {
XCTAssertFalse(Utils.isValid(address: "rU6K7V3Po4sBBBBBaU@#$%qs2qTQJWDw1"))
}
func testIsValidAddressTooLong() {
XCTAssertFalse(Utils.isValid(address: "rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1"))
}
func testIsValidAddressTooShort() {
XCTAssertFalse(Utils.isValid(address: "rU6K7V3Po4s2qTQJWDw1"))
}
// MARK: - isValidXAddress
func testIsValidXAddressWithXAddress() {
// GIVEN a valid X-Address.
let address = "XVfC9CTCJh6GN2x8bnrw3LtdbqiVCUvtU3HnooQDgBnUpQT"
// WHEN the address is validated for being an X-Address.
let isValid = Utils.isValidXAddress(address: address)
// THEN the address is reported as valid.
XCTAssertTrue(isValid)
}
func testIsValidXAddressWithClassicAddress() {
// GIVEN a valid classic address.
let address = "rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1"
// WHEN the address is validated for being an X-Address.
let isValid = Utils.isValidXAddress(address: address)
// THEN the address is reported as invalid.
XCTAssertFalse(isValid)
}
func testIsValidXAddressWithInvalidAddress() {
// GIVEN an invalid address.
let address = "xrp"
// WHEN the address is validated for being an X-Address.
let isValid = Utils.isValidXAddress(address: address)
// THEN the address is reported as invalid.
XCTAssertFalse(isValid)
}
// MARK: - isValidClassicAddress
func testIsValidClassicAddressWithXAddress() {
// GIVEN a valid X-Address.
let address = "XVfC9CTCJh6GN2x8bnrw3LtdbqiVCUvtU3HnooQDgBnUpQT"
// WHEN the address is validated for being a classic address.
let isValid = Utils.isValidClassicAddress(address: address)
// THEN the address is reported as valid.
XCTAssertFalse(isValid)
}
func testIsValidClassicAddressWithClassicAddress() {
// GIVEN a valid classic address.
let address = "rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1"
// WHEN the address is validated for being a classic address.
let isValid = Utils.isValidClassicAddress(address: address)
// THEN the address is reported as invalid.
XCTAssertTrue(isValid)
}
func testIsValidClassicAddressWithInvalidAddress() {
// GIVEN an invalid address.
let address = "xrp"
// WHEN the address is validated for being a classic address.
let isValid = Utils.isValidClassicAddress(address: address)
// THEN the address is reported as invalid.
XCTAssertFalse(isValid)
}
// MARK: - encode
func testEncodeMainNetXAddressWithAddressAndTag() {
// GIVEN a valid classic address and a tag.
let address = "rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1"
let tag: UInt32 = 12_345
// WHEN they are encoded to an X-Address on MainNet.
let xAddress = Utils.encode(classicAddress: address, tag: tag)
// THEN the result is as expected.
XCTAssertEqual(xAddress, "XVfC9CTCJh6GN2x8bnrw3LtdbqiVCUvtU3HnooQDgBnUpQT")
}
func testEncodeTestNetXAddressWithAddressAndTag() {
// GIVEN a valid classic address and a tag.
let address = "rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1"
let tag: UInt32 = 12_345
// WHEN they are encoded to an X-Address on MainNet.
let xAddress = Utils.encode(classicAddress: address, tag: tag, isTest: true)
// THEN the result is as expected.
XCTAssertEqual(xAddress, "TVsBZmcewpEHgajPi1jApLeYnHPJw82v9JNYf7dkGmWphmh")
}
func testEncodeXAddressWithAddressOnly() {
// GIVEN a valid classic address.
let address = "rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1"
// WHEN it is encoded to an x-address.
let xAddress = Utils.encode(classicAddress: address)
// THEN the result is as expected.
XCTAssertEqual(xAddress, "XVfC9CTCJh6GN2x8bnrw3LtdbqiVCUFyQVMzRrMGUZpokKH")
}
func testEncodeXAddressWithInvalidAddress() {
// GIVEN an invalid address.
let address = "xrp"
// WHEN it is encoded to an x-address.
let xAddress = Utils.encode(classicAddress: address)
// THEN the result is undefined.
XCTAssertNil(xAddress)
}
func testEncodeXAddressWithAddressOnlyOnTestnet() {
// GIVEN a valid classic address without a tag on testnet.
let address = "rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1"
// WHEN it is encoded to an X-Address.
let xAddress = Utils.encode(classicAddress: address, isTest: true)
// THEN the result is as expected.
XCTAssertEqual(xAddress, "TVsBZmcewpEHgajPi1jApLeYnHPJw8VrMCKS5g28oDXYiVA")
}
// MARK: - decode
func testDecodeMainNetXAddressWithAddressAndTag() {
// GIVEN an X-Address on MainNet that encodes an address and a tag.
let address = "XVfC9CTCJh6GN2x8bnrw3LtdbqiVCUvtU3HnooQDgBnUpQT"
// WHEN it is decoded to an classic address
guard let classicAddressTuple = Utils.decode(xAddress: address) else {
XCTFail("Failed to decode a valid X-Address")
return
}
// THEN the decoded address and tag as are expected.
XCTAssertEqual(classicAddressTuple.classicAddress, "rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1")
XCTAssertEqual(classicAddressTuple.tag, 12_345)
XCTAssertFalse(classicAddressTuple.isTest)
}
func testDecodeTestNetXAddressWithAddressAndTag() {
// GIVEN an X-Address on Testnet that encodes an address and a tag.
let address = "TVsBZmcewpEHgajPi1jApLeYnHPJw82v9JNYf7dkGmWphmh"
// WHEN it is decoded to an classic address
guard let classicAddressTuple = Utils.decode(xAddress: address) else {
XCTFail("Failed to decode a valid X-Address")
return
}
// THEN the decoded address and tag as are expected.
XCTAssertEqual(classicAddressTuple.classicAddress, "rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1")
XCTAssertEqual(classicAddressTuple.tag, 12_345)
XCTAssertTrue(classicAddressTuple.isTest)
}
func testDecodeXAddressWithAddressOnly() {
// GIVEN an x-address that encodes an address and no tag.
let address = "XVfC9CTCJh6GN2x8bnrw3LtdbqiVCUFyQVMzRrMGUZpokKH"
// WHEN it is decoded to an classic address
guard let classicAddressTuple = Utils.decode(xAddress: address) else {
XCTFail("Failed to decode a valid X-Address")
return
}
// THEN the decoded address and tag as are expected.
XCTAssertEqual(classicAddressTuple.classicAddress, "rU6K7V3Po4snVhBBaU29sesqs2qTQJWDw1")
XCTAssertNil(classicAddressTuple.tag)
}
func testDecodXAddresWithInvalidAddress() {
// GIVEN an invalid address
let address = "xrp"
// WHEN it is decoded to an classic address
let classicAddressTuple = Utils.decode(xAddress: address)
// THEN the decoded address is undefined.
XCTAssertNil(classicAddressTuple)
}
// MARK: - toTransactionHash
func testToTransactionHashValidTransaction() {
// GIVEN a transaction blob.
// swiftlint:disable line_length
let transactionBlobHex = "120000240000000561400000000000000168400000000000000C73210261BBB9D242440BA38375DAD79B146E559A9DFB99055F7077DA63AE0D643CA0E174473045022100C8BB1CE19DFB1E57CDD60947C5D7F1ACD10851B0F066C28DBAA3592475BC3808022056EEB85CC8CD41F1F1CF635C244943AD43E3CF0CE1E3B7359354AC8A62CF3F488114F8942487EDB0E4FD86190BF8DCB3AF36F608839D83141D10E382F805CD7033CC4582D2458922F0D0ACA6"
// swiftlint:enable line_length
// WHEN the transaction blob is converted to a hash.
let transactionHash = Utils.toTransactionHash(transactionBlobHex: transactionBlobHex)
// THEN the transaction blob is as expected.
XCTAssertEqual(
transactionHash,
"7B9F6E019C2A79857427B4EF968D77D683AC84F5A880830955D7BDF47F120667"
)
}
func testToTransactionHashInvalidTransaction() {
// GIVEN an invalid transaction blob.
let transactionBlobHex = "xrp"
// WHEN the transaction blob is converted to a hash.
let transactionHash = Utils.toTransactionHash(transactionBlobHex: transactionBlobHex)
// THEN the hash is nil.
XCTAssertNil(transactionHash)
}
// MARK: - dropsToXrp
func testDropsToXrpWorksWithTypicalAmount() throws {
// GIVEN a typical, valid drops value, WHEN converted to xrp
let xrp: String = try Utils.dropsToXrp("2000000")
// THEN the conversion is as expected
XCTAssertEqual("2", xrp, "2 million drops equals 2 XRP")
}
func testDropsToXrpWorksWithFractions() throws {
// GIVEN drops amounts that convert to fractional xrp amounts
// WHEN converted to xrp THEN the conversion is as expected
var xrp: String = try Utils.dropsToXrp("3456789")
XCTAssertEqual("3.456789", xrp, "3,456,789 drops equals 3.456789 XRP")
xrp = try Utils.dropsToXrp("3400000")
XCTAssertEqual("3.4", xrp, "3,400,000 drops equals 3.4 XRP")
xrp = try Utils.dropsToXrp("1")
XCTAssertEqual("0.000001", xrp, "1 drop equals 0.000001 XRP")
xrp = try Utils.dropsToXrp("1.0")
XCTAssertEqual("0.000001", xrp, "1.0 drops equals 0.000001 XRP")
xrp = try Utils.dropsToXrp("1.00")
XCTAssertEqual("0.000001", xrp, "1.00 drops equals 0.000001 XRP")
}
func testDropsToXrpWorksWithZero() throws {
// GIVEN several equivalent representations of zero
// WHEN converted to xrp, THEN the result is zero
var xrp: String = try Utils.dropsToXrp("0")
XCTAssertEqual("0", xrp, "0 drops equals 0 XRP")
// negative zero is equivalent to zero
xrp = try Utils.dropsToXrp("-0")
XCTAssertEqual("0", xrp, "-0 drops equals 0 XRP")
xrp = try Utils.dropsToXrp("0.00")
XCTAssertEqual("0", xrp, "0.00 drops equals 0 XRP")
xrp = try Utils.dropsToXrp("000000000")
XCTAssertEqual("0", xrp, "000000000 drops equals 0 XRP")
}
func testDropsToXrpWorksWithNegativeValues() throws {
// GIVEN a negative drops amount
// WHEN converted to xrp
let xrp: String = try Utils.dropsToXrp("-2000000")
// THEN the conversion is also negative
XCTAssertEqual("-2", xrp, "-2 million drops equals -2 XRP")
}
func testDropsToXrpWorksWithValueEndingWithDecimalPoint() throws {
// GIVEN a positive or negative drops amount that ends with a decimal point
// WHEN converted to xrp THEN the conversion is successful and correct
var xrp: String = try Utils.dropsToXrp("2000000.")
XCTAssertEqual("2", xrp, "2000000. drops equals 2 XRP")
xrp = try Utils.dropsToXrp("-2000000.")
XCTAssertEqual("-2", xrp, "-2000000. drops equals -2 XRP")
}
func testDropsToXrpThrowsWithAnAmountWithTooManyDecimalPlaces() {
XCTAssertThrowsError(try Utils.dropsToXrp("1.2"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
XCTAssertThrowsError(try Utils.dropsToXrp("0.10"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
}
func testDropsToXrpThrowsWithAnInvalidValue() {
// GIVEN invalid drops values, WHEN converted to xrp, THEN an exception is thrown
XCTAssertThrowsError(try Utils.dropsToXrp("FOO"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
XCTAssertThrowsError(try Utils.dropsToXrp("1e-7"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
XCTAssertThrowsError(try Utils.dropsToXrp("2,0"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
XCTAssertThrowsError(try Utils.dropsToXrp("."), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
}
func testDropsToXrpThrowsWithAnAmountMoreThanOneDecimalPoint() {
// GIVEN invalid drops values that contain more than one decimal point
// WHEN converted to xrp THEN an exception is thrown
XCTAssertThrowsError(try Utils.dropsToXrp("1.0.0"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
XCTAssertThrowsError(try Utils.dropsToXrp("..."), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
}
func testDropsToXrpThrowsWithNullArgument() {
// GIVEN a nil drops value, WHEN converted to XRP,
// THEN an exception is thrown
// TODO: do we need this test case?
}
// MARK: - xrpToDrops
func testXrpToDropsWorksWithATypicalAmount() throws {
// GIVEN an xrp amount that is typical and valid
// WHEN converted to drops
let drops: String = try Utils.xrpToDrops("2")
// THEN the conversion is successful and correct
XCTAssertEqual("2000000", drops, "2 XRP equals 2 million drops")
}
func testXrpToDropsWorksWithFractions() throws {
// GIVEN xrp amounts that are fractional
// WHEN converted to drops THEN the conversions are successful and correct
var drops: String = try Utils.xrpToDrops("3.456789")
XCTAssertEqual("3456789", drops, "3.456789 XRP equals 3,456,789 drops")
drops = try Utils.xrpToDrops("3.400000")
XCTAssertEqual("3400000", drops, "3.400000 XRP equals 3,400,000 drops")
drops = try Utils.xrpToDrops("0.000001")
XCTAssertEqual("1", drops, "0.000001 XRP equals 1 drop")
drops = try Utils.xrpToDrops("0.0000010")
XCTAssertEqual("1", drops, "0.0000010 XRP equals 1 drop")
}
func testXrpToDropsWorksWithZero() throws {
// GIVEN xrp amounts that are various equivalent representations of zero
// WHEN converted to drops THEN the conversions are equal to zero
var drops: String = try Utils.xrpToDrops("0")
XCTAssertEqual("0", drops, "0 XRP equals 0 drops")
drops = try Utils.xrpToDrops("-0"); // negative zero is equivalent to zero
XCTAssertEqual("0", drops, "-0 XRP equals 0 drops")
drops = try Utils.xrpToDrops("0.000000")
XCTAssertEqual("0", drops, "0.000000 XRP equals 0 drops")
drops = try Utils.xrpToDrops("0.0000000")
XCTAssertEqual("0", drops, "0.0000000 XRP equals 0 drops")
}
func testXrpToDropsWorksWithNegativeValues() throws {
// GIVEN a negative xrp amount
// WHEN converted to drops THEN the conversion is also negative
let drops: String = try Utils.xrpToDrops("-2")
XCTAssertEqual("-2000000", drops, "-2 XRP equals -2 million drops")
}
func testXrpToDropsWorksWithAValueEndingWithADecimalPoint() throws {
// GIVEN an xrp amount that ends with a decimal point
// WHEN converted to drops THEN the conversion is correct and successful
var drops: String = try Utils.xrpToDrops("2.")
XCTAssertEqual("2000000", drops, "2. XRP equals 2000000 drops")
drops = try Utils.xrpToDrops("-2.")
XCTAssertEqual("-2000000", drops, "-2. XRP equals -2000000 drops")
}
func testXrpToDropsThrowsWithAnAmountWithTooManyDecimalPlaces() {
// GIVEN an xrp amount with too many decimal places
// WHEN converted to a drops amount THEN an exception is thrown
XCTAssertThrowsError(try Utils.xrpToDrops("1.1234567"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
XCTAssertThrowsError(try Utils.xrpToDrops("0.0000001"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
}
func testXrpToDropsThrowsWithAnInvalidValue() {
// GIVEN xrp amounts represented as various invalid values
// WHEN converted to drops THEN an exception is thrown
XCTAssertThrowsError(try Utils.xrpToDrops("FOO"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
XCTAssertThrowsError(try Utils.xrpToDrops("1e-7"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
XCTAssertThrowsError(try Utils.xrpToDrops("2,0"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
XCTAssertThrowsError(try Utils.xrpToDrops("."), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
}
func testXrpToDropsThrowsWithAnAmountMoreThanOneDecimalPoint() {
// GIVEN an xrp amount with more than one decimal point, or all decimal points
// WHEN converted to drops THEN an exception is thrown
XCTAssertThrowsError(try Utils.xrpToDrops("1.0.0"), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
XCTAssertThrowsError(try Utils.xrpToDrops("..."), "Exception not thrown") { error in
guard
error as? XRPLedgerError != nil
else {
XCTFail("Error thrown was not XRPLedgerError")
return
}
}
}
func testXrpToDropsThrowsWithNullArgument() {
// GIVEN a nil xrp value, WHEN converted to drops,
// THEN an exception is thrown
// TODO: do we need this test case?
}
}
| true
|
7a1ac1617f2c960206b6e2f9492b327e8700c1b6
|
Swift
|
beairs/TreeTableViewDemo
|
/TreeTableViewDemo/Extension.swift
|
UTF-8
| 3,603
| 2.875
| 3
|
[] |
no_license
|
//
// Extension.swift
// TreeTableViewDemo
//
// Created by Beairs on 2020/5/27.
// Copyright © 2020 Beairs. All rights reserved.
//
import Foundation
import UIKit
extension UILabel {
class func creat(font: UIFont?, color: UIColor = .black) -> UILabel {
return UILabel().then({ (l) in
l.font = font
l.textColor = color
})
}
}
extension UIFont {
// 常规
class func pingFangRegular(size: CGFloat) -> UIFont? {
return UIFont.init(name: "PingFangSC-Regular", size: size)
}
// 中
class func pingFangMedium(size: CGFloat) -> UIFont? {
return UIFont.init(name: "PingFangSC-Medium", size: size)
}
// 粗
class func pingFangSemibold(size: CGFloat) -> UIFont? {
return UIFont.init(name: "PingFangSC-Semibold", size: size)
}
class var PingFang_Bold22: UIFont? { return UIFont.init(name: "PingFangSC-Semibold", size: 22) }
class var PingFang_Bold20: UIFont? { return UIFont.init(name: "PingFangSC-Semibold", size: 20) }
class var PingFang_Bold18: UIFont? { return UIFont.init(name: "PingFangSC-Semibold", size: 18) }
class var PingFang_Medium17: UIFont? { return UIFont.init(name: "PingFangSC-Medium", size: 17) }
class var PingFang_Medium16: UIFont? { return UIFont.init(name: "PingFangSC-Medium", size: 16) }
class var PingFang_Regular16: UIFont? { return UIFont.init(name: "PingFangSC-Regular", size: 16) }
class var PingFang_Regular14: UIFont? { return UIFont.init(name: "PingFangSC-Regular", size: 14) }
class var PingFang_Regular12: UIFont? { return UIFont.init(name: "PingFangSC-Regular", size: 12) }
}
extension UIColor {
class var nblack: UIColor { return hexColor("191D21")}
class var ngray: UIColor { return hexColor("999BA1") }
class var icon: UIColor { return hexColor("e5e5e5") }
class func hexColor(_ string: String, alpha: CGFloat = 1.0) -> UIColor {
guard (string.count == 7 && string.hasPrefix("#")) || string.count == 6 else {
return .clear
}
var colorString = string.lowercased()
if (colorString.count == 7 && colorString.hasPrefix("#")) {
colorString = String(colorString[colorString.index(after: colorString.startIndex) ..< colorString.endIndex])
}
let dictionary: [Character: CGFloat] = [
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"a": 10,
"b": 11,
"c": 12,
"d": 13,
"e": 14,
"f": 15
]
var value: CGFloat = 0
var array = [CGFloat]()
for (i, c) in colorString.enumerated(){
let v: CGFloat = dictionary[c] ?? 0
if i % 2 == 0 {
value += v*16
} else {
value += v
array.append(value)
value = 0
}
}
return UIColor.init(red: array[0] / 255.0,
green: array[1] / 255.0,
blue: array[2] / 255.0,
alpha: alpha)
}
}
extension Array {
func forEachHandle(handle: ((Int, Bool, Element)->Void)) {
guard count > 0 else { return }
for i in 0 ..< count {
handle(i, i == count - 1, self[i])
}
}
}
| true
|
dec6ff829ffc3f2e93f0b4b9fc9bbb38766e34c3
|
Swift
|
21st-century-code-noob/Shield-For-Dementia-Patient
|
/Shield For Dementia/ViewController/PopupViewController.swift
|
UTF-8
| 1,298
| 2.53125
| 3
|
[] |
no_license
|
//
// PopupViewController.swift
// Shield For Dementia Patient
//
// Created by apple on 9/5/19.
// Copyright © 2019 彭孝诚. All rights reserved.
//
import UIKit
class PopupViewController: UIViewController, SBCardPopupContent {
@IBOutlet weak var messageLabel: UILabel!
var popupViewController: SBCardPopupViewController?
var allowsTapToDismissPopupCard: Bool = true
var allowsSwipeToDismissPopupCard: Bool = true
static func create() -> UIViewController{
let storyboard = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "PopupViewController") as! PopupViewController
return storyboard
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func dismissButton(_ sender: Any) {
self.popupViewController?.close()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
9222ece3366ce3ecc7e3510a0656a7139fd03d16
|
Swift
|
sreeku44/Pokemon-Sighting-GET-POST
|
/Pokemon Sighting GET & POST/AddPokemonViewController.swift
|
UTF-8
| 2,423
| 2.703125
| 3
|
[] |
no_license
|
//
// AddPokemonViewController.swift
// Pokemon Sighting GET & POST
//
// Created by Sreekala Santhakumari on 3/7/17.
// Copyright © 2017 Klas. All rights reserved.
//
import UIKit
protocol addPokemonSaveDelegate {
func addPokemonSave(aPS:Pokemon)
}
class AddPokemonViewController: UIViewController {
var delegate : addPokemonSaveDelegate?
@IBOutlet var enterPokemonNameTextField: UITextField!
@IBOutlet var enterPokemonImageUrlTextField: UITextField!
@IBOutlet var enterLatitudeTextField: UITextField!
@IBOutlet var enterLongitudeTextField: UITextField!
@IBAction func addPokemonSaveButton(_ sender: Any) {
let pokemon = Pokemon(name: enterPokemonNameTextField.text!, imageURL: enterPokemonImageUrlTextField.text!, latitude: Float(enterLatitudeTextField.text!)!, longitude: Float(enterLongitudeTextField.text!)!)
self.delegate?.addPokemonSave(aPS: pokemon)
let url = URL(string: "https://still-wave-26435.herokuapp.com/pokemon/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let postBodypokemonDictionaries :[String:Any] = ["name":enterPokemonNameTextField.text! ,"imageURL":enterPokemonImageUrlTextField.text!, "latitude" : Float(enterLatitudeTextField.text!)! , "longitude" : Float(enterLongitudeTextField.text!)!]
let postDatapokemonDictionaries = try! JSONSerialization.data(withJSONObject: postBodypokemonDictionaries, options: [])
request.httpBody = postDatapokemonDictionaries
URLSession.shared.dataTask(with: request) { (data, response, error) in
let json = try! JSONSerialization.jsonObject(with: data!, options: [])
}.resume()
dismiss(animated: true, completion: nil)
}
@IBAction func addPokemonCloseButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
7a65c46b16b6bdd3f072003773f4220a98c64205
|
Swift
|
splitio/ios-client
|
/Split/FetcherEngine/Recorder/UniqueKeysRecorderWorker.swift
|
UTF-8
| 2,432
| 2.578125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// UniqueKeysRecorderWorker.swift
// Split
//
// Created by Javier Avrudsky on 18/12/2020.
// Copyright © 2020 Split. All rights reserved.
//
import Foundation
class UniqueKeysRecorderWorker: RecorderWorker {
private let uniqueKeyStorage: PersistentUniqueKeysStorage
private let uniqueKeysRecorder: HttpUniqueKeysRecorder
private let flushChecker: RecorderFlushChecker?
private let rowsPerPush = ServiceConstants.uniqueKeyBulkSize
init(uniqueKeyStorage: PersistentUniqueKeysStorage,
uniqueKeysRecorder: HttpUniqueKeysRecorder,
flushChecker: RecorderFlushChecker? = nil) {
self.uniqueKeyStorage = uniqueKeyStorage
self.uniqueKeysRecorder = uniqueKeysRecorder
self.flushChecker = flushChecker
}
func flush() {
var rowCount = 0
var failedUniqueKeys = [UniqueKey]()
repeat {
let keys = uniqueKeyStorage.pop(count: rowsPerPush)
rowCount = keys.count
if rowCount > 0 {
Logger.d("Sending unique keys")
do {
_ = try uniqueKeysRecorder.execute(group(keys: keys))
// Removing sent uniqueKey
uniqueKeyStorage.delete(keys)
Logger.i("Unique keys posted successfully")
} catch let error {
Logger.e("Unique keys error: \(String(describing: error))")
failedUniqueKeys.append(contentsOf: keys)
}
}
} while rowCount == rowsPerPush
// Activate non sent uniqueKey to retry in next iteration
uniqueKeyStorage.setActiveAndUpdateSendCount(failedUniqueKeys.compactMap { $0.storageId })
if let flushChecker = self.flushChecker {
flushChecker.update(count: failedUniqueKeys.count,
bytes: failedUniqueKeys.count *
ServiceConstants.estimatedImpressionSizeInBytes)
}
}
private func group(keys: [UniqueKey]) -> UniqueKeys {
var grouped = [String: Set<String>]()
keys.forEach { uniqueKey in
let userKey = uniqueKey.userKey
grouped[userKey] = uniqueKey.features.union(grouped[userKey] ?? Set<String>())
}
return UniqueKeys(keys: grouped.map { userKey, features in
return UniqueKey(userKey: userKey, features: features)
})
}
}
| true
|
0a19507c64393fe4428e80f2524c21eaf4ca9e42
|
Swift
|
msaveleva/lazy-pomodoro-ios
|
/LazyPomodoro/ViewModel/ProgressStackViewModels/TodayProgressStackViewModel.swift
|
UTF-8
| 965
| 2.53125
| 3
|
[] |
no_license
|
//
// TodayLazyProgressViewModel.swift
// LazyPomodoro
//
// Created by Maria Saveleva on 20/03/2019.
// Copyright © 2019 Maria Saveleva. All rights reserved.
//
import Foundation
import RxSwift
class TodayLazyProgressViewModel: LazyProgressViewConfigurable {
public let title: String
init(title: String) { //TODO msaveleva: init with additional services to read values from saves settings.
self.title = title
}
func getInitialProgressText() -> String {
return "0/0" //TODO msaveleva: implement
}
func progressTextObservable() -> Observable<String?> {
return Observable<String?>.create { observer in
//TODO msaveleva: implement
return Disposables.create()
}
}
func progressValueObservable() -> Observable<Float> {
return Observable<Float>.create { observer in
//TODO msaveleva: implement
return Disposables.create()
}
}
}
| true
|
7228c0b97e72e0c886987b2dccb14a2b91aa9a07
|
Swift
|
0162890/PocketTicket
|
/PocketTicket/ViewControllers/ContentsViewController.swift
|
UTF-8
| 1,380
| 2.65625
| 3
|
[] |
no_license
|
//
// ContentsViewController.swift
// PocketTicket
//
// Created by 하연 on 2017. 2. 20..
// Copyright © 2017년 hayeon. All rights reserved.
//
import UIKit
class ContentsViewController: UIViewController {
var currentTicket : Ticket?
@IBOutlet weak var genreLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var theaterLabel: UILabel!
@IBOutlet weak var seatLabel: UILabel!
@IBOutlet weak var actorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if currentTicket != nil{
setData()
} else {
}
}
func setData(){
//Genre
self.genreLabel.text = currentTicket?.genre
//Date
let dateFormat = DateFormatter()
dateFormat.dateFormat = "yyyy.MM.dd EE ah:mm"
let selectedDate = currentTicket?.date
let dateString = dateFormat.string(from: selectedDate as! Date)
self.dateLabel.text = dateString
//theater
self.theaterLabel.text = currentTicket?.theater?.theaterName
//Seat
self.seatLabel.text = currentTicket?.seat
//actor
self.actorLabel.text = currentTicket?.actor
}
}
| true
|
88fbd1ff147ab5f39ab99fa7bd36eb8e1d400bb3
|
Swift
|
sidshah13/Swift-Link-Preview
|
/SwiftLinkPreview/Classes/SwiftLinkPreview.swift
|
UTF-8
| 12,467
| 3.03125
| 3
|
[
"MIT"
] |
permissive
|
//
// SwiftLinkPreview.swift
// SwiftLinkPreview
//
// Created by Leonardo Cardoso on 09/06/2016.
// Copyright © 2016 leocardz.com. All rights reserved.
//
import Foundation
import Alamofire
public class SwiftLinkPreview {
// MARK: - Vars
static let minimumRelevant: Int = 120
private var text: String!
private var url: NSURL!
private var result: [String: AnyObject] = [:]
private var request: Alamofire.Request?
// MARK: - Constructor
public init() {
}
// MARK: - Functions
// Make preview
public func preview(text: String!, onSuccess: ([String: AnyObject]) -> (), onError: (PreviewError) -> ()) {
self.result = [
"url": "",
"finalUrl": "",
"canonicalUrl": "",
"title": "",
"description": "",
"images": [],
"image": ""
]
self.text = text
if let url = self.extractURL() {
self.url = url
self.result["url"] = self.url.absoluteString
self.unshortenURL(url, completion: { unshortened in
self.result["finalUrl"] = unshortened
self.extractCanonicalURL()
self.extractInfo({
onSuccess(self.result)
}, onError: onError)
})
} else {
onError(PreviewError(type: .NoURLHasBeenFound, url: self.text))
}
}
// Fill remaining info about the crawling
private func fillRemainingInfo(title: String, description: String, images: [String], image: String) {
self.result["title"] = title
self.result["description"] = description
self.result["images"] = images
self.result["image"] = image
}
// Cancel request
public func cancel() {
if let request = self.request {
request.cancel()
}
}
}
// Extraction functions
extension SwiftLinkPreview {
// Extract first URL from text
private func extractURL() -> NSURL? {
let explosion = self.text.characters.split{$0 == " "}.map(String.init)
for var piece in explosion {
piece = piece.trim
if let url = NSURL(string: piece.trim) {
if url.absoluteString.isValidURL() {
return url
}
}
}
return nil
}
// Unshorten URL by following redirections
private func unshortenURL(url: NSURL, completion: (NSURL) -> ()) {
request = Alamofire.request(.GET, url.absoluteString, parameters: [:])
.response { request, response, data, error in
if let finalResult = response?.URL {
if(finalResult.absoluteString == url.absoluteString) {
completion(url)
} else {
self.unshortenURL(finalResult, completion: completion)
}
} else {
completion(url)
}
}
}
// Extract HTML code and the information contained on it
private func extractInfo(completion: () -> (), onError: (PreviewError) -> ()) {
if let url: NSURL = self.result["finalUrl"] as? NSURL {
if(url.absoluteString.isImage()) {
self.fillRemainingInfo("", description: "", images: [url.absoluteString], image: url.absoluteString)
completion()
} else {
do {
var htmlCode = try String(contentsOfURL: url)
htmlCode = htmlCode.extendedTrim
// htmlCode = htmlCode.deleteHTMLTag("script")
// htmlCode = htmlCode.deleteHTMLTag("link")
// htmlCode = htmlCode.deleteHTMLTag("path")
// htmlCode = htmlCode.deleteHTMLTag("style")
// htmlCode = htmlCode.deleteHTMLTag("iframe")
// htmlCode = htmlCode.deleteHTMLTag("a")
// htmlCode = htmlCode.deleteTagByPattern(Regex.aPattern)
// htmlCode = htmlCode.deleteHtmlComments()
// htmlCode = htmlCode.deleteCData()
// htmlCode = htmlCode.deleteInputs()
self.crawlMetaTags(htmlCode)
self.crawlTitle(htmlCode)
self.crawlDescription(htmlCode)
self.crawlImages(htmlCode)
completion()
} catch _ as NSError {
onError(PreviewError(type: .ParseError, url: url.absoluteString))
}
}
} else {
self.fillRemainingInfo("", description: "", images: [], image: "")
completion()
}
}
// Extract get canonical URL
private func extractCanonicalURL() {
if var canonicalUrl = Regex.pregMatchFirst((self.result["finalUrl"] as! NSURL).absoluteString, regex: Regex.cannonicalUrlPattern, index: 1) {
canonicalUrl = canonicalUrl.replace("http://", with: "").replace("https://", with: "")
if let slash = canonicalUrl.rangeOfString("/") {
let endIndex = canonicalUrl.startIndex.distanceTo(slash.endIndex)
canonicalUrl = canonicalUrl.substring(0, end: endIndex > 1 ? endIndex - 1 : 0)
}
self.result["canonicalUrl"] = canonicalUrl
} else {
self.result["canonicalUrl"] = self.result["url"]
}
}
}
// Tag functions
extension SwiftLinkPreview {
// Search for meta tags
private func crawlMetaTags(htmlCode: String) {
let possibleTags = ["title", "description", "image"]
let metatags = Regex.pregMatchAll(htmlCode, regex: Regex.metatagPattern, index: 1)
for metatag in metatags {
for tag in possibleTags {
if (metatag.rangeOfString("property=\"og:\(tag)\"") != nil ||
metatag.rangeOfString("property='og:\(tag)'") != nil ||
metatag.rangeOfString("property=\"twitter:\(tag)\"") != nil ||
metatag.rangeOfString("property='twitter:\(tag)'") != nil ||
metatag.rangeOfString("name=\"\(tag)\"") != nil ||
metatag.rangeOfString("name='\(tag)'") != nil) {
if((self.result[tag] as! String).isEmpty) {
if let value = Regex.pregMatchFirst(metatag, regex: Regex.metatagContentPattern, index: 2) {
self.result[tag] = value.decoded
}
}
}
}
}
}
// Crawl for title if needed
private func crawlTitle(htmlCode: String) {
if let title: String = self.result["title"] as? String {
if title.isEmpty {
if let value = Regex.pregMatchFirst(htmlCode, regex: Regex.tittlePattern, index: 2) {
self.result["title"] = value.decoded
}
}
}
}
// Crawl for description if needed
private func crawlDescription(htmlCode: String) {
if let description: String = self.result["description"] as? String {
if description.isEmpty {
if let value: String = self.crawlCode(htmlCode) {
self.result["description"] = value
}
}
}
}
// Crawl for images
private func crawlImages(htmlCode: String) {
let mainImage: String = self.result["image"] as! String
if mainImage.isEmpty {
if let images: [String] = self.result["images"] as? [String] {
if images.isEmpty {
if let values: [String] = Regex.pregMatchAll(htmlCode, regex: Regex.imageTagPattern, index: 1) {
var imgs: [String] = []
for value in values {
var value = value
if !value.hasPrefix("https://") && !value.hasPrefix("http://") && !value.hasPrefix("ftp://") {
value = (value.hasPrefix("//") ? "http:" : (self.result["finalUrl"] as! NSURL).absoluteString) + value
}
imgs.append(value)
}
self.result["images"] = imgs
if imgs.count > 0 {
self.result["image"] = imgs[0]
}
}
}
}
} else {
self.result["images"] = [mainImage]
}
}
// Crawl the entire code
private func crawlCode(content: String) -> String {
let resultSpan = self.getTagContent("span", content: content)
let resultParagraph = self.getTagContent("p", content: content)
let resultDiv = self.getTagContent("div", content: content)
var result = resultSpan
if (resultParagraph.characters.count > result.characters.count) {
if (resultParagraph.characters.count >= resultDiv.characters.count) {
result = resultParagraph
} else {
result = resultDiv
}
}
return result
}
private func getTagContent(tag: String, content: String) -> String {
let pattern = Regex.tagPattern(tag)
var result = ""
var currentMatch = ""
let index = 2
let matches = Regex.pregMatchAll(content, regex: pattern, index: index)
for match in matches {
currentMatch = match.extendedTrim.tagsStripped
if (currentMatch.characters.count >= SwiftLinkPreview.minimumRelevant) {
result = match
break
}
}
if result.isEmpty {
if let match = Regex.pregMatchFirst(content, regex: pattern, index: 2) {
result = match.extendedTrim.tagsStripped
}
}
return result.decoded
}
}
| true
|
9103cbdbf11b0d65baa4f365152cb4f4c7b0b788
|
Swift
|
akaHEPTA/CICCC-SwiftAGDS-Assignments
|
/SwiftIntro/1. SwiftBasics/Strings.playground/Contents.swift
|
UTF-8
| 1,960
| 4.1875
| 4
|
[] |
no_license
|
//: # Strings
import UIKit
import Foundation
//: ## Defining Strings using string literals
let myFirstString = "mo 💰" // string literals
let mySecondString = "mo\' problems"
//: ## String concatenation
let theTruth = myFirstString + ", " + mySecondString
let theTruth2 = "\(myFirstString), \(mySecondString)"
let theTruth3 = "💰 can't buy me 💖."
let theBaseballTeamInAtlanta = "Atlanta Braves"
var jamesFavoriteBaseballTeam = "Atlanta Braves"
var nWithTilde = "ca\u{006E}\u{0303} not"
print(nWithTilde)
// String.Index
let startIndex = nWithTilde.startIndex
let spaceIndex = nWithTilde.firstIndex(of: " ")!
print(nWithTilde[startIndex..<spaceIndex])
nWithTilde.unicodeScalars.count
nWithTilde.count
//: ## Emoji characters
let similarTruth = "💰can't buy me 💖"
// Here's one way to initialize an empty Swift string
var characterPoorString = ""
// And here's another
let potentialRichString = String()
//: ## String interpolation
//: ### Plain string
var doggyDiet = "Lulu eats 25lbs of dog food per month"
//: ### String with variables
var dogName = "Ferris"
var ferrisPic = UIImage(named:"Springerdoodle\(dogName).jpg")!
doggyDiet = "\(dogName) eats 25lbs of dog food per month"
//: ### String with variables and expression
var lbsPerDay = 0.75
var daysPerMonth: Double = 30.0
doggyDiet = "\(dogName) eats 🇨🇦?lbs of dog food per month"
var frankiePic = UIImage(named:"frankie.jpeg")!
lbsPerDay = 0.25
dogName = "Lil Frankie"
doggyDiet = "\(dogName) eats ?lbs of dog food per month"
//: ## A String isn't just a String
//: ### Through the .characters property we can access an array of characters
var password = "Meet me in St. Louis"
for ch in password {
if ch == "e" {
print("found an e!")
}
}
//: ### A String can be treated as an NSString
let newPassword = password.replacingOccurrences(of: "e", with: "3")
// Swift (new) <-> Objective-C (old)
// NSString -> Objective-C
// convert NSString -> String(NSString)
| true
|
b780414d0354173a6e575ea6e1e1c8d3200382bc
|
Swift
|
arunkumar-rakv/News
|
/News/Controllers/MenuViewController.swift
|
UTF-8
| 791
| 2.84375
| 3
|
[] |
no_license
|
//
// MenuViewController.swift
// News
//
// Created by admin on 28/09/20.
// Copyright © 2020 Sample. All rights reserved.
//
import UIKit
enum Menu: Int {
case home
case develop
case document
}
class MenuViewController: UITableViewController {
var menuPressedType: ((Menu) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let menu = Menu(rawValue: indexPath.row) else { return }
dismiss(animated: true) { [weak self] in
print("Dismissing: \(menu)")
self?.menuPressedType?(menu)
}
}
}
| true
|
a66f47161f5e1edecfb9e8d456261f82fe61bdb7
|
Swift
|
kimsb/bingobonanza
|
/bingobonanza/SessionHandler.swift
|
UTF-8
| 10,094
| 2.546875
| 3
|
[] |
no_license
|
//
// SessionHandler.swift
// bingobonanza
//
// Created by Kim Stephen Bovim on 02/01/2020.
// Copyright © 2020 Kim Stephen Bovim. All rights reserved.
//
import Foundation
import WatchConnectivity
class SessionHandler : NSObject, WCSessionDelegate {
// 1: Singleton
static let shared = SessionHandler()
// 2: Property to manage session
var session = WCSession.default
private var questions = [String:Questions]()
private var lastQuestion: Question?
private let listKeys = ["7", "8", "C", "W"]
private var currentKey = "7"
override init() {
super.init()
// 3: Start and avtivate session if it's supported
if isSuported() {
session.delegate = self
session.activate()
}
print("isPaired?: \(session.isPaired), isWatchAppInstalled?: \(session.isWatchAppInstalled)")
}
func isSuported() -> Bool {
return WCSession.isSupported()
}
// MARK: - WCSessionDelegate
// 4: Required protocols
// a
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
print("activationDidCompleteWith activationState:\(activationState) error:\(String(describing: error))")
}
// b
func sessionDidBecomeInactive(_ session: WCSession) {
print("sessionDidBecomeInactive: \(session)")
}
// c
func sessionDidDeactivate(_ session: WCSession) {
print("sessionDidDeactivate: \(session)")
// Reactivate session
/**
* This is to re-activate the session on the phone when the user has switched from one
* paired watch to second paired one. Calling it like this assumes that you have no other
* threads/part of your code that needs to be given time before the switch occurs.
*/
self.session.activate()
}
/// Observer to receive messages from watch and we be able to response it
///
/// - Parameters:
/// - session: session
/// - message: message received
/// - replyHandler: response handler
func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
let listKey = message["nextQuestion"] as! String
if (currentKey != listKey) {
lastQuestion = nil
currentKey = listKey
}
let correct = message["correct"] as? Bool
if (correct != nil) {
let lastAnagram = message["lastAnagram"] as! String
if (lastQuestion?.anagram != lastAnagram) {
print("returned lastAnagram: \(lastAnagram) last anagram is: \(String(describing: lastQuestion?.anagram))")
replyHandler(["anagram": lastQuestion!.anagram,
"answers": lastQuestion!.answers,
"due": getDue()])
return
}
lastQuestion!.setTimeToShow(answeredCorrect: correct!)
print("last anagram: \(lastAnagram)")
}
let question = getNextQuestion(lastAnswered: lastQuestion)
if (question != nil && question!.timeToShow == Date.distantFuture) {
question?.firstShown = Date()
}
//dette blir stygt...
if (question != nil) {
replyHandler(["anagram": question!.anagram,
"answers": question!.answers,
"due": getDue(),
//"percentage": getPercentage(),
"newToday": questions[currentKey]!.getNewToday(),
"wellDoneToday": wellDoneToday()])
} else {
replyHandler(["anagram": "FAAAAIL",
"answers": "feilfeil",
"due": 999,
//"percentage": "0.00",
"newToday": 0,
"wellDoneToday": false])
}
}
func wellDoneToday() -> Bool {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let octoberFirst = formatter.date(from: "2023/10/01 00:00")!
let today = Calendar.current.startOfDay(for: Date())
let numberOfDaysTilOctoberFirst = Calendar.current.dateComponents([.day], from: today, to: octoberFirst).day!
let newToday = questions[currentKey]!.getNewToday()
return (currentKey == "W" && getDue() == 0)
|| (currentKey == "C" && newToday >= questions["C"]!.getNewCount() / numberOfDaysTilOctoberFirst)
|| (currentKey == "7" && newToday >= questions["7"]!.getNewCount() / numberOfDaysTilOctoberFirst)
|| (currentKey == "8" && newToday >= (13130 - questions["8"]!.getSeen()) / numberOfDaysTilOctoberFirst)
}
func getNewTodayText() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let octoberFirst = formatter.date(from: "2023/10/01 00:00")!
let today = Calendar.current.startOfDay(for: Date())
let numberOfDaysTilOctoberFirst = Calendar.current.dateComponents([.day], from: today, to: octoberFirst).day!
let newToday = questions[currentKey]!.getNewToday()
if (currentKey == "W") {
return getDue() == 0 ? "\u{1F389}\u{1F929}\u{1F57A}" : ""
}
if (currentKey == "C") {
return newToday >= questions["C"]!.getNewCount() / numberOfDaysTilOctoberFirst ? "New: \(newToday) \u{1F389}\u{1F929}\u{1F57A}" : newToday > 0 ? "New: \(newToday) \u{1F44F}" : ""
}
if (currentKey == "7") {
return newToday >= questions["7"]!.getNewCount() / numberOfDaysTilOctoberFirst ? "New: \(newToday) \u{1F389}\u{1F929}\u{1F57A}" : newToday > 0 ? "New: \(newToday) \u{1F44F}" : ""
}
// current == 8 ønsker 20% (13130)
return newToday >= (13130 - questions["8"]!.getSeen()) / numberOfDaysTilOctoberFirst ? "New: \(newToday) \u{1F389}\u{1F929}\u{1F57A}" : newToday > 0 ? "New: \(newToday) \u{1F44F}" : ""
}
func getDue() -> Int {
questions[currentKey]!.getDue()
}
func getPercentage() -> String {
String(format: "%.2f", questions[currentKey]!.getPercentage())
}
func getSeenCount() -> Int {
questions[currentKey]!.getSeen()
}
func setCurrentKey(keyIndex: Int) {
currentKey = listKeys[keyIndex]
}
func getNextQuestion(lastAnswered: Question? = nil) -> Question? {
//TODO - denne krasjer når null
lastQuestion = questions[currentKey]?.getNextQuestion(lastQuestion: lastAnswered)
return lastQuestion
}
func saveQuestions() {
DispatchQueue.global(qos: .userInitiated).async {
NSKeyedArchiver.archiveRootObject(self.questions, toFile: Questions.ArchiveURL.path)
}
}
func loadQuestions() {
if let loadedQuestions = NSKeyedUnarchiver.unarchiveObject(withFile: Questions.ArchiveURL.path) as? [String:Questions] {
print("finner load")
questions = loadedQuestions
//Noen blir lagret med timeToShow = distant future.
//Tror kanskje det skjer når både klokka og mobilen er aktiv..?
//for question in questions["7"]!.seenQuestions {
// print("\(question.anagram): next: \(question.timeToShow) firstSeen: \(question.firstShown)")
//}
} else {
questions["7"] = Questions(
newQuestions: linesToQuestions(lines: loadQuestionsFromResources(resource: "2022-unseen-7")),
seenQuestions: linesToSeenQuestions(lines: loadQuestionsFromResources(resource: "2022-seen-7")))
questions["8"] = Questions(
newQuestions: linesToQuestions(lines: loadQuestionsFromResources(resource: "2022-unseen-8")),
seenQuestions: linesToSeenQuestions(lines: loadQuestionsFromResources(resource: "2022-seen-8")))
questions["C"] = Questions(
newQuestions: linesToQuestions(lines: loadQuestionsFromResources(resource: "2022-erantslik-C")))
questions["W"] = Questions(
newQuestions: linesToQuestions(lines: loadQuestionsFromResources(resource: "2022-erantslik-W")))
}
}
func linesToSeenQuestions(lines: [String]) -> [Question] {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = Locale.current
var questionArray = [Question]()
for line in lines {
let components = line.components(separatedBy: ";")
let componentsB = components[0].components(separatedBy: " ")
let daysToAdd = Int(componentsB[0])!
let timeToShow = dateFormatter.date(from: "\(componentsB[1]) 00:00:00")!
let anagram = componentsB[2]
let answers = components[1].components(separatedBy: " ")
questionArray.append(Question(anagram: anagram, answers: answers, timeToShow: timeToShow, daysToAdd: daysToAdd))
}
return questionArray
}
func linesToQuestions(lines: [String]) -> [Question] {
var questionArray = [Question]()
for line in lines {
let components = line.components(separatedBy: ";")
let anagram = components[0]
let answers = components[1].components(separatedBy: " ")
questionArray.append(Question(anagram: anagram, answers: answers))
}
return questionArray
}
func loadQuestionsFromResources(resource: String) -> [String] {
let path = Bundle.main.path(forResource: resource, ofType: "txt")
let contents = try! String(contentsOfFile: path!, encoding: String.Encoding.utf8)
let lines = contents.split(separator:"\n")
var liste = [String]()
for line in lines {
liste.append(String(line))
}
return liste
}
}
| true
|
79d875fc51a9be07e26f382a942ddbdc938ae501
|
Swift
|
joncardasis/SizeSlideButton
|
/SizeSlideButton-Demo/ViewController.swift
|
UTF-8
| 2,594
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
//
// Created by Jonathan Cardasis on 6/30/16.
// Copyright © 2016 Jonathan Cardasis. All rights reserved.
//
import UIKit
/* A test viewcontroller */
class ViewController: UIViewController {
var debugBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let condensedFrame = CGRect(x: 280, y: 70, width: 32, height: 32) //Width and Height should be equal
let fancyControl = SizeSlideButton(condensedFrame: condensedFrame)
//let fancyControl = SizeSlideButton(frame: CGRect(x: 10, y: 30, width: 352, height: 32))
/* Additional Setup */
fancyControl.trackColor = UIColor.white
fancyControl.handle.color = UIColor(red: 255/255.0, green: 111/255.0, blue: 0, alpha: 1)
//fancyControl.handlePadding = 0.0 //Add no extra padding around the handle
//fancyControl.animationType = .linear
fancyControl.addTarget(self, action: #selector(newSizeSelected), for: .touchDragFinished)
fancyControl.addTarget(self, action: #selector(sizeSliderTapped), for: .touchUpInside)
self.view.addSubview(fancyControl)
/* Test for moving frame and changing padding */
//fancyControl.frame = CGRect(x: 50, y: 130, width: 200, height: 50)
//fancyControl.handlePadding = 0.0
/* A button to test for click-through on the fancyControl as well as appear when tapped */
debugBtn = UIButton(frame: CGRect(x: 165, y: 75, width: 100, height: 22))
debugBtn.setTitle("Tapped", for: UIControlState())
debugBtn.alpha = 0
debugBtn.addTarget(self, action: #selector(test), for: .touchUpInside) //For testing purposes
self.view.insertSubview(debugBtn, belowSubview: fancyControl)
}
func newSizeSelected(_ sender: SizeSlideButton){
//Do something once a size is selected and the control let go
let multipler = sender.handle.height
print("Value: \(sender.value)")
print("Multiplier: \(multipler)")
}
func sizeSliderTapped(_ sender: SizeSlideButton){
//Do something when the button is tapped
UIView.animate(withDuration: 0.3, animations: {
self.debugBtn.alpha = 1
}, completion: { (done) in
UIView.animate(withDuration: 0.3, delay: 0.65, options: .curveEaseIn, animations: {
self.debugBtn.alpha = 0
}, completion: nil)
})
}
func test(){
print("Clickarooo!")
}
}
| true
|
6f5267c67d3dfb12a3c97b0c96f7832240c85e4a
|
Swift
|
LiuLongyang0305/LeetCode
|
/swift/Offer/1626_calculator-lcci.swift
|
UTF-8
| 1,179
| 3.515625
| 4
|
[] |
no_license
|
// https://leetcode-cn.com/problems/calculator-lcci/
class Solution {
private let operatorsSet = Set<Character>("+-*/")
func calculate(_ s: String) -> Int {
let sCopy = s.replacingOccurrences(of: " ", with: "")
var numbers = sCopy.components(separatedBy: CharacterSet.init(charactersIn: "+-*/")).map { Int(String($0))!}
var operators = [Character]()
sCopy.forEach { (ch) in
if operatorsSet.contains(ch) {
operators.append(ch)
}
}
var idx = 0
while idx < operators.count {
if operators[idx] == "*" || operators[idx] == "/" {
numbers[idx] = operators[idx] == "*" ? numbers[idx] * numbers[idx + 1] : numbers[idx] / numbers[idx + 1]
numbers.remove(at: idx + 1)
operators.remove(at: idx)
} else {
idx += 1
}
}
var ans = numbers[0]
for idx in 0..<operators.count {
if operators[idx] == "+" {
ans += numbers[idx + 1]
} else {
ans -= numbers[idx + 1]
}
}
return ans
}
}
| true
|
6710c43e93fd86fd53d03bd7be52c02340155426
|
Swift
|
atnon1/Yandex-algorithm-training
|
/2.0. Дивизион B/ДЗ 5. Префиксные суммы. Два указателя/D/Решение.swift
|
UTF-8
| 390
| 3.25
| 3
|
[] |
no_license
|
import Foundation
let seq = Array(readLine()!)
var openBracketCnt = 0
var isCorrect = true
for bracket in seq {
if bracket == "(" {
openBracketCnt += 1
}
if bracket == ")" {
openBracketCnt -= 1
}
if openBracketCnt < 0 {
isCorrect = false
break
}
}
if openBracketCnt != 0 {
isCorrect = false
}
print( isCorrect ? "YES" : "NO")
| true
|
1c3d1e4d0fa7e1143f400f756ff30907ce0fa9af
|
Swift
|
jotape26/PokeFinder
|
/PokeFinder/Controllers/PokemonDetailViewController.swift
|
UTF-8
| 8,973
| 2.5625
| 3
|
[] |
no_license
|
//
// PokemonDetailViewController.swift
// PokeFinder
//
// Created by João Leite on 04/02/21.
//
import UIKit
import RxSwift
import RxCocoa
class PokemonDetailViewController: UIViewController {
private weak var viewModel : PokemonViewModel!
private let accentColor : BehaviorRelay<UIColor> = BehaviorRelay(value: .white)
private var imgPokemon : UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
private lazy var lbPokemonName : UILabel = {
let title = UILabel()
title.translatesAutoresizingMaskIntoConstraints = false
title.font = UIFont.systemFont(ofSize: 25.0, weight: .semibold)
title.numberOfLines = 0
self.accentColor
.asDriver()
.drive(onNext: {
title.textColor = $0
})
.disposed(by: disposeBag)
return title
}()
private lazy var lbPokemonTypes : UILabel = {
let title = UILabel()
title.translatesAutoresizingMaskIntoConstraints = false
title.font = UIFont.systemFont(ofSize: 16.0)
title.numberOfLines = 0
title.text = viewModel.pokemonTypeString
self.accentColor
.asDriver()
.drive(onNext: {
title.textColor = $0
})
.disposed(by: disposeBag)
return title
}()
private lazy var weightStack : UIStackView = {
let mainStack = UIStackView()
mainStack.translatesAutoresizingMaskIntoConstraints = false
mainStack.axis = .horizontal
mainStack.spacing = 5.0
let iconImage = UIImageView(image: UIImage(named: "weight-icon"))
iconImage.translatesAutoresizingMaskIntoConstraints = false
iconImage.contentMode = .scaleAspectFit
iconImage.tintColor = .lightGray
iconImage.widthAnchor.constraint(equalTo: iconImage.heightAnchor).isActive = true
let labelStack = UIStackView()
labelStack.translatesAutoresizingMaskIntoConstraints = false
labelStack.axis = .vertical
labelStack.spacing = 0.0
labelStack.distribution = .fill
let weightTitle = UILabel()
weightTitle.textColor = .lightGray
weightTitle.textAlignment = .center
weightTitle.translatesAutoresizingMaskIntoConstraints = false
weightTitle.font = UIFont.systemFont(ofSize: 13.0, weight: .semibold)
weightTitle.numberOfLines = 0
weightTitle.text = "Peso"
let weightValue = UILabel()
weightValue.textAlignment = .center
weightValue.translatesAutoresizingMaskIntoConstraints = false
weightValue.font = UIFont.systemFont(ofSize: 16.0)
weightValue.numberOfLines = 0
weightValue.text = "\(Int(viewModel.pokemonWeight).description)Kg"
self.accentColor
.asDriver()
.drive(onNext: {
weightValue.textColor = $0
})
.disposed(by: disposeBag)
labelStack.addArrangedSubview(weightValue)
labelStack.addArrangedSubview(weightTitle)
mainStack.addArrangedSubview(iconImage)
mainStack.addArrangedSubview(labelStack)
mainStack.heightAnchor.constraint(equalToConstant: 35.0).isActive = true
return mainStack
}()
private lazy var heightStack : UIStackView = {
let mainStack = UIStackView()
mainStack.translatesAutoresizingMaskIntoConstraints = false
mainStack.axis = .horizontal
mainStack.spacing = 5.0
let iconImage = UIImageView(image: UIImage(named: "ruler-icon"))
iconImage.translatesAutoresizingMaskIntoConstraints = false
iconImage.contentMode = .scaleAspectFit
iconImage.tintColor = .lightGray
iconImage.widthAnchor.constraint(equalTo: iconImage.heightAnchor).isActive = true
let labelStack = UIStackView()
labelStack.translatesAutoresizingMaskIntoConstraints = false
labelStack.axis = .vertical
labelStack.spacing = 0.0
labelStack.distribution = .fill
let heightTitle = UILabel()
heightTitle.textColor = .lightGray
heightTitle.textAlignment = .center
heightTitle.translatesAutoresizingMaskIntoConstraints = false
heightTitle.font = UIFont.systemFont(ofSize: 13.0, weight: .semibold)
heightTitle.numberOfLines = 0
heightTitle.text = "Altura"
let heightValue = UILabel()
heightValue.textAlignment = .center
heightValue.translatesAutoresizingMaskIntoConstraints = false
heightValue.font = UIFont.systemFont(ofSize: 16.0)
heightValue.numberOfLines = 0
heightValue.text = "\(Int(viewModel.pokemonHeight).description)m"
self.accentColor
.asDriver()
.drive(onNext: {
heightValue.textColor = $0
})
.disposed(by: disposeBag)
labelStack.addArrangedSubview(heightValue)
labelStack.addArrangedSubview(heightTitle)
mainStack.addArrangedSubview(iconImage)
mainStack.addArrangedSubview(labelStack)
mainStack.heightAnchor.constraint(equalToConstant: 35.0).isActive = true
return mainStack
}()
private var contentView : UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 5.0
view.backgroundColor = .white
return view
}()
private var disposeBag : DisposeBag = DisposeBag()
convenience init(viewModel vm: PokemonViewModel) {
self.init()
viewModel = vm
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.lbPokemonName.text = viewModel.name.capitalized
view.backgroundColor = .white
view.addSubview(contentView)
view.addSubview(imgPokemon)
view.addSubview(lbPokemonName)
view.addSubview(lbPokemonTypes)
contentView.addSubview(weightStack)
contentView.addSubview(heightStack)
NSLayoutConstraint.activate([
imgPokemon.centerXAnchor.constraint(equalTo: view.centerXAnchor),
imgPokemon.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50),
imgPokemon.heightAnchor.constraint(equalToConstant: 150),
imgPokemon.widthAnchor.constraint(equalToConstant: 150),
lbPokemonName.topAnchor.constraint(equalTo: imgPokemon.bottomAnchor, constant: 0),
lbPokemonName.centerXAnchor.constraint(equalTo: imgPokemon.centerXAnchor),
lbPokemonTypes.topAnchor.constraint(equalTo: lbPokemonName.bottomAnchor, constant: 5),
lbPokemonTypes.centerXAnchor.constraint(equalTo: imgPokemon.centerXAnchor),
contentView.topAnchor.constraint(equalTo: imgPokemon.bottomAnchor, constant: -75),
contentView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 10),
contentView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 20),
contentView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -20),
weightStack.trailingAnchor.constraint(equalTo: contentView.centerXAnchor, constant: -20),
weightStack.topAnchor.constraint(equalTo: lbPokemonTypes.bottomAnchor, constant: 20),
heightStack.topAnchor.constraint(equalTo: weightStack.topAnchor),
heightStack.leadingAnchor.constraint(equalTo: contentView.centerXAnchor, constant: 20)
])
viewModel.imageDriver
.drive(onNext: { newImage in
self.imgPokemon.image = newImage
let colors = newImage.getColors()
self.accentColor.accept(colors?.secondary ?? .white)
UIView.animate(withDuration: 0.2) {
self.view.backgroundColor = colors?.background
self.lbPokemonName.textColor = colors?.secondary
self.contentView.layer.shadowColor = UIColor.black.cgColor
self.contentView.layer.shadowOpacity = 0.5
self.contentView.layer.shadowOffset = .zero
self.contentView.layer.shadowRadius = 10
}
})
.disposed(by: disposeBag)
viewModel.requestPokemonImage()
}
}
| true
|
4972a92887a82a2dca1fb0d2197024b0a2e58976
|
Swift
|
AddinDev/whatsup
|
/whatsup/Intro/ContentView.swift
|
UTF-8
| 538
| 2.515625
| 3
|
[] |
no_license
|
//
// ContentView.swift
// whatsup
//
// Created by addjn on 16/10/20.
//
import SwiftUI
import Firebase
struct ContentView: View {
@State var isLogged = UserDefaults.standard.bool(forKey: "isLogged")
var body: some View {
ZStack {
IntroView(isLogged: self.$isLogged).opacity(isLogged ? 0 : 1)
MainContainer(isLogged: self.$isLogged).opacity(isLogged ? 1 : 0)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
| true
|
064c286d6aa3f20ebfb935f9fee0bc11c28fec73
|
Swift
|
perlmunger/Aggregate
|
/Aggregate/DetailTableViewController.swift
|
UTF-8
| 1,323
| 2.671875
| 3
|
[] |
no_license
|
//
// DetailTableViewController.swift
// Aggregate
//
// Created by Matt Long on 6/22/15.
// Copyright © 2015 Matt Long. All rights reserved.
//
import UIKit
import CoreData
class DetailTableViewController: UITableViewController {
@IBOutlet weak var detailDescriptionLabel: UILabel!
var managedObjectContext:NSManagedObjectContext?
var productLine:String? {
didSet {
self.title = productLine!
self.products = Product.productsForProductLine(productLine: productLine!, managedObjectContext: self.managedObjectContext!)
}
}
var products:[Product]? {
didSet {
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.products?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DetailCell", for: indexPath as IndexPath)
if let product = self.products?[indexPath.row] {
cell.textLabel?.text = product.fullNameWithCounts
}
return cell
}
}
| true
|
7016ba172cae87d52f1f6965db3d982e0ce42a2f
|
Swift
|
mayankaryaca/YellowTaxi
|
/Yellow Taxi /Yellow Taxi/Model/User.swift
|
UTF-8
| 290
| 2.84375
| 3
|
[] |
no_license
|
//
// User.swift
// Yellow Taxi
//
// Created by Mayank Arya on 2021-03-31.
//
import Foundation
class User{
let username : String
let password : String
init(username : String, password : String){
self.username = username
self.password = password
}
}
| true
|
c7113cc3fb0d5b4a295b3ac0748f500cfcae67f5
|
Swift
|
FTChinese/FTCCApp-iOS
|
/Page/PaidPostCell.swift
|
UTF-8
| 5,858
| 2.59375
| 3
|
[] |
no_license
|
//
// ChannelCell.swift
// Page
//
// Created by Oliver Zhang on 2017/6/13.
// Copyright © 2017年 Oliver Zhang. All rights reserved.
//
import UIKit
import SafariServices
// TODO: Paid Post Cell is just a copy from Channel Cell. Should seperate two sets of code.
// MARK: It is important that this is a seperate XIB and class otherwise some normal content cells will not be able to be selected, as a result of some weird bug in collection view.
class PaidPostCell: CustomCell {
// MARK: - Style settings for this class
let imageWidth = 187
let imageHeight = 140
//var adModel: AdModel?
var pageTitle = ""
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var headline: UILabel!
@IBOutlet weak var lead: UILabel!
@IBOutlet weak var containerViewWidthConstraint: NSLayoutConstraint!
@IBOutlet weak var border: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var sign: PaddingLabel!
// MARK: Use the data source to update UI for the cell. This is unique for different types of cell.
override func updateUI() {
setupLayout()
requestAd()
sizeCell()
}
private func requestAd() {
containerView.backgroundColor = UIColor(hex: Color.Ad.background)
border.backgroundColor = nil
// MARK: - Load the image of the item
imageView.backgroundColor = UIColor(hex: Color.Content.background)
// MARK: - if adModel is already available from itemCell, no need to get the data from internet
if let adModel = itemCell?.adModel, adModel.headline != nil {
//self.adModel = adModel
showAd()
print ("Paid Post: use data from fetches to layout this cell! ")
return
} else {
print ("Paid Post: there is no headline from adMoel. Clear the view")
imageView.image = nil
headline.text = nil
lead.text = nil
sign.text = nil
}
}
private func showAd() {
if let adModel = itemCell?.adModel {
headline.text = adModel.headline?.removeHTMLTags()
if let leadText = adModel.lead?.removeHTMLTags() {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 8
paragraphStyle.lineBreakMode = .byTruncatingTail
let setStr = NSMutableAttributedString.init(string: leadText)
setStr.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSMakeRange(0, (leadText.characters.count)))
lead.attributedText = setStr
}
sign.text = "广告"
sign.backgroundColor = UIColor(hex: Color.Ad.signBackground)
sign.topInset = 2
sign.bottomInset = 2
sign.leftInset = 5
sign.rightInset = 5
// let randomIndex = Int(arc4random_uniform(UInt32(2)))
// if randomIndex == 1 {
// headline.text = "卡地亚广告"
// }
// MARK: - Report Impressions
Impressions.report(adModel.impressions)
// MARK: - Add the tap
addTap()
if let imageString0 = adModel.imageString {
let imageString = ImageService.resize(imageString0, width: imageWidth, height: imageHeight)
// MARK: If the asset is already downloaded, no need to request from the Internet
if let data = Download.readFile(imageString, for: .cachesDirectory, as: nil) {
showAdImage(data)
//print ("image already in cache:\(imageString)")
return
}
if let url = URL(string: imageString) {
Download.getDataFromUrl(url) { [weak self] (data, response, error) in
guard let data = data else {
return
}
DispatchQueue.main.async { () -> Void in
self?.showAdImage(data)
}
Download.saveFile(data, filename: imageString, to: .cachesDirectory, as: nil)
}
}
}
}
}
private func showAdImage(_ data: Data) {
imageView.image = UIImage(data: data)
}
private func setupLayout() {
// MARK: - Update Styles and Layouts
containerView.backgroundColor = UIColor(hex: Color.Content.background)
headline.textColor = UIColor(hex: Color.Content.headline)
headline.font = headline.font.bold()
lead.textColor = UIColor(hex: Color.Content.lead)
sign.textColor = UIColor(hex: Color.Ad.sign)
layoutMargins.left = 0
layoutMargins.right = 0
layoutMargins.top = 0
layoutMargins.bottom = 0
containerView.layoutMargins.left = 0
containerView.layoutMargins.right = 0
}
private func sizeCell() {
// MARK: - Use calculated cell width to diplay auto-sizing cells
let cellMargins = layoutMargins.left + layoutMargins.right
let containerViewMargins = containerView.layoutMargins.left + containerView.layoutMargins.right
if let cellWidth = cellWidth {
self.contentView.translatesAutoresizingMaskIntoConstraints = false
let containerWidth = cellWidth - cellMargins - containerViewMargins
containerViewWidthConstraint.constant = containerWidth
}
}
}
//TODO: Paid Post Ad should be moved to a subclass rather than the channel cell
| true
|
686fd5b566882c71075c34ee639b41d7e501f1f3
|
Swift
|
lukaskasa/Eclipse
|
/Eclipse/Views/Cells/MarsImageCell.swift
|
UTF-8
| 840
| 2.59375
| 3
|
[] |
no_license
|
//
// MarsImageCell.swift
// Eclipse
//
// Created by Lukas Kasakaitis on 03.09.19.
// Copyright © 2019 Lukas Kasakaitis. All rights reserved.
//
import UIKit
/// UICollectionViewCell - used to load in the mars rover image with th camera name underneath the image
class MarsImageCell: UICollectionViewCell {
// MARK: - Outlets
@IBOutlet weak var marsPhotoImageView: UIImageView!
@IBOutlet weak var marsPhotoDateLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
// MARK: - View Life Cycle
override func awakeFromNib() {
super.awakeFromNib()
}
/// Configure the cell with the image and camera name
func configure(from roverData: MarsRoverImage) {
marsPhotoImageView.image = roverData.image
marsPhotoDateLabel.text = roverData.camera.name
}
}
| true
|
4b379e026cfaf5c07ebcb3555ab7b38ede2c853a
|
Swift
|
lostw/LostwKit
|
/Source/Log/FileRotateDestination.swift
|
UTF-8
| 2,049
| 2.65625
| 3
|
[] |
no_license
|
//
// FileRotateDestination.swift
// Example
//
// Created by William on 2020/5/26.
// Copyright © 2020 Wonders. All rights reserved.
//
import UIKit
public class FileRotateDestination: BaseDestination {
var fileDestination: FileDestination
var maxFileNum: Int
public init(directoryURL: URL? = nil, maxFileNum: Int = 5) {
let dir: URL = directoryURL ?? lostw.folder.cache.appendingPathComponent("log")
var isDir: ObjCBool = false
let result = FileManager.default.fileExists(atPath: dir.path, isDirectory: &isDir)
if !result || !isDir.boolValue {
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true, attributes: nil)
}
let fileURL = dir.appendingPathComponent(Date().toString(style: "yyyyMMddHHmmss'.log'"))
self.fileDestination = FileDestination(logFileURL: fileURL)
self.fileDestination.format = "$Dyyyy-MM-dd HH:mm:ss.SSS |$d $C$L$c | $T |$N.$F.$l - $M"
self.maxFileNum = maxFileNum
super.init()
self.prune(dir: dir)
}
override public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String? {
return fileDestination.send(level, msg: msg, thread: thread, file: file, function: function, line: line, context: context)
}
func prune(dir: URL) {
let fileMgr = FileManager.default
if var files = try? fileMgr.contentsOfDirectory(at: dir, includingPropertiesForKeys: [], options: []) {
if files.count <= maxFileNum {
return
}
files.sort {$0.lastPathComponent > $1.lastPathComponent}
for i in maxFileNum..<files.count {
let url = files[i]
do {
try fileMgr.removeItem(at: url)
} catch {
print("Error attempting to delete the unneeded file <\(url.path)>: \(error)")
}
}
}
}
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.