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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
14cf580d7986f78aa40959ca9a70c345491f3bda
|
Swift
|
RyanCCollins/ios-interview
|
/GitHubProjectViewController.swift
|
UTF-8
| 6,468
| 2.953125
| 3
|
[] |
no_license
|
import UIKit
class GitHubProjectViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UICollectionViewDelegate, UICollectionViewDataSource {
// project UI
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var completionPercentage: UILabel!
@IBOutlet weak var openIssues: UILabel!
@IBOutlet weak var closedIssues: UILabel!
@IBOutlet weak var allIssuesTable: UITableView!
@IBOutlet weak var contributorsCollection: UICollectionView!
// new issue UI
@IBOutlet weak var newIssueName: UITextField!
@IBOutlet weak var newIssueDescription: UITextView!
@IBOutlet weak var postNewIssueButton: UIButton!
// data model
// We will be using our Model classes, so we don't need seperate variables anymore :)
override func viewDidLoad() {
super.viewDidLoad()
makeCallsToGithubAPI()
allIssuesTable.delegate = self
allIssuesTable.dataSource = self
contributorsCollection.delegate = self
contributorsCollection.dataSource = self
newIssueName.hidden = true
newIssueDescription.hidden = true
postNewIssueButton.hidden = true
}
func makeCallsToGithubAPI() {
// All of the network calls happen in the github API and we can access them through the API Singleton
}
@IBAction func newIssueButtonPressed(sender: AnyObject) {
newIssueName.hidden = false
newIssueDescription.hidden = false
postNewIssueButton.hidden = false
}
@IBAction func postNewIssueButtonPressed(sender: AnyObject) {
postNewIssue()
//Update the UI here
}
func postNewIssue() {
GitHubAPI.postNewIssue(success, error in {
if error != nil {
// Handle the error
} else {
//update the UI
}
})
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return issues.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("IssueCell") as! IssueCell
// [code that stylizes the cell]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// The comments and other data are being loaded by the GitHubAPI class, so we can access them via the Singleton
// [code that pushes a new view controller with comment data]
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return contributors.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = contributorsCollection.dequeueReusableCellWithReuseIdentifier("ContributorCell", forIndexPath: indexPath) as! ContributorCell
// [code that stylizes the cell]
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath:NSIndexPath) {
// The code for the network Query happens in the GitHubAPI and we can access the model objects when needed.
// [code that pushes a new view controller with contributor data]
}
}
import CoreData
@objc(Project)
class Project {
@NSManaged var name: NSString
@NSManaged var completionPercentage: NSNumber
@NSManaged var issues: [Issue]?
@NSManaged var contributors: [Contributor]?
/* Mandatory override of init for inserting into ManageObjectContext */
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
/* Our keys will let us get the stored data. Issues and contributors stored seperately and accessed with NSPredicate 1 -> M */
struct Keys {
static let name = "name"
static let completionPercentage = "completionPercentage"
static let issues = "issues"
static let contributors = "contributors"
}
/* Custom init */
init(dictionary: [String: AnyObject?], context: NSManagedObjectContext) {
/* Get associated entity from our context */
let entity = NSEntityDescription.entityForName("Project", inManagedObjectContext: context)!
/* Super, get to work! */
super.init(entity: entity, insertIntoManagedObjectContext: context)
/* Assign our properties */
name = dictionary[Keys.name] as! NSString
completionPercentage = dictionary[Keys.completionPercentage] as! NSNumber
}
/* Other various model methods here for storing the data fetched */
}
class Issue {
/* Standard CoreData ManageObject methods and properties */
}
class Contributor {
/* Standard CoreData ManageObject methods and properties */
}
class GitHubAPI {
typealias CompletionHandler = (result: AnyObject!, error: NSError?) -> Void
/* This class is responsible for making the API network calls to Github and returns callbacks with the results. */
func taskForGETMethod(var urlString: String, parameters: [String : AnyObject]?, completionHandler: CompletionHandler) -> NSURLSessionDataTask {
/* Make parameters for the network call
* Create a session and task.
* Check our status code
* Proceed with Parsing the JSON
* Return the task
*/
/* GUARD: For a successful status respose*/
}
func taskForPostMethod(var urlString: String, parameters: [String : AnyObject]?, completionHandler: CompletionHandler) -> NSURLSessionDataTask {
/* Make parameters for the network call
* Create a session and task.
* Check our status code
* Proceed with Parsing the JSON
* Return the task
*/
/* GUARD: For a successful status respose*/
}
class func parseJSONDataWithCompletionHandler(data: NSData, completionHandler: (result: AnyObject!, error: NSError?) -> Void) {
//Parse JSON and return it via the completion handler
}
}
class GitHubAPI {
//Convenience methods for getting data from the GithubAPI
}
| true
|
66c17caca150940064e041ae68709ab71f928290
|
Swift
|
matthihat/ItemFinder
|
/ItemFinderTests/Search Options Menu View Tests.swift
|
UTF-8
| 1,483
| 2.671875
| 3
|
[] |
no_license
|
//
// Search Options Menu View Tests.swift
// ItemFinderTests
//
// Created by Mattias Törnqvist on 2020-06-09.
// Copyright © 2020 Mattias Törnqvist. All rights reserved.
//
import XCTest
@testable import ItemFinder
class Search_Options_Menu_View_Tests: XCTestCase {
var sut: SearchOptionsMenuView!
var currentCity: String!
var currentAdminArea: String!
var expectedResultCity: String!
var expectedAdminArea: String!
// given
override func setUp() {
super.setUp()
sut = SearchOptionsMenuView()
currentCity = "Söderhamn"
currentAdminArea = "Gävleborg"
expectedResultCity = "Search items in: Söderhamn"
expectedAdminArea = "Extend search to: Gävleborg"
}
override func tearDown() {
super.tearDown()
sut = nil
currentCity = nil
currentAdminArea = nil
expectedResultCity = nil
expectedAdminArea = nil
}
// when
func test_citylabel_displays_current_city() {
sut.displayCityLocation(currentCity)
guard let text = sut.cityLabel.text else { return }
// then
XCTAssertEqual(expectedResultCity, text)
}
func test_administrative_area_label_displays_current_area() {
sut.displayAdminAreaLocation(currentAdminArea)
guard let text = sut.administrativeAreaLabel.text else { return }
XCTAssertEqual(expectedAdminArea, text)
}
}
| true
|
af736327f281e9ee9005da97d5f56cfc931f2f22
|
Swift
|
kyleboss/Right-After
|
/Pepr/LocationModel.swift
|
UTF-8
| 1,536
| 3.234375
| 3
|
[] |
no_license
|
//
// LocationModel.swift
// Pepr
//
// Created by Kyle Boss on 9/5/16.
// Copyright © 2016 Kyle Boss. All rights reserved.
//
import Foundation
class LocationModel: NSObject {
var city: String
var state: String
var streetAddress: String
var zip: String
var latitude: Double?
var longitude: Double?
init(city: String, state: String, streetAddress: String, zip: String, latitude: Double?, longitude: Double?) {
self.city = city
self.state = state
self.streetAddress = streetAddress
self.zip = zip
self.latitude = latitude
self.longitude = longitude
}
class func isLocation(doctorComponent: String, startedAddress: Bool, finishedAddress: Bool) -> Bool {
if doctorComponent.characters.count <= 4 { return false }
let lastFiveChars = doctorComponent.substringFromIndex(doctorComponent.endIndex.advancedBy(-5))
let hasZipCode = self.stringIsNumeric(lastFiveChars)
return startedAddress && !finishedAddress && hasZipCode
}
class func isStreetAddress(doctorComponent: String, startedAddress: Bool) -> Bool {
let firstCharIsDigit = doctorComponent.characters.first >= "0" && doctorComponent.characters.first <= "9"
return !startedAddress && firstCharIsDigit
}
class func stringIsNumeric(string: String) -> Bool
{
let badCharacters = NSCharacterSet.decimalDigitCharacterSet().invertedSet
return string.rangeOfCharacterFromSet(badCharacters) == nil
}
}
| true
|
033f36c854077f587840e7891ca1be2fdc19f5cc
|
Swift
|
zjjzmw1/mysuper
|
/mysuper/首页/HomeCell.swift
|
UTF-8
| 2,882
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
//
// HomeCell.swift
// mysuper
//
// Created by zhangmingwei on 2017/8/15.
// Copyright © 2017年 niaoyutong. All rights reserved.
//
import UIKit
import Cartography
class HomeCell: UITableViewCell {
let cellHeight: CGFloat = 150.0
var bgImageV: UIImageView! // 超市背景图片
var nameLbl: UILabel! // 超市名称
var detailLbl: UILabel! // 超市简单介绍
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.bgImageV = UIImageView.init(frame: CGRect.init(x: 0, y: 1, width: SCREEN_WIDTH, height: cellHeight))
self.contentView.addSubview(self.bgImageV)
constrain(bgImageV) { bgImageV in
bgImageV.left == bgImageV.superview!.left
bgImageV.right == bgImageV.superview!.right
bgImageV.top == bgImageV.superview!.top + 1
bgImageV.bottom == bgImageV.superview!.bottom
}
bgImageV.backgroundColor = UIColor.lightGray
bgImageV.layer.masksToBounds = true
bgImageV.contentMode = .scaleAspectFill
nameLbl = Tool.initALabel(frame: .zero, textString: "", font: FONT_PingFang(fontSize: 20), textColor: UIColor.white)
nameLbl.textAlignment = .center
self.contentView.addSubview(nameLbl)
constrain(bgImageV,nameLbl) { bgImageV,nameLbl in
nameLbl.left == bgImageV.left + 10
nameLbl.right == bgImageV.right - 10
nameLbl.top == bgImageV.top + 0
nameLbl.height == cellHeight/2.0
}
detailLbl = Tool.initALabel(frame: .zero, textString: "", font: FONT_PingFang(fontSize: 14), textColor: UIColor.white)
detailLbl.textAlignment = .center
self.contentView.addSubview(detailLbl)
detailLbl.numberOfLines = 0
detailLbl.sizeToFit()
constrain(nameLbl,detailLbl) { nameLbl,detailLbl in
detailLbl.left == nameLbl.left
detailLbl.right == nameLbl.right
detailLbl.top == nameLbl.bottom + 0
detailLbl.height == cellHeight/2.0
}
self.backgroundColor = UIColor.getSeparatorColorSwift()
self.selectionStyle = .none
}
func updateCell(row: Int, dict: Dictionary<String, String>) {
nameLbl.text = dict["name"]
detailLbl.text = dict["detail"]
if row % 2 == 0 {
self.bgImageV.backgroundColor = UIColor.colorRGB16(value: 0xFD9B27)
} else {
self.bgImageV.backgroundColor = UIColor.getMainColorSwift()
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| true
|
a898d716eefad4d236b429863bcdd36da15f85cf
|
Swift
|
albertopeam/clean-architecture
|
/CleanArchitecture/core/airquality/AirQuality.swift
|
UTF-8
| 3,201
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// AirQuality.swift
// CleanArchitecture
//
// Created by Alberto on 27/8/18.
// Copyright © 2018 Alberto. All rights reserved.
//
import Foundation
class AirQualityComponent {
static func assemble() -> AirQualityProtocol {
let url = "https://api.openaq.org/v1/measurements?coordinates={{lat}},{{lon}}&limit=1¶meter={{measure}}&has_geo=true"
let measurements = ["pm25", "pm10", "no2", "o3"]
var airQualityWorkers = Array<Worker>()
for measure in measurements {
let airQualityWorker = AirQualityWorker(url: url.replacingOccurrences(of: "{{measure}}", with: measure))
airQualityWorkers.append(airQualityWorker)
}
let locationWorker = LocationWorker()
let airQualityEntity = AirQualityEntity()
return AirQuality(locationWorker: locationWorker, airQualityWorkers: airQualityWorkers, airQualityEntity: airQualityEntity)
}
}
struct AirQualityData {
let location:Location
let date:String
let type:String
let measure:Measure
}
struct AirQualityResult:Equatable {
let location:Location
let date:Date
let aqi:AQIName
let no2:Measure
let o3:Measure
let pm10:Measure
let pm2_5:Measure
static func == (lhs: AirQualityResult, rhs: AirQualityResult) -> Bool {
return lhs.location == rhs.location &&
lhs.date == rhs.date &&
lhs.aqi == rhs.aqi &&
lhs.no2 == rhs.no2 &&
lhs.o3 == rhs.o3 &&
lhs.pm10 == rhs.pm10 &&
lhs.pm2_5 == rhs.pm2_5;
}
}
struct Measure {
let value:Double
let unit:String
static func == (lhs: Measure, rhs: Measure) -> Bool {
return lhs.value == rhs.value && lhs.unit == rhs.unit
}
}
enum AQIName:Int {
case vl, l, m, h, vh
}
enum AirQualityError: Error, Equatable {
case noNetwork, decoding, timeout, unauthorized, other
}
protocol AirQualityProtocol {
func getAirQuality(output:AirQualityOutputProtocol)
}
protocol AirQualityOutputProtocol {
func onGetAirQuality(airQuality:AirQualityResult)
func onErrorAirQuality(error:Error)
}
class AirQuality:AirQualityProtocol {
private let locationWorker:Worker
private let airQualityWorkers:Array<Worker>
private let airQualityEntity:AirQualityEntity
init(locationWorker:Worker, airQualityWorkers:Array<Worker>, airQualityEntity:AirQualityEntity) {
self.locationWorker = locationWorker
self.airQualityWorkers = airQualityWorkers
self.airQualityEntity = airQualityEntity
}
func getAirQuality(output:AirQualityOutputProtocol) {
async {
let location = try await(promise: Promises.once(worker: self.locationWorker)) as! Location
let airQualityDatas:Array<AirQualityData> = try await(promise: Promises.all(workers: self.airQualityWorkers, params: location)) as! Array<AirQualityData>
return self.airQualityEntity.process(airQualityDatas: airQualityDatas)
}.success { (airQualityResult) in
output.onGetAirQuality(airQuality: airQualityResult)
}.error { (error) in
output.onErrorAirQuality(error: error)
}
}
}
| true
|
ea5ec44438eb3d02867a8a243b0f3032e1530130
|
Swift
|
Malosiboss/Hackwich_eleven
|
/Hackwich_eleven/Resturant.swift
|
UTF-8
| 564
| 2.8125
| 3
|
[] |
no_license
|
//
// Resturant.swift
// Hackwich_eleven
//
// Created by Noah Nua on 4/13/21.
//
import UIKit
import MapKit
class Resturant: NSObject, MKAnnotation{
let resturantTitle: String
let resturantType: String
var coordinate: CLLocationCoordinate2D
init(title: String, type: String, coordinate: CLLocationCoordinate2D)
{
self.resturantTitle = title
self.resturantType = type
self.coordinate = coordinate
super.init()
}
var subtitle: String?{
return resturantTitle
}
}
| true
|
9eb7790df2eda9963fca5290f24472310b44b79a
|
Swift
|
manshiro/RChat
|
/RChat-iOS/RChat/Views/Chat Messages/ChatBubbleView.swift
|
UTF-8
| 3,173
| 2.9375
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ChatBubbleView.swift
// RChat
//
// Created by Andrew Morgan on 04/12/2020.
//
import SwiftUI
struct ChatBubbleView: View {
let chatMessage: ChatMessage
var author: Chatster?
private var isLessThanOneDay: Bool { chatMessage.timestamp.timeIntervalSinceNow > -60 * 60 * 24 }
private var isMyMessage: Bool { author == nil }
private enum Dimensions {
static let authorHeight: CGFloat = 25
static let padding: CGFloat = 4
static let horizontalOffset: CGFloat = 100
static let cornerRadius: CGFloat = 15
}
var body: some View {
HStack {
if isMyMessage { Spacer().frame(width: Dimensions.horizontalOffset) }
VStack {
HStack {
if let author = author {
HStack {
if let photo = author.avatarImage {
AvatarThumbNailView(photo: photo, imageSize: Dimensions.authorHeight)
}
if let name = author.displayName {
Text(name)
.font(.caption)
} else {
Text(author.userName)
.font(.caption)
}
Spacer()
}
.frame(maxHeight: Dimensions.authorHeight)
.padding(Dimensions.padding)
}
Spacer()
Text(chatMessage.timestamp, style: isLessThanOneDay ? .time : .date)
.font(.caption)
}
HStack {
if let photo = chatMessage.image {
ThumbnailWithExpand(photo: photo)
.padding(Dimensions.padding)
}
if let location = chatMessage.location {
if location.count == 2 {
MapThumbnailWithExpand(location: location.map { $0 })
.padding(Dimensions.padding)
}
}
if chatMessage.text != "" {
Text(chatMessage.text)
.padding(Dimensions.padding)
}
Spacer()
}
}
.padding(Dimensions.padding)
.background(Color(isMyMessage ? "MyBubble" : "OtherBubble"))
.clipShape(RoundedRectangle(cornerRadius: Dimensions.cornerRadius))
if !isMyMessage { Spacer().frame(width: Dimensions.horizontalOffset) }
}
}
}
struct ChatBubbleView_Previews: PreviewProvider {
static var previews: some View {
AppearancePreviews(
Group {
ChatBubbleView(chatMessage: .sample, author: .sample)
ChatBubbleView(chatMessage: .sample3)
ChatBubbleView(chatMessage: .sample33)
}
)
.padding()
.previewLayout(.sizeThatFits)
}
}
| true
|
048aeea5dc1418df74b7f07552ecb07406e854f6
|
Swift
|
MatthewGarlington/TeaTime
|
/TeaTimer/TeaDetailViews/ChamomileTeaView.swift
|
UTF-8
| 4,758
| 3.1875
| 3
|
[] |
no_license
|
//
// ChamomileTeaView.swift
// TeaTimer
//
// Created by Matthew Garlington on 1/21/21.
//
import SwiftUI
struct ChamomileTeaView: View {
var body: some View {
VStack {
VStack(alignment: .leading) {
Text("Chamomile Tea")
.foregroundColor(.init(#colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)))
.bold()
.font(.system(size: 40))
}.padding(.top, 50)
ZStack {
Spacer()
.frame(width: 420, height: 780)
.background(Color.secondary)
.opacity(0.8)
.cornerRadius(30)
ScrollView {
VStack {
Text("""
Chamomile is a pretty, elegant, and fragrant herb that belongs in the Asteraceae plant family. (32) People have been using chamomile for therapeutic purposes for centuries, and today it’s a popular tea—especially among people who are looking to unwind before bed. Chamomile tea is made from the dried flowers of the chamomile plant.
There are two primary varieties of chamomile: German Chamomile and Roman Chamomile (which is sometimes called English Chamomile). (33) They’re different species of the same plant, though they grow a bit differently and have a slightly different appearance.
""" )
.padding()
.foregroundColor(.white)
HStack(spacing: 20) {
EgyptianTile()
GermanTile()
}
HStack(spacing: 20) {
RomanTile()
ZStack(alignment: .top) {
Spacer()
.frame(width: 175, height: 300)
.background(Color.secondary)
.opacity(0.5)
.cornerRadius(15)
VStack {
ZStack(alignment: .bottom) {
Image("")
.resizable()
.frame(width: 175, height: 125)
.cornerRadius(15)
Spacer()
.frame(width: 175, height: 30)
.background(Color.secondary)
.cornerRadius(5)
.opacity(1.0)
Text("")
.foregroundColor(.white)
}
ZStack {
Spacer()
.frame(width: 175 , height: 150)
.background(Color.secondary)
.opacity(0.8)
.cornerRadius(15)
Text("")
.foregroundColor(.white)
}
}
}
}
}
}
}.background(Color.black).ignoresSafeArea()
.navigationBarHidden(false)
}.background(Color.black)
}
}
struct ChamomileTeaView_Previews: PreviewProvider {
static var previews: some View {
ChamomileTeaView()
}
}
| true
|
95e3a488e17948b8117613b86b5a3dd612054246
|
Swift
|
Apodini/Apodini
|
/Tests/ApodiniTests/ModifierTests/ResponseTransformerTests.swift
|
UTF-8
| 8,121
| 2.515625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// This source file is part of the Apodini open source project
//
// SPDX-FileCopyrightText: 2019-2021 Paul Schmiedmayer and the Apodini project authors (see CONTRIBUTORS.md) <paul.schmiedmayer@tum.de>
//
// SPDX-License-Identifier: MIT
//
import XCTest
import XCTApodini
@testable import Apodini
@testable import ApodiniREST
import XCTApodiniNetworking
final class ResponseTransformerTests: ApodiniTests {
private static var emojiTransformerExpectation: XCTestExpectation?
private static var helloTransformerExpectation: XCTestExpectation?
private struct Content<T: Decodable>: Decodable {
let data: T
}
private struct OptionalText: Handler {
let text: String?
init(_ text: String?) {
self.text = text
}
func handle() -> String? {
text
}
}
private struct ResponseHandler: Handler {
let response: Apodini.Response<String>
func handle() -> Apodini.Response<String> {
response
}
}
private struct EmojiResponseTransformer: ResponseTransformer {
private let emojis: String
init(emojis: String = "✅") {
self.emojis = emojis
}
func transform(content string: String) -> String {
ResponseTransformerTests.emojiTransformerExpectation?.fulfill()
return "\(emojis) \(string) \(emojis)"
}
}
private struct OptionalEmojiResponseTransformer: ResponseTransformer {
private let emojis: String
init(emojis: String = "✅") {
self.emojis = emojis
}
func transform(content string: String?) -> String {
ResponseTransformerTests.emojiTransformerExpectation?.fulfill()
return "\(emojis) \(string ?? "❓") \(emojis)"
}
}
private func expect<T: Decodable & Comparable>(_ data: T, in response: HTTPResponse) throws {
XCTAssertEqual(response.status, .ok)
let content = try response.bodyStorage.getFullBodyData(decodedAs: Content<T>.self)
XCTAssert(content.data == data, "Expected \(data) but got \(content.data)")
waitForExpectations(timeout: 0, handler: nil)
}
func testSimpleResponseTransformer() throws {
struct TestWebService: WebService {
var content: some Component {
Text("Hello")
.response(EmojiResponseTransformer())
Group("paul") {
Text("Hello Paul")
.operation(.update)
.response(EmojiResponseTransformer(emojis: "🚀"))
}
Group("bernd") {
Text("Hello Bernd")
.response(EmojiResponseTransformer())
.operation(.create)
}
}
var configuration: Configuration {
REST()
}
}
try TestWebService().start(app: app)
ResponseTransformerTests.emojiTransformerExpectation = self.expectation(description: "EmojiTransformer is executed")
try app.testable().test(.GET, "/") { res in
try expect("✅ Hello ✅", in: res)
}
ResponseTransformerTests.emojiTransformerExpectation = self.expectation(description: "EmojiTransformer is executed")
try app.testable().test(.PUT, "/paul/") { res in
try expect("🚀 Hello Paul 🚀", in: res)
}
ResponseTransformerTests.emojiTransformerExpectation = self.expectation(description: "EmojiTransformer is executed")
try app.testable().test(.POST, "/bernd/") { res in
try expect("✅ Hello Bernd ✅", in: res)
}
}
func testOptionalResponseTransformer() throws {
struct TestWebService: WebService {
var content: some Component {
OptionalText(nil)
.response(OptionalEmojiResponseTransformer())
Group("paul") {
OptionalText("Hello Paul")
.response(OptionalEmojiResponseTransformer(emojis: "🚀"))
}
}
var configuration: Configuration {
REST()
}
}
try TestWebService().start(app: app)
ResponseTransformerTests.emojiTransformerExpectation = self.expectation(description: "EmojiTransformer is executed")
try app.testable().test(.GET, "/") { res in
try expect("✅ ❓ ✅", in: res)
}
ResponseTransformerTests.emojiTransformerExpectation = self.expectation(description: "EmojiTransformer is executed")
try app.testable().test(.GET, "/paul/") { res in
try expect("🚀 Hello Paul 🚀", in: res)
}
}
func testResponseTransformer() throws {
struct TestWebService: WebService {
var content: some Component {
Group("nothing") {
ResponseHandler(response: .nothing)
.response(EmojiResponseTransformer())
}
Group("send") {
ResponseHandler(response: .send("Paul"))
.response(EmojiResponseTransformer())
.response(EmojiResponseTransformer(emojis: "🚀"))
}
Group("final") {
ResponseHandler(response: .final("Paul"))
.response(EmojiResponseTransformer())
.response(EmojiResponseTransformer(emojis: "🚀"))
.response(EmojiResponseTransformer(emojis: "🎸"))
}
Group("end") {
ResponseHandler(response: .end)
.response(EmojiResponseTransformer())
}
}
var configuration: Configuration {
REST()
}
}
try TestWebService().start(app: app)
try app.testable().test(.GET, "/nothing") { response in
XCTAssertEqual(response.status, .noContent)
XCTAssertEqual(response.bodyStorage.readableBytes, 0)
}
ResponseTransformerTests.emojiTransformerExpectation = self.expectation(description: "EmojiTransformer is executed")
ResponseTransformerTests.emojiTransformerExpectation?.expectedFulfillmentCount = 2
try app.testable().test(.GET, "/send") { res in
try expect("🚀 ✅ Paul ✅ 🚀", in: res)
}
ResponseTransformerTests.emojiTransformerExpectation = self.expectation(description: "EmojiTransformer is executed")
ResponseTransformerTests.emojiTransformerExpectation?.expectedFulfillmentCount = 3
try app.testable().test(.GET, "/final") { res in
try expect("🎸 🚀 ✅ Paul ✅ 🚀 🎸", in: res)
}
try app.testable().test(.GET, "/end") { response in
XCTAssertEqual(response.status, .noContent)
XCTAssertEqual(response.bodyStorage.readableBytes, 0)
}
}
func testFailingResponseTransformer() throws {
let response: Apodini.Response<Int> = .final(42)
XCTAssertRuntimeFailure(
EmojiResponseTransformer()
.transform(response: response.typeErased, on: self.app.eventLoopGroup.next())
)
XCTAssertRuntimeFailure(
EmojiResponseTransformer()
.transform(response: response.typeErased, on: self.app.eventLoopGroup.next())
)
XCTAssertRuntimeFailure(
OptionalEmojiResponseTransformer()
.transform(response: response.typeErased, on: self.app.eventLoopGroup.next())
)
XCTAssertRuntimeFailure(
OptionalEmojiResponseTransformer()
.transform(response: response.typeErased, on: self.app.eventLoopGroup.next())
)
}
}
| true
|
51503da82551b884fff55a5d5d9d76273aac0a34
|
Swift
|
jamesmorrisapps/StudioSesh
|
/Model/Artform.swift
|
UTF-8
| 1,123
| 3.015625
| 3
|
[] |
no_license
|
//
// Artform.swift
// StudioSeshApp
//
// Created by James B Morris on 8/17/18.
// Copyright © 2018 James B Morris. All rights reserved.
//
import Foundation
// This file contains a model of Artforms: arts and/or passions of Users and what they specialize in, nil for venues
// IMPORTANT: this is already instantiated within the User model, therefore this class is predominantly unused. However, this class can be utilized in the future for querying Users based on Artform instead of username
class Artform {
var artforms: String? // arts and/or passions of Users and what they specialize in, nil for venues
var uid: String? // userId of Users with artforms
}
extension Artform {
// compile and transform Artforms and respective data into an array of dictionaries, then return such as a Artform object (useful for working with and displaying Artforms in tableViews and collectionViews)
static func transformArtform(dict: [String : Any]) -> Artform {
let artform = Artform()
artform.artforms = dict["artforms"] as? String
artform.uid = dict["uid"] as? String
return artform
}
}
| true
|
9a691cfea8fb0f5c93feae7ac1985f1c470c667c
|
Swift
|
kodon0/iOS_Apps
|
/BaxChat/BaxChat/Controllers/LoginViewController.swift
|
UTF-8
| 2,907
| 2.78125
| 3
|
[] |
no_license
|
//
// LoginViewController.swift
// BaxChat
//
// Created by Kieran O'Donnell on 02/02/2021.
// Copyright © 2021 baxmanduppa. All rights reserved.
//
import UIKit
import Firebase
class LoginViewController: UIViewController {
@IBOutlet weak var emailTextfield: UITextField!
@IBOutlet weak var passwordTextfield: UITextField!
// Define the show alert function
func showAlert(message: String) {
let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
@IBAction func loginPressed(_ sender: UIButton) {
if let email = emailTextfield.text, let password = passwordTextfield.text {
Auth.auth().signIn(withEmail: email, password: password) { authResult, error in
if error != nil { //Need to ensure logic for when error IS nil
if let errCode = AuthErrorCode(rawValue: error!._code) {
// switch statement to flip between different error codes https://firebase.google.com/docs/reference/swift/firebaseauth/api/reference/Enums/AuthErrorCode#/c:@E@FIRAuthErrorCode@FIRAuthErrorCodeInvalidCustomToken
switch errCode {
case .invalidEmail:
print("Invalid email")
self.showAlert(message: "Invalid email")
case .emailAlreadyInUse:
print("Email in use")
self.showAlert(message: "Email in use")
case .operationNotAllowed:
print("Operation not allowed")
self.showAlert(message: "Operation not allowed")
case .invalidCustomToken:
print("Invalid token")
self.showAlert(message: "Invalid token")
case .wrongPassword:
print("Incorrect password")
self.showAlert(message: "Incorrect password")
case .userDisabled:
print("User banned")
self.showAlert(message: "User banned")
case .userNotFound:
print("User doesn't exist")
self.showAlert(message: "User doesn't exist")
default:
print("Create User Error: \(error!)")
}
}
} else {
self.performSegue(withIdentifier: K.loginSegue, sender: self)
}
}
}
}
}
| true
|
a72ae61a40324b454aff79a7cd78bdda58caa335
|
Swift
|
mdtaps/MivaApp
|
/MivaOrders/Model/OrderResponse/ProductSubscriptionTerm.swift
|
UTF-8
| 796
| 2.671875
| 3
|
[] |
no_license
|
//
// ProductSubscriptionTerm.swift
// MivaOrders
//
// Created by Mark Tapia on 2/24/19.
// Copyright © 2019 Mark Tapia. All rights reserved.
//
import Foundation
struct ProductSubscriptionTerm: Decodable {
let id: Int
let productId: Int
let frequency: String
let term: Int
let description: String
let everyNDaysTerm: Int
let fixedDayOfTheWeek: Int
let fixedDayOfTheMonth: Int
let subscriptionCount: Int
enum CodingKeys: String, CodingKey {
case id
case productId = "product_id"
case frequency
case term
case description = "descrip"
case everyNDaysTerm = "n"
case fixedDayOfTheWeek = "fixed_dow"
case fixedDayOfTheMonth = "fixed_dom"
case subscriptionCount = "sub_count"
}
}
| true
|
cffb1de8c0df368a7bdcf994cb06b271a57d235a
|
Swift
|
msplapps/Swift4-in-30days
|
/GenericsDemo/GenericsDemo/Reusable.swift
|
UTF-8
| 862
| 2.953125
| 3
|
[] |
no_license
|
//
// Reusable.swift
// GenericsDemo
//
// Created by PurushothamReddy on 10/07/18.
// Copyright © 2018 Purushotham. All rights reserved.
//
import UIKit
protocol Reusable {
}
/// MARK: - UITableView
extension Reusable where Self:UITableViewCell {
static var reuseIdentifier:String {
return String(describing: self)
}
}
extension UITableViewCell:Reusable {
}
extension UITableView {
func register<T:UITableViewCell>(_:T.Type){
register(T.self, forCellReuseIdentifier: T.reuseIdentifier)
}
func dequeReusableCell<T:UITableViewCell>(forIdexpath indexPath:IndexPath) -> T{
guard let cell = dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else{
fatalError("Coud not de quecell with this identifier")
}
return cell
}
}
| true
|
83715186681094a1156edcb7f175b2e7a217ab79
|
Swift
|
vapor/postgres-nio
|
/Sources/PostgresNIO/New/Connection State Machine/ExtendedQueryStateMachine.swift
|
UTF-8
| 21,815
| 2.75
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
import NIOCore
struct ExtendedQueryStateMachine {
private enum State {
case initialized(ExtendedQueryContext)
case messagesSent(ExtendedQueryContext)
case parseCompleteReceived(ExtendedQueryContext)
case parameterDescriptionReceived(ExtendedQueryContext)
case rowDescriptionReceived(ExtendedQueryContext, [RowDescription.Column])
case noDataMessageReceived(ExtendedQueryContext)
/// A state that is used if a noData message was received before. If a row description was received `bufferingRows` is
/// used after receiving a `bindComplete` message
case bindCompleteReceived(ExtendedQueryContext)
case streaming([RowDescription.Column], RowStreamStateMachine)
/// Indicates that the current query was cancelled and we want to drain rows from the connection ASAP
case drain([RowDescription.Column])
case commandComplete(commandTag: String)
case error(PSQLError)
case modifying
}
enum Action {
case sendParseDescribeBindExecuteSync(PostgresQuery)
case sendParseDescribeSync(name: String, query: String)
case sendBindExecuteSync(PSQLExecuteStatement)
// --- general actions
case failQuery(EventLoopPromise<PSQLRowStream>, with: PSQLError)
case succeedQuery(EventLoopPromise<PSQLRowStream>, with: QueryResult)
case evaluateErrorAtConnectionLevel(PSQLError)
case succeedPreparedStatementCreation(EventLoopPromise<RowDescription?>, with: RowDescription?)
case failPreparedStatementCreation(EventLoopPromise<RowDescription?>, with: PSQLError)
// --- streaming actions
// actions if query has requested next row but we are waiting for backend
case forwardRows([DataRow])
case forwardStreamComplete([DataRow], commandTag: String)
case forwardStreamError(PSQLError, read: Bool)
case read
case wait
}
private var state: State
private var isCancelled: Bool
init(queryContext: ExtendedQueryContext) {
self.isCancelled = false
self.state = .initialized(queryContext)
}
mutating func start() -> Action {
guard case .initialized(let queryContext) = self.state else {
preconditionFailure("Start should only be called, if the query has been initialized")
}
switch queryContext.query {
case .unnamed(let query, _):
return self.avoidingStateMachineCoW { state -> Action in
state = .messagesSent(queryContext)
return .sendParseDescribeBindExecuteSync(query)
}
case .executeStatement(let prepared, _):
return self.avoidingStateMachineCoW { state -> Action in
switch prepared.rowDescription {
case .some(let rowDescription):
state = .rowDescriptionReceived(queryContext, rowDescription.columns)
case .none:
state = .noDataMessageReceived(queryContext)
}
return .sendBindExecuteSync(prepared)
}
case .prepareStatement(let name, let query, _):
return self.avoidingStateMachineCoW { state -> Action in
state = .messagesSent(queryContext)
return .sendParseDescribeSync(name: name, query: query)
}
}
}
mutating func cancel() -> Action {
switch self.state {
case .initialized:
preconditionFailure("Start must be called immediatly after the query was created")
case .messagesSent(let queryContext),
.parseCompleteReceived(let queryContext),
.parameterDescriptionReceived(let queryContext),
.rowDescriptionReceived(let queryContext, _),
.noDataMessageReceived(let queryContext),
.bindCompleteReceived(let queryContext):
guard !self.isCancelled else {
return .wait
}
self.isCancelled = true
switch queryContext.query {
case .unnamed(_, let eventLoopPromise), .executeStatement(_, let eventLoopPromise):
return .failQuery(eventLoopPromise, with: .queryCancelled)
case .prepareStatement(_, _, let eventLoopPromise):
return .failPreparedStatementCreation(eventLoopPromise, with: .queryCancelled)
}
case .streaming(let columns, var streamStateMachine):
precondition(!self.isCancelled)
self.isCancelled = true
self.state = .drain(columns)
switch streamStateMachine.fail() {
case .wait:
return .forwardStreamError(.queryCancelled, read: false)
case .read:
return .forwardStreamError(.queryCancelled, read: true)
}
case .commandComplete, .error, .drain:
// the stream has already finished.
return .wait
case .modifying:
preconditionFailure("Invalid state: \(self.state)")
}
}
mutating func parseCompletedReceived() -> Action {
guard case .messagesSent(let queryContext) = self.state else {
return self.setAndFireError(.unexpectedBackendMessage(.parseComplete))
}
return self.avoidingStateMachineCoW { state -> Action in
state = .parseCompleteReceived(queryContext)
return .wait
}
}
mutating func parameterDescriptionReceived(_ parameterDescription: PostgresBackendMessage.ParameterDescription) -> Action {
guard case .parseCompleteReceived(let queryContext) = self.state else {
return self.setAndFireError(.unexpectedBackendMessage(.parameterDescription(parameterDescription)))
}
return self.avoidingStateMachineCoW { state -> Action in
state = .parameterDescriptionReceived(queryContext)
return .wait
}
}
mutating func noDataReceived() -> Action {
guard case .parameterDescriptionReceived(let queryContext) = self.state else {
return self.setAndFireError(.unexpectedBackendMessage(.noData))
}
switch queryContext.query {
case .unnamed, .executeStatement:
return self.avoidingStateMachineCoW { state -> Action in
state = .noDataMessageReceived(queryContext)
return .wait
}
case .prepareStatement(_, _, let promise):
return self.avoidingStateMachineCoW { state -> Action in
state = .noDataMessageReceived(queryContext)
return .succeedPreparedStatementCreation(promise, with: nil)
}
}
}
mutating func rowDescriptionReceived(_ rowDescription: RowDescription) -> Action {
guard case .parameterDescriptionReceived(let queryContext) = self.state else {
return self.setAndFireError(.unexpectedBackendMessage(.rowDescription(rowDescription)))
}
// In Postgres extended queries we receive the `rowDescription` before we send the
// `Bind` message. Well actually it's vice versa, but this is only true since we do
// pipelining during a query.
//
// In the actual protocol description we receive a rowDescription before the Bind
// In Postgres extended queries we always request the response rows to be returned in
// `.binary` format.
let columns = rowDescription.columns.map { column -> RowDescription.Column in
var column = column
column.format = .binary
return column
}
self.avoidingStateMachineCoW { state in
state = .rowDescriptionReceived(queryContext, columns)
}
switch queryContext.query {
case .unnamed, .executeStatement:
return .wait
case .prepareStatement(_, _, let eventLoopPromise):
return .succeedPreparedStatementCreation(eventLoopPromise, with: rowDescription)
}
}
mutating func bindCompleteReceived() -> Action {
switch self.state {
case .rowDescriptionReceived(let queryContext, let columns):
switch queryContext.query {
case .unnamed(_, let eventLoopPromise), .executeStatement(_, let eventLoopPromise):
return self.avoidingStateMachineCoW { state -> Action in
state = .streaming(columns, .init())
let result = QueryResult(value: .rowDescription(columns), logger: queryContext.logger)
return .succeedQuery(eventLoopPromise, with: result)
}
case .prepareStatement:
return .evaluateErrorAtConnectionLevel(.unexpectedBackendMessage(.bindComplete))
}
case .noDataMessageReceived(let queryContext):
return self.avoidingStateMachineCoW { state -> Action in
state = .bindCompleteReceived(queryContext)
return .wait
}
case .initialized,
.messagesSent,
.parseCompleteReceived,
.parameterDescriptionReceived,
.bindCompleteReceived,
.streaming,
.drain,
.commandComplete,
.error:
return self.setAndFireError(.unexpectedBackendMessage(.bindComplete))
case .modifying:
preconditionFailure("Invalid state")
}
}
mutating func dataRowReceived(_ dataRow: DataRow) -> Action {
switch self.state {
case .streaming(let columns, var demandStateMachine):
// When receiving a data row, we must ensure that the data row column count
// matches the previously received row description column count.
guard dataRow.columnCount == columns.count else {
return self.setAndFireError(.unexpectedBackendMessage(.dataRow(dataRow)))
}
return self.avoidingStateMachineCoW { state -> Action in
demandStateMachine.receivedRow(dataRow)
state = .streaming(columns, demandStateMachine)
return .wait
}
case .drain(let columns):
guard dataRow.columnCount == columns.count else {
return self.setAndFireError(.unexpectedBackendMessage(.dataRow(dataRow)))
}
// we ignore all rows and wait for readyForQuery
return .wait
case .initialized,
.messagesSent,
.parseCompleteReceived,
.parameterDescriptionReceived,
.noDataMessageReceived,
.rowDescriptionReceived,
.bindCompleteReceived,
.commandComplete,
.error:
return self.setAndFireError(.unexpectedBackendMessage(.dataRow(dataRow)))
case .modifying:
preconditionFailure("Invalid state")
}
}
mutating func commandCompletedReceived(_ commandTag: String) -> Action {
switch self.state {
case .bindCompleteReceived(let context):
switch context.query {
case .unnamed(_, let eventLoopPromise), .executeStatement(_, let eventLoopPromise):
return self.avoidingStateMachineCoW { state -> Action in
state = .commandComplete(commandTag: commandTag)
let result = QueryResult(value: .noRows(commandTag), logger: context.logger)
return .succeedQuery(eventLoopPromise, with: result)
}
case .prepareStatement:
preconditionFailure("Invalid state: \(self.state)")
}
case .streaming(_, var demandStateMachine):
return self.avoidingStateMachineCoW { state -> Action in
state = .commandComplete(commandTag: commandTag)
return .forwardStreamComplete(demandStateMachine.end(), commandTag: commandTag)
}
case .drain:
precondition(self.isCancelled)
self.state = .commandComplete(commandTag: commandTag)
return .wait
case .initialized,
.messagesSent,
.parseCompleteReceived,
.parameterDescriptionReceived,
.noDataMessageReceived,
.rowDescriptionReceived,
.commandComplete,
.error:
return self.setAndFireError(.unexpectedBackendMessage(.commandComplete(commandTag)))
case .modifying:
preconditionFailure("Invalid state")
}
}
mutating func emptyQueryResponseReceived() -> Action {
preconditionFailure("Unimplemented")
}
mutating func errorReceived(_ errorMessage: PostgresBackendMessage.ErrorResponse) -> Action {
let error = PSQLError.server(errorMessage)
switch self.state {
case .initialized:
return self.setAndFireError(.unexpectedBackendMessage(.error(errorMessage)))
case .messagesSent,
.parseCompleteReceived,
.parameterDescriptionReceived,
.bindCompleteReceived:
return self.setAndFireError(error)
case .rowDescriptionReceived, .noDataMessageReceived:
return self.setAndFireError(error)
case .streaming, .drain:
return self.setAndFireError(error)
case .commandComplete:
return self.setAndFireError(.unexpectedBackendMessage(.error(errorMessage)))
case .error:
preconditionFailure("""
This state must not be reached. If the query `.isComplete`, the
ConnectionStateMachine must not send any further events to the substate machine.
""")
case .modifying:
preconditionFailure("Invalid state")
}
}
mutating func noticeReceived(_ notice: PostgresBackendMessage.NoticeResponse) -> Action {
//self.queryObject.noticeReceived(notice)
return .wait
}
mutating func errorHappened(_ error: PSQLError) -> Action {
return self.setAndFireError(error)
}
// MARK: Customer Actions
mutating func requestQueryRows() -> Action {
switch self.state {
case .streaming(let columns, var demandStateMachine):
return self.avoidingStateMachineCoW { state -> Action in
let action = demandStateMachine.demandMoreResponseBodyParts()
state = .streaming(columns, demandStateMachine)
switch action {
case .read:
return .read
case .wait:
return .wait
}
}
case .drain:
return .wait
case .initialized,
.messagesSent,
.parseCompleteReceived,
.parameterDescriptionReceived,
.noDataMessageReceived,
.rowDescriptionReceived,
.bindCompleteReceived:
preconditionFailure("Requested to consume next row without anything going on.")
case .commandComplete, .error:
preconditionFailure("The stream is already closed or in a failure state; rows can not be consumed at this time.")
case .modifying:
preconditionFailure("Invalid state")
}
}
// MARK: Channel actions
mutating func channelReadComplete() -> Action {
switch self.state {
case .initialized,
.commandComplete,
.drain,
.error,
.messagesSent,
.parseCompleteReceived,
.parameterDescriptionReceived,
.noDataMessageReceived,
.rowDescriptionReceived,
.bindCompleteReceived:
return .wait
case .streaming(let columns, var demandStateMachine):
return self.avoidingStateMachineCoW { state -> Action in
let rows = demandStateMachine.channelReadComplete()
state = .streaming(columns, demandStateMachine)
switch rows {
case .some(let rows):
return .forwardRows(rows)
case .none:
return .wait
}
}
case .modifying:
preconditionFailure("Invalid state")
}
}
mutating func readEventCaught() -> Action {
switch self.state {
case .messagesSent,
.parseCompleteReceived,
.parameterDescriptionReceived,
.noDataMessageReceived,
.rowDescriptionReceived,
.bindCompleteReceived:
return .read
case .streaming(let columns, var demandStateMachine):
precondition(!self.isCancelled)
return self.avoidingStateMachineCoW { state -> Action in
let action = demandStateMachine.read()
state = .streaming(columns, demandStateMachine)
switch action {
case .wait:
return .wait
case .read:
return .read
}
}
case .initialized,
.commandComplete,
.drain,
.error:
// we already have the complete stream received, now we are waiting for a
// `readyForQuery` package. To receive this we need to read!
return .read
case .modifying:
preconditionFailure("Invalid state")
}
}
// MARK: Private Methods
private mutating func setAndFireError(_ error: PSQLError) -> Action {
switch self.state {
case .initialized(let context),
.messagesSent(let context),
.parseCompleteReceived(let context),
.parameterDescriptionReceived(let context),
.rowDescriptionReceived(let context, _),
.noDataMessageReceived(let context),
.bindCompleteReceived(let context):
self.state = .error(error)
if self.isCancelled {
return .evaluateErrorAtConnectionLevel(error)
} else {
switch context.query {
case .unnamed(_, let eventLoopPromise), .executeStatement(_, let eventLoopPromise):
return .failQuery(eventLoopPromise, with: error)
case .prepareStatement(_, _, let eventLoopPromise):
return .failPreparedStatementCreation(eventLoopPromise, with: error)
}
}
case .drain:
self.state = .error(error)
return .evaluateErrorAtConnectionLevel(error)
case .streaming(_, var streamStateMachine):
self.state = .error(error)
switch streamStateMachine.fail() {
case .wait:
return .forwardStreamError(error, read: false)
case .read:
return .forwardStreamError(error, read: true)
}
case .commandComplete, .error:
preconditionFailure("""
This state must not be reached. If the query `.isComplete`, the
ConnectionStateMachine must not send any further events to the substate machine.
""")
case .modifying:
preconditionFailure("Invalid state")
}
}
var isComplete: Bool {
switch self.state {
case .commandComplete, .error:
return true
case .noDataMessageReceived(let context), .rowDescriptionReceived(let context, _):
switch context.query {
case .prepareStatement:
return true
case .unnamed, .executeStatement:
return false
}
case .initialized, .messagesSent, .parseCompleteReceived, .parameterDescriptionReceived, .bindCompleteReceived, .streaming, .drain:
return false
case .modifying:
preconditionFailure("Invalid state: \(self.state)")
}
}
}
extension ExtendedQueryStateMachine {
/// So, uh...this function needs some explaining.
///
/// While the state machine logic above is great, there is a downside to having all of the state machine data in
/// associated data on enumerations: any modification of that data will trigger copy on write for heap-allocated
/// data. That means that for _every operation on the state machine_ we will CoW our underlying state, which is
/// not good.
///
/// The way we can avoid this is by using this helper function. It will temporarily set state to a value with no
/// associated data, before attempting the body of the function. It will also verify that the state machine never
/// remains in this bad state.
///
/// A key note here is that all callers must ensure that they return to a good state before they exit.
///
/// Sadly, because it's generic and has a closure, we need to force it to be inlined at all call sites, which is
/// not ideal.
@inline(__always)
private mutating func avoidingStateMachineCoW<ReturnType>(_ body: (inout State) -> ReturnType) -> ReturnType {
self.state = .modifying
defer {
assert(!self.isModifying)
}
return body(&self.state)
}
private var isModifying: Bool {
if case .modifying = self.state {
return true
} else {
return false
}
}
}
| true
|
c52509fb020c81f2f0e8d4a7761e8c3773ee312d
|
Swift
|
manhlv1999/ListenBook
|
/ListeningBookTableView/Views/ProfileView/AboutusTableViewCell.swift
|
UTF-8
| 3,486
| 2.5625
| 3
|
[] |
no_license
|
import UIKit
class AboutusTableViewCell: UITableViewCell {
var stackView: UIStackView = {
var stackview = UIStackView()
stackview.axis = .horizontal
stackview.alignment = .center
stackview.distribution = .fill
stackview.spacing = 10
stackview.translatesAutoresizingMaskIntoConstraints = false
return stackview
}()
var imageViews: UIImageView = {
var imageview = UIImageView()
imageview.backgroundColor = .orange
imageview.layer.cornerRadius = 5
imageview.widthAnchor.constraint(equalToConstant: 8).isActive = true
imageview.heightAnchor.constraint(equalToConstant: 20).isActive = true
imageview.translatesAutoresizingMaskIntoConstraints = false
return imageview
}()
var titleLabel: UILabel = {
var label = UILabel()
label.text = "Description"
label.font = .systemFont(ofSize: 25)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
var subTitleLabel: UILabel = {
var label = UILabel()
label.text = "In your feeling , works, or family, do you have the experience of do not wiant to do it In your feeling , works, or family, do you have the experience of do not wiant to do it In your feeling , works, or family, do you have the experience of do not wiant to do it In your feeling , works, or family, do you have the experience of do not wiant to do it In your feeling , works, or family, do you have the experience of do not wiant to do it In your feeling , works, or family, do you have the experience of do not wiant to do it In your feeling , works, or family, do you have the experience of do not wiant to do it In your feeling , works, or family, do you have the experience of do not wiant to do it In your feeling , works, or family, do you have the experience of do not wiant to do it"
label.numberOfLines = 0
label.font = .systemFont(ofSize: 15)
label.textColor = .systemGray
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
setupConstraints()
}
func setupUI(){
self.selectionStyle = .none
self.addSubview(stackView)
stackView.addArrangedSubview(imageViews)
stackView.addArrangedSubview(titleLabel)
self.addSubview(subTitleLabel)
}
func setupConstraints(){
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20),
stackView.topAnchor.constraint(equalTo: self.topAnchor, constant: 20),
subTitleLabel.topAnchor.constraint(equalTo: self.imageViews.bottomAnchor, constant: 20),
subTitleLabel.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 20),
subTitleLabel.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -20),
subTitleLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -20)
])
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| true
|
9ec22753dcda65331e917f48d6a36b1ae8c728b3
|
Swift
|
minddocdev/twilio-chat-ios
|
/Sources/TwilioChatClient/TCHUsers.swift
|
UTF-8
| 1,848
| 2.6875
| 3
|
[] |
no_license
|
// Converted to Swift 5 by MindDoc - https://minddoc.de
//
// TCHUsers.swift
// Twilio Chat Client
//
// Copyright (c) 2018 Twilio, Inc. All rights reserved.
//
import Foundation
//* Representation of a chat channel's users list.
open class TCHUsers: NSObject {
/**
Obtain a list of user descriptors for the specified channel.
@param channel The channel to load the user descriptors for.
@param completion Completion block that will specify the result of the operation and an array of user descriptors.
*/
public func userDescriptors(for channel: TCHChannel, completion: TCHUserDescriptorPaginatorCompletion) {
}
/**
Obtain a static snapshot of the user descriptor object for the given identity.
@param identity The identity of the user to obtain.
@param completion Completion block that will specify the result of the operation and the user descriptor.
*/
public func userDescriptor(withIdentity identity: String, completion: TCHUserDescriptorCompletion) {
}
/**
Obtain a subscribed user object for the given identity.
If no current subscription exists for this user, this will
fetch the user and subscribe them.
The least recently used user object will be unsubscribed if you reach your instance's
user subscription limit.
@param identity The identity of the user to obtain.
@param completion Completion block that will specify the result of the operation and the newly subscribed user.
*/
public func subscribedUser(withIdentity identity: String, completion: TCHUserCompletion) {
}
/**
Obtain a reference to all currently subscribed users in the system.
@return An array of subscribed TCHUser objects.
*/
public func subscribedUsers() -> [TCHUser] {
// STUB
return []
}
}
| true
|
7d03cce1b77790cedf6d5a9479c89a2f684270ee
|
Swift
|
LuizZak/SwiftRewriter
|
/Tests/Core/SwiftASTTests/SyntaxNodeTests.swift
|
UTF-8
| 1,921
| 2.890625
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause",
"MIT"
] |
permissive
|
import XCTest
@testable import SwiftAST
class SyntaxNodeTests: XCTestCase {
func testIsDescendent() {
let root = TestSyntaxNode()
let child = TestSyntaxNode()
let unrelatedChild = TestSyntaxNode()
let grandchild = TestSyntaxNode()
root.addChild(child)
child.addChild(grandchild)
root.addChild(unrelatedChild)
XCTAssert(root.isDescendent(of: root))
XCTAssert(grandchild.isDescendent(of: root))
XCTAssert(grandchild.isDescendent(of: child))
XCTAssert(unrelatedChild.isDescendent(of: root))
XCTAssertFalse(grandchild.isDescendent(of: unrelatedChild))
}
func testFirstAncestor() {
let root = TestSyntaxNode()
let child = OtherTestSyntaxNode()
let grandChild = TestSyntaxNode()
let grandGrandChild = SyntaxNode()
root.addChild(child)
child.addChild(grandChild)
grandChild.addChild(grandGrandChild)
XCTAssert(grandGrandChild.firstAncestor(ofType: SyntaxNode.self) === grandChild)
XCTAssert(grandGrandChild.firstAncestor(ofType: OtherTestSyntaxNode.self) === child)
XCTAssert(grandGrandChild.firstAncestor(ofType: TestSyntaxNode.self) === grandChild)
XCTAssertNil(root.firstAncestor(ofType: OtherTestSyntaxNode.self))
XCTAssertNil(root.firstAncestor(ofType: SyntaxNode.self))
}
}
class TestSyntaxNode: SyntaxNode {
private var _children: [SyntaxNode] = []
override var children: [SyntaxNode] {
return _children
}
func addChild(_ child: SyntaxNode) {
child.parent = self
_children.append(child)
}
}
class OtherTestSyntaxNode: SyntaxNode {
private var _children: [SyntaxNode] = []
override var children: [SyntaxNode] {
return _children
}
func addChild(_ child: SyntaxNode) {
child.parent = self
_children.append(child)
}
}
| true
|
b0b13057cbfb802189febc976fd38821cfb93e06
|
Swift
|
philipparndt/mqtt-analyzer
|
/src/MQTTAnalyzer/views/host/form/auth/certificates/CertificateAuthenticationView.swift
|
UTF-8
| 1,398
| 2.8125
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// AuthPicker.swift
// MQTTAnalyzer
//
// Created by Philipp Arndt on 2020-02-25.
// Copyright © 2020 Philipp Arndt. All rights reserved.
//
import Foundation
import SwiftUI
struct CertificateAuthenticationView: View {
@Binding var host: HostFormModel
var body: some View {
Group {
List {
CertificateFileItemView(type: .p12, file: $host.certP12)
}
HStack {
Text("Password")
.font(.headline)
Spacer()
SecureField("password", text: $host.certClientKeyPassword)
.disableAutocorrection(true)
.autocapitalization(.none)
.multilineTextAlignment(.trailing)
.font(.body)
}
}
}
}
struct CertificateFileItemView: View {
let type: CertificateFileType
@Binding var file: CertificateFile?
var body: some View {
NavigationLink(destination: CertificateFilePickerView(type: type,
file: $file,
location: getSelectedLocation())) {
HStack {
Text("\(type.getName())")
.font(.headline)
Spacer()
Group {
if !isSelected() {
Text("select")
.foregroundColor(.gray)
}
else {
Text(getFilename())
}
}.font(.body)
}
}
}
func getSelectedLocation() -> CertificateLocation {
return file?.location ?? .local
}
func isSelected() -> Bool {
return file != nil
}
func getFilename() -> String {
return file?.name ?? ""
}
}
| true
|
3a44859b3f8438a7bec6763f84b9579478082362
|
Swift
|
ATerechshenkov/Contacts
|
/Contacts/Contacts.swift
|
UTF-8
| 2,197
| 3.078125
| 3
|
[] |
no_license
|
//
// Contacts.swift
// Contacts
//
// Created by Terechshenkov Andrey on 12/10/20.
//
import Foundation
enum Honorific: String {
case mr = "Mr."
case mrs = "Mrs."
case miss = "Miss"
case ms = "Ms."
case mx = "Mx."
case dr = "Dr."
case lady = "Lady"
case lord = "Lord"
}
struct Contact {
var image: String?
var honorific: String?
var firstName: String
var lastName: String?
var phone: String
var favourite: Bool = false
var fullName: String {
get {
var fullName = firstName
if let honorific = honorific {
fullName = honorific + " " + fullName
}
if let lastName = lastName {
fullName += " " + lastName
}
return fullName
}
}
mutating func switchFavourite() {
favourite = !favourite
}
static var contacts: [Contact] {
get {[
Contact(image: "sheldon", honorific: Honorific.dr.rawValue, firstName: "Sheldon", lastName: "Cooper", phone: "+138847366738", favourite: false),
Contact(image: "penny", honorific: Honorific.miss.rawValue, firstName: "Penny", phone: "+124238420939", favourite: true),
Contact(image: "leonard", honorific: Honorific.dr.rawValue, firstName: "Leonard", lastName: "Hofstadter", phone: "+1388400388", favourite: true),
Contact(image: "howard", honorific: Honorific.mr.rawValue, firstName: "Howard", lastName: "Wolowitz", phone: "+18283776262", favourite: false),
Contact(image: "raj", honorific: Honorific.dr.rawValue, firstName: "Raj", lastName: "Koothappali", phone: "+19923737474", favourite: true),
Contact(image: "amy", honorific: Honorific.dr.rawValue, firstName: "Amy", lastName: "Farrah Fowler", phone: "+129883743839", favourite: false),
Contact(image: "bernadette", honorific: Honorific.dr.rawValue, firstName: "Bernadette", lastName: "Rostenkowski-Wolowitz", phone: "+1230843884", favourite: true),
Contact(image: "bert", honorific: Honorific.dr.rawValue, firstName: "Bertram", lastName: "Kibbler", phone: "+1230843884", favourite: false)
]}
}
}
| true
|
7231d40fa1ae40019559e51e65c3f058a888c7be
|
Swift
|
zdq1179169386/Designpatterns
|
/备忘录模式/备忘录模式/JDQSOriginator.swift
|
UTF-8
| 1,137
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
//
// JDQSOriginator.swift
// 备忘录模式
//
// Created by qrh on 2019/7/30.
// Copyright © 2019 zdq. All rights reserved.
//
import UIKit
//创建备忘录,可以恢复或记录内部状态
class JDQSOriginator: NSObject {
private var point: Int
private var level: Int
override init() {
self.point = 0;
self.level = 0;
}
func play() {
print("游戏开始了,当前等级\(self.level),当前积分\(self.point)")
self.level += 1
self.point += 10
print("当前等级\(self.level),当前积分\(self.point)")
}
func exit() {
print("游戏结束,当前等级\(self.level),当前积分\(self.point)")
}
func restore(memo: JDQSMemento) {
self.point = memo.point
self.level = memo.level
print("恢复,当前等级\(self.level),当前积分\(self.point)")
}
func createMemo() -> JDQSMemento {
return JDQSMemento(point: self.point, level: self.level)
}
func printMemo() {
print("打印,当前等级\(self.level),当前积分\(self.point)")
}
}
| true
|
f2ea6b0c8619186b3d5169336749305fc1105482
|
Swift
|
senseiphoneX/Emoji-Names
|
/Emoji Names/View Controllers/PasteDisambiguationViewController.swift
|
UTF-8
| 3,362
| 2.71875
| 3
|
[] |
no_license
|
//
// PasteDisambiguationViewController.swift
// Emoji Names
//
// Created by Cal Stephens on 11/19/17.
// Copyright © 2017 Cal Stephens. All rights reserved.
//
import UIKit
import AdaptiveFormSheet
// MARK: PasteDisambiguationViewControllerDelegate
protocol PasteDisambiguationViewControllerDelegate: class {
func pasteDisambiguationViewController(
_ viewController: PasteDisambiguationViewController,
didSelectEmoji emoji: String)
}
// MARK: PasteDisambiguationViewController
class PasteDisambiguationViewController: AFSModalViewController {
var pastedEmoji: [String]!
weak var delegate: PasteDisambiguationViewControllerDelegate?
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var collectionView: UICollectionView!
// MARK: Presentation
static func present(for pastedEmoji: [String], over source: UIViewController) {
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Paste Disambiguation") as! PasteDisambiguationViewController
if let delegate = source as? PasteDisambiguationViewControllerDelegate {
viewController.delegate = delegate
}
viewController.pastedEmoji = pastedEmoji
source.present(viewController, animated: true, completion: nil)
}
// MARK: User Interaction
@IBAction func cancelButtonPressed() {
self.dismiss(animated: true, completion: nil)
}
@IBAction func doneButtonPressed() {
self.dismiss(animated: true, completion: nil)
if let selectedIndex = collectionView.indexPathsForSelectedItems?.first?.item {
delegate?.pasteDisambiguationViewController(self,
didSelectEmoji: pastedEmoji[selectedIndex])
}
}
}
// MARK: AFSModalOptionsProvider
extension PasteDisambiguationViewController: AFSModalOptionsProvider {
var dismissWhenUserTapsDimmer: Bool? {
return false
}
}
// MARK: UICollectionViewDataSource
extension PasteDisambiguationViewController: UICollectionViewDataSource {
func collectionView(
_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int
{
return pastedEmoji.count
}
func collectionView(
_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EmojiCell", for: indexPath) as! EmojiCell
cell.decorate(for: pastedEmoji[indexPath.item])
return cell
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension PasteDisambiguationViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
doneButton.isHidden = false
}
}
// MARK: EmojiCell
class EmojiCell: UICollectionViewCell {
@IBOutlet weak var emojiLabel: UILabel!
@IBOutlet weak var selectionView: UIView!
func decorate(for emoji: String) {
Setting.preferredEmojiStyle.value.showEmoji(emoji, in: emojiLabel)
}
override var isSelected: Bool {
didSet {
selectionView.isHidden = !isSelected
}
}
}
| true
|
024895c942e2c9254921abe6b57f60cdb5136de7
|
Swift
|
IlijaMihajlovic/Core-ML-And-Vision-Object-Classifier-Lightweight-Version
|
/CoreMLAndVisionObjectClassifierLightweightVersion/CoreMLAndVisionObjectClassifierLightweightVersion/Extensions/ActivityIndicatorExtension.swift
|
UTF-8
| 956
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
//
// File.swift
// CoreMLAndVisionObjectClassifierLightweightVersion
//
// Created by Ilija Mihajlovic on 4/11/19.
// Copyright © 2019 Ilija Mihajlovic. All rights reserved.
//
import UIKit
// MARK: - Activity Indicator With A Dimmed Background
var vSpinner: UIView?
extension UIViewController {
func showSpinner(onView : UIView) {
let spinnerView = UIView.init(frame: onView.bounds)
spinnerView.backgroundColor = UIColor.init(red: 0.5, green: 0.5, blue: 0.5, alpha: 0.5)
let ai = UIActivityIndicatorView.init(style: .whiteLarge)
ai.startAnimating()
ai.center = spinnerView.center
DispatchQueue.main.async {
spinnerView.addSubview(ai)
onView.addSubview(spinnerView)
}
vSpinner = spinnerView
}
func removeSpinner() {
DispatchQueue.main.async {
vSpinner?.removeFromSuperview()
vSpinner = nil
}
}
}
| true
|
5b84a321040183378ccf9de6cdc249c751acff2d
|
Swift
|
mciargo/swiftui13
|
/Udemy1-05/Udemy1-05/SwiftUIView.tarea.swift
|
UTF-8
| 1,414
| 3
| 3
|
[] |
no_license
|
//
// SwiftUIView.tarea.swift
// Udemy1-05
//
// Created by Mauro Ciargo on 4/22/20.
// Copyright © 2020 Mauro Ciargo. All rights reserved.
//
//.shadow(color: .black, radius: 0.1, x: 2, y: 2)
//Text("foto de zepelin") .fontWeight(.heavy) .foregroundColor(.orange) .font(.largeTitle) .multilineTextAlignment(.center) .shadow(color: .black, radius: 0.1, x: 2, y: 2)
import SwiftUI
private var numHeart = 0
struct SwiftUIView_tarea: View {
var count = 0
var body: some View {
VStack{
Button(action: {
numHeart = 1 + numHeart
print("boton pulsado")
print(numHeart)
}){
HStack{
Image(systemName:"person.badge.plus.fill")
.font(.system(size:40))
Text(" Pasajeros").font(.system(size:30))
}
}
.buttonStyle(BasicButtonStyle())
Text(String(numHeart)).fontWeight(.heavy) .font(.system(size:60)) .foregroundColor(.orange) .font(.largeTitle) .multilineTextAlignment(.center) .shadow(color: .black, radius: 0.1, x: 2, y: 2)
/*Forma del Boton */
}/*final de vstack*/
}
}
struct SwiftUIView_tarea_Previews: PreviewProvider {
static var previews: some View {
SwiftUIView_tarea()
}
}
| true
|
051a82184f904329732bc9df90af8835ca7cc411
|
Swift
|
owen-yang/SplitKeys
|
/Keyboard/SingleKeyboard.swift
|
UTF-8
| 2,017
| 2.59375
| 3
|
[] |
no_license
|
//
// SingleKeyboardView.swift
// SplitKeys
//
// Created by Owen Yang on 10/4/16.
// Copyright © 2016 SplitKeys. All rights reserved.
//
import UIKit
class SingleKeyboard: Keyboard {
private let button = UIView()
let label = UILabel()
let tapGestureRecognizer = UITapGestureRecognizer()
let longPressGestureRecognizer = UILongPressGestureRecognizer()
override init(frame: CGRect) {
super.init(frame: frame)
longPressGestureRecognizer.minimumPressDuration = Settings.holdTime
button.addGestureRecognizer(tapGestureRecognizer)
button.addGestureRecognizer(longPressGestureRecognizer)
addSubview(button)
button.backgroundColor = defaultButtonColor
button.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: button, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: button, attribute: .left, relatedBy: .equal, toItem: self, attribute: .left, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: button, attribute: .right, relatedBy: .equal, toItem: self, attribute: .right, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: button, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0))
let labelOffset = CGFloat(Settings.contrastBarSize / 2)
button.addSubview(label)
label.font = defaultLabelFont
label.numberOfLines = 2
label.translatesAutoresizingMaskIntoConstraints = false
addConstraint(NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: labelOffset))
}
}
| true
|
e22a9f890f5e1e37b0be03ef4ab3497ade6ceedf
|
Swift
|
magrus87/TDP
|
/TinkoffPoints/Services/DepositPoints/DepositPointsAPIService.swift
|
UTF-8
| 3,456
| 2.734375
| 3
|
[] |
no_license
|
//
// DepositPointsAPIService.swift
// TinkoffPoints
//
// Created by Alexander Makarov on 15/09/2019.
// Copyright © 2019 magrus87. All rights reserved.
//
import Foundation
protocol DepositPointsAPIService {
func fetchPoints(latitude: Double,
longitude: Double,
radius: Int,
partners: [String]?,
success: (([PointsResponseModel]?) -> Void)?,
failure: ((Error) -> Void)?)
func fetchPartners(accountType: String,
success: (([PartnersResponseModel]?) -> Void)?,
failure: ((Error) -> Void)?)
}
final class DepositPointsAPIServiceImpl: DepositPointsAPIService {
private var network: Network
private var urlFactory = DepositPointsUrlFactoryImpl()
init(network: Network) {
self.network = network
}
func fetchPoints(latitude: Double,
longitude: Double,
radius: Int,
partners: [String]?,
success: (([PointsResponseModel]?) -> Void)?,
failure: ((Error) -> Void)?) {
var parameters: [String : Any] = ["latitude": latitude,
"longitude": longitude,
"radius": radius]
if let partners = partners {
parameters["partners"] = partners.reduce("") { $0 + ",\($1)" }
}
let request = NetworkRequestDefault(url: urlFactory.urlPath(with: .points),
method: .get,
headers: nil,
parameters: parameters)
send(request: request,
success: success,
failure: failure)
}
func fetchPartners(accountType: String,
success: (([PartnersResponseModel]?) -> Void)?,
failure: ((Error) -> Void)?) {
let request = NetworkRequestDefault(url: urlFactory.urlPath(with: .partners),
method: .get,
headers: nil,
parameters: ["accountType": accountType])
send(request: request,
success: success,
failure: failure)
}
// MARK: - private
private func send<T: Decodable>(request: NetworkRequest,
success: ((T?) -> Void)?,
failure: ((Error) -> Void)?) {
network.send(request: request) { (data, error) in
if let error = error {
failure?(error)
return
}
guard let data = data else {
failure?(NetworkError.emptyData)
return
}
let decoder = JSONDecoder()
do {
let response = try decoder.decode(DepositResponse<T>.self, from: data)
guard response.resultCode == "OK" else {
failure?(NetworkError.invalidData)
return
}
success?(response.payload)
} catch {
failure?(NetworkError.serializationError(description: error.localizedDescription))
}
}
}
}
| true
|
2d9b9f2e514305826d1d22f9c4ceeebc9da2f8cb
|
Swift
|
costaa17/ai1ProductivityApp-xcode9
|
/My Great Productivity App/OrderByPicker.swift
|
UTF-8
| 948
| 2.8125
| 3
|
[] |
no_license
|
//
// OrderByPicker.swift
// My Great Productivity App
//
// Created by Ana Vitoria do Valle Costa on 2/22/17.
// Copyright © 2017 Ana Vitoria do Valle Costa. All rights reserved.
//
import Foundation
import UIKit
class OrderByPicker: UIPickerView, UIPickerViewDataSource, UIPickerViewDelegate {
var parentVc: UIViewController?
let arr = ["Priority", "Same List Together", "Same List Separated", "A-Z", "It Doesn't Matter"]
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return arr.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return arr[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
parentVc?.updateOrderBy(row: row)
}
}
| true
|
8142efe8b788cd1a0971d81ef0810f98453b1b3f
|
Swift
|
point550/Aureal
|
/Aureal/USBWatcher.swift
|
UTF-8
| 2,146
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
class USBWatcher {
private let deviceMonitor = HIDDeviceMonitor(
AuraProductIDs.map {
HIDMonitorData(
vendorId: AsusUSBVendorID,
productId: $0
)
},
reportSize: AuraCommandLength
)
private lazy var daemon: Thread = {
Thread(target: deviceMonitor, selector: #selector(deviceMonitor.start), object: nil)
}()
var onDeviceConnected: ((HIDDevice) -> Void)?
var onDeviceDisconnected: ((String) -> Void)?
var onDeviceData: ((HIDDevice, Data) -> Void)?
deinit {
NotificationCenter.default.removeObserver(self)
}
init() {
NotificationCenter.default.addObserver(self, selector: #selector(self.hidDeviceConnected), name: .HIDDeviceConnected, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.hidDeviceDisconnected), name: .HIDDeviceDisconnected, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.hidDeviceDataReceived), name: .HIDDeviceDataReceived, object: nil)
}
func start() {
daemon.start()
}
func stop() {
daemon.cancel()
}
@objc
private func hidDeviceConnected(notification: NSNotification) {
guard
let obj = notification.object as? NSDictionary,
let device = obj["device"] as? HIDDevice
else {
return
}
onDeviceConnected?(device)
}
@objc
private func hidDeviceDisconnected(notification: NSNotification) {
guard
let obj = notification.object as? NSDictionary,
let id = obj["id"] as? String
else {
return
}
onDeviceDisconnected?(id)
}
@objc
private func hidDeviceDataReceived(notification: NSNotification) {
guard
let obj = notification.object as? NSDictionary,
let data = obj["data"] as? Data,
let device = obj["device"] as? HIDDevice
else {
return
}
onDeviceData?(device, data)
}
}
| true
|
6a11c745bfe12c8ea8d2ac39657c4b78e4ff11c9
|
Swift
|
Eldaradelshin/EAInstClient
|
/EAInstClient/AppDelegate.swift
|
UTF-8
| 1,593
| 2.671875
| 3
|
[] |
no_license
|
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow()
let firstViewController: UIViewController
if Credential.isUserAuthenticated {
let mainViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "MainViewController")
firstViewController = mainViewController
} else {
guard let authorizationViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:"AuthorizationViewController") as?
AuthorizationViewController else {
return false
}
authorizationViewController.delegate = self
firstViewController = authorizationViewController
}
self.window?.rootViewController = firstViewController
self.window?.makeKeyAndVisible()
return true
}
}
extension AppDelegate:AuthorizationViewControllerDelegate {
func authorizationViewController(_ viewController: UIViewController, authorizedWith token: String?) {
Credential.token = token
let mainViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:"MainViewController")
viewController.present(mainViewController, animated: true, completion: nil)
}
}
| true
|
ac362c73959dc3fb0b040dd143dfe1f417ca2481
|
Swift
|
EastblueOkay/HorizontalCrossFlowLayout
|
/single/single/HorizontalCrossFlowLayout/HorizontalCrossFlowLayout.swift
|
UTF-8
| 3,613
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
//
// HorizontalCrossFlowLayout.swift
// emotionKeyboard
//
// Created by 兰轩轩 on 2016/9/28.
// Copyright © 2016年 兰轩轩. All rights reserved.
// 水平横向排布流体布局
import UIKit
class HorizontalCrossFlowLayout: UICollectionViewFlowLayout {
//MARK: - 私有变量
/// 每行的元素个数
fileprivate var kNumbersPerLine : Int = 0
/// 每列的元素个数
fileprivate var kNumbersPerCol : Int = 0
//MARK: - 懒加载
/// 计算所有Cell位置大小属性值
lazy var layoutAttrs : [UICollectionViewLayoutAttributes] = {
var arr = [UICollectionViewLayoutAttributes]()
//计算UICollectionViewLayoutAttributes
let sections = self.collectionView?.numberOfSections ?? 0
for index in 0..<sections{
let itemNum = self.collectionView?.numberOfItems(inSection: index) ?? 0
for itemIndex in 0..<itemNum{
let attr = UICollectionViewLayoutAttributes(forCellWith: IndexPath(item: itemIndex, section: index))
arr.append(attr)
}
}
let perPageCount = self.kNumbersPerLine * self.kNumbersPerCol
for index in 0..<arr.count{
let currentPage = index / perPageCount
let countInSinglePage = index % perPageCount
//列号
let colNumber = countInSinglePage % self.kNumbersPerLine
//行号
let rowNumber = countInSinglePage / self.kNumbersPerLine
//计算frame
let x = CGFloat(currentPage) * (self.collectionView?.frame.width)! + self.itemSize.width * CGFloat(colNumber)
let y = self.itemSize.height * CGFloat(rowNumber)
arr[index].frame = CGRect(origin: CGPoint(x: x, y: y), size: self.itemSize)
}
return arr
}()
/// 计算ContentSize
override var collectionViewContentSize: CGSize{
get{
var count = 0
for index in 0..<(self.collectionView?.numberOfSections ?? 0){
count += collectionView?.numberOfItems(inSection: index) ?? 0
}
let page = count / (kNumbersPerLine * kNumbersPerCol)
return CGSize(width: self.collectionView!.frame.width * CGFloat(page), height: 0)
}
}
/// 唯一初始化方法
///
/// - parameter colNumber: 行数
/// - parameter lineNumber: 列数
///
/// - returns: HorizontalCrossFlowLayout
init(colNumber : Int, lineNumber : Int) {
self.kNumbersPerLine = colNumber
self.kNumbersPerCol = lineNumber
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 准备布局 设置一些属性
override func prepare() {
super.prepare()
scrollDirection = .horizontal
}
/// 获取指定区域的布局
///
/// - parameter rect: 指定区域
///
/// - returns: 布局属性
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return layoutAttrs
}
/// 单个Item的属性
///
/// - parameter indexPath: indexPath位置
///
/// - returns: UICollectionViewLayoutAttributes属性值
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
let count = indexPath.section * kNumbersPerCol * kNumbersPerLine + indexPath.item
return layoutAttrs[count]
}
}
| true
|
6a6161803cdc1641dac7aaa97d57c3b0d8feed1a
|
Swift
|
Liaoworking/SwiftUI-Usage
|
/SwiftUI-Usage/SwiftUI-Usage/viewModel/LoadDataViewModel.swift
|
UTF-8
| 959
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
//
// loadDataViewModel.swift
// SwiftUI-Usage
//
// Created by Run Liao on 2019/9/15.
// Copyright © 2019 Run Liao. All rights reserved.
//
import Foundation
import SwiftUI
import Combine
final class LoadDataViewModel: ObservableObject {
@Published var todoModel: TodoModel = TodoModel()
func fetchUserInfo() {
var request = URLRequest(url: URL(string: "https://jsonplaceholder.typicode.com/todos/1")!)
request.httpMethod = "GET"
let session = URLSession.shared.dataTask(with: request) { (data, response, error) in
let model = try! JSONDecoder().decode(TodoModel.self, from: data!)
// must in the main thread
DispatchQueue.main.async {
self.todoModel = model
}
}
session.resume()
}
}
struct TodoModel: Codable {
var userId: Int?
var id: Int?
var title: String?
var completed: Bool?
var location: String?
}
| true
|
2ea8a871b2f8d9751c9fae22ff143c63e6a1e3da
|
Swift
|
Snoozy/marble-ios
|
/Cillo/Model/Cells/NotificationCell.swift
|
UTF-8
| 3,866
| 3.015625
| 3
|
[] |
no_license
|
//
// NotificationCell.swift
// Cillo
//
// Created by Andrew Daley on 6/15/15.
// Copyright (c) 2015 Cillo. All rights reserved.
//
import UIKit
/// Cell that corresponds to reuse identifier "Notification".
///
/// Used to format Notifications in UITableViews.
class NotificationCell: UITableViewCell {
// MARK: IBOutlets
/// Displays `notification.notificationMessage`
@IBOutlet weak var messageAttributedLabel: TTTAttributedLabel!
/// Displays `notification.titleUser.photoURL` asynchronously
@IBOutlet weak var photoButton: UIButton!
/// Displays the time since this notification occured.
@IBOutlet weak var timeLabel: UILabel!
/// Custom border between cells.
///
/// This IBOutlet may not be assigned in the storyboard, meaning the UITableViewController managing this cell wants to use default UITableView separators.
@IBOutlet weak var separatorView: UIView?
// MARK: Constants
/// Struct containing all relevent fonts for the elements of a NotificationCell.
struct NotificationFonts {
/// Bold font of the text contained within messageAttributedLabel.
static let boldMessageAttributedLabelFont = UIFont.boldSystemFontOfSize(15.0)
/// Italic font of the text contained within messageAttributedLabel.
static let italicMessageAttributedLabelFont = UIFont.italicSystemFontOfSize(15.0)
/// Font of the text contained within messageAttributedLabel.
static let messageAttributedLabelFont = UIFont.systemFontOfSize(15.0)
/// Font of the text contained within timeLabel.
static let timeLabelFont = UIFont.systemFontOfSize(12.0)
}
/// Vertical space needed besides `separatorView`
class var vertSpaceNeeded: CGFloat {
return 70.0
}
// MARK: Setup Helper Functions
/// Assigns all delegates of cell to the given parameter.
///
/// :param: delegate The delegate that will be assigned to elements of the cell pertaining to the required protocols specified in the function header.
func assignDelegatesForCellTo<T: UIViewController where T: TTTAttributedLabelDelegate>(delegate: T) {
messageAttributedLabel.delegate = delegate
}
/// Calculates the height of the cell given the properties of `notification`.
///
/// :param: post The post that this cell is based on.
/// :param: width The width of the cell in the tableView.
/// :param: dividerHeight The height of the `separatorView` in the tableView.
/// :returns: The height that the cell should be in the tableView.
class func heightOfNotificationCellForNotification(notification: Notification, withElementWidth width: CGFloat, andDividerHeight dividerHeight: CGFloat) -> CGFloat {
return NotificationCell.vertSpaceNeeded + dividerHeight
}
/// Makes this NotificationCell's IBOutlets display the correct values of the corresponding Notification.
///
/// :param: notification The corresponding Notification to be displayed by this NotificationCell.
/// :param: buttonTag The tags of all buttons in this NotificationCell corresponding to their index in the array holding them.
/// :param: * Pass the precise index of the notification in its model array.
func makeCellFromNotification(notification: Notification, withButtonTag buttonTag: Int) {
let scheme = ColorScheme.defaultScheme
photoButton.setBackgroundImageToImageWithURL(notification.titleUser.photoURL, forState: .Normal)
photoButton.clipsToBounds = true
photoButton.layer.cornerRadius = 5.0
messageAttributedLabel.setupWithAttributedText(notification.notificationMessage)
timeLabel.text = "\(notification.time) ago"
timeLabel.font = NotificationCell.NotificationFonts.timeLabelFont
timeLabel.textColor = scheme.touchableTextColor()
photoButton.tag = buttonTag
separatorView?.backgroundColor = scheme.dividerBackgroundColor()
}
}
| true
|
44d322377837adf8a0a4e0145d27e8599f0cf7dc
|
Swift
|
BenziAhamed/Nevergrid
|
/NeverGrid/Source/InputFeedbackSystem.swift
|
UTF-8
| 968
| 2.6875
| 3
|
[
"ISC"
] |
permissive
|
//
// InputFeedbackSystem.swift
// NeverGrid
//
// Created by Benzi on 16/10/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
import Foundation
import SpriteKit
import UIKit
// provides visual feedback of a player's move
class InputFeedbackSystem : System {
override init(_ world: WorldMapper) {
super.init(world)
world.eventBus.subscribe(GameEvent.DoPlayerMove, handler: self)
}
override func handleEvent(event:Int, _ data:AnyObject?) {
let move = data as! UInt
let sprite = textSprite("move_\(Direction.Name[move]!)")
sprite.position = CGPointMake(
world.scene!.frame.midX,
5.0 + sprite.frame.height/2.0
)
world.scene!.hudNode.addChild(sprite)
sprite.runAction(
SKAction.waitForDuration(5.0)
.followedBy(SKAction.scaleTo(0.0, duration: 0.2))
.followedBy(SKAction.removeFromParent())
)
}
}
| true
|
a10d1a7bd74a05c1ce18acdfc4a9ede18f132696
|
Swift
|
loc02998375/ParrotScreensaver
|
/Parrot/MultipleRandomDisappearanceParrotsRoutine.swift
|
UTF-8
| 1,179
| 2.859375
| 3
|
[] |
no_license
|
//
// MultipleRandomDisappearanceParrotsRoutine.swift
// Parrot
//
// Created by Loc Nguyen on 2/05/2016.
// Copyright © 2016 RollingPotato. All rights reserved.
//
import Cocoa
class MultipleRandomDisappearanceParrotsRoutine: MultipleParrotsRoutine {
private var disappearanceMgr: [Bool]
override init() {
disappearanceMgr = []
super.init()
// increase the number of parrot comparing to the parent class
// because there is a 33% of not having to draw parrot -> same performance as parent
numColunms = 8
numRows = 8
// randomly determine upside down or not
for _ in 0..<(numColunms * numRows) {
let rand = Int(arc4random_uniform(3))
disappearanceMgr.append(rand == 1 || rand == 0)
}
createManagers()
}
override internal func drawParrotAtRect(rect: NSRect, screenSize: NSSize, frameNumber: Int, subScreenNumber: Int) {
if !disappearanceMgr[subScreenNumber] {
super.drawParrotAtRect(rect, screenSize: screenSize, frameNumber: frameNumber, subScreenNumber: subScreenNumber)
}
}
}
| true
|
8282f17af9f2736947188583042c94ae700ae303
|
Swift
|
p41155a/firebasePractice
|
/firebasePractice/ViewController.swift
|
UTF-8
| 3,048
| 2.890625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// firebasePractice
//
// Created by MC975-107 on 27/09/2019.
// Copyright © 2019 comso. All rights reserved.
//
import UIKit
import Firebase
class ViewController: UIViewController, UITableViewDataSource {
var ref : DatabaseReference!
@IBOutlet weak var tableView: UITableView!
var todos = [String]()
override func viewDidLoad() {
let rootRef = Database.database().reference()
rootRef.child("memos").observe(.value) { snapshot in
let memosDic = snapshot.value as? [String: Any] ?? [:]
for (key, value) in memosDic {
print("key \(key) value\(value)")
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.todos.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TodoCell", for: indexPath)
cell.textLabel!.text = self.todos[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
self.todos.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with: .fade)
}
@IBAction func addTodo(_ sender: Any) {
let dialog = UIAlertController(title: "새 할일 추가", message: nil, preferredStyle: .alert)
dialog.addTextField()
let okAction = UIAlertAction(title: "확인", style: .default) { (action : UIAlertAction) in
if let newTodo = dialog.textFields?[0].text {
print("입력할 할일 : \(newTodo)")
self.todos.append(newTodo)
self.tableView.reloadData()
/*
self.ref = Database.database().reference()
// ref에 fireDatabase의 주소를 넣어줍니다.
// reference는 데이터베이스의 특정 위치를 나타내며, 해당 데이터베이스 위치로 데이터를 읽거나 쓸 수 있게 만들어 줍니다.
let itemsRef = self.ref.child("list")
let itemRef = itemsRef.childByAutoId()
//데이터베이스의 위치(ref)의 child라고 하네요.
//child는 지정된 상대 경로에있는 위치의 주소를 가져오는 프로퍼티
itemRef.setValue(["title": newTodo])
*/
}
}
let cancelAction = UIAlertAction(title: "취소", style: .cancel, handler: nil)
dialog.addAction(okAction)
dialog.addAction(cancelAction)
self.show(dialog, sender: nil)
}
}
| true
|
435f8f82a733bd04fbf19fc11339e33a1f4df392
|
Swift
|
MirellaLDS/AtividadeIOSBasico
|
/projetoMirella/projetoMirella/CadastroViewController.swift
|
UTF-8
| 1,600
| 2.6875
| 3
|
[] |
no_license
|
//
// CadastroViewController.swift
// projetoMirella
//
// Created by aluno on 15/01/19.
// Copyright © 2019 aluno. All rights reserved.
//
import UIKit
class CadastroViewController: UIViewController {
@IBOutlet weak var nomeField: UITextField!
@IBOutlet weak var loginField: UITextField!
@IBOutlet weak var senhaField: UITextField!
@IBAction func cadastrar(_ sender: UIButton) {
let userName: String = self.nomeField.text ?? ""
let userLogin = self.loginField.text ?? ""
let userPw = self.senhaField.text ?? ""
let usuario: Usuario = Usuario(nome: userName, login: userLogin, senha: userPw)
Database.instance().insert(add: usuario)
let itens = Database.instance().list()
print("count \(itens)")
self.navigationController?.popViewController(animated: true)
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
// override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
//
// if identifier == "save_id" {
//
// return true
// }
// return false
// }
// 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
|
0aa095df2b7f041015b5d3b46bdd822275d51c1d
|
Swift
|
sanderbrugge/ShowMusic
|
/ShowMusic/Models/Playlist.swift
|
UTF-8
| 248
| 3.0625
| 3
|
[] |
no_license
|
/**
* Playlist model that conforms to Codable to deserialize data to it.
* We can assume that this data will always be available
*/
struct Playlist: Codable {
public private(set) var title: String
public private(set) var albums: [Int]
}
| true
|
5e09dd31572da1d35988f65d77f47e96ba96d832
|
Swift
|
jarnal/MarvelSeries
|
/LumAppsComics/Protocols/Windowable.swift
|
UTF-8
| 2,914
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
//
// Windowable.swift
// LumAppsComics
//
// Created by Jonathan Arnal on 19/12/2018.
// Copyright © 2018 Jonathan Arnal. All rights reserved.
//
import UIKit
protocol Windowable: class {
var window: UIWindow? { get set }
var duration: Double { get }
}
extension Windowable where Self: UIViewController {
//****************************************************
// MARK: - Window business
//****************************************************
/// 📲 Show the current controller in a new window
func show() {
view.alpha = 0
if window == nil {
let newWindow = UIWindow(frame: UIScreen.main.bounds)
newWindow.autoresizingMask = [.flexibleWidth, .flexibleHeight]
newWindow.isOpaque = false
newWindow.backgroundColor = UIColor.clear
newWindow.rootViewController = self
window = newWindow
}
window?.makeKeyAndVisible()
animateIn(duration: duration, then: nil)
}
/// 📲 Hides the current controller
func hide(then completion: (() -> Void)?) {
animateOut(duration: duration, then: {
self.window?.isHidden = true
self.window?.removeFromSuperview()
self.window = nil
completion?()
})
}
//****************************************************
// MARK: - Animations
//****************************************************
/// 💫 Animates the current controller when it's added to window
///
/// - Parameters:
/// - duration: duration of the animation
/// - completion: completion block called after animation is finished
private func animateIn(duration: Double, then completion: (() -> Void)?) {
view.frame = CGRect(x: 0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
UIView.animate(withDuration: duration, animations: {
self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
self.view.alpha = 1
}, completion: { (finished) in
completion?()
})
}
/// 💫 Animates the current controller when it's removed from window
///
/// - Parameters:
/// - duration: duration of the animation
/// - completion: completion block called after animation is finished
private func animateOut(duration: Double, then completion: (() -> Void)?) {
view.layer.removeAllAnimations()
UIView.animate(withDuration: duration, animations: { () -> Void in
self.view.frame = CGRect(x: 0, y: self.view.frame.height, width: self.view.frame.width, height: self.view.frame.height)
self.view.alpha = 0
}) { (finished) -> Void in
completion?()
}
}
}
| true
|
5ae96b6f19b6665c201b03d82451783340246e29
|
Swift
|
kkloberdanz/Finance-Tracker
|
/Finance Tracker Test/Images.swift
|
UTF-8
| 10,903
| 2.859375
| 3
|
[] |
no_license
|
//
// Images.swift
// Recent Tab
//
// Created by Mengyao Liu on 11/2/15.
// Copyright © 2015 Mengyao Liu. All rights reserved.
//
import Foundation
import UIKit
var startDate = NSDate()
var endDate = NSDate()
extension UIImage {
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage {
let radiansToDegrees: (CGFloat) -> CGFloat = {
return $0 * (180.0 / CGFloat(M_PI))
}
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0 / 180.0 * CGFloat(M_PI)
}
// calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size))
let t = CGAffineTransformMakeRotation(degreesToRadians(degrees));
rotatedViewBox.transform = t
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap = UIGraphicsGetCurrentContext()
// Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0, rotatedSize.height / 2.0);
// // Rotate the image context
CGContextRotateCTM(bitmap, degreesToRadians(degrees));
// Now, draw the rotated/scaled image into the context
var yFlip: CGFloat
if(flip){
yFlip = CGFloat(-1.0)
} else {
yFlip = CGFloat(1.0)
}
CGContextScaleCTM(bitmap, yFlip, -1.0)
CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
func isFirstTimeOpening() -> Bool {
let userDef: NSUserDefaults = NSUserDefaults.standardUserDefaults()
if (userDef.integerForKey("firstTime")) == 0 {
NSUserDefaults.standardUserDefaults().setObject(1, forKey: "firstTime")
return true
} else {
return false
}
}
let userDefaults = NSUserDefaults.standardUserDefaults()
class ImagesArray {
var date:String
var imageName: String
var category: String
var heading: String
var amount: Double
var location: String
var description: String
var repeating: String
init (date: String, imageName: String, category: String, heading: String, amount: Double, location: String, description: String, repeating:String){
self.date = date
self.imageName = imageName
self.category = category
self.heading = heading
self.amount = amount
self.location = location
self.description = description
self.repeating = repeating
}
}
var date: String = "\(NSDate())"
let storedImagesArray = ""
var theImages : [ImagesArray] = []
var isStartUp: Bool = true
var dateArray : [String] = []
var imageArray : [String] = []
var categoryArray : [String] = []
var headingArray : [String] = []
var amountArray : [Double] = []
var locationArray : [String] = []
var descriptionArray : [String] = []
var repeatingArray : [String] = []
func saveDataArray() {
var index = 0
dateArray = []
imageArray = []
categoryArray = []
headingArray = []
amountArray = []
locationArray = []
descriptionArray = []
repeatingArray = []
for i in theImages {
dateArray.append(theImages[index].date)
imageArray.append(theImages[index].imageName)
categoryArray.append(theImages[index].category)
headingArray.append(theImages[index].heading)
amountArray.append(theImages[index].amount)
locationArray.append(theImages[index].location)
descriptionArray.append(theImages[index].description)
repeatingArray.append(theImages[index].repeating)
index = index + 1
}
print (theImages)
NSUserDefaults.standardUserDefaults().setObject(dateArray, forKey: "dateArray")
NSUserDefaults.standardUserDefaults().setObject(imageArray, forKey: "imageArray")
NSUserDefaults.standardUserDefaults().setObject(categoryArray, forKey: "categoryArray")
NSUserDefaults.standardUserDefaults().setObject(headingArray, forKey: "headingArray")
NSUserDefaults.standardUserDefaults().setObject(amountArray, forKey: "amountArray")
NSUserDefaults.standardUserDefaults().setObject(locationArray, forKey: "locationArray")
NSUserDefaults.standardUserDefaults().setObject(descriptionArray, forKey: "descriptionArray")
NSUserDefaults.standardUserDefaults().setObject(repeatingArray, forKey: "repeatingArray")
print("saved!!")
}
func restoreDataArray() {
let userDef: NSUserDefaults = NSUserDefaults.standardUserDefaults()
dateArray = userDef.arrayForKey("dateArray") as! [String]
imageArray = userDef.arrayForKey("imageArray") as! [String]
categoryArray = userDef.arrayForKey("categoryArray") as! [String]
headingArray = userDef.arrayForKey("headingArray") as! [String]
amountArray = userDef.arrayForKey("amountArray") as! [Double]
locationArray = userDef.arrayForKey("locationArray") as! [String]
descriptionArray = userDef.arrayForKey("descriptionArray") as! [String]
repeatingArray = userDef.arrayForKey("repeatingArray") as! [String]
var index = 0
while (index < dateArray.count) {
let date = dateArray[index]
let imageName = imageArray[index]
let category = categoryArray[index]
let heading = headingArray[index]
let amount = amountArray[index]
let location = locationArray[index]
let description = descriptionArray[index]
let repeating = repeatingArray[index]
let image : ImagesArray
image = ImagesArray( date: date, imageName: imageName, category: category, heading: heading, amount: amount, location: location, description: description, repeating: repeating)
theImages.append(image)
index = index + 1
}
}
var balance: Double = 0.0
class Images {
func numberOfImages() -> Int {
return theImages.count
}
func dateForIndex(index: Int) -> NSDate{
let image: ImagesArray = theImages[index]
let fileName:String = image.date
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let date = dateFormatter.dateFromString(fileName)
return date!
//return image.date
//return NSDate()
}
func dateStringForIndex(index: Int) -> String{
let image: ImagesArray = theImages[index]
return image.date
}
func imageNameForIndex(index: Int) -> UIImage {
let image: ImagesArray = theImages[index]
let fileName:String = image.imageName
let fileManager = NSFileManager.defaultManager()
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let getImagePath = (paths as NSString).stringByAppendingPathComponent("\(fileName).jpg")
if (fileManager.fileExistsAtPath(getImagePath)){
return UIImage(contentsOfFile: getImagePath)!.imageRotatedByDegrees(90, flip: false)
}
else{
return UIImage(contentsOfFile: "no_image.jpg")!
}
}
func categoryForIndex(index: Int) -> String {
let image: ImagesArray = theImages[index]
return image.category
}
func imageHeadingForIndex(index: Int) -> String {
let image: ImagesArray = theImages[index]
return image.heading
}
func imageAmountForIndex(index: Int) -> Double {
let image: ImagesArray = theImages[index]
return image.amount
}
func imageLocationForIndex(index: Int) -> String {
let image: ImagesArray = theImages[index]
return image.location
}
func imageDescriptionForIndex(index: Int) -> String {
let image: ImagesArray = theImages[index]
return image.description
}
func repeatingForIndex(index: Int) -> String {
let image: ImagesArray = theImages[index]
return image.repeating
}
func lengthOfImagesArray() -> Int {
let image: Int = theImages.count
return image
}
func saveImages(UIImageName: UIImage, fileName: String) {
let selectedImage: UIImage = UIImageName
let fileManager = NSFileManager.defaultManager()
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let filePathToWrite = "\(paths)/\(fileName).jpg"
let imageData: NSData = UIImagePNGRepresentation(selectedImage)!
fileManager.createFileAtPath(filePathToWrite, contents: imageData, attributes: nil)
let getImagePath = (paths as NSString).stringByAppendingPathComponent("\(fileName).jpg")
if (fileManager.fileExistsAtPath(getImagePath)){
print("FILE AVAILABLE");
}
else{
print("FILE NOT AVAILABLE");
}
}
func addItemToImagesArray( date: NSDate, imageName: UIImage, category: String, heading: String, amount: Double, location: String, description: String, repeating:String){
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" //format style. Browse online to get a format that fits your needs.
let dateString:String = dateFormatter.stringFromDate(NSDate())
let image : ImagesArray
image = ImagesArray( date: dateString, imageName: dateString, category: category, heading: heading, amount: amount, location: location, description: description, repeating: repeating)
theImages.append(image)
saveImages(imageName, fileName: dateString)
print("\(theImages.count)", terminator: "")
print("added!!")
print("\(theImages.count)", terminator: "")
}
func editItemToImagesArray( date: String, imageName: UIImage, category: String, heading: String, amount: Double, location: String, description: String, repeating:String, index: Int){
let image : ImagesArray
image = ImagesArray( date: date, imageName: date, category: category, heading: heading, amount: amount, location: location, description: description, repeating: repeating)
theImages[index] = image
saveImages(imageName, fileName: date)
print("\(theImages.count)", terminator: "")
}
}
| true
|
369f917e66687e6557a17c2f2a89cfbe502aed2b
|
Swift
|
Praveeeenn/NoteDictate
|
/NoteDictate WatchKit Extension/InterfaceController.swift
|
UTF-8
| 2,480
| 2.734375
| 3
|
[] |
no_license
|
//
// InterfaceController.swift
// NoteDictate WatchKit Extension
//
// Created by Praveen on 08/03/20.
// Copyright © 2020 Praveen. All rights reserved.
//
import WatchKit
import Foundation
final class InterfaceController: WKInterfaceController {
@IBOutlet weak var table: WKInterfaceTable!
var notes: [String] = [String]()
var savePath = InterfaceController.getDocumentsDirectory().appendingPathComponent("notes").path
override func awake(withContext context: Any?) {
super.awake(withContext: context)
notes = NSKeyedUnarchiver.unarchiveObject(withFile: savePath) as? [String] ?? []
self.setupTable()
}
private func setupTable() {
table.setNumberOfRows(notes.count, withRowType: "Row")
for rowIndex in 0..<notes.count {
self.set(row: rowIndex, to: self.notes[rowIndex])
}
}
func set(row rowIndex: Int, to text: String) {
guard let row = table.rowController(at: rowIndex) as? NoteSelectRow else { return }
row.textLabel.setText(text)
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
@IBAction func addNewNoteAction() {
print("Add new note")
self.presentTextInputController(withSuggestions: nil, allowedInputMode: .plain) { [weak self] (result) in
guard let strongSelf = self else { return }
guard let resultString = result?.first as? String else { return }
strongSelf.table.insertRows(at: IndexSet(integer: strongSelf.notes.count), withRowType: "Row")
strongSelf.set(row: strongSelf.notes.count, to: resultString)
strongSelf.notes.append(resultString)
NSKeyedArchiver.archiveRootObject(strongSelf.notes, toFile: strongSelf.savePath)
}
}
override func contextForSegue(withIdentifier segueIdentifier: String, in table: WKInterfaceTable, rowIndex: Int) -> Any? {
return ["index": String(rowIndex + 1), "note": notes[rowIndex]]
}
static func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
}
| true
|
005efa19bc3f3e70a1b6d068ff8398bdd6f34f45
|
Swift
|
Nikssssss/CFT_FoodDelivery
|
/FoodDelivery/Extensions/UIView + Extension.swift
|
UTF-8
| 1,592
| 3.125
| 3
|
[] |
no_license
|
//
// UIView + Extension.swift
// FoodDelivery
//
// Created by Никита Гусев on 09.03.2021.
//
import Foundation
import UIKit
extension UIView {
func addTopBorderWithColor(color: UIColor, width: CGFloat) {
let border = UIView()
self.addSubview(border)
border.backgroundColor = color
border.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.left.right.equalToSuperview()
make.height.equalTo(width)
}
}
func addRightBorderWithColor(color: UIColor, width: CGFloat) {
let border = UIView()
border.backgroundColor = color
border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
border.frame = CGRect(x: self.frame.size.width - width, y: 0, width: width, height: self.frame.size.height)
self.addSubview(border)
}
func addBottomBorderWithColor(color: UIColor, width: CGFloat) -> UIView{
let border = UIView()
border.backgroundColor = color
border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
border.frame = CGRect(x: 0, y: frame.size.height - width, width: frame.size.width, height: width)
self.addSubview(border)
return border
}
func addLeftBorderWithColor(color: UIColor, width: CGFloat) {
let border = UIView()
border.backgroundColor = color
border.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
border.frame = CGRect(x: 0, y: 0, width: width, height: self.frame.size.height)
self.addSubview(border)
}
}
| true
|
19c11d6e8678e0256cd8cb945b4df58fbd5b83b9
|
Swift
|
juliarodriguezdev/PrepareForTakeOff
|
/PrepareForTakeOff/Helper+Extensions/StringFormatter.swift
|
UTF-8
| 2,005
| 3.203125
| 3
|
[] |
no_license
|
//
// StringFormatter.swift
// PrepareForTakeOff
//
// Created by Julia Rodriguez on 10/20/19.
// Copyright © 2019 Julia Rodriguez. All rights reserved.
//
import Foundation
extension String {
// to convert to a string and add to the calendar maybe
func convertToDate(format: String = "yyyy-MM-dd HH:mm:ss") -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale.current
guard let date = dateFormatter.date(from: self) else {
preconditionFailure("Verify the format")
}
return date
}
func convertToHeaderString() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
guard let transformedDate = formatter.date(from: self) else { return self}
formatter.dateFormat = "EEEE, MMMM d, yyyy"
let formatedDateString = formatter.string(from: transformedDate)
return formatedDateString
}
func convertToRowTitle() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let transformDate = formatter.date(from: self) else { return self}
formatter.dateFormat = "MMM d, yyyy 'at' h:mm a"
let formmatedRowString = formatter.string(from: transformDate)
return formmatedRowString
}
func converToSoleTime() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
guard let timeSnapshot = formatter.date(from: self) else { return self}
formatter.dateFormat = "h:mm a"
return formatter.string(from: timeSnapshot)
// return formattedTime
}
func capitalizingFirstletter() -> String {
return prefix(1).capitalized + dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstletter()
}
}
| true
|
2e29daf3212dda441f4f7fd24b0ce553602f7632
|
Swift
|
Davidzhu001/pdfTool
|
/pdfTool/ViewController.swift
|
UTF-8
| 2,850
| 2.578125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// pdfTool
//
// Created by Weicheng Zhu on 12/4/16.
// Copyright © 2016 Weicheng Zhu. All rights reserved.
//
import Cocoa
import Quartz
class ViewController: NSViewController {
@IBOutlet weak var currentPageLabel: NSTextField!
@IBAction func openFile(_ sender: Any) {
let file_url = openFile()
print(file_url)
}
@IBOutlet weak var inputValue: NSTextField!
@IBOutlet weak var originPdfView: PDFView!
@IBOutlet var previewPdfView: PDFView!
struct PdfFiles {
var originVersion = PDFDocument();
var workingVersion = PDFDocument();
var previewVersion = PDFDocument();
}
var originPDF = PDFDocument();
var newPDF = PDFDocument();
@IBAction func confirmButton(_ sender: Any) {
let inputInt = Int(self.inputValue.intValue)
if inputInt < (self.originPdfView.document?.pageCount)! {
self.originPdfView.go(to: self.originPDF.page(at: inputInt)! )
newPDF.insert((self.originPdfView.document?.page(at: inputInt))!, at: 0)
print(newPDF.pageCount)
} else
{
currentPageLabel.stringValue = "Out of page number"
}
}
override func viewDidLoad() {
super.viewDidLoad()
let path = Bundle.main.path(forResource: "myPDF", ofType: "pdf")!
let url = NSURL(fileURLWithPath: path)
let pdf = PDFDocument(url: url as URL)
self.originPDF = pdf!
self.originPdfView.autoScales = true;
self.originPdfView.document = self.originPDF
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func writeFile(filename :String, file :PDFDocument) {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
let newFilePath = documentsDirectory.appendingPathComponent(filename + ".pdf")
file.write(to: newFilePath)
}
func openFile() -> String {
let myFileDialog: NSOpenPanel = NSOpenPanel()
myFileDialog.allowedFileTypes = ["pdf"]
myFileDialog.runModal()
// Get the path to the file chosen in the NSOpenPanel
let path = myFileDialog.url?.path
if path != nil {
print(path!)
let url = NSURL(fileURLWithPath: path!)
self.originPDF = PDFDocument(url: url as URL)!
self.newPDF = PDFDocument(url: url as URL)!
self.previewPdfView.document = PDFDocument(url: url as URL)!
self.originPdfView.document = PDFDocument(url: url as URL)!
return path!
} else{
return "nothing selected"
}
}
}
| true
|
5e877032f43ded24dd3ea41020f0b34f4968395d
|
Swift
|
fyname/BluetoothPrint
|
/BlueTooth/BlueToothPrinter.swift
|
UTF-8
| 9,580
| 2.796875
| 3
|
[] |
no_license
|
//
// BlueToothPrinter.swift
//
// Created by Karsa wang on 7/10/15.
// Copyright (c) 2015 Karsa wang. All rights reserved.
//
import Foundation
import CoreBluetooth
import UIKit
import CoreGraphics
let CR = 0x0d
let ESC = 0x1B
class BlueToothPrinter {
static let instance = BlueToothPrinter()
var printCharacteristic: CBCharacteristic?
var currentConnect: CBPeripheral?
func testPrint() {
let encoding = CFStringConvertEncodingToNSStringEncoding(UInt32(CFStringEncodings.GB_18030_2000.rawValue))
self.enlargeFont(0x22)
self.writeData(NSString(string: "商户名称").dataUsingEncoding(encoding)!)
self.printAndGoNLine(1)
self.enlargeFont(0x00)
self.writeData(NSString(string: "=========================").dataUsingEncoding(encoding)!)
self.printAndGoNLine(1)
self.writeData(NSString(string: "圣女果x1 2.00").dataUsingEncoding(encoding)!)
self.printAndGoNLine(1)
self.writeData(NSString(string: "圣女果x1 2.00").dataUsingEncoding(encoding)!)
self.printAndGoNLine(1)
self.writeData(NSString(string: "圣女果x1 2.00").dataUsingEncoding(encoding)!)
self.printAndGoNLine(1)
self.writeData(NSString(string: "圣女果x1 2.00").dataUsingEncoding(encoding)!)
self.printAndGoNLine(1)
self.writeData(NSString(string: "=========================").dataUsingEncoding(encoding)!)
self.printAndGoNLine(1)
self.printCode("")
self.printAndGoNLine(5)
}
/*
// [解释]:清除打印缓冲区中的数据,复位打印机打印参数到打印机缺省参数。
// [注意]:不是完全恢复到出厂设置,系统参数设置不会被更改。
*/
func resetPrinter() {
self.writeData(NSData(bytes: [0x1B, 0x40], length: 2))
}
/*
// 用该命令唤醒打印机后,至少需要延迟20毫秒后才能向打印机发送数据,否则 可能导致打印机打印乱码。
// 如果打印机在没有休眠时接收到此命令,打印机将忽略此命令。
// 建议开发者在任何时候打印数据前先发送此命令。
// 打印机从休眠状态被唤醒时,打印参数与休眠前的参数保持一致。
*/
func wakeUpPrinter() {
self.writeData(NSData(bytes: [0x00], length: 1))
}
/*
// 将打印缓冲区中的数据全部打印出来并返回标准模式。 打印后,删除打印缓冲区中的数据。
// 该命令设置打印位置为行的起始点。 如果打印机设置在黑标检测状态,则打印缓冲区中的数据后,走纸到黑标处, 如果黑标不存在,则走纸30cm后停止,预印刷黑标的规范请见附录C.预印刷黑 标说明。
// 如果在非黑标检测状态,则仅打印缓冲区的内容,不走纸。
*/
func printAndGoToNextPage() {
self.writeData(NSData(bytes: [0x0C], length: 1))
}
func printAndGoToNextLine() {
self.writeData(NSData(bytes: [0x0A], length: 1))
}
func printAndEnter() {
self.writeData(NSData(bytes: [0x0D], length: 1))
}
/*
打印缓冲区数据并进纸n个垂直点距。
0 ≤ n ≤ 255,一个垂直点距为0.125mm,以下同。
*/
func printAndGoForNPoint(n: Int8) {
self.writeData(NSData(bytes: [0x1B, 0x4A, n], length: 3))
}
func printAndGoNLine(n: Int8) {
self.writeData(NSData(bytes: [0x1B, 0x64, n], length: 3))
}
func printTAB() {
self.writeData(NSData(bytes: [0x09], length: 1))
}
func printTAB2(nL:Int8, nH:Int8) {
self.writeData(NSData(bytes: [0x1C, 0x55, nL, nH], length: 4))
}
func chosePrintMode(n: Int8) {
self.writeData(NSData(bytes: [0x1B, 0x21, n], length: 3))
}
/*
[描述]: n 值用为表示响应的倍高、倍宽信息
*/
func enlargeFont(n: Int8) {
self.writeData(NSData(bytes: [0x1D, 0x21, n], length: 3))
}
func chooseFont(n: Int8) {
self.writeData(NSData(bytes: [0x1B, 0x4D, n], length: 3))
}
func underLineSwitch() {
self.writeData(NSData(bytes: [0x1B, 0x2D], length: 2))
}
func setReversePrint(enabled: Bool) {
if enabled {
self.writeData(NSData(bytes: [0x1D, 0x42, 0x00], length: 3))
} else {
self.writeData(NSData(bytes: [0x1D, 0x42, 0x01], length: 3))
}
}
/*
//字体旋转N个90度,N为0就取消旋转
*/
func rotateFont(n: Int8) {
if n <= 3 && n >= 0 {
self.writeData(NSData(bytes: [0x1B, 0x56, n], length: 3))
}
}
func setTAB() {
}
func setAbsoulutePosition(nL: Int8, nH: Int8) {
self.writeData(NSData(bytes: [0x1B, 0x24, nL, nH], length: 4))
}
func setRelationPosition(nL: Int8, nH: Int8) {
self.writeData(NSData(bytes: [0x1B, 0x5C, nL, nH], length: 4))
}
func resetDefaultLineSpace() {
self.writeData(NSData(bytes: [0x1B, 0x32], length: 2))
}
func setLineSpace(n: Int8) {
self.writeData(NSData(bytes: [0x1B, 0x33, n], length: 3))
}
func setCharacterSpace(n: Int8) {
self.writeData(NSData(bytes: [0x1B, 0x20, n], length: 3))
}
func setLeftPrintSpace(nL: Int8, nH: Int8) {
self.writeData(NSData(bytes: [0x1D, 0x4C, nL, nH], length: 4))
}
func setAlignment(n: Int8) {
self.writeData(NSData(bytes: [0x1B, 0x61, n], length: 3))
}
func setDotMatrix(mode: Int8, n1: Int8, n2: Int8, dotsContent: [Int8]) {
self.writeData(NSData(bytes: [0x1B, 0x33, mode], length: 3))
self.writeData(NSData(bytes: [n1,n2], length: 2))
self.writeData(NSData(bytes: dotsContent, length: dotsContent.count))
}
func defineDownLoadBitmap(x: Int8, y: Int8, content: [Int8]) {
self.writeData(NSData(bytes: [0x1D, 0x2A, x, y], length: 4))
self.writeData(NSData(bytes: content, length: content.count))
}
func printDownLoadBitmap(n: Int8) {
self.writeData(NSData(bytes: [0x1D, 0x2F, n], length: 3))
}
func printPreSavedBitMap(n: Int8) {
self.writeData(NSData(bytes: [0x1C, 0x50, n], length: 3))
}
func printCurve(content: [Int8]) {
if content.count > 4 {
let count = content.count/4
self.writeData(NSData(bytes: [0x1D, 0x27, count], length: 3))
self.writeData(NSData(bytes: content, length: content.count))
}
}
func printCurveText() {
}
func setUserCharactics(n: Int8) {
self.writeData(NSData(bytes: [0x1B, 0x25, n], length: 3))
}
func setUserCharactics2(n: Int8) {
self.writeData(NSData(bytes: [0x1B, 0x3f, n], length: 3))
}
func defineUserCharactics() {
}
func enterHANZIMode() {
self.writeData(NSData(bytes: [0x1C, 0x26], length: 2))
}
func exitHANZIMode() {
self.writeData(NSData(bytes: [0x1C, 0x2E], length: 2))
}
func defineUserHANZI(nL: Int8, nH: Int8, content: [Int8]) {
self.writeData(NSData(bytes: [0x1C, 0x32], length: 2))
self.writeData(NSData(bytes: [nL,nH], length: 2))
self.writeData(NSData(bytes: content, length: content.count))
}
func writeData(data: NSData) {
if self.setUp() {
self.currentConnect?.writeValue(data, forCharacteristic: self.printCharacteristic, type: CBCharacteristicWriteType.WithResponse)
}
}
func setUp() -> Bool {
if nil == self.currentConnect || self.printCharacteristic == nil {
if let connect = BlueToothManager.shareInstance().currentConnect {
self.currentConnect = connect
if connect.state == CBPeripheralState.Connected {
for ser in connect.services {
if let service = ser as? CBService {
if service.characteristics != nil && service.characteristics.count > 0 {
for cha in service.characteristics {
if let characteristic = cha as? CBCharacteristic {
if characteristic.UUID.UUIDString == print_service_uuid || service.UUID.UUIDString == print_service_uuid {
self.printCharacteristic = characteristic
return true
}
}
}
}
}
}
}
}
return false
}
return true
}
func printCode(str: String) {
if self.setUp() {
self.writeData(NSData(bytes:[0x1d] , length: 1))
self.writeData(NSData(bytes:[0x68] , length: 1))
self.writeData(NSData(bytes:[120] , length: 1))
self.writeData(NSData(bytes:[0x1d] , length: 1))
self.writeData(NSData(bytes:[0x48] , length: 1))
self.writeData(NSData(bytes:[0x01] , length: 1))
self.writeData(NSData(bytes:[0x1d] , length: 1))
self.writeData(NSData(bytes:[0x6B] , length: 1))
self.writeData(NSData(bytes:[0x02] , length: 1))
self.writeData(NSString(string: "091955826335").dataUsingEncoding(NSUTF8StringEncoding)!)
self.writeData(NSData(bytes:[0x00] , length: 1))
}
}
}
| true
|
2dcff564978d61ec6f223cf326f6d8360b1d4779
|
Swift
|
tausiffrana/BottomPopup
|
/BottomPopup/ViewController/ViewController.swift
|
UTF-8
| 1,784
| 2.859375
| 3
|
[] |
no_license
|
//
// ViewController.swift
// BottomPopup
//
// Created by Apple on 03/09/21.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var btnShowPopup: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
btnShowPopup.addTarget(self, action: #selector(showPopup), for: .touchUpInside)
}
@objc func showPopup() {
guard let popupViewController = CustomPopupView.instantiate() else { return }
popupViewController.delegate = self
popupViewController.titleString = "I am custom popup"
let popupVC = PopupViewController(contentController: popupViewController, position: .bottom(0), popupWidth: self.view.frame.width, popupHeight: 300)
popupVC.cornerRadius = 15
popupVC.backgroundAlpha = 0.0
popupVC.backgroundColor = .clear
popupVC.canTapOutsideToDismiss = true
popupVC.shadowEnabled = true
popupVC.delegate = self
popupVC.modalPresentationStyle = .popover
self.present(popupVC, animated: true, completion: nil)
}
}
extension ViewController : PopupViewControllerDelegate, CustomPopupViewDelegate
{
// MARK: Default Delegate Methods For Dismiss Popup
public func popupViewControllerDidDismissByTapGesture(_ sender: PopupViewController)
{
dismiss(animated: true)
{
debugPrint("Popup Dismiss")
}
}
// MARK: Custom Delegate Methods For Dismiss Popup on Action
func customPopupViewExtension(sender: CustomPopupView, didSelectNumber: Int)
{
dismiss(animated: true)
{
if didSelectNumber == 1
{
debugPrint("Custom Popup Dismiss On Done Button Action")
}
}
}
}
| true
|
086df0095c6d493de9a069765276be9a47b14045
|
Swift
|
medenzon/Game459
|
/Game459/Controllers/MenuViewController.swift
|
UTF-8
| 776
| 2.5625
| 3
|
[] |
no_license
|
//
// MenuViewController.swift
// Game459
//
// Created by Michael Edenzon on 2/7/19.
// Copyright © 2019 Michael Edenzon. All rights reserved.
//
import UIKit
class MenuViewController: ViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = Color.anthracite
// let frame = CGRect(x: 0, y: -200, width: view.frame.width, height: view.frame.height + 200)
//
// let starsView = StarsView(frame: frame, points: 25)
//
// view.addSubview(starsView)
// view.sendSubviewToBack(starsView)
}
override var shouldAutorotate: Bool {
return false
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| true
|
b5681997bfa3abf5039413aafdfd7ea5828d2779
|
Swift
|
AlexanderPLv/SettingsApp
|
/SettingsApp/SettingsVC.swift
|
UTF-8
| 2,432
| 2.6875
| 3
|
[] |
no_license
|
//
// SettingsVC.swift
// SettingsApp
//
// Created by MacMini on 24/06/2019.
// Copyright © 2019 com.blablabla. All rights reserved.
//
import UIKit
class SettingsVC: UITableViewController {
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
@IBOutlet weak var likesDevelopmentSwitch: UISwitch!
@IBOutlet weak var coolMeterLabel: UILabel!
@IBOutlet weak var coolMeterSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
loadSettings()
}
private func saveSettings() {
let settingsDictionary: [String : Any?] = ["firstName": firstNameTextField.text,
"lastName": lastNameTextField.text,
"likesDev": likesDevelopmentSwitch.isOn,
"coolMeter": Int(coolMeterSlider.value)]
UserDefaults.standard.set(settingsDictionary, forKey: "settings")
}
func loadSettings() {
guard let settingsDictionary = UserDefaults.standard.dictionary(forKey: "settings") else { return }
guard let firstName = settingsDictionary["firstName"] as? String,
let lastName = settingsDictionary["lastName"] as? String,
let likesDev = settingsDictionary["likesDev"] as? Bool,
let coolMeter = settingsDictionary["coolMeter"] as? Int
else { return }
firstNameTextField.text = firstName
lastNameTextField.text = lastName
likesDevelopmentSwitch.isOn = likesDev
coolMeterLabel.text = String(coolMeter)
coolMeterSlider.value = Float(coolMeter)
}
@IBAction func didSlideCoolMeter(_ sender: UISlider) {
let wholeNumber = Int(sender.value)
coolMeterLabel.text = String(wholeNumber)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.section == 2 else { return }
saveSettings()
didSaveAlert()
}
func didSaveAlert() {
let alert = UIAlertController(title: "Settings saved", message: nil, preferredStyle: .alert)
let action = UIAlertAction(title: "Dismiss", style: .cancel)
alert.addAction(action)
present(alert, animated: true)
}
}
| true
|
6c341d46893f46e654a34df48504ac1972cc7945
|
Swift
|
dmilotz/Virtual-Tourist
|
/Virtual tourist/PhotoModel.swift
|
UTF-8
| 425
| 2.78125
| 3
|
[] |
no_license
|
//
// PhotoModel.swift
// Virtual tourist
//
// Created by Dirk Milotz on 1/28/17.
// Copyright © 2017 Dirk Milotz. All rights reserved.
//
import Foundation
struct PhotoModel{
let photoId: String
let farm: Int
let secret: String
let server: String
let title: String
var photoUrl: URL{
return URL(string: "https://farm\(farm).staticflickr.com/\(server)/\(photoId)_\(secret)_m.jpg")!
}
}
| true
|
fa3717d4e0e9501baaf54e078c65b93ef318d739
|
Swift
|
w2huy/msugrades
|
/msugrades/Scenes/Courses/Views/SearchBarView.swift
|
UTF-8
| 2,433
| 2.953125
| 3
|
[] |
no_license
|
//
// SearchBarView.swift
// msugrades
//
// Created by William Huynh on 12/29/20.
//
import SwiftUI
import UIKit
struct SearchBarView: View {
@ObservedObject var viewModel: CoursesViewModel
var placeholder: String
@Binding var error: Bool
@Binding var searchText: String
@Binding var isSearching: Bool
var body: some View {
HStack{
HStack{
TextField(placeholder, text: $searchText, onCommit: {
isSearching = false
viewModel.loadData(course: searchText) { (res) in
error = !res
print(error)
}
UIApplication.shared.endEditing()
})
.disableAutocorrection(true)
.padding(.leading, 16)
}
.padding()
.padding(.horizontal)
.onTapGesture(perform: {
isSearching = true
})
.overlay(
HStack{
Image(systemName: "magnifyingglass")
Spacer()
if isSearching {
Button(action: {
searchText = ""
}, label: {
Image(systemName: "xmark.circle.fill")
.padding(.vertical)
})
Button(action: {
isSearching.toggle()
UIApplication.shared.endEditing()
}, label: {
Text("Cancel")
.fontWeight(.light)
})
}
}.padding(.horizontal)
.foregroundColor(.gray)
).transition(.move(edge: .trailing))
}
}
}
extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
struct SearchBarView_Previews: PreviewProvider {
static var previews: some View {
SearchBarView(viewModel: CoursesViewModel(), placeholder: "Search by Course Code", error: .constant(true), searchText: .constant(""), isSearching: .constant(true))
}
}
| true
|
12b9966891598397f14dc41e505d56af1c1e0bb5
|
Swift
|
ihoorados/Factory
|
/Factory/Flow.swift
|
UTF-8
| 1,648
| 3.46875
| 3
|
[] |
no_license
|
//
// Flow.swift
// Factory
//
// Created by Hoorad Ramezani on 2/7/21.
//
import Foundation
protocol Router {
associatedtype Question : Hashable
associatedtype Answer
func routeTo(question: Question, answerCallBack: @escaping (Answer) -> Void)
func routeTo(result:[Question:Answer])
}
class Flow<Question, Answer, R: Router> where R.Question == Question, R.Answer == Answer{
private let router : R
private let Questions: [Question]
private var result: [Question:Answer] = [:]
init(router:R,question:[Question]) {
self.router = router
self.Questions = question
}
func start(){
if let firstQuestion = Questions.first{
router.routeTo(question: firstQuestion, answerCallBack: nextCallBack(from:firstQuestion))
}else{
router.routeTo(result: result)
}
}
private func nextCallBack(from question:Question) -> (Answer) -> Void{
return{ [weak self] in self?.routeNext(question, $0) }
}
private func routeNext(_ question: Question,_ answer: Answer){
if let CurrentQuestionIndex = Questions.firstIndex(of:question){
result[question] = answer
let nextQuestionIndex = CurrentQuestionIndex+1
if nextQuestionIndex < Questions.count{
let nextQuestion = Questions[nextQuestionIndex]
router.routeTo(
question: nextQuestion,
answerCallBack: nextCallBack(from:nextQuestion))
}else {
router.routeTo(result: result)
}
}
}
}
| true
|
c0d86af99a79de106d7d89a6e833efa5ff5a988a
|
Swift
|
ikejay/WinDelivery
|
/WinDelivery/LoginViewController.swift
|
UTF-8
| 3,321
| 2.546875
| 3
|
[] |
no_license
|
//
// LoginViewController.swift
// WinDelivery
//
// Created by Isaac Botwe on 19/01/2019.
// Copyright © 2019 Isaac Annan. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class LoginViewController: UIViewController {
@IBOutlet weak var phoneNumField: UITextField!
@IBOutlet weak var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func didPressSignInButton(_ sender: Any) {
let myNumber = phoneNumField.text!
let myPassword = passwordField.text!
Alamofire.request("https://poba.tech/windelivery/public/api/v1/auth/login",
method: .post,
parameters: ["phone": myNumber, "password": myPassword,
"fcm_device_id":"5467285905"])
.responseJSON { response in
// 2
var value = JSON(response.result.value!)
if value["success"].stringValue == "true"{
self.remember()
//
// let alert = UIAlertController(title: "Error", message: "Your Name Is: \(value["data"]["user"]["name"].stringValue)", preferredStyle: .alert)
// alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
//alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
// self.present(alert, animated: true)
// alertMessager(title: "Alert", message: "Your Name Is: \(value["data"]["user"]["name"])")
// alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
// //alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
//
// self.present(alert, animated: true)
print("Your Name Is: \(value["data"]["user"]["name"])")
navigateToPage(from: self, storyboardName: "Main", id: "mainTabBarControllerID")
}
else{
let alert = UIAlertController(title: "Error", message: "\(value["error"]["message"])", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
//alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
self.present(alert, animated: true)
alertMessager(title: "Error", message: "\(value["error"]["message"])")
print("\(value["error"]["message"])")
}
}
}
func remember(){
UserDefaults.standard.set(phoneNumField.text, forKey: "mobileNumber")
UserDefaults.standard.set(passwordField.text, forKey: "password")
}
}
| true
|
b1e763ca7396a465b7e2e8fd271fcb9b2f2a1285
|
Swift
|
Vegas-iOS-Developers/LasVegasArtWorkTour
|
/LasVegasArtWorkTour/LocationService.swift
|
UTF-8
| 3,249
| 3.140625
| 3
|
[] |
no_license
|
//
// LocationService.swift
// LasVegasArtWorkTour
//
// Created by Joel Bell on 11/6/16.
// Copyright © 2016 ROKIBI. All rights reserved.
//
import Foundation
import CoreLocation
extension CLLocation {
static private let MetersPerMile: CLLocationDistance = 1609.344
/**
* miles(from:) -> CLLocationDistance
*
* Easily get the distance in miles between two CLLocation's
*/
func miles(from location: CLLocation) -> CLLocationDistance {
let metersFromHere = self.distance(from: location)
let milesFromHere = metersFromHere / CLLocation.MetersPerMile
return milesFromHere
}
}
enum LocationServiceError: Error {
case notAuthorized
case noResult
}
enum LocationServiceResult {
case success(location: CLLocation)
case failure(error: Error)
}
class LocationService: NSObject, CLLocationManagerDelegate {
fileprivate lazy var _locationManager: CLLocationManager = {
let manager = CLLocationManager()
manager.distanceFilter = kCLDistanceFilterNone
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.delegate = self
return manager
}()
/**
* completion
*
* Closure that is called when location fetching has completed.
*/
internal var completion: ((LocationServiceResult) -> Void)?
/**
* fetchLocation(:completion)
*
* Fetches the current location, sends back result in completion handler.
*/
internal func fetchLocation(completion: @escaping (LocationServiceResult) -> Void) {
self.completion = completion
switch CLLocationManager.authorizationStatus() {
case .denied, .restricted:
let result = LocationServiceResult.failure(error: LocationServiceError.notAuthorized)
completion(result)
case .notDetermined:
_locationManager.requestWhenInUseAuthorization()
fallthrough
case .authorizedAlways, .authorizedWhenInUse:
_locationManager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// If the error passed back is a "denied" error, lets create our own
// notAuthorized error to return so we keep the API consistent.
// Mainly this is encountered if the user is presented with
// the option to allow, but hits deny.
var error = error as Error
if (error as! CLError).code == .denied {
error = LocationServiceError.notAuthorized
}
let result = LocationServiceResult.failure(error: error)
self.completion?(result)
self.completion = nil
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let newLocation = locations.last else {
let result = LocationServiceResult.failure(error: LocationServiceError.noResult)
self.completion?(result)
self.completion = nil
return
}
let result = LocationServiceResult.success(location: newLocation)
self.completion?(result)
self.completion = nil
}
}
| true
|
059ffa9dc5a5543df8ff830fb6599744f8f37263
|
Swift
|
sohaeb/Windsor-Techies
|
/Windsor Techies/Tabs/HomeTab/MainViewController.swift
|
UTF-8
| 3,093
| 2.578125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// UWindsor Msa
//
// Created by may on 2016-09-12.
// Copyright © 2016 sohaeb. All rights reserved.
//
import UIKit
import SwifteriOS
import Firebase
class MainViewController: UIViewController {
// MARK:
// MARK: Variables
var ref: DatabaseReference!
let timesFunc = FetchingTimes()
// MARK:
// MARK: Outlets
@IBOutlet weak var embeddedView: UIView!
@IBOutlet weak var tabBar: UITabBarItem!
@IBOutlet weak var textField: UITextView!
@IBOutlet weak var firstJLabel: UILabel!
@IBOutlet weak var secondJLabel: UILabel!
@IBOutlet weak var firstLocationJumLabel: UILabel!
@IBOutlet weak var secondJumLocationLabel: UILabel!
@IBOutlet weak var firstVal_1: UILabel!
@IBOutlet weak var firstValu_2: UILabel!
@IBOutlet weak var secondValu_1: UILabel!
@IBOutlet weak var secondValu_2: UILabel!
@IBOutlet weak var thirdValu_1: UILabel!
@IBOutlet weak var thirdValu_2: UILabel!
@IBOutlet weak var fourthValu_1: UILabel!
@IBOutlet weak var fourthValu_2: UILabel!
@IBOutlet weak var fifthValu_1: UILabel!
@IBOutlet weak var fifthValu_2: UILabel!
func firebase() {
ref = Database.database().reference(withPath: "server/jumuah")
// To find how many FB pages has event
ref.observe(.value, with: { (snapshot) in
let postDict = snapshot.value as? [String : AnyObject] ?? [:]
print(postDict)
if let jumuLoc1 = postDict["first_jumuah_loction"],
let jumuTime1 = postDict["first_jumuah_time"],
let jumLoc2 = postDict["second_Jumuah_location"],
let jumTime2 = postDict["second_Jumuah_time"] {
self.firstJLabel.text = (jumuTime1 as! String)
self.secondJLabel.text = (jumTime2 as! String)
self.firstLocationJumLabel.text = jumuLoc1 as? String
self.secondJumLocationLabel.text = (jumLoc2 as! String)
} else {
print("error")
}
})
}
// MARK:
// MARK: ViewWillLoad
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let timesArray = timesFunc.findingTheDateInTheArrayAndSIplayingIt()
firstVal_1.text = timesArray[0]
firstValu_2.text = timesArray[1]
secondValu_1.text = timesArray[3]
secondValu_2.text = timesArray[4]
thirdValu_1.text = timesArray[5]
thirdValu_2.text = timesArray[6]
fourthValu_1.text = timesArray[7]
fourthValu_2.text = timesArray[8]
fifthValu_1.text = timesArray[9]
fifthValu_2.text = timesArray[10]
}
// MARK:
// MARK: ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
self.firebase()
tabBar.title = ""
tabBar.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0)
}
}
| true
|
718c6d76671422368bdaea9d4d2c254c4642501f
|
Swift
|
tmozden/lifeLog
|
/LifeLog/Model/DrinkLog.swift
|
UTF-8
| 1,443
| 3.296875
| 3
|
[] |
no_license
|
//
// DrinkLog.swift
// LifeLog
//
// Created by Travis Mozden on 7/7/21.
//
import Foundation
enum DrinkType: String, Codable, CaseIterable, Identifiable, Displayable {
case water
case coffee
case tea
case beer
case wine
case mixDrink
case sportsDrink
case fancyCoffee
case pop
case dietPop
var id: String {
return self.rawValue
}
var displayText: String {
switch self {
case .water: return "Water"
case .coffee: return "Coffee"
case .tea: return "Tea"
case .beer: return "Beer"
case .wine: return "Wine"
case .mixDrink: return "Mix Drink"
case .sportsDrink: return "Sports Drink"
case .fancyCoffee: return "Fancy Coffee"
case .pop: return "Pop"
case .dietPop: return "Diet Pop"
}
}
}
struct DrinkLog: Codable, Identifiable {
let id: String
let type: DrinkType
let timestamp: Date
}
class DrinkLogBuilder: ObservableObject {
@Published var id: String
@Published var type: DrinkType
@Published var timestamp: Date
init(from log: DrinkLog) {
id = log.id
type = log.type
timestamp = log.timestamp
}
init() {
id = UUID().uuidString
type = .water
timestamp = Date()
}
func build() -> DrinkLog {
return DrinkLog(id: id, type: type, timestamp: timestamp)
}
}
| true
|
764aea4a0cba527b9b3754ee0f284e8687956f8a
|
Swift
|
20161104574/a-b
|
/a+b.playground/Contents.swift
|
UTF-8
| 244
| 3.671875
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
let numbers = [12,25,1,35,27]
let numbersSorted = numbers.sort({ n1, n2 in
//进行从小到大的排序
return n2 > n1
})
print(numbersSorted) //[1, 12, 25, 27, 35]
| true
|
7c7362c5e03299a3b03c21c3f51166660a73c2bc
|
Swift
|
ismailbozk/Tremolo
|
/Tremolo/Classes/Networking.swift
|
UTF-8
| 1,324
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
//
// Networking.swift
// Networking
//
// Created by Ismail Bozkurt on 30/12/2019.
// Copyright © 2019 Ismail Bozkurt. All rights reserved.
//
import Foundation
/// Pre Request Task which is meant to be running before the actual network call.
public typealias PreNetworkRequestOperation = QueuedAsyncNetworkOperation<Result<URLRequest, Error>>
/// Network call that will be runnning after _PreNetworkRequestOperation_ and before _PostNetworkRequestOperation_.
public typealias NetworkRequestOperation = QueuedAsyncNetworkOperation<NetworkResponse>
/// Post Request Task which is meant to be used as a post network request response task.
public typealias PostNetworkRequestOperation = NetworkRequestOperation
/// Network request callback for any network call.
public typealias NetworkResult = Result<(urlResponse: URLResponse, data: Data), Error>
/// Network call response wrapper
/// - Parameters:
/// - request: URLRequest to be performed
/// - responseResult: response which came from network call, either an URLError or an Data and URLResponse tuple.
public struct NetworkResponse {
public let request: URLRequest
public let responseResult: NetworkResult
public init(request: URLRequest, responseResult: NetworkResult) {
self.request = request
self.responseResult = responseResult
}
}
| true
|
bd4e90e3e50832d7cbf980af4b8258d16f8cc926
|
Swift
|
TeamChallenge/approul
|
/Roul/Extension+UIColor.swift
|
UTF-8
| 1,600
| 3.046875
| 3
|
[] |
no_license
|
//
// Extension+UIColor.swift
// Catie
//
// Created by Thiago Vinhote on 14/10/16.
// Copyright © 2016 Thiago Vinhote. All rights reserved.
//
import UIKit
extension UIColor {
public static func colorFromHex(_ rgbValue:UInt32, alpha:Double=1.0) -> UIColor {
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}
public static func adjustBrightness(_ color:UIColor, amount:CGFloat) -> UIColor {
var hue:CGFloat = 0
var saturation:CGFloat = 0
var brightness:CGFloat = 0
var alpha:CGFloat = 0
if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
brightness += (amount-1.0)
brightness = max(min(brightness, 1.0), 0.0)
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
return color
}
public func adjustBrightness(_ amount:CGFloat) -> UIColor {
var hue:CGFloat = 0
var saturation:CGFloat = 0
var brightness:CGFloat = 0
var alpha:CGFloat = 0
if self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
brightness += (amount-1.0)
brightness = max(min(brightness, 1.0), 0.0)
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
return self
}
}
| true
|
61264ab8350667f082f4832ae7d99909ff442010
|
Swift
|
marcusrossel/rede
|
/Common/Preview Content/PreviewData.swift
|
UTF-8
| 4,005
| 2.921875
| 3
|
[] |
no_license
|
//
// PreviewData.swift
// Rede / Common
//
// Created by Marcus Rossel on 22.09.20.
//
import SwiftUI
enum PreviewData {
// MARK: URLs
static let urls: [URL] = [
URL(string: "https://swift.org")!,
URL(string: "https://tech.guardsquare.com/posts/swift-native-method-swizzling/")!,
URL(string: "http://literatejava.com/exceptions/")!,
URL(string: "http://bostonreview.net/philosophy-religion/")!,
URL(string: "https://engineering.shopify.com/blogs/engineering/what-is-nix")!,
URL(string: "http://marcusrossel.com/2020-07-13/counting-complexity")!,
URL(string: "https://www.youtube.com/watch?v=7pSqk-XV2QM")!,
URL(string: "https://markmap.js.org")!,
URL(string: "http://marcusrossel.com")!
]
// MARK: Bookmarks
private static let hour: Double = 60 * 60
private static let day: Double = 24 * hour
static let bookmarks: [Bookmark] = [
Bookmark(
title: "Swift.org",
url: urls[0],
folderID: folderIDs[1]
),
Bookmark(
title: "Native Method Swizzling",
url: urls[1],
additionDate: Date().addingTimeInterval(-3 * hour),
readDate: Date(),
folderID: folderIDs[1]
),
Bookmark(
title: "Exceptions",
url: urls[2],
additionDate: Date().addingTimeInterval(-5 * day),
folderID: folderIDs[1]
),
Bookmark(
title: "Philosophy & Religion",
url: urls[3],
readDate: Date(),
folderID: folderIDs[2]
),
Bookmark(
title: "What is Nix?",
url: urls[4],
additionDate: Date().addingTimeInterval(-100 * day),
readDate: Date().addingTimeInterval(-50 * day),
folderID: folderIDs[3]
),
Bookmark(
title: "The Complexity of Counting",
url: urls[5],
additionDate: Date().addingTimeInterval(-1 * hour),
readDate: Date().addingTimeInterval(-1 * hour),
folderID: folderIDs[3]
),
Bookmark(
title: "How Kodak Detected the Atomic Bomb",
url: urls[6],
folderID: folderIDs[4]
),
Bookmark(
title: "markmap-lib",
url: urls[7],
additionDate: Date().addingTimeInterval(-2 * day),
folderID: folderIDs[5]
),
Bookmark(
title: "marcus'",
url: urls[8],
additionDate: Date().addingTimeInterval(-1 * day),
folderID: folderIDs[5]
)
]
// MARK: Folder IDs
static let folderIDs: [Folder.ID] = (1...6).map { _ in Folder.ID() }
// MARK: Folders
static let folders: [Folder] = [
Folder(
id: folderIDs[0],
name: "Empty"
),
/*Folder(
id: folderIDs[1],
name: "Programming",
bookmarks: Array(bookmarks[0...2]),
icon: Icon(name: "command", color: .green)
),
Folder(
id: folderIDs[2],
name: "Social",
bookmarks: Array(bookmarks[3...3]),
icon: Icon(name: "person.fill", color: .yellow)
),
Folder(
id: folderIDs[3],
name: "Math",
bookmarks: Array(bookmarks[4...5]),
sorting: .byTitle,
icon: Icon(name: "number", color: .red)
),
Folder(
id: folderIDs[4],
name: "Videos",
bookmarks: Array(bookmarks[6...6]),
sorting: .byDate,
icon: Icon(name: "tropicalstorm", color: .blue)
),
Folder(
id: folderIDs[5],
name: "Tools",
bookmarks: Array(bookmarks[7...8]),
sorting: .byDate,
icon: Icon(name: "hammer.fill", color: .white)
)*/
]
}
| true
|
defbb98bfb8e20f5f2349453980df6b0e9ac5bcd
|
Swift
|
nelt23/Shortcuts-Collection-View
|
/CollectionViewShortcut/CollectionViewShortcut/CVC/CVCExtension/CVCGestureExtension.swift
|
UTF-8
| 3,972
| 2.65625
| 3
|
[] |
no_license
|
//
// CVCGestureExtension.swift
// CollectionViewShortcut
//
// Created by Nuno Martins on 14/02/2019.
// Copyright © 2019 Nuno Martins. All rights reserved.
//
import UIKit
extension CollectionViewController: UIGestureRecognizerDelegate {
func gestureRecognizer (_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
// quando queremos selecionar o CheckMark
@objc func TapGesture (_ gesture: UITapGestureRecognizer) {
let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView))
if let selectedIndexPath = selectedIndexPath {
let cell = collectionView.cellForItem(at: selectedIndexPath) as! CollectionViewCell
if cell.checkmarkView.checked == false {
cell.checkmarkView.checked = true
countNumberOfCellsSelected += 1
ListElementsTrash[selectedIndexPath.row] = 1
} else {
cell.checkmarkView.checked = false
countNumberOfCellsSelected -= 1
ListElementsTrash[selectedIndexPath.row] = 0
}
if countNumberOfCellsSelected == 0 {
self.navigationItem.title = "Lists"
item.isEnabled = false
} else {
self.navigationItem.title = "\(countNumberOfCellsSelected) selected"
item.isEnabled = true
}
}
}
@objc func PressGesture (_ gesture: UILongPressGestureRecognizer) {
// quando nao se move a celula de sitio queremos que a animação diminua para a escala correta
switch gesture.state {
case .began:
selectedIndexPath = self.collectionView.indexPathForItem(at: gesture.location(in: self.collectionView))
if let selectedIndexPath = self.selectedIndexPath {
let cellSource = self.collectionView.cellForItem(at: selectedIndexPath) as! CollectionViewCell
centerX = self.collectionView.convert(cellSource.center, to: nil).x
centerY = self.collectionView.convert(cellSource.center, to: nil).y
}
case .ended:
if cellMoved == false {
UIView.animate(withDuration: 0.35, animations: {
self.imageView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.imageView.alpha = 1.0
self.imageView.center.x = self.centerX
self.imageView.center.y = self.centerY
}) { (_ Finish: Bool) in
self.imageView.removeFromSuperview()
self.collectionView.isScrollEnabled = true
self.collectionView.addGestureRecognizer(self.tapGesture)
self.animateCell = true
self.collectionView.reloadData()
}
} else {
cellMoved = false
}
default:
break
}
}
// O PanGesture é que tem o translation (UILongPressGestureRecognizer nao tem)
@objc func PanGesture (_ gesture: UIPanGestureRecognizer) {
let translation = gesture.translation(in: nil)
switch (gesture.state) {
case .began:
self.collectionView.isScrollEnabled = false
case .changed:
imageView.center = CGPoint(x: centerX + translation.x, y: centerY + translation.y)
default:
break
}
}
}
| true
|
3276b0ace5fcdb1b554bf94767c3d0169201ca4d
|
Swift
|
dfortuna/Craic
|
/Craic/Extensions/UITextView+Extensions.swift
|
UTF-8
| 670
| 2.671875
| 3
|
[] |
no_license
|
//
// UITextView+Extensions.swift
// Craic
//
// Created by Denis Fortuna on 30/6/20.
// Copyright © 2020 Denis Fortuna. All rights reserved.
//
import Foundation
import UIKit
extension UITextView {
func dynamicHeight() {
//TextView text and height constraint need to be set before using this method.
self.isScrollEnabled = false
let size = CGSize(width: self.frame.width, height: .infinity)
let estimatedSize = self.sizeThatFits(size)
self.constraints.forEach{ (constraint) in
if constraint.firstAttribute == .height {
constraint.constant = estimatedSize.height
}
}
}
}
| true
|
b4374f296cd91d95d2a78621ae70096c2ad0638d
|
Swift
|
differenz-system/Differenz_Chat
|
/SwiftUIChatApp/View/CustomView/gridViewItem.swift
|
UTF-8
| 2,526
| 2.984375
| 3
|
[] |
no_license
|
//
// gridViewItem.swift
// SwiftUIChatApp
//
// Created by differenz147 on 30/07/21.
//
import SwiftUI
struct gridViewItem: View {
//MARK: - Properties
var useName:String
var initalizeName:String
var activeStatusValue: activeStatus
//MARK: - Body
var body: some View {
ZStack {
GeometryReader(content: { geometry in
VStack {
Text(initalizeName)
.font(.system(size: 30))
.fontWeight(.semibold)
.foregroundColor(.white)
.frame(width: geometry.size.width, height: geometry.size.height, alignment: .center)
.background(
RoundedRectangle(cornerRadius: 20)
.stroke(self.activeStatusValue == activeStatus.hide ? Color("menu") : self.activeStatusValue == activeStatus.active ? .green : .red, lineWidth: 10)
)
}
.background(Color.randomDark)
.cornerRadius(20)
.overlay(
VStack {
Text(useName)
.foregroundColor(.white)
.font(.system(size: 18))
.lineLimit(1)
.frame(width: geometry.size.width, height: geometry.size.height/2, alignment: .center)
.background(Color.white.opacity(0.3))
.clipShape(CustomShape())
}
,alignment: .bottom
)
.frame(width: geometry.size.width, height: geometry.size.height, alignment: .center)
})
}
.frame(minWidth: 40, idealWidth: UIScreen.main.bounds.width*0.43 - 30, maxWidth: UIScreen.main.bounds.width*0.9, minHeight: 40, idealHeight: UIScreen.main.bounds.height*0.18, maxHeight: UIScreen.main.bounds.height*0.23, alignment: .center)
}
}
//MARK: - Preview
struct gridViewItem_Previews: PreviewProvider {
static var previews: some View {
gridViewItem(useName: "Harris Roess", initalizeName: "HR", activeStatusValue: .hide)
.preferredColorScheme(.light)
.previewLayout(.sizeThatFits)
.padding()
}
}
| true
|
1e74aebbfb9e74cf685033720278a33c52fcd8ec
|
Swift
|
hidesec/Restaurant-App
|
/Restaurant App/LoginController.swift
|
UTF-8
| 3,111
| 2.609375
| 3
|
[] |
no_license
|
//
// LoginController.swift
// Restaurant App
//
// Created by sarkom3 on 22/04/19.
// Copyright © 2019 sarkom3. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class LoginController: UIViewController {
@IBOutlet weak var emailLogin: UITextField!
@IBOutlet weak var passwordLogin: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func Login(_ sender: Any) {
goToLogin()
}
@IBAction func goToRegister(_ sender: Any) {
let controller = self.storyboard?.instantiateViewController(withIdentifier: "registerController") as! RegisterController
self.present(controller, animated: true, completion: nil)
}
func goToLogin(){
if emailLogin.text?.count != 0 {
if passwordLogin.text?.count != 0 {
let parameters:Parameters = ["email": emailLogin.text!,
"password": passwordLogin.text!]
let url = URL(string: "http://10.10.20.29/LoginRegister/login.php")
//sukses
AF.request(url!, method: .post, parameters: parameters).responseJSON { (response) in
let json = JSON(response.value!)
if json["error"] == false {
let controller = self.storyboard?.instantiateViewController(withIdentifier: "tabBarController") as! UITabBarController
self.present(controller, animated: true, completion: nil)
//session
let defaults = UserDefaults.standard
defaults.set(true, forKey: "ISUSERLOGGEDIN")
defaults.synchronize()
defaults.set(json["user"]["name"].stringValue, forKey: "name")
} else{
let alert = UIAlertController(title: "WARNING!", message: "Email atau password yang Anda masukkan salah!", preferredStyle: .alert)
let alertButton = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(alertButton)
self.present(alert, animated: true, completion: nil)
}
}
}else{
let alert = UIAlertController(title: "WARNING!", message: "Password Anda kosong!", preferredStyle: .alert)
let alertButton = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(alertButton)
self.present(alert, animated: true, completion: nil)
}
}else{
let alert = UIAlertController(title: "WARNING!", message: "Email Anda kosong!", preferredStyle: .alert)
let buttonAlert = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(buttonAlert)
self.present(alert, animated: true, completion: nil)
}
}
}
| true
|
09f797bccc3914a53ac121c5a96855706cbb0517
|
Swift
|
PikPak-App/iOS
|
/Pik Pak/Pictures.swift
|
UTF-8
| 2,231
| 2.796875
| 3
|
[] |
no_license
|
//
// Pictures.swift
// Pik Pak
//
// Created by Andrew on 9/12/15.
// Copyright (c) 2015 Pik Pak. All rights reserved.
//
import UIKit
import Firebase
class Pictures: NSObject {
class func sendPictureToEvent(picture: UIImage,eventID: String) {
//var scaledImage: UIImage = scaleUIImageToSize(picture, size: CGSizeMake(0.5*picture.size.width, 0.5*picture.size.height))
var imageData: NSData = UIImageJPEGRepresentation(picture, 0.25)
var imageString: NSString = imageData.base64EncodedStringWithOptions(.allZeros)
//send to pictures list that contains data
var rootRef = Firebase(url: "https://pikapic.firebaseio.com/")
var photosRef = rootRef.childByAppendingPath("pictures/")
let uuid = UIDevice.currentDevice().identifierForVendor.UUIDString
var picDic = ["base64":imageString,"owner":uuid,"event":eventID]
photosRef.childByAutoId().setValue(picDic)
}
class func scaleUIImageToSize(let image: UIImage, let size: CGSize) -> UIImage {
let hasAlpha = false
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
image.drawInRect(CGRect(origin: CGPointZero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return scaledImage
}
class func upvote(pic:Picture)
{
var rootRef = Firebase(url: "https://pikapic.firebaseio.com/")
var photosRef = rootRef.childByAppendingPath("pictures/")
var picRef = photosRef.childByAppendingPath(pic.id)
var updatedScore = pic.score + 1
var scoreDict = ["Score":updatedScore]
picRef.updateChildValues(scoreDict)
}
class func downvote(pic:Picture)
{
var rootRef = Firebase(url: "https://pikapic.firebaseio.com/")
var photosRef = rootRef.childByAppendingPath("pictures/")
var picRef = photosRef.childByAppendingPath(pic.id)
var updatedScore = pic.score - 1
var scoreDict = ["Score":updatedScore]
picRef.updateChildValues(scoreDict)
}
}
| true
|
6b5170d458e98ccf398f248c5b2c91741ed5a722
|
Swift
|
thachgiasoft/SwiftUI-Course
|
/SwiftUI-Course/ViewModels/QuestionListViewModel.swift
|
UTF-8
| 2,559
| 2.90625
| 3
|
[] |
no_license
|
//
// QuestionsViewModel.swift
// SwiftUI-Course
//
// Created by Ravi Bastola on 2/7/21.
//
import SwiftUI
class QuestionListViewModel: Identifiable, Hashable {
// MARK:- Conformance to identifiable.
let id: UUID = UUID()
// MARK:- Property of Model
let item: Items
// MARK:- Init
init(item: Items) {
self.item = item
}
// MARK:- Stored Properties
var title: String {
if let title = item.title {
return title
}
return ""
}
var views: String {
if let views = item.viewCount {
return views.description
}
return ""
}
var answerCount: String {
if let answer = item.answerCount {
return answer.description
}
return ""
}
var scoreCount: String {
if let score = item.score {
return score.description
}
return ""
}
var questionId: Int {
item.questionID
}
var formattedDate: String {
let date = Date(timeIntervalSince1970: TimeInterval(item.creationDate))
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM d, yyyy"
return dateFormatter.string(from: date)
}
var textForegroundColor: Color {
return .white
}
// MARK:- Settings View Model to compute view color according to the selected theme.
let settingsViewModel = SettingsViewModel()
var answerBlockBackgroundColor: Color {
return settingsViewModel.setting == 1 ? Color(#colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1)) : .orange
}
var votesBlockBackgroundColor: Color {
return settingsViewModel.setting == 1 ? Color(#colorLiteral(red: 0.1098039216, green: 0.7921568627, blue: 1, alpha: 1)) : .blue
}
var tags: String {
if let tags = item.tags {
return tags.joined(separator: ",")
}
return ""
}
var ownerName: String {
item.owner.displayName
}
var body: String {
item.body ?? "Unavailable"
}
static func == (lhs: QuestionListViewModel, rhs: QuestionListViewModel) -> Bool {
return lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static var placeholder: QuestionListViewModel {
return .init(item: Items.placeholder)
}
}
| true
|
b6927e356ab71e9c9269bdb670ae6d282c8112ec
|
Swift
|
wyland/SQL
|
/Sources/SQL/Query/Operator.swift
|
UTF-8
| 787
| 3.46875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
public enum Operator {
case equal
case greaterThan
case greaterThanOrEqual
case lessThan
case lessThanOrEqual
case contains
case containedIn
case like
case ilike
}
extension Operator: StatementStringRepresentable {
public var sqlString: String {
switch self {
case .equal:
return "="
case .greaterThan:
return ">"
case .greaterThanOrEqual:
return ">="
case .lessThan:
return "<"
case .lessThanOrEqual:
return "<="
case .contains:
return "CONTAINS"
case .containedIn:
return "IN"
case .like:
return "LIKE"
case .ilike:
return "ILIKE"
}
}
}
| true
|
0d994d4ca1cd4d920a56cea689cb9da8991ec7eb
|
Swift
|
ramirezi29/preCourseWork.BNR
|
/Pages/Array.xcplaygroundpage/Contents.swift
|
UTF-8
| 3,011
| 3.875
| 4
|
[] |
no_license
|
//var bucketList: Array<String>
//var bucketList: [String] = ["Get iOS dev job"] // <- infrence feature
var bucketList = ["Get iOS dev job"]
bucketList.append("Own a 4 rental properites")
bucketList.append("Do a 360 ollie")
bucketList.append("Have kids")
bucketList.append("Own my own buisness")
bucketList.append("Own a boat with jet skies")
bucketList.remove(at: 2)
bucketList
print(bucketList.count)
print(bucketList[0...3]) // Subscripting
print(bucketList[2])
bucketList[2] += ", Pos 3 or 5" // add info to an existing string
bucketList
bucketList[0] = "Get a 300k a year, personal iOS buisness"
bucketList
print("---------NeXT EXAMPLE 2----------")
/*
------------------------------------
Uisng a Loop to apppend items from one array to another
----------------------------------
*/
var bucketList2 = ["Climb Mt. Everest"]
var newItems = ["Fly hot air ballon to Fiji", "Watch the Lord of the Rings triliogy in one day", "Go on a walkabout", "Scuba dive in the Great Blue Hole", "Find a triple rainbow"]
for items in newItems {
bucketList2.append(items)
}
bucketList2.remove(at:2)
print(bucketList2.count)
print(bucketList2[0...2])
bucketList2[2] += " in Australia"
bucketList2[0] = "Climb Mt Timpanogas"
bucketList2
print("---------NeXT EXAMPLE 3----------")
/*
------------------------------------
Refactoring with the addition and assignment operator
----------------------------------
*/
var bucketList3 = ["Climb Mt. Everest"]
var newItems3 = ["Fly hot air balloon to Fiji", "Watch the Lord of the Rings triliogy in one day", "Go on a walkabout", "Scuba dive in the Great Blue Hole", "Find a triple rainbow"]
bucketList3 += newItems3
bucketList3
bucketList3.remove(at:2)
print(bucketList3.count)
print(bucketList3[0...2])
bucketList3[2] += " in Australia"
bucketList3[0] = "Climb Mt Timpanogas"
bucketList3.insert("Toboggan across Alaska", at: 2)
bucketList3
print(bucketList3.count)// 6 Items now
// Comparing if things are the same in the list
var myronsList = ["Climb Mt Timpanogas", "Fly hot air balloon to Fiji", "Toboggan across Alaska", "Go on a walkabout in Australia", "Scuba dive in the Great Blue Hole", "Find a triple rainbow"]
let equal = (bucketList3 == myronsList)
print(equal)
/*
------------------------------------
Immutable Array
----------------------------------
*/
print("---------NeXT EXAMPLE 4--------------")
let lunches = [
"Cheeseburger",
"Veggie Pizza",
"Chicken Bean Burrito",
"Falafel Wrap"
]
print(lunches)
//
print("_______Bronze Challenge____________-")
var toDoList = ["Take out garbage", "Pay bills", "Cross off finished items"]
print(toDoList.count)
print(toDoList.contains("Take out garbage"))
//
if toDoList.isEmpty {
print("This Array has no elements.")
} else {
print("This array contains \(toDoList.count) elements.")
}
toDoList.reverse()
print(toDoList)
print("------")
toDoList.reversed().forEach {print($0)}
print("------------Gold Challange----------")
var i = bucketList3.index(of: "Fly hot air balloon to Fiji")
print(i)
| true
|
f7d91d4b85e31ab2b4a73bbd1daa8e1ab826bfe5
|
Swift
|
nsmachine/Forecaster
|
/ForecasterSDKTests/DarkSkyModelTest.swift
|
UTF-8
| 1,820
| 2.625
| 3
|
[] |
no_license
|
//
// DarkSkyModelTest.swift
// ForecasterSDK
//
// Created by nsmachine on 5/18/17.
// Copyright © 2017 nsmachine. All rights reserved.
//
import Foundation
import XCTest
@testable import ForecasterSDK
class DarkSkyModelTest: XCTestCase {
func testForecastModelObject() {
guard let json = jsonFromFile("darksky", ofType: "json") else { XCTFail(); return }
let currentlyJSON = json["currently"]
let hourlyJSON = json["hourly"]["data"][0]
let dailyJSON = json["daily"]["data"][0]
let objectType: DarkSkyModel.Type = Forecast.self
guard let currentForecast = objectType.init(json: currentlyJSON) as? Forecast else { XCTFail(); return }
XCTAssertTrue(currentForecast.condition == .clear)
XCTAssertTrue(currentForecast.temperature == 79.86)
XCTAssertTrue(currentForecast.feelsLike == 79.86)
XCTAssertTrue(currentForecast.windDirection == .SW)
guard let hourlyForecast = objectType.init(json: hourlyJSON) as? Forecast else { XCTFail(); return }
XCTAssertTrue(hourlyForecast.condition == .clear)
XCTAssertTrue(hourlyForecast.temperature == 79.86)
XCTAssertTrue(hourlyForecast.feelsLike == 79.86)
XCTAssertTrue(hourlyForecast.windDirection == .SW)
guard let dailyForecast = objectType.init(json: dailyJSON) as? Forecast else { XCTFail(); return }
XCTAssertTrue(dailyForecast.condition == .partlyCloudy )
XCTAssertTrue(dailyForecast.maxTemperature == 90.94)
XCTAssertTrue(dailyForecast.minTemperature == 62.24)
XCTAssertTrue(dailyForecast.windDirection == .SW)
XCTAssertTrue(dailyForecast.sunriseTime > 0.0)
XCTAssertTrue(dailyForecast.sunsetTime > 0.0)
}
}
| true
|
2a97f4a8d1589d30b5356f376fecdd43c3795849
|
Swift
|
KeenanHauber/Trips-Example-Project
|
/Trips (Example Project)/Interface/ScheduledAirportView.swift
|
UTF-8
| 767
| 2.609375
| 3
|
[] |
no_license
|
//
// ScheduledAirportView.swift
// Trips (Example Project)
//
// Created by Keenan Hauber on 1/5/21.
//
import UIKit
class ScheduledAirportView: UIView, NibLoadable {
@IBOutlet weak var contentStackView: UIStackView!
@IBOutlet weak var airportCodeLabel: UILabel!
@IBOutlet weak var cityNameLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
var leftAligned = false {
didSet {
contentStackView.alignment = leftAligned ? .leading : .trailing
}
}
func setTextColor(to newColor: UIColor?) {
dateLabel.textColor = newColor
timeLabel.textColor = newColor
cityNameLabel.textColor = newColor
airportCodeLabel.textColor = newColor
}
}
| true
|
d64f32a859df885a3b689de2c99aad2c84fb2268
|
Swift
|
Fanovic/WeatherApp
|
/WeatherApp/CitiesModule/Interactor/CitiesInteractor.swift
|
UTF-8
| 612
| 2.71875
| 3
|
[] |
no_license
|
//
// CitiesInteractor.swift
// WeatherApp
//
// Created by Lucas Fanovich on 14/12/2020.
//
import Foundation
class CitiesInteractor: CitiesInteractorProtocol {
var presenter: CitiesPresenterProtocol?
func fetch() {
var list: [City] = []
list.append(City(id: 3433955, name: "Buenos Aires"))
list.append(City(id: 3833367, name: "Ushuaia"))
list.append(City(id: 3849140, name: "La Quiaca"))
list.append(City(id: 7116866, name: "Villa Mercedes"))
list.append(City(id: 3430863, name: "Mar del Plata"))
presenter?.onRequestSuccess(list)
}
}
| true
|
4c5c4895be232635bda39f30b85a9a776651decf
|
Swift
|
cheeseonhead/episode-code-samples
|
/0024-zip-pt2/Zip.playground/Pages/01-episode.xcplaygroundpage/Contents.swift
|
UTF-8
| 9,960
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
func zip2<A, B>(_ xs: [A], _ ys: [B]) -> [(A, B)] {
var result: [(A, B)] = []
(0..<min(xs.count, ys.count)).forEach { idx in
result.append((xs[idx], ys[idx]))
}
return result
}
func zip3<A, B, C>(_ xs: [A], _ ys: [B], _ zs: [C]) -> [(A, B, C)] {
return zip2(xs, zip2(ys, zs)) // [(A, (B, C))]
.map { a, bc in (a, bc.0, bc.1) }
}
func zip2<A, B, C>(
with f: @escaping (A, B) -> C
) -> ([A], [B]) -> [C] {
return { zip2($0, $1).map(f) }
}
func zip3<A, B, C, D>(
with f: @escaping (A, B, C) -> D
) -> ([A], [B], [C]) -> [D] {
return { zip3($0, $1, $2).map(f) }
}
func zip2<A, B>(_ a: A?, _ b: B?) -> (A, B)? {
guard let a = a, let b = b else { return nil }
return (a, b)
}
func zip3<A, B, C>(_ a: A?, _ b: B?, _ c: C?) -> (A, B, C)? {
return zip2(a, zip2(b, c))
.map { a, bc in (a, bc.0, bc.1) }
}
func zip2<A, B, C>(
with f: @escaping (A, B) -> C
) -> (A?, B?) -> C? {
return { zip2($0, $1).map(f) }
}
func zip3<A, B, C, D>(
with f: @escaping (A, B, C) -> D
) -> (A?, B?, C?) -> D? {
return { zip3($0, $1, $2).map(f) }
}
enum Result<A, E> {
case success(A)
case failure(E)
}
func map<A, B, E>(_ f: @escaping (A) -> B) -> (Result<A, E>) -> Result<B, E> {
return { result in
switch result {
case let .success(a):
return .success(f(a))
case let .failure(e):
return .failure(e)
}
}
}
func zip2<A, B, E>(_ a: Result<A, E>, _ b: Result<B, E>) -> Result<(A, B), E> {
switch (a, b) {
case let (.success(a), .success(b)):
return .success((a, b))
case let (.success, .failure(e)):
return .failure(e)
case let (.failure(e), .success):
return .failure(e)
case let (.failure(e1), .failure(e2)):
// return .failure(e1)
return .failure(e2)
}
}
import NonEmpty
enum Validated<A, E> {
case valid(A)
case invalid(NonEmptyArray<E>)
}
func map<A, B, E>(_ f: @escaping (A) -> B) -> (Validated<A, E>) -> Validated<B, E> {
return { result in
switch result {
case let .valid(a):
return .valid(f(a))
case let .invalid(e):
return .invalid(e)
}
}
}
func zip2<A, B, E>(_ a: Validated<A, E>, _ b: Validated<B, E>) -> Validated<(A, B), E> {
switch (a, b) {
case let (.valid(a), .valid(b)):
return .valid((a, b))
case let (.valid, .invalid(e)):
return .invalid(e)
case let (.invalid(e), .valid):
return .invalid(e)
case let (.invalid(e1), .invalid(e2)):
return .invalid(e1 + e2)
}
}
func zip2<A, B, C, E>(
with f: @escaping (A, B) -> C
) -> (Validated<A, E>, Validated<B, E>) -> Validated<C, E> {
return { zip2($0, $1) |> map(f) }
}
func zip3<A, B, C, E>(_ a: Validated<A, E>, _ b: Validated<B, E>, _ c: Validated<C, E>) -> Validated<(A, B, C), E> {
return zip2(a, zip2(b, c))
|> map { a, bc in (a, bc.0, bc.1) }
}
func zip3<A, B, C, D, E>(
with f: @escaping (A, B, C) -> D
) -> (Validated<A, E>, Validated<B, E>, Validated<C, E>) -> Validated<D, E> {
return { zip3($0, $1, $2) |> map(f) }
}
import Foundation
func compute(_ a: Double, _ b: Double) -> Double {
return sqrt(a) + sqrt(b)
}
func validate(_ a: Double, label: String) -> Validated<Double, String> {
return a < 0
? .invalid(NonEmptyArray("\(label) must be non-negative."))
: .valid(a)
}
zip2(with: compute)(
validate(-1, label: "first"),
validate(-3, label: "second")
)
//compute(validate(2, label: "first"), validate(3, label: "second"))
struct Func<R, A> {
let apply: (R) -> A
}
func map<A, B, R>(_ f: @escaping (A) -> B) -> (Func<R, A>) -> Func<R, B> {
return { r2a in
return Func { r in
f(r2a.apply(r))
}
}
}
func zip2<A, B, R>(_ r2a: Func<R, A>, _ r2b: Func<R, B>) -> Func<R, (A, B)> {
return Func<R, (A, B)> { r in
(r2a.apply(r), r2b.apply(r))
}
}
func zip3<A, B, C, R>(
_ r2a: Func<R, A>,
_ r2b: Func<R, B>,
_ r2c: Func<R, C>
) -> Func<R, (A, B, C)> {
return zip2(r2a, zip2(r2b, r2c)) |> map { ($0, $1.0, $1.1) }
}
func zip2<A, B, C, R>(
with f: @escaping (A, B) -> C
) -> (Func<R, A>, Func<R, B>) -> Func<R, C> {
return { zip2($0, $1) |> map(f) }
}
func zip3<A, B, C, D, R>(
with f: @escaping (A, B, C) -> D
) -> (Func<R, A>, Func<R, B>, Func<R, C>) -> Func<R, D> {
return { zip3($0, $1, $2) |> map(f) }
}
zip2(
with: +)(Func { 2 }, Func { 3 }).apply(())
let randomNumber = Func<Void, Int> {
(try? String(contentsOf: URL(string: "https://www.random.org/integers/?num=1&min=1&max=30&col=1&base=10&format=plain&rnd=new")!))
.map { $0.trimmingCharacters(in: .newlines) }
.flatMap(Int.init)
?? 0
}
randomNumber.apply(())
let aWordFromPointFree = Func<Void, String> {
(try? String(contentsOf: URL(string: "https://www.pointfree.co")!))
.map { $0.split(separator: " ")[1566] }
.map(String.init)
?? "PointFree"
}
aWordFromPointFree.apply(())
zip2(
with: [String].init(repeating:count:))(aWordFromPointFree, randomNumber).apply(())
struct F3<A> {
let run: (@escaping (A) -> Void) -> Void
}
func map<A, B>(_ f: @escaping (A) -> B) -> (F3<A>) -> F3<B> {
return { f3 in
return F3 { callback in
f3.run { callback(f($0)) }
}
}
}
func zip2<A, B>(_ fa: F3<A>, _ fb: F3<B>) -> F3<(A, B)> {
return F3<(A, B)> { callback in
// callback
var a: A?
var b: B?
fa.run {
a = $0
if let b = b { callback(($0, b)) }
}
fb.run {
b = $0
if let a = a { callback((a, $0)) }
}
// fa.run { a in
// fb.run { b in
// callback((a, b))
// }
// }
}
}
func zip2<A, B, C>(
with f: @escaping (A, B) -> C
) -> (F3<A>, F3<B>) -> F3<C> {
return { zip2($0, $1) |> map(f) }
}
func zip3<A, B, C>(_ fa: F3<A>, _ fb: F3<B>, _ fc: F3<C>) -> F3<(A, B, C)> {
return zip2(fa, zip2(fb, fc)) |> map { ($0, $1.0, $1.1) }
}
func zip3<A, B, C, D>(
with f: @escaping (A, B, C) -> D
) -> (F3<A>, F3<B>, F3<C>) -> F3<D> {
return { zip3($0, $1, $2) |> map(f) }
}
func delay(by duration: TimeInterval, line: UInt = #line, execute: @escaping () -> Void) {
print("delaying line \(line) by \(duration)")
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
execute()
print("executed line \(line)")
}
}
let anInt = F3<Int> { callback in
delay(by: 0.5) {
callback(42)
}
}
let aMessage = F3<String> { callback in
delay(by: 1) {
callback("Hello!")
}
}
zip2(aMessage, anInt)
zip2(with: [String].init(repeating:count:))(
aMessage,
anInt
).run { value in
print(value)
}
// ((A, B) -> C) -> ([A], [B]) -> [C]
// ((A, B) -> C) -> ( A?, B?) -> C?
// ((A, B) -> C) -> (Validated<E, A>, Validated<E, B>) -> Validated<E, C>
// ((A, B) -> C) -> (Func<R, A>, Func<R, B>) -> Func<R, C>
// ((A, B) -> C) -> (F3<A>, F4<B>) -> F3<C>
/*:
# The Many Faces of Zip: Part 2
## Exercises
1.) Can you make the `zip2` function on our `F3` type thread safe?
*/
// TODO
/*:
2.) Generalize the `F3` type to a type that allows returning values other than `Void`: `struct F4<A, R> { let run: (@escaping (A) -> R) -> R }`. Define `zip2` and `zip2(with:)` on the `A` type parameter.
*/
// TODO
/*:
3.) Find a function in the Swift standard library that resembles the function above. How could you use `zip2` on it?
*/
// TODO
/*:
4.) This exercise explore what happens when you nest two types that each support a `zip` operation.
- Consider the type `[A]? = Optional<Array<A>>`. The outer layer `Optional` has `zip2` defined, but also the inner layer `Array` has a `zip2`. Can we define a `zip2` on `[A]?` that makes use of both of these zip structures? Write the signature of such a function and implement it.
*/
// TODO
/*:
- Using the `zip2` defined above write an example usage of it involving two `[A]?` values.
*/
// TODO
/*:
- Consider the type `[Validated<A, E>]`. We again have have a nesting of types, each of which have their own `zip2` operation. Can you define a `zip2` on this type that makes use of both `zip` structures? Write the signature of such a function and implement it.
*/
// TODO
/*:
- Using the `zip2` defined above write an example usage of it involving two `[Validated<A, E>]` values.
*/
// TODO
/*:
- Consider the type `Func<R, A?>`. Again we have a nesting of types, each of which have their own `zip2` operation. Can you define a `zip2` on this type that makes use of both structures? Write the signature of such a function and implement it.
*/
// TODO
/*:
- Consider the type `Func<R, [A]>`. Again we have a nesting of types, each of which have their own `zip2` operation. Can you define a `zip2` on this type that makes use of both structures? Write the signature of such a function and implement it.
*/
// TODO
/*:
- Do you see anything common in the implementation of all of your functions?
*/
// TODO
/*:
5.) In this series of episodes on `zip` we have described zipping types as a kind of way to swap the order of containers, e.g. we can transform a tuple of arrays to an array of tuples `([A], [B]) -> [(A, B)]`. There’s a more general concept that aims to flip contains of any type. Implement the following to the best of your ability, and describe in words what they represent:
- `sequence: ([A?]) -> [A]?`
- `sequence: ([Result<A, E>]) -> Result<[A], E>`
- `sequence: ([Validated<A, E>]) -> Validated<[A], E>`
- `sequence: ([F3<A>]) -> F3<[A]`
- `sequence: (Result<A?, E>) -> Result<A, E>?`
- `sequence: (Validated<A?, E>) -> Validated<A, E>?`
- `sequence: ([[A]]) -> [[A]]`.
Note that you can still flip the order of these containers even though they are both the same container type. What does this represent? Evaluate the function on a few sample nested arrays.
Note that all of these functions also represent the flipping of containers, e.g. an array of optionals transforms into an optional array, an array of results transforms into a result of an array, or a validated optional transforms into an optional validation, etc.
*/
// TODO
| true
|
0fd5fe6be76ee86b2feadf90a170f7dc29f13071
|
Swift
|
nad27298/football-apple-tv
|
/FootballTV/Controller/Pick/PickViewController.swift
|
UTF-8
| 2,631
| 2.5625
| 3
|
[] |
no_license
|
//
// PickViewController.swift
// FootballTV
//
// Created by nguyenhuyson2 on 11/6/20.
// Copyright © 2020 Nguyen Anh Dao. All rights reserved.
//
import UIKit
import Alamofire
import Kingfisher
class PickViewController: UIViewController, ClassPickDelegate {
@IBOutlet weak var tableView: UITableView!
var nameTour:Array<String> = ["National", "Premier League", "La Liga", "Bundesliga", "Seri A", "Ligue 1"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: "PickTableViewCell", bundle: nil), forCellReuseIdentifier: "PickTableViewCell")
let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
backgroundImage.image = UIImage(named: "Frame 22")
backgroundImage.contentMode = UIView.ContentMode.scaleAspectFill
self.view.insertSubview(backgroundImage, at: 0)
}
}
extension PickViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return nameTour[section]
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let headerView = view as? UITableViewHeaderFooterView {
headerView.textLabel?.textColor = .white
headerView.textLabel?.font = UIFont(name: "Futura Medium", size: 35)
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return nameTour.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:PickTableViewCell = tableView.dequeueReusableCell(withIdentifier: "PickTableViewCell") as! PickTableViewCell
cell.getDataAllPickFromSever(index: indexPath.section)
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 240
}
func tableView(_ tableView: UITableView, canFocusRowAt indexPath: IndexPath) -> Bool {
return false
}
func backtoPickViewController() {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let new:NewsViewController = storyboard.instantiateViewController(withIdentifier: "News") as! NewsViewController
self.present(new, animated: true, completion: nil)
}
}
| true
|
b1359e77e807cc4a174a9c097aab8c0ecb7b23dc
|
Swift
|
ftwdjw/Swift-moving-averages
|
/movingAverage.playground/Contents.swift
|
UTF-8
| 2,737
| 3.984375
| 4
|
[] |
no_license
|
//: moving averages
import UIKit
import Accelerate
//extension converts to a string with 2 place accuracy for easier reading
extension Double {
var convertToString: String {return self.asSinglePrecisionString()}
func asSinglePrecisionString() -> String {
let strOfNumber = String(format: "%4.2f", self)
return strOfNumber
}
}
let PI = 3.14159265359.convertToString
PI
func round1( a: [Double]) -> [String] {
//this function used with extension to make double arrays easier to read
var result = [String](repeating:"", count:a.count)
for i in (0..<a.count){
result[i] = a[i].convertToString
}
return result
}
let randomArraySize = 20
let doubleRandoms = (1...randomArraySize).map { _ in Double (arc4random()) }
print("double random numbers= \(doubleRandoms)\n")
func normalize (a: [Double]) -> (out:[Double], mean1:Double, std:Double) {
//Compute mean and standard deviation and then calculate new elements to have a zero mean and a unit standard deviation. Double precision.
var mean = 0.0
var standardDeviation = 0.0
//this is only for initialization. not setting anything
var result = [Double](repeating:0.0, count:a.count)
vDSP_normalizeD(a, 1,&result, 1, &mean, &standardDeviation, UInt(a.count))
return (out:result, mean1:mean, std:standardDeviation)
}
let normRandom = normalize(a: doubleRandoms)
let out1=round1(a: normRandom.out)
print("normalized random numbers= \(out1)\n")
func movingAverage (a:[Double], numberSum: Int) -> [Double]
{
var result = [Double](repeating:0.0, count:a.count)
var sum:Double = 0.0
for index in (0..<a.count){
if index<numberSum{
result[index]=a[index]
}
else{
sum=0.0
for k in (0..<numberSum){
sum=sum+a[index-k]
}
result[index]=sum/Double(numberSum)
}
}
return result
}
func sub (a: [Double], b: [Double]) -> [Double] {
//This function subtracts the first N elements of A - B and leaves the result in C. This function subtracts the first N elements of B from A and leaves the result in C.
assert(a.count == b.count, "Expected arrays of the same length, instead got arrays of two different lengths")
var result = [Double](repeating:0.0, count:a.count)
vDSP_vsubD(a, 1, b, 1, &result, 1, UInt(a.count))
return result
}
let averagedNumbers = movingAverage(a: normRandom.out, numberSum: 5)
let out2=round1(a: averagedNumbers)
print("moving averaged numbers= \(out2)\n")
let difference1 = sub(a: normRandom.out, b: averagedNumbers)
let out3=round1(a: difference1)
print("differences= \(out3)\n")
| true
|
1b49c6fe27d6c657447ebe108dc3accefcd9a3aa
|
Swift
|
AlexDanDobrin/DRX-RO-2021-Project
|
/Draexlmaier/Controllers/ReportViewController.swift
|
UTF-8
| 4,335
| 2.6875
| 3
|
[] |
no_license
|
//
// ReportViewController.swift
// Draexlmaier
//
// Created by Alex Dobrin on 05/05/2021.
//
import UIKit
import CoreData
class ReportViewController: UITableViewController {
var assets: [Asset_employee] = [Asset_employee]()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
// let currentDate = Date()
//
// print(currentDate)
//
// loadAssets(
// with: Asset_employee.fetchRequest(),
// predicate: NSPredicate(format: "end_of_life > %@", currentDate as NSDate),
// by: NSSortDescriptor(key: "end_of_life", ascending: true)
// )
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
let currentDate = Date()
loadAssets(
with: Asset_employee.fetchRequest(),
predicate: NSPredicate(format: "end_of_life > %@", currentDate as NSDate),
by: NSSortDescriptor(key: "end_of_life", ascending: true)
)
}
// MARK: - TableView DataSource Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return assets.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ReportCell", for: indexPath) as! ReportCell
cell.asset = assets[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
func loadAssets(with request: NSFetchRequest<Asset_employee>, predicate: NSPredicate? = nil, by sortDescriptor: NSSortDescriptor? = nil) {
request.predicate = predicate
if let descriptor = sortDescriptor {
request.sortDescriptors = [descriptor]
}
do {
assets = try context.fetch(request)
} catch {
print("Error fetching assets from context, \(error)")
}
tableView.reloadData()
}
}
func dayPrinter(of day: Int) -> String {
switch day {
case 1:
return "1st"
case 2:
return "2nd"
case 3:
return "3rd"
case 4...31:
return "\(day)th"
default:
return "Error"
}
}
func monthPrinter(of month: Int) -> String {
switch month {
case 1:
return("of January")
case 2:
return("of February")
case 3:
return("of March")
case 4:
return("of April")
case 5:
return("of May")
case 6:
return("of June")
case 7:
return("of July")
case 8:
return("of August")
case 9:
return("of September")
case 10:
return("of October")
case 11:
return("of November")
case 12:
return("of December")
default:
return("Error")
}
}
extension Date {
func get(_ components: Calendar.Component..., calendar: Calendar = Calendar.current) -> DateComponents {
return calendar.dateComponents(Set(components), from: self)
}
func get(_ component: Calendar.Component, calendar: Calendar = Calendar.current) -> Int {
return calendar.component(component, from: self)
}
}
class ReportCell: UITableViewCell {
var asset: Asset_employee? {
didSet {
assetImage.image = UIImage(systemName: "\(asset!.asset_id).square")
employeeIdLabel.text = "Employee: \(String(asset!.empl_id))"
costCenterIdLabel.text = "Center: \(String(asset!.cstc_nr))"
if let month = asset!.end_of_life?.get(.month), let day = asset!.end_of_life?.get(.day), let year = asset!.end_of_life?.get(.year) {
dateLabel.text = "Until: \(dayPrinter(of: day)) \(monthPrinter(of: month)), \(year)"
} else {
dateLabel.text = "Until: Error"
}
dateLabel.textAlignment = .center
}
}
@IBOutlet weak var assetImage: UIImageView!
@IBOutlet weak var employeeIdLabel: UILabel!
@IBOutlet weak var costCenterIdLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
}
| true
|
28ce70957974e065555a87a5c958f103e6773da9
|
Swift
|
FrederikBuur/LeagueHelper-iOS
|
/LeagueHelper/models/match/MatchReference.swift
|
UTF-8
| 917
| 2.75
| 3
|
[] |
no_license
|
//
// MatchReference.swift
// LeagueHelper
//
// Created by Frederik Buur on 29/11/2018.
// Copyright © 2018 Frederik Buur. All rights reserved.
//
import Foundation
import SwiftyJSON
struct MatchReference {
var gameId: Int
var champion: Int
var platformId: Int
var queue: Int
static func parseJsonArray(json: JSON) -> [MatchReference] {
var matchReferences: [MatchReference] = []
json.arrayValue.forEach { (matchReference) in
let mr = MatchReference.parseJson(json: matchReference)
matchReferences.append(mr)
}
return matchReferences
}
static func parseJson(json: JSON) -> MatchReference {
return MatchReference(
gameId: json["gameId"].intValue,
champion: json["champion"].intValue,
platformId: json["platformId"].intValue,
queue: json["queue"].intValue)
}
}
| true
|
752c469231f58d28f4df9ab5492528e0764b0b4c
|
Swift
|
asapkent/PickAColor
|
/PickAColor/ColorTableViewController.swift
|
UTF-8
| 1,557
| 3.109375
| 3
|
[] |
no_license
|
//
// ColorTableViewController.swift
// PickAColor
//
// Created by Robert Jeffers on 10/31/20.
//
import UIKit
var colors: [UIColor] = []
class ColorTableViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
pickRandomColors()
}
func pickRandomColors() {
for _ in 0..<100 {
colors.append(createColors())
}
}
func createColors() -> UIColor {
let randomColor = UIColor(red: CGFloat.random(in: 0...1.0), green: CGFloat.random(in: 0...1.0), blue: CGFloat.random(in: 0...1.0), alpha: 1)
return randomColor
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// casting allows access to color prop in other VC
let vc = segue.destination as! SelectedColorViewController
vc.color = sender as? UIColor
}
}
extension ColorTableViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return colors.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.backgroundColor = colors[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let color = colors[indexPath.row]
performSegue(withIdentifier: "colorvc", sender: color)
}
}
| true
|
43cfdaa97c0f950f2600a8c229008cba36124783
|
Swift
|
swapnil-salunke/UITestSample
|
/UITestSample/Strings+Localisable.swift
|
UTF-8
| 1,079
| 2.9375
| 3
|
[] |
no_license
|
//
// Strings+Localisable.swift
// UITestSample
//
// Created by Salunke, Swapnil Uday (US - Mumbai) on 30/03/20.
// Copyright © 2020 Swapnil Salunke. All rights reserved.
//
import UIKit
extension String {
/*
Swift friendly localization syntax, replaces NSLocalizedString
- Returns: The localized string.
*/
func localized() -> String {
return localized(tableName: nil, bundle: Bundle.main)
}
/*
Swift friendly localization syntax, replaces NSLocalizedString.
- parameter tableName: The receiver’s string table to search. If tableName is `nil`
or is an empty string, the method attempts to use `Localizable.strings`.
- parameter bundle: The receiver’s bundle to search. If bundle is `nil`,
the method attempts to use main bundle.
- returns: The localized string.
*/
func localized(tableName: String?, bundle: Bundle?) -> String {
let bundle: Bundle = bundle ?? Bundle.main
return bundle.localizedString(forKey: self, value: nil, table: tableName)
}
}
| true
|
f44c11affa70b42ea247eb5f09caf0ae81c3c356
|
Swift
|
abakhtin/SwiftLocation
|
/Sources/SwiftLocation/Request/Requests/Autocomplete/Services/Autocomplete-Google.swift
|
UTF-8
| 12,952
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// Autocomplete+Google.swift
//
// Copyright (c) 2020 Daniele Margutti (hello@danielemargutti.com).
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CoreLocation
import MapKit
public extension Autocomplete {
class Google: JSONNetworkHelper, AutocompleteProtocol {
// MARK: - Public Properties
/// Type of autocomplete operation
public var operation: AutocompleteOp
/// Timeout interval for request.
public var timeout: TimeInterval? = 5
/// API Key
/// See https://developers.google.com/places/web-service/get-api-key.
public var APIKey: String
/// This will send `X-Ios-Bundle-Identifier` header to the request.
/// You can set it directly from the credentials store as `.googleBundleRestrictionID`.
/// NOTE: If you enable app-restrictions in the api-console, these headers must be sent.
public var bundleRestrictionID: String? = SwiftLocation.credentials[.googleBundleRestrictionID]
/// Restrict results to be of certain type, `nil` to ignore this filter.
public var placeTypes: Set<PlaceTypes>? = nil
/// The distance (in meters) within which to return place results.
/// Note that setting a radius biases results to the indicated area,
/// but may not fully restrict results to the specified area.
/// More info: https://developers.google.com/places/web-service/autocomplete#location_biasing
/// and https://developers.google.com/places/web-service/autocomplete#location_restrict.
public var radius: Float? = nil
/// The point around which you wish to retrieve place information
public var location: CLLocationCoordinate2D?
/// Returns only those places that are strictly within the region defined by location and radius.
/// This is a restriction, rather than a bias, meaning that results outside this region will
/// not be returned even if they match the user input.
public var strictBounds: Bool = false
/// The language code, indicating in which language the results should be returned, if possible.
public var locale: String?
/// A grouping of places to which you would like to restrict your results up to 5 countries.
/// Countries must be added in ISO3166-1_alpha-2 version you can found:
/// https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2.
public var countries: Set<String>?
/// Description
public var description: String {
return JSONStringify([
"apiKey": APIKey.trunc(length: 5),
"timeout": timeout,
"placeTypes": placeTypes,
"radius": radius,
"location": location,
"strictBounds": strictBounds,
"locale": locale,
"countries": countries
])
}
// MARK: - Private Properties
/// Partial searcher.
private var partialQuerySearcher: MKLocalSearchCompleter?
private var fullQuerySearcher: MKLocalSearch?
/// Callback to call at the end of the operation.
private var callback: ((Result<[Autocomplete.Data], LocationError>) -> Void)?
// MARK: - Initialization
/// Search for matches of a partial search address.
/// Returned values is an array of `Autocomplete.AutocompleteResult.partial`.
///
/// - Parameters:
/// - partialMatch: partial match of the address.
/// - region: Use this property to limit search results to the specified geographic area.
public init(partialMatches partialAddress: String, APIKey: String = SharedCredentials[.google]) {
self.operation = .partialMatch(partialAddress)
self.APIKey = APIKey
super.init()
}
/// You can use this method when you have a full address and you want to get the details.
///
/// - Parameter addressDetail: full address
/// If you want to get the details of a partial search result obtained from `init(partialMatches:region)` call, you
/// can use this method passing the full address.
/// You can also pass the `id` of `PartialAddressMatch` to get more info about a partial matched result.
///
/// - Parameters:
/// - fullAddress: full address to search
/// - region: Use this property to limit search results to the specified geographic area.
public init(detailsFor fullAddress: String, APIKey: String = SharedCredentials[.google]) {
self.operation = .addressDetail(fullAddress)
self.APIKey = APIKey
super.init()
}
/// Initialize with request to get details for given result item.
/// - Parameters:
/// - resultItem: result item, PartialAddressMatch.
/// - APIKey: API Key.
public init?(detailsFor resultItem: PartialAddressMatch?, APIKey: String = SharedCredentials[.google]) {
guard let id = resultItem?.id else {
return nil
}
self.operation = .addressDetail(id)
self.APIKey = APIKey
super.init()
}
// MARK: - Public Functions
public func executeAutocompleter(_ completion: @escaping ((Result<[Autocomplete.Data], LocationError>) -> Void)) {
do {
guard !APIKey.isEmpty else {
throw LocationError.invalidAPIKey
}
self.callback = completion
let request = try buildRequest()
switch operation {
case .partialMatch: executePartialAddressSearch(request)
case .addressDetail: executeAddressDetails(request)
}
} catch {
completion(.failure(error as? LocationError ?? LocationError.internalError))
}
}
// MARK: - Private Function
private func executePartialAddressSearch(_ request: URLRequest) {
executeDataRequest(request: request, validateResponse: nil) { [weak self] result in
guard let self = self else { return }
do {
switch result {
case .failure(let error):
self.callback?(.failure(error))
case .success(let data):
guard let jsonData = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
self.callback?(.failure(.parsingError))
return
}
// Custom error message returned from call.
let errorMessage: String? = jsonData.valueForKeyPath(keyPath: "error_message")
if (errorMessage?.isEmpty ?? true) == false {
self.callback?(.failure(.other(errorMessage!)))
}
let places = PartialAddressMatch.fromGoogleList( jsonData.valueForKeyPath(keyPath: "predictions") )
self.callback?(.success(places))
}
} catch {
self.callback?(.failure(.generic(error)))
}
}
}
private func executeAddressDetails(_ request: URLRequest) {
executeDataRequest(request: request, validateResponse: nil) { result in
switch result {
case .failure(let error):
self.callback?(.failure(error))
case .success(let data):
do {
guard let detailPlace = try GeoLocation.fromGoogleSingle(data) else {
self.callback?(.failure(.notFound))
return
}
self.callback?(.success([.place(detailPlace)]))
} catch {
self.callback?(.failure(.other(error.localizedDescription)))
}
}
}
}
private func requestURL() -> URL {
switch operation {
case .partialMatch:
return URL(string: "https://maps.googleapis.com/maps/api/place/autocomplete/json")!
case .addressDetail:
return URL(string: "https://maps.googleapis.com/maps/api/place/details/json")!
}
}
private func buildRequest() throws -> URLRequest {
// Options
var queryItems = [URLQueryItem]()
queryItems.append(URLQueryItem(name: "key", value: APIKey))
queryItems.appendIfNotNil(URLQueryItem(name: "types", optional: placeTypes?.map { $0.rawValue }.joined(separator: ",")))
queryItems.appendIfNotNil(URLQueryItem(name: "location", optional: location?.commaLatLng))
queryItems.appendIfNotNil(URLQueryItem(name: "radius", optional: (radius != nil ? String(radius!) : nil)))
if strictBounds {
queryItems.append(URLQueryItem(name: "strictbounds", value: nil))
}
queryItems.appendIfNotNil(URLQueryItem(name: "language", optional: locale?.lowercased()))
queryItems.appendIfNotNil(URLQueryItem(name: "components", optional: countries?.map {
return "country:\($0)"
}.joined(separator: "|")))
switch operation {
case .partialMatch(let partialAddress):
queryItems.append(URLQueryItem(name: "input", value: partialAddress))
case .addressDetail(let address):
queryItems.append(URLQueryItem(name: "placeid", value: address))
}
// Generate url
var urlComponents = URLComponents(url: requestURL(), resolvingAgainstBaseURL: false)
urlComponents?.queryItems = queryItems
guard let fullURL = urlComponents?.url else {
throw LocationError.internalError
}
var request = URLRequest(url: fullURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: timeout ?? TimeInterval.highInterval)
request.addValue(bundleRestrictionID ?? "", forHTTPHeaderField: HTTPHeaders.googleBundleRestriction)
return request
}
}
}
// MARK: - Autocomplete.Google Extensions
public extension Autocomplete.Google {
/// Restrict results from a Place Autocomplete request to be of a certain type.
/// See: https://developers.google.com/places/web-service/autocomplete#place_types
///
/// - geocode: return only geocoding results, rather than business results.
/// - address: return only geocoding results with a precise address.
/// - establishment: return only business results.
/// - regions: return any result matching the following types: `locality, sublocality, postal_code, country, administrative_area_level_1, administrative_area_level_2`
/// - cities: return results that match `locality` or `administrative_area_level_3`.
enum PlaceTypes: String, CustomStringConvertible {
case geocode
case address
case establishment
case regions
case cities
public var description: String {
rawValue
}
}
}
| true
|
9509a69f20804e72a4001a68f943538d03cb904a
|
Swift
|
BabyShung/LongPressButton
|
/LongPressButton/UIView+Shadow.swift
|
UTF-8
| 877
| 2.703125
| 3
|
[] |
no_license
|
//
// UIView+Shadow.swift
// LongPressButton
//
// Created by Hao Zheng on 9/25/16.
// Copyright © 2016 Hao Zheng. All rights reserved.
//
import UIKit
extension UIView {
func addInsetShadow(radius: CGFloat, alpha: CGFloat) {
let color: UIColor = .black
let shadowView = UIView(frame: CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height))
let shadow = CAGradientLayer.init()
//top
shadow.startPoint = CGPoint.init(x: 0.5, y: 0)
shadow.endPoint = CGPoint.init(x: 0.5, y: 1)
shadow.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: radius)
//bottom
shadow.startPoint = CGPoint.init(x: 0.5, y: 0)
shadow.endPoint = CGPoint.init(x: 0.5, y: 1)
shadow.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: radius)
}
}
| true
|
bcd80d7f2049d4e98d51e0289dd9f2e3a778bd00
|
Swift
|
fmo91/PigeonIncubator
|
/Pigeon/Pigeon/Utils/QueryCacheListener.swift
|
UTF-8
| 593
| 2.53125
| 3
|
[] |
no_license
|
//
// QueryCacheListener.swift
// Pigeon
//
// Created by Fernando Martín Ortiz on 23/08/2020.
// Copyright © 2020 Fernando Martín Ortiz. All rights reserved.
//
import Foundation
import Combine
protocol QueryCacheListener {
associatedtype Response: Codable
}
extension QueryCacheListener {
func listenQueryCache(for key: QueryKey) -> AnyPublisher<QueryState<Response>, Never> {
NotificationCenter.default.publisher(for: key.notificationName)
.map(\.object)
.filter { $0 is Response }
.map { .succeed($0 as! Response) }
.eraseToAnyPublisher()
}
}
| true
|
53d6a25e7978e8a5701317ae810223181cfd990e
|
Swift
|
AlexPereaCode/Covid-Info-SwiftUI
|
/CovidInfo/Observable Objects/ImageFromURL.swift
|
UTF-8
| 682
| 2.75
| 3
|
[] |
no_license
|
//
// ImageFromURL.swift
// CovidInfo
//
// Created by Alejandro Perea Navarrete on 12/4/21.
//
import SwiftUI
import Combine
class ImageFromURL: ObservableObject {
@Published var image = Image(systemName: "flag.slash")
var subscriber = Set<AnyCancellable>()
func getImage(url:URL) {
URLSession.shared
.dataTaskPublisher(for: url)
.map(\.data)
.compactMap { UIImage(data: $0) }
.map { Image(uiImage: $0) }
.replaceEmpty(with: Image(systemName: "flag.slash"))
.replaceError(with: Image(systemName: "flag.slash"))
.assign(to: \.image, on: self)
.store(in: &subscriber)
}
}
| true
|
163d4187fd228f9c9bc03cbcffdb3b8891da3970
|
Swift
|
mimzivvimzi/FreeFleaMarketApp
|
/FreeFleaMarketApp/Views/Controllers/EditEventViewController.swift
|
UTF-8
| 10,823
| 2.734375
| 3
|
[] |
no_license
|
//
// EditEventViewController.swift
// FreeFleaMarketApp
//
// Created by Michelle Lau on 2020/04/18.
// Copyright © 2020 Michelle Lau. All rights reserved.
//
import UIKit
import Firebase
class EditEventViewController: UITableViewController {
@IBOutlet weak var titleField: UITextField!
@IBOutlet weak var dateField: UITextField!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var locationField: UITextField!
@IBOutlet weak var descriptionField: UITextField!
@IBOutlet weak var selectedImage: UIImageView!
var selectedEvent : FetchedEvent?
let storageRef = Storage.storage().reference()
let reference = Database.database().reference()
// CREATE A NEW postID
let newPostID = UUID().uuidString
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Edit Event"
titleField.text = selectedEvent?.title
dateField.text = selectedEvent?.date
locationField.text = selectedEvent?.location
descriptionField.text = selectedEvent?.details
if let postID = selectedEvent?.postID {
let reference = storageRef.child("Images/\(postID).jpg")
print(reference)
selectedImage.sd_setImage(with: reference)
}
}
@IBAction func dateSelected(_ sender: UIDatePicker) {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US")
dateFormatter.dateStyle = DateFormatter.Style.medium
dateFormatter.timeStyle = DateFormatter.Style.short
let dateToString = dateFormatter.string(from: datePicker.date)
dateField.text = dateToString
}
@IBAction func uploadPhoto(_ sender: UIButton) {
let alert = UIAlertController(title: "Upload a photo", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (_) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerController.SourceType.camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}))
alert.addAction(UIAlertAction(title: "Photo album", style: .default, handler: { (_) in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.sourceType = UIImagePickerController.SourceType.photoLibrary
self.present(imagePicker, animated: true, completion: nil)
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (_) in
}))
self.present(alert, animated: true, completion: {
})
}
@IBAction func saveEvent(_ sender: UIButton) {
// DELETE THE OLD IMAGE
if let postID = selectedEvent?.postID {
let imageRef = Storage.storage().reference().child("Images/\(postID).jpg")
imageRef.delete { error in
if let error = error {
// Uh-oh, an error occurred!
} else {
// File deleted successfully
}
}
}
// ADD THE NEW IMAGE
if selectedImage.image != nil {
let image = selectedImage.image!
let imageRef = Storage.storage().reference().child("Images/\(newPostID).jpg")
StorageService.uploadImage(image, at: imageRef) { (downloadURL) in
guard let downloadURL = downloadURL else {
return
}
let urlString = downloadURL.absoluteString
// print("image url: \(urlString)")
self.saveEvent(imageURL: urlString)
}
} else {
let alert = UIAlertController(title: "Image not selected", message: "Please select an image.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true)
}
}
// UPDATING THE PHOTO
// if selectedImage.image != nil {
// let image = selectedImage.image!
// if let postID = selectedEvent?.postID {
// let imageRef = Storage.storage().reference().child("Images/\(postID).jpg")
//
// // TRYING TO DELETE THE IMAGE AND REUPLOAD A NEW ONE
//// imageRef.delete { error in
//// if let error = error {
//// // Uh-oh, an error occurred!
//// } else {
//// // File deleted successfully
//// }
//// }
// let newImageRef = Storage.storage().reference().child("Images/\(postID).jpg")
// StorageService.uploadImage(image, at: newImageRef) { (downloadURL) in
// guard let downloadURL = downloadURL else {
// return
// }
// let urlString = downloadURL.absoluteString
// print("image url: \(urlString)")
// self.saveEvent(imageURL: urlString)
// }
// }
// } else {
// let alert = UIAlertController(title: "Image not selected", message: "Please select an image.", preferredStyle: .alert)
// alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
// self.present(alert, animated: true)
// }
// }
func saveEvent(imageURL: String) {
// TESTING OUT IF WE DELETE THE EVENT AND CREATING A NEW ONE. THAT WAY, THE IMAGE WILL HAVE A NEW ID.
// DELETE THE EVENT
if let postID = self.selectedEvent?.postID {
self.remove(postID: postID)
}
// ADD A NEW EVENT WITH A NEW postID
if Auth.auth().currentUser != nil {
let ref = Database.database().reference()
let userID = Auth.auth().currentUser!.uid
let newEvent = FetchedEvent(user: userID, title: titleField.text ?? "", date: dateField.text ?? "", location: locationField.text ?? "", image: imageURL, details: descriptionField.text ?? "")
let eventPost = ["userID": newEvent.user,
"title" : newEvent.title,
"date" : newEvent.date,
"startTime": newEvent.date,
"endTime" : "",
"location" : newEvent.location,
"imageURL" : newEvent.imageURL,
"details": newEvent.details] as [String : Any]
ref.child("posts").child("\(newPostID)").setValue(eventPost)
let ViewController = self.storyboard?.instantiateViewController(withIdentifier: "EventList") as! UINavigationController
self.view.window?.rootViewController = ViewController
} else {
print("No one is signed in")
}
// SAVE CHANGES
// if Auth.auth().currentUser != nil {
// let ref = Database.database().reference()
// let userID = Auth.auth().currentUser!.uid
// if let postID = selectedEvent?.postID {
// let updatedEvent = FetchedEvent(user: userID, title: titleField.text ?? "", date: dateField.text ?? "", location: locationField.text ?? "", image: imageURL, details: descriptionField.text ?? "")
// let eventPost = ["userID": userID,
// "title" : updatedEvent.title,
// "date" : updatedEvent.date,
// "startTime": updatedEvent.date,
// "endTime" : "",
// "location" : updatedEvent.location,
// "imageURL" : updatedEvent.imageURL,
// "details": updatedEvent.details] as [String : Any]
// ref.child("posts").child("\(postID)").updateChildValues(eventPost)
// }
// let ViewController = self.storyboard?.instantiateViewController(withIdentifier: "EventList") as! UINavigationController
// self.view.window?.rootViewController = ViewController
// } else {
// print("No one is signed in")
// }
}
@IBAction func deleteTapped(_ sender: UIButton) {
let alert = UIAlertController(title: "Delete Event", message: "Are you sure you want to permanently delete this event?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { action in
if let postID = self.selectedEvent?.postID {
self.remove(postID: postID)
let imageRef = Storage.storage().reference().child("Images/\(postID).jpg")
imageRef.delete { error in
if let error = error {
// Uh-oh, an error occurred!
} else {
// File deleted successfully
}
}
}
// if let postID = self.selectedEvent?.postID {
// self.remove(postID: postID)
// }
let ViewController = self.storyboard?.instantiateViewController(withIdentifier: "EventList") as! UINavigationController
self.view.window?.rootViewController = ViewController
}))
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
func remove(postID: String) {
let reference = self.reference.child("posts").child("\(postID)")
reference.removeValue { error, _ in
print(error)
}
}
}
extension EditEventViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey(rawValue: UIImagePickerController.InfoKey.originalImage.rawValue)] as? UIImage {
selectedImage.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}
}
| true
|
80a045a98fcf6e2771862f162dc983a3adc602e1
|
Swift
|
SaadTahirTintash/Project-Training
|
/Footy-Crazy/Utilities/FCOpenLink.swift
|
UTF-8
| 826
| 2.828125
| 3
|
[] |
no_license
|
//
// FCOpenLink.swift
// Footy-Crazy
//
// Created by Tintash on 24/07/2019.
// Copyright © 2019 Tintash. All rights reserved.
//
import SafariServices
//MARK:- Definition
protocol FCOpenLink {}
//MARK:- Extension
extension FCOpenLink {
/// Opens a link in safari without leaving the app
///
/// - Parameters:
/// - urlString: url link to open
/// - nvc: navigation controller for coming back to last screen
func openLinkInSafari(_ urlString: String,
_ nvc: UINavigationController?) {
guard let url = URL(string: urlString) else {
print(FCConstants.ERRORS.invalidUrl)
return
}
let svc = SFSafariViewController(url: url)
nvc?.present(svc, animated: true, completion: nil)
}
}
| true
|
16b6d4d3e71927af46175a6fa2f96b08b1fae7ef
|
Swift
|
HoangTrongKhanh/CoreDataExample
|
/CoreDataExample/NSDate+Extension.swift
|
UTF-8
| 592
| 2.84375
| 3
|
[] |
no_license
|
//
// NSDate+Extension.swift
// CoreDataExample
//
// Created by Hoàng Khánh on 4/18/18.
// Copyright © 2018 Hoàng Khánh. All rights reserved.
//
import Foundation
extension NSDate {
static func calculateDate(day: Int, month: Int, year: Int) -> NSDate {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
let calculateDate = formatter.date(from: "\(year)/\(month)/\(day) 0:0") as NSDate?
return calculateDate!
}
}
| true
|
1bd11153f2f8bffa243ca3802f29a36d9778071c
|
Swift
|
BeeWise/travelling-ios-app
|
/Travelling/Travelling/Models/Place/Place.swift
|
UTF-8
| 1,043
| 3.265625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
//
// Place.swift
// Travelling
//
// Created by Dimitri Strauneanu on 13/09/2020.
//
import Foundation
public class Place: Codable, Equatable {
public static func == (lhs: Place, rhs: Place) -> Bool {
return lhs.id == rhs.id &&
lhs.location == rhs.location &&
lhs.createdAt == rhs.createdAt &&
lhs.name == rhs.name &&
lhs.description == rhs.description &&
lhs.commentCount == rhs.commentCount &&
lhs.photo == rhs.photo
}
var id: String
var location: Location
var createdAt: String?
var name: String?
var description: String?
var commentCount: Int = 0
var photo: Photo?
init(id: String, location: Location) {
self.id = id
self.location = location
}
enum CodingKeys: String, CodingKey {
case id
case location
case createdAt = "created_at"
case name
case description
case commentCount = "comment_count"
case photo
}
}
| true
|
7ad2d384af76db48aed21678762f75519485c384
|
Swift
|
skorulis/SKComponents
|
/SKComponents/Classes/KeyboardPlaceholder.swift
|
UTF-8
| 2,370
| 2.65625
| 3
|
[
"MIT"
] |
permissive
|
//
// KeyboardPlaceholder.swift
// SKComponents
//
// Created by Alexander Skorulis on 3/5/18.
//
import UIKit
public class KeyboardPlaceholder: UIView {
@IBOutlet var heightContraint:NSLayoutConstraint?
private var _heightOffset:CGFloat?
private var heightOffset:CGFloat {
if (_heightOffset == nil) {
guard let w = self.window else {return 0}
let r = w.convert(self.bounds, from: self)
let offset = w.frame.size.height - r.maxY
_heightOffset = max(offset, 0)
}
return _heightOffset ?? 0
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.isUserInteractionEnabled = false
self.setupNotifications()
if heightContraint == nil {
self.heightContraint = self.constraints.filter { $0.firstAttribute == NSLayoutConstraint.Attribute.height}.first
}
}
private func setupNotifications() {
let nc = NotificationCenter.default
nc.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
nc.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(notification:NSNotification) {
if (superview != nil && (window == nil || window?.frame.size.height == 0)) {
return; //UIView isn't yet on screen
}
guard let keyboardInfo = notification.userInfo else {return}
guard let keyboardFrameBeginRect = (keyboardInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {return}
guard let duration = keyboardInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else {return}
let height = keyboardFrameBeginRect.size.height - self.heightOffset
set(height: height)
UIView.animate(withDuration: duration) {
self.superview?.layoutIfNeeded()
}
}
@objc func keyboardWillHide(notification:NSNotification) {
self.set(height: 0)
}
private func set(height:CGFloat) {
self.heightContraint?.constant = height
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| true
|
2f9dfa16b62b0ef7ad7066b16ea42f74b6ba1c66
|
Swift
|
huangboju/QMUI.swift
|
/QMUI.swift/QMUIKit/UIComponents/QMUIMoreOperationController.swift
|
UTF-8
| 35,621
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
//
// QMUIMoreOperationController.swift
// QMUI.swift
//
// Created by 黄伯驹 on 2017/7/10.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
private let kQMUIMoreOperationItemViewTagOffset = 999
/// 操作面板上item的类型,QMUIMoreOperationItemTypeImportant类型的item会放到第一行的scrollView,QMUIMoreOperationItemTypeNormal类型的item会放到第二行的scrollView。
@objc enum QMUIMoreOperationItemType: Int {
case important = 0 // 将item放在第一行显示
case normal = 1 // 将item放在第二行显示
}
/// 更多操作面板的delegate。
@objc protocol QMUIMoreOperationControllerDelegate {
/// 即将显示操作面板
@objc optional func willPresent(_ moreOperationController: QMUIMoreOperationController)
/// 已经显示操作面板
@objc optional func didPresent(_ moreOperationController: QMUIMoreOperationController)
/// 即将降下操作面板,cancelled参数是用来区分是否触发了maskView或者cancelButton按钮降下面板还是手动调用hide方法来降下面板。
@objc optional func willDismiss(_ moreOperationController: QMUIMoreOperationController, cancelled: Bool)
/// 已经降下操作面板,cancelled参数是用来区分是否触发了maskView或者cancelButton按钮降下面板还是手动调用hide方法来降下面板。
@objc optional func didDismiss(_ moreOperationController: QMUIMoreOperationController, cancelled: Bool)
/// itemView 点击事件,可以与 itemView.handler 共存,可通过 itemView.tag 或者 itemView.indexPath 来区分不同的 itemView
@objc optional func moreOperationController(_ moreOperationController: QMUIMoreOperationController, didSelect itemView: QMUIMoreOperationItemView)
}
class QMUIMoreOperationItemView: QMUIButton {
private var _indexPath: IndexPath?
private(set) var indexPath: IndexPath? {
get {
if moreOperationController != nil {
return moreOperationController?.indexPath(with: self)
} else {
return nil
}
}
set {
_indexPath = newValue
}
}
fileprivate weak var moreOperationController: QMUIMoreOperationController?
typealias QMUIMoreOperationItemHandler = (QMUIMoreOperationController, QMUIMoreOperationItemView) -> Void
var handler: QMUIMoreOperationItemHandler?
override var isHighlighted: Bool {
didSet {
imageView?.alpha = isHighlighted ? ButtonHighlightedAlpha : 1
}
}
private var _tag: Int = 0
override var tag: Int {
set {
_tag = newValue + kQMUIMoreOperationItemViewTagOffset
}
get {
// 为什么这里用-1而不是0:如果一个 itemView 通过带 tag: 参数初始化,那么 itemView.tag 最小值为 0,而如果一个 itemView 不通过带 tag: 的参数初始化,那么 itemView.tag 固定为 0,可见 tag 为 0 代表的意义不唯一,为了消除歧义,这里用 -1 代表那种不使用 tag: 参数初始化的 itemView
return max(-1, _tag - kQMUIMoreOperationItemViewTagOffset)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
imagePosition = .top
adjustsButtonWhenHighlighted = false
qmui_automaticallyAdjustTouchHighlightedInScrollView = true
titleLabel?.numberOfLines = 0
titleLabel?.textAlignment = .center
imageView?.contentMode = .center
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init(image: UIImage,
selectedImage: UIImage? = nil,
title: String,
selectedTitle: String? = nil,
tag: Int = 0,
handler: QMUIMoreOperationItemHandler?) {
self.init(frame: .zero)
setImage(image, for: .normal)
setImage(selectedImage, for: .selected)
setImage(selectedImage, for: [.highlighted, .selected])
setTitle(title, for: .normal)
setTitle(selectedTitle, for: [.highlighted, .selected])
setTitle(selectedTitle, for: .selected)
self.handler = handler
self.tag = tag
}
override var description: String {
return "\(type(of: self)):\t\(self)\nimage:\t\t\t\(String(describing: image(for: .normal)))\nselectedImage:\t\(String(describing: image(for: .selected) == image(for: .normal) ? nil : image(for: .selected)))\ntitle:\t\t\t\(String(describing: title(for: .normal)))\nselectedTitle:\t\(String(describing: title(for: .selected) == title(for: .normal) ? nil : title(for: .selected)))\nindexPath:\t\t\(indexPath?.item ?? -1)\ntag:\t\t\t\t\(tag)"
}
// 被添加到某个 QMUIMoreOperationController 时要调用,用于更新 itemView 的样式,以及 moreOperationController 属性的指针
// @param moreOperationController 如果为空,则会自动使用 [QMUIMoreOperationController appearance]
fileprivate func formatItemViewStyle(with moreOperationController: QMUIMoreOperationController?) -> QMUIMoreOperationController {
var vc: QMUIMoreOperationController
if moreOperationController != nil {
vc = moreOperationController!
// 将事件放到 controller 级别去做,以便实现 delegate 功能
addTarget(vc, action: #selector(QMUIMoreOperationController.handleItemViewEvent(_:)), for: .touchUpInside)
} else {
// 参数 nil 则默认使用 appearance 的样式
vc = QMUIMoreOperationController.appearance()
}
titleLabel?.font = vc.itemTitleFont
titleEdgeInsets = UIEdgeInsets(top: vc.itemTitleMarginTop, left: 0, bottom: 0, right: 0)
setTitleColor(vc.itemTitleColor, for: .normal)
imageView?.backgroundColor = vc.itemBackgroundColor
return vc
}
}
/**
* 更多操作面板。在iOS上是一个比较常见的控件,比如系统的相册分享;或者微信的webview分享都会从底部弹出一个面板。<br/>
* 这个控件一般分为上下两行,第一行会显示比较重要的操作入口,第二行是一些次要的操作入口。
* QMUIMoreOperationController就是这样的一个控件,可以通过QMUIMoreOperationItemType来设置操作入口要放在第一行还是第二行。
*/
class QMUIMoreOperationController: UIViewController, QMUIModalPresentationViewControllerDelegate {
// 面板上半部分(不包含取消按钮)背景色
var contentBackgroundColor = UIColorWhite {
didSet {
contentView.backgroundColor = contentBackgroundColor
}
}
// 面板距离屏幕的上下左右间距
var contentEdgeMargin: CGFloat = 10 {
didSet {
updateCornerRadius()
}
}
// 面板的最大宽度
var contentMaximumWidth = QMUIHelper.screenSizeFor55Inch.width - 20
// 面板的圆角大小,当值大于 0 时会设置 self.view.clipsToBounds = true
var contentCornerRadius: CGFloat = 10 {
didSet {
updateCornerRadius()
}
}
// 面板内部的 padding,UIScrollView 会布局在除去 padding 之后的区域
var contentPaddings: UIEdgeInsets = .zero
// 每一行之间的顶部分隔线,对第一行无效
var scrollViewSeparatorColor: UIColor = UIColor(r: 0, g: 0, b: 0, a: 0.15) {
didSet {
updateScrollViewsBorderStyle()
}
}
// // 每一行内部的 padding
var scrollViewContentInsets: UIEdgeInsets = UIEdgeInsets.init(top: 14, left: 8, bottom: 14, right: 8) {
didSet {
for scrollView in mutableScrollViews {
scrollView.contentInset = scrollViewContentInsets
}
setViewNeedsLayoutIfLoaded()
}
}
// 按钮的背景色
var itemBackgroundColor = UIColorClear {
didSet {
for section in mutableItems {
for itemView in section {
itemView.imageView?.backgroundColor = itemBackgroundColor
}
}
}
}
// 按钮的标题颜色
var itemTitleColor = UIColorGrayDarken {
didSet {
for section in mutableItems {
for itemView in section {
itemView.setTitleColor(itemTitleColor, for: .normal)
}
}
}
}
// 按钮的标题字体
var itemTitleFont = UIFontMake(11) {
didSet {
for section in mutableItems {
for itemView in section {
itemView.titleLabel?.font = itemTitleFont
itemView.setNeedsLayout()
}
}
}
}
// 按钮内 imageView 的左右间距(按钮宽度 = 图片宽度 + 左右间距 * 2),通常用来调整文字的宽度
var itemPaddingHorizontal: CGFloat = 16 {
didSet {
setViewNeedsLayoutIfLoaded()
}
}
// 按钮标题距离文字之间的间距
var itemTitleMarginTop: CGFloat = 9 {
didSet {
for section in mutableItems {
for itemView in section {
itemView.titleEdgeInsets = UIEdgeInsets.init(top: itemTitleMarginTop, left: 0, bottom: 0, right: 0)
itemView.setNeedsLayout()
}
}
}
}
// 按钮与按钮之间的最小间距
var itemMinimumMarginHorizontal: CGFloat = 0 {
didSet {
setViewNeedsLayoutIfLoaded()
}
}
// 是否要自动计算默认一行展示多少个 item,true 表示尽量让每一行末尾露出半个 item 暗示后面还有内容,false 表示直接根据 itemMinimumMarginHorizontal 来计算布局。默认为 true。
var automaticallyAdjustItemMargins: Bool = true {
didSet {
setViewNeedsLayoutIfLoaded()
}
}
// 取消按钮的背景色
var cancelButtonBackgroundColor = UIColorWhite {
didSet {
cancelButton.backgroundColor = cancelButtonBackgroundColor
updateExtendLayerAppearance()
}
}
// 取消按钮的标题颜色
var cancelButtonTitleColor = UIColorBlue {
didSet {
cancelButton.setTitleColor(cancelButtonTitleColor, for: .normal)
cancelButton.setTitleColor(cancelButtonTitleColor.withAlphaComponent(ButtonHighlightedAlpha), for: .highlighted)
}
}
// 取消按钮的顶部分隔线颜色
var cancelButtonSeparatorColor = UIColor(r: 0, g: 0, b: 0, a: 0.15) {
didSet {
cancelButton.qmui_borderColor = cancelButtonSeparatorColor
}
}
// 取消按钮的字体
var cancelButtonFont = UIFontBoldMake(17) {
didSet {
cancelButton.titleLabel?.font = cancelButtonFont
cancelButton.setNeedsLayout()
}
}
// 取消按钮的高度
var cancelButtonHeight: CGFloat = 56
// 取消按钮距离内容面板的间距
var cancelButtonMarginTop: CGFloat = 0 {
didSet {
cancelButton.qmui_borderPosition = cancelButtonMarginTop > 0 ? .none : .top
updateCornerRadius()
setViewNeedsLayoutIfLoaded()
}
}
/// 代理
weak var delegate: QMUIMoreOperationControllerDelegate?
// 放 UIScrollView 的容器,与 cancelButton 区分开
private(set) var contentView: UIView!
// 获取当前的所有 UIScrollView
var scrollViews: [UIScrollView] {
let scrollViews = mutableScrollViews
return scrollViews
}
/// 取消按钮,如果不需要,则自行设置其 hidden 为 true
private(set) var cancelButton: QMUIButton!
/// 在 iPhoneX 机器上是否延伸底部背景色。因为在 iPhoneX 上我们会把整个面板往上移动 safeArea 的距离,如果你的面板本来就配置成撑满全屏的样式,那么就会露出底部的空隙,isExtendBottomLayout 可以帮助你把空暇填补上。默认为false。
var isExtendBottomLayout: Bool = false {
didSet {
if isExtendBottomLayout {
extendLayer.isHidden = false
updateExtendLayerAppearance()
} else {
extendLayer.isHidden = true
}
}
}
/// 获取当前所有的item
var items: [[QMUIMoreOperationItemView]] {
get {
let items = mutableItems
return items
}
set {
for section in mutableItems {
for itemView in section {
itemView.removeFromSuperview()
}
}
mutableItems.removeAll()
mutableItems = newValue
for scrollView in mutableScrollViews {
scrollView.removeFromSuperview()
}
mutableScrollViews.removeAll()
for (index, itemViewSection) in mutableItems.enumerated() {
let scrollView = addScrollView(at: index)
for itemView in itemViewSection {
_add(itemView, to: scrollView)
}
}
setViewNeedsLayoutIfLoaded()
}
}
private var mutableScrollViews: [UIScrollView] = []
private var mutableItems: [[QMUIMoreOperationItemView]] = [[]]
/// 更多操作面板是否正在显示
private(set) var isShowing = false
private(set) var isAnimating = false
private var extendLayer: CALayer!
// 是否通过点击取消按钮或者遮罩来隐藏面板,默认为 false
private var hideByCancel: Bool = false
convenience init() {
self.init(nibName: nil, bundle: nil)
didInitialized()
}
override init(nibName _: String?, bundle _: Bundle?) {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func didInitialized() {
if #available(iOS 9.0, *) {
loadViewIfNeeded()
} else {
view.alpha = 1
}
contentBackgroundColor = QMUIMoreOperationController.appearance().contentBackgroundColor
contentEdgeMargin = QMUIMoreOperationController.appearance().contentEdgeMargin
contentMaximumWidth = QMUIMoreOperationController.appearance().contentMaximumWidth
contentCornerRadius = QMUIMoreOperationController.appearance().contentCornerRadius
contentPaddings = QMUIMoreOperationController.appearance().contentPaddings
scrollViewSeparatorColor = QMUIMoreOperationController.appearance().scrollViewSeparatorColor
scrollViewContentInsets = QMUIMoreOperationController.appearance().scrollViewContentInsets
itemBackgroundColor = QMUIMoreOperationController.appearance().itemBackgroundColor
itemTitleColor = QMUIMoreOperationController.appearance().itemTitleColor
itemTitleFont = QMUIMoreOperationController.appearance().itemTitleFont
itemPaddingHorizontal = QMUIMoreOperationController.appearance().itemPaddingHorizontal
itemTitleMarginTop = QMUIMoreOperationController.appearance().itemTitleMarginTop
itemMinimumMarginHorizontal = QMUIMoreOperationController.appearance().itemMinimumMarginHorizontal
automaticallyAdjustItemMargins = QMUIMoreOperationController.appearance().automaticallyAdjustItemMargins
cancelButtonBackgroundColor = QMUIMoreOperationController.appearance().cancelButtonBackgroundColor
cancelButtonTitleColor = QMUIMoreOperationController.appearance().cancelButtonTitleColor
cancelButtonSeparatorColor = QMUIMoreOperationController.appearance().cancelButtonSeparatorColor
cancelButtonFont = QMUIMoreOperationController.appearance().cancelButtonFont
cancelButtonHeight = QMUIMoreOperationController.appearance().cancelButtonHeight
cancelButtonMarginTop = QMUIMoreOperationController.appearance().cancelButtonMarginTop
isExtendBottomLayout = QMUIMoreOperationController.appearance().isExtendBottomLayout
}
override func viewDidLoad() {
super.viewDidLoad()
contentView = UIView()
contentView.backgroundColor = contentBackgroundColor
view.addSubview(contentView)
cancelButton = QMUIButton()
cancelButton.qmui_automaticallyAdjustTouchHighlightedInScrollView = true
cancelButton.adjustsButtonWhenHighlighted = false
cancelButton.titleLabel?.font = cancelButtonFont
cancelButton.backgroundColor = cancelButtonBackgroundColor
cancelButton.setTitle("取消", for: .normal)
cancelButton.setTitleColor(cancelButtonTitleColor, for: .normal)
cancelButton.setTitleColor(cancelButtonTitleColor.withAlphaComponent(ButtonHighlightedAlpha), for: .highlighted)
cancelButton.qmui_borderPosition = .bottom
cancelButton.qmui_borderColor = cancelButtonSeparatorColor
cancelButton.addTarget(self, action: #selector(handleCancelButtonEvent(_:)), for: .touchUpInside)
view.addSubview(cancelButton)
extendLayer = CALayer()
extendLayer.isHidden = !self.isExtendBottomLayout
extendLayer.qmui_removeDefaultAnimations()
view.layer.addSublayer(extendLayer)
updateExtendLayerAppearance()
updateCornerRadius()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var layoutY = view.bounds.height
if !extendLayer.isHidden {
extendLayer.frame = CGRect(x: 0, y: layoutY, width: view.bounds.width, height: IPhoneXSafeAreaInsets.bottom)
if view.clipsToBounds {
print("QMUIMoreOperationController,\(type(of: self)) 需要显示 extendLayer,但却被父级 clip 掉了,可能看不到")
}
}
let isCancelButtonShowing = !cancelButton.isHidden
if isCancelButtonShowing {
cancelButton.frame = CGRect(x: 0, y: layoutY - cancelButtonHeight, width: view.bounds.width, height: cancelButtonHeight)
cancelButton.setNeedsLayout()
layoutY = cancelButton.frame.minY - cancelButtonMarginTop
}
contentView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: layoutY)
layoutY = contentPaddings.top
let contentWidth: CGFloat = contentView.bounds.width - contentPaddings.horizontalValue
for (index, scrollView) in mutableScrollViews.enumerated() {
scrollView.frame = CGRect(x: contentPaddings.left, y: layoutY, width: contentWidth, height: scrollView.frame.height)
// 要保护 safeAreaInsets 的区域,而这里不使用 scrollView.qmui_safeAreaInsets 是因为此时 scrollView 的 safeAreaInsets 仍然为 0,但 scrollView.superview.safeAreaInsets 已经正确了,所以使用 scrollView.superview 也即 self.view 的
// 底部的 insets 暂不考虑
// UIEdgeInsets scrollViewSafeAreaInsets = scrollView.qmui_safeAreaInsets;
let scrollViewSafeAreaInsets = UIEdgeInsets(top: fmax(view.qmui_safeAreaInsets.top - scrollView.qmui_top, 0), left: fmax(view.qmui_safeAreaInsets.left - scrollView.qmui_left, 0), bottom: 0, right: fmax(view.qmui_safeAreaInsets.right - (view.qmui_width - scrollView.qmui_right), 0))
let itemSection = mutableItems[index]
var exampleItemWidth: CGFloat = 0
if let exampleItemView = itemSection.first, let width = exampleItemView.imageView?.image?.size.width {
exampleItemWidth = width + itemPaddingHorizontal * 2
}
let scrollViewVisibleWidth = contentWidth - scrollView.contentInset.left - scrollViewSafeAreaInsets.left // 注意计算列数时不需要考虑 contentInset.right 的
var columnCount = (scrollViewVisibleWidth + itemMinimumMarginHorizontal) / (exampleItemWidth + itemMinimumMarginHorizontal)
// 让初始状态下在 scrollView 右边露出半个 item
if automaticallyAdjustItemMargins {
columnCount = suitableColumnCount(columnCount)
}
let finalItemMarginHorizontal = (scrollViewVisibleWidth - exampleItemWidth * columnCount) / columnCount
var maximumItemHeight: CGFloat = 0
var itemViewMinX: CGFloat = scrollViewSafeAreaInsets.left
for itemView in itemSection {
let itemSize = itemView.sizeThatFits(CGSize(width: exampleItemWidth, height: CGFloat.greatestFiniteMagnitude)).flatted
maximumItemHeight = fmax(maximumItemHeight, itemSize.height)
itemView.frame = CGRect(x: itemViewMinX, y: 0, width: exampleItemWidth, height: itemSize.height)
itemViewMinX = itemView.frame.maxX + finalItemMarginHorizontal
}
scrollView.contentSize = CGSize(width: itemViewMinX - finalItemMarginHorizontal + scrollViewSafeAreaInsets.right, height: maximumItemHeight)
scrollView.frame = scrollView.frame.setHeight(scrollView.contentSize.height + scrollView.contentInset.verticalValue)
layoutY = scrollView.frame.maxY
}
}
private func suitableColumnCount(_ columnCount: CGFloat) -> CGFloat {
// 根据精准的列数,找到一个合适的、能让半个 item 刚好露出来的列数。例如 3.6 会被转换成 3.5,3.2 会被转换成 2.5。
var result: CGFloat = 0
if (CGFloat(Int(columnCount)) + 0.5) == CGFloat(Int(columnCount)) {
result = (CGFloat(Int(columnCount)) - 1) + 0.5
}
result = CGFloat(Int(columnCount)) + 0.5
return result
}
/// 弹出面板,一般在 init 完并且设置好 items 之后就调用这个接口来显示面板
func showFromBottom() {
if isShowing || isAnimating {
return
}
hideByCancel = true
let modalPresentationViewController = QMUIModalPresentationViewController()
modalPresentationViewController.delegate = self
modalPresentationViewController.maximumContentViewWidth = contentMaximumWidth
modalPresentationViewController.contentViewMargins = UIEdgeInsets(top: contentEdgeMargin, left: contentEdgeMargin, bottom: contentEdgeMargin, right: contentEdgeMargin)
modalPresentationViewController.contentViewController = self
modalPresentationViewController.layoutClosure = { (containerBounds, keyboardHeight, contentViewDefaultFrame) in
modalPresentationViewController.contentView?.frame = contentViewDefaultFrame.setY(containerBounds.height - modalPresentationViewController.contentViewMargins.bottom - contentViewDefaultFrame.height - modalPresentationViewController.view.qmui_safeAreaInsets.bottom)
}
modalPresentationViewController.showingAnimationClosure = { [weak self] (dimmingView: UIView?, containerBounds: CGRect, _: CGFloat, contentViewFrame: CGRect, _ completion: ((Bool) -> Void)?) in
if let strongSelf = self {
strongSelf.delegate?.willPresent?(strongSelf)
}
dimmingView?.alpha = 0
modalPresentationViewController.contentView?.frame = contentViewFrame.setY(containerBounds.height)
UIView.animate(withDuration: 0.25, delay: 0, options: .curveOut, animations: {
dimmingView?.alpha = 1
modalPresentationViewController.contentView?.frame = contentViewFrame
}, completion: { (finished) in
if let strongSelf = self {
strongSelf.isShowing = true
strongSelf.isAnimating = false
strongSelf.delegate?.didPresent?(strongSelf)
}
completion?(finished)
})
}
modalPresentationViewController.hidingAnimationClosure = { (dimmingView: UIView?, containerBounds: CGRect, _ : CGFloat, _ completion: ((_ finished: Bool) -> Void)?) in
UIView.animate(withDuration: 0.25, delay: 0, options: .curveOut, animations: {
dimmingView?.alpha = 0
if let contentView = modalPresentationViewController.contentView {
contentView.frame = contentView.frame.setY(containerBounds.height)
}
}, completion: { (finished) in
completion?(finished)
})
}
isAnimating = true
modalPresentationViewController.show(true, completion: nil)
}
/// 隐藏面板
func hideToBottom() {
if !isShowing || isAnimating {
return
}
hideByCancel = false
qmui_modalPresentationViewController?.hide(true, completion: nil)
}
@objc func handleCancelButtonEvent(_ button: QMUIButton) {
if !isShowing || isAnimating {
return
}
qmui_modalPresentationViewController?.hide(true, completion: nil)
}
@objc func handleItemViewEvent(_ itemView: QMUIMoreOperationItemView) {
delegate?.moreOperationController?(self, didSelect: itemView)
itemView.handler?(self, itemView)
}
/// 添加一个 itemView 到指定 section 的末尾
func add(_ itemView: QMUIMoreOperationItemView, in section: Int) {
if section == mutableItems.count {
// 创建新的 itemView section
mutableItems.append([itemView])
} else {
mutableItems[section].append(itemView)
}
itemView.moreOperationController = self
if (section == mutableScrollViews.count) {
// 创建新的 section
addScrollView(at: section)
}
if section < mutableScrollViews.count {
_add(itemView, to: mutableScrollViews[section])
}
setViewNeedsLayoutIfLoaded()
}
/// 插入一个 itemView 到指定的位置,NSIndexPath 请使用 section-item 组合,其中 section 表示行,item 表示 section 里的元素序号
func insert(_ itemView: QMUIMoreOperationItemView, at indexPath: IndexPath) {
if indexPath.section == mutableItems.count {
// 创建新的 itemView section
mutableItems.append([itemView])
} else {
mutableItems[indexPath.section].insert(itemView, at: indexPath.item)
}
itemView.moreOperationController = self
if (indexPath.section == mutableScrollViews.count) {
// 创建新的 section
addScrollView(at: indexPath.section)
}
if indexPath.section < mutableScrollViews.count {
itemView.moreOperationController = itemView.formatItemViewStyle(with: self)
mutableScrollViews[indexPath.section].insertSubview(itemView, at:indexPath.item)
}
setViewNeedsLayoutIfLoaded()
}
/// 移除指定位置的 itemView,NSIndexPath 请使用 section-item 组合,其中 section 表示行,item 表示 section 里的元素序号
func removeItemView(at indexPath: IndexPath) {
let itemView = mutableScrollViews[indexPath.section].subviews[indexPath.item] as! QMUIMoreOperationItemView
itemView.moreOperationController = nil
itemView.removeFromSuperview()
var itemViewSection = mutableItems[indexPath.section]
itemViewSection.remove(object: itemView)
mutableItems[indexPath.section] = itemViewSection
if itemViewSection.count == 0 {
mutableItems.remove(object: itemViewSection)
mutableScrollViews[indexPath.section].removeFromSuperview()
mutableScrollViews.remove(at: indexPath.section)
updateScrollViewsBorderStyle()
}
setViewNeedsLayoutIfLoaded()
}
/// 获取指定 tag 的 itemView,如果不存在则返回 nil
func itemView(with tag: Int) -> QMUIMoreOperationItemView? {
var result: QMUIMoreOperationItemView?
for section in mutableItems {
for itemView in section {
if itemView.tag == tag {
result = itemView
break
}
}
}
return result
}
/// 获取指定 itemView 在当前控件里的 indexPath,如果不存在则返回 nil
func indexPath(with itemView: QMUIMoreOperationItemView) -> IndexPath? {
for section in 0..<mutableItems.count {
if let index = mutableItems[section].firstIndex(of: itemView) {
return IndexPath(item: index, section: section)
}
}
return nil
}
@discardableResult
private func addScrollView(at index: Int) -> UIScrollView {
let scrollView = generateScrollView(index)
contentView.addSubview(scrollView)
mutableScrollViews.append(scrollView)
updateScrollViewsBorderStyle()
return scrollView
}
private func _add(_ itemView: QMUIMoreOperationItemView, to scrollView: UIScrollView) {
itemView.moreOperationController = itemView.formatItemViewStyle(with: self)
scrollView.addSubview(itemView)
}
private func generateScrollView(_ index: Int) -> UIScrollView {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.alwaysBounceHorizontal = true
scrollView.qmui_borderColor = scrollViewSeparatorColor
scrollView.qmui_borderPosition = index != 0 ? .top : .none
scrollView.scrollsToTop = false
if #available(iOS 11, *) {
scrollView.contentInsetAdjustmentBehavior = .never
}
scrollView.contentInset = scrollViewContentInsets
scrollView.qmui_scrollToTopForce(true, animated: false)
return scrollView
}
private func updateScrollViewsBorderStyle() {
for (idx, scrollView) in mutableScrollViews.enumerated() {
scrollView.qmui_borderColor = scrollViewSeparatorColor
scrollView.qmui_borderPosition = idx != 0 ? .top : .none
}
}
private func setViewNeedsLayoutIfLoaded() {
if isShowing {
qmui_modalPresentationViewController?.updateLayout()
view.setNeedsLayout()
} else if isViewLoaded {
view.setNeedsLayout()
}
}
private func updateExtendLayerAppearance() {
extendLayer.backgroundColor = cancelButtonBackgroundColor.cgColor
}
private func updateCornerRadius() {
if cancelButtonMarginTop > 0 {
view.layer.cornerRadius = 0
view.clipsToBounds = false
contentView.layer.cornerRadius = contentCornerRadius
cancelButton.layer.cornerRadius = contentCornerRadius
} else {
view.layer.cornerRadius = contentCornerRadius
view.clipsToBounds = view.layer.cornerRadius > 0 // 有圆角才需要 clip
contentView.layer.cornerRadius = 0
cancelButton.layer.cornerRadius = 0
}
}
}
extension QMUIMoreOperationController: QMUIModalPresentationContentViewControllerProtocol {
func preferredContentSize(inModalPresentationViewController controller: QMUIModalPresentationViewController, limitSize: CGSize) -> CGSize {
var resultSize = limitSize
var contentHeight = cancelButton.isHidden ? 0 : cancelButtonHeight + cancelButtonMarginTop
for (idx, scrollView) in mutableScrollViews.enumerated() {
let itemSection = mutableItems[idx]
var exampleItemWidth: CGFloat = 0
if let exampleItemView = itemSection.first, let width = exampleItemView.imageView?.image?.size.width {
exampleItemWidth = width + itemPaddingHorizontal * 2
}
var maximumItemHeight: CGFloat = 0
for itemView in itemSection {
let itemSize = itemView.sizeThatFits(CGSize(width: exampleItemWidth, height: CGFloat.greatestFiniteMagnitude))
maximumItemHeight = fmax(maximumItemHeight, itemSize.height)
}
contentHeight += maximumItemHeight + scrollView.contentInset.verticalValue
}
if mutableScrollViews.count > 0 {
contentHeight += contentPaddings.verticalValue
}
resultSize.height = contentHeight;
return resultSize
}
}
extension QMUIMoreOperationController {
static func appearance() -> QMUIMoreOperationController {
DispatchQueue.once(token: QMUIMoreOperationController._onceToken) {
QMUIMoreOperationController.resetAppearance()
}
return QMUIMoreOperationController.moreOperationViewControllerAppearance!
}
private static let _onceToken = UUID().uuidString
static var moreOperationViewControllerAppearance: QMUIMoreOperationController?
private static func resetAppearance() {
let moreOperationViewControllerAppearance = QMUIMoreOperationController(nibName: nil, bundle: nil)
if #available(iOS 9.0, *) {
moreOperationViewControllerAppearance.loadViewIfNeeded()
} else {
moreOperationViewControllerAppearance.view.alpha = 1
}
moreOperationViewControllerAppearance.contentBackgroundColor = UIColorWhite
moreOperationViewControllerAppearance.contentEdgeMargin = 10
moreOperationViewControllerAppearance.contentMaximumWidth = QMUIHelper.screenSizeFor55Inch.width - moreOperationViewControllerAppearance.contentEdgeMargin * 2
moreOperationViewControllerAppearance.contentCornerRadius = 10
moreOperationViewControllerAppearance.contentPaddings = UIEdgeInsets(top: 10, left: 0, bottom: 5, right: 0)
moreOperationViewControllerAppearance.scrollViewSeparatorColor = UIColor(r: 0, g: 0, b: 0, a: 0.15)
moreOperationViewControllerAppearance.scrollViewContentInsets = UIEdgeInsets(top: 14, left: 8, bottom: 14, right: 8)
moreOperationViewControllerAppearance.itemBackgroundColor = UIColorClear
moreOperationViewControllerAppearance.itemTitleColor = UIColorGrayDarken
moreOperationViewControllerAppearance.itemTitleFont = UIFontMake(11)
moreOperationViewControllerAppearance.itemPaddingHorizontal = 16
moreOperationViewControllerAppearance.itemTitleMarginTop = 9
moreOperationViewControllerAppearance.itemMinimumMarginHorizontal = 0
moreOperationViewControllerAppearance.automaticallyAdjustItemMargins = true
moreOperationViewControllerAppearance.cancelButtonBackgroundColor = UIColorWhite
moreOperationViewControllerAppearance.cancelButtonTitleColor = UIColorBlue
moreOperationViewControllerAppearance.cancelButtonSeparatorColor = UIColor(r: 0, g: 0, b: 0, a: 0.15)
moreOperationViewControllerAppearance.cancelButtonFont = UIFontBoldMake(16)
moreOperationViewControllerAppearance.cancelButtonHeight = 56.0
moreOperationViewControllerAppearance.cancelButtonMarginTop = 0
moreOperationViewControllerAppearance.isExtendBottomLayout = false
QMUIMoreOperationController.moreOperationViewControllerAppearance = moreOperationViewControllerAppearance
}
}
| true
|
5619d66a80496bb79157a5ac83222ee374ad49d0
|
Swift
|
thisisxvr/mrror
|
/Mrror/OptionsViewController.swift
|
UTF-8
| 2,638
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// OptionsViewController.swift
// Mrror
//
// Created by Xavier Francis on 21/08/17.
// Copyright © 2017 Xavier Francis. All rights reserved.
//
import UIKit
// Protocol used to send data back to parent ViewController.
protocol DataEnteredDelegate: class {
func optionsModified(to options: [String: Any])
}
class OptionsViewController: UIViewController {
// MARK: Properties.
@IBOutlet weak var lineWidthSlider: UISlider!
weak var delegate: DataEnteredDelegate? = nil
var options = [String: Any]() // Options bag: SHP = Shape, LIN = Line width, CLR = Color.
var optionsTmp = [String: Any]() // Default / previous values.
// MARK: Overrides.
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Options"
// Blur the background.
// if !UIAccessibilityIsReduceTransparencyEnabled() {
// self.view.backgroundColor = UIColor.clear
//
// let blurEffectView = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.light))
// blurEffectView.frame = self.view.bounds
// blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
//
// self.view.insertSubview(blurEffectView, at: 0)
// } else {
// self.view.backgroundColor = UIColor.lightGray
// }
// Sets the line width slider to real value.
lineWidthSlider.setValue(Float(optionsTmp["LIN"] as! CGFloat), animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
// Set to previous values if no options were selected.
if options["LIN"] == nil { options["LIN"] = optionsTmp["LIN"] }
if options["CLR"] == nil { options["CLR"] = optionsTmp["CLR"] }
// Pass options bag back and return to canvas.
delegate?.optionsModified(to: options)
// performSegue(withIdentifier: "unwindToCanvasSegue", sender: self)
}
// MARK: Event handlers.
@IBAction func colorSelected(_ sender: UIButton) {
switch sender.tag {
case 0:
options["CLR"] = UIColor.blue.cgColor
case 1:
options["CLR"] = UIColor.red.cgColor
case 2:
options["CLR"] = UIColor.yellow.cgColor
case 3:
options["CLR"] = UIColor.purple.cgColor
case 4:
options["CLR"] = UIColor.green.cgColor
default:
options["CLR"] = UIColor.blue.cgColor
}
}
@IBAction func lineWidthChanged(_ sender: UISlider) {
options["LIN"] = CGFloat(sender.value)
}
}
| true
|
d6fcf37adc6b70fb0134fe67fc9f40a17bfbbcff
|
Swift
|
Hulyaydogmus/IOS-PlayGraunds
|
/Functions.playground/Contents.swift
|
UTF-8
| 508
| 4.21875
| 4
|
[] |
no_license
|
import UIKit
func myFunction(){
print("My Function")
}
print("print")
myFunction()
//Input & Output & Return
//func sumFunction(x: Int, y: Int){
// print(x + y)
//}
//sumFunction(x: 10, y: 20)
func sumFunction(x: Int, y: Int) -> Int{
return x + y
}
let myFunctionVariable = sumFunction(x: 10, y: 20)
print(myFunctionVariable)
func logicFunction(a : Int, b: Int) -> String{
if a > b {
return "Greater"
}else {
return "Less"
}
}
logicFunction(a: -10, b: 0)
| true
|
b054fc8d276b6aba8c2cd50ad756b9804191813b
|
Swift
|
ProVir/ServiceContainerKit
|
/ExampleServiceLocators/Injects/SLInject.swift
|
UTF-8
| 5,010
| 2.515625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// SLInject.swift
// ServiceLocator
//
// Created by Короткий Виталий on 06.05.2020.
// Copyright © 2020 ProVir. All rights reserved.
//
import Foundation
private var serviceLocatorShared: ServiceLocator?
private var lazyInjects: [SLInjectWrapper] = []
public extension ServiceLocator {
func setupForInject() {
serviceLocatorShared = self
let list = lazyInjects
lazyInjects = []
list.forEach {
$0.inject?.setServiceLocator(self)
}
}
}
@propertyWrapper
public final class SLInject<ServiceType>: SLInjectBase {
fileprivate var lazyInit: ((ServiceLocator?) -> Void)?
private var factory: (() -> ServiceType)?
private var service: ServiceType?
public init<Key: ServiceLocatorKey>(_ key: Key, lazy: Bool = false, file: StaticString = #file, line: UInt = #line) where Key.ServiceType == ServiceType {
setup { [unowned self] locator in
guard let locator = locator else {
fatalError("Not found ServiceLocator for Inject", file: file, line: line)
}
if lazy {
self.factory = { locator.getServiceOrFatal(key: key, file: file, line: line) }
} else {
self.service = locator.getServiceOrFatal(key: key, file: file, line: line)
}
}
}
public init<Key: ServiceLocatorParamsKey>(_ key: Key, params: Key.ParamsType, lazy: Bool = false, file: StaticString = #file, line: UInt = #line) where Key.ServiceType == ServiceType {
setup {[unowned self] locator in
guard let locator = locator else {
fatalError("Not found ServiceLocator for Inject", file: file, line: line)
}
if lazy {
self.factory = { locator.getServiceOrFatal(key: key, params: params, file: file, line: line) }
} else {
self.service = locator.getServiceOrFatal(key: key, params: params, file: file, line: line)
}
}
}
public var wrappedValue: ServiceType {
lazyInit?(nil)
if let service = self.service {
return service
} else if let service = factory?() {
self.service = service
self.factory = nil
return service
} else {
fatalError("Unknown error in Inject")
}
}
}
@propertyWrapper
public final class SLOptionalInject<ServiceType>: SLInjectBase {
fileprivate var lazyInit: ((ServiceLocator?) -> Void)?
private var factory: (() -> ServiceType?)?
private var service: ServiceType?
public init<Key: ServiceLocatorKey>(_ key: Key, lazy: Bool = false, file: StaticString = #file, line: UInt = #line) where Key.ServiceType == ServiceType {
setup { [unowned self] locator in
guard let locator = locator else {
fatalError("Not found ServiceLocator for Inject", file: file, line: line)
}
if lazy {
self.factory = { locator.getServiceAsOptional(key: key) }
} else {
self.service = locator.getServiceAsOptional(key: key)
}
}
}
public init<Key: ServiceLocatorParamsKey>(_ key: Key, params: Key.ParamsType, lazy: Bool = false, file: StaticString = #file, line: UInt = #line) where Key.ServiceType == ServiceType {
setup { [unowned self] locator in
guard let locator = locator else {
fatalError("Not found ServiceLocator for Inject", file: file, line: line)
}
if lazy {
self.factory = { locator.getServiceAsOptional(key: key, params: params) }
} else {
self.service = locator.getServiceAsOptional(key: key, params: params)
}
}
}
public var wrappedValue: ServiceType? {
lazyInit?(nil)
if let service = self.service {
return service
} else if let service = factory?() {
self.service = service
self.factory = nil
return service
} else {
return nil
}
}
}
private protocol SLInjectBase: class {
var lazyInit: ((ServiceLocator?) -> Void)? { get set }
func setup(_ configurator: @escaping (ServiceLocator?) -> Void)
func setServiceLocator(_ locator: ServiceLocator)
}
extension SLInjectBase {
func setup(_ configurator: @escaping (ServiceLocator?) -> Void) {
if let locator = serviceLocatorShared {
configurator(locator)
} else {
self.lazyInit = configurator
lazyInjects.append(.init(inject: self))
}
}
func setServiceLocator(_ locator: ServiceLocator) {
lazyInit?(locator)
lazyInit = nil
}
}
private final class SLInjectWrapper {
weak var inject: SLInjectBase?
init(inject: SLInjectBase) {
self.inject = inject
}
}
| true
|
bdcd6fc17ce2581be2e2c5ddb4adf613a024ebe0
|
Swift
|
FFIB/leetcode
|
/leetcode/Linked List/MiddleoftheLinkedList.swift
|
UTF-8
| 1,306
| 3.59375
| 4
|
[] |
no_license
|
//
// MiddleoftheLinkedList.swift
// leetcode
//
// Created by FFIB on 2018/8/22.
// Copyright © 2018 FFIB. All rights reserved.
//
import Foundation
//876. Middle of the Linked List
/*
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
Note:
The number of nodes in the given list will be between 1 and 100.
*/
extension Solution {
func middleNode(_ head: ListNode?) -> ListNode? {
var list = head
var p = head
var count = 0
while list != nil {
count += 1
if count % 2 == 0 && count != 2 {
p = p?.next
}
list = list?.next
}
return head?.next != nil ? p?.next : p
}
}
| true
|
e6d6316b1ef49f7f40bc8f3ae6412cc88368ac09
|
Swift
|
Brightify/Reactant
|
/Source/Utils/Visibility/Visibility.swift
|
UTF-8
| 460
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
//
// Visibility.swift
// Reactant
//
// Created by Filip Dolnik on 21.11.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import Foundation
/**
* ## Visible
* View is fully visible with no modifications.
* ## Hidden
* View is not visible, but its dimensions stay the same.
* ## Collapsed
* View is not visible and is squashed on either X or Y axis.
*/
@objc
public enum Visibility: Int {
case visible
case hidden
case collapsed
}
| true
|
46bc051dac1cfd1917b8013245e3ba4a5c3ace18
|
Swift
|
gusadi09/BacaBuku
|
/BacaBuku/View/Component/Cell/BukuCell.swift
|
UTF-8
| 1,250
| 2.921875
| 3
|
[] |
no_license
|
//
// BukuCell.swift
// BacaBuku
//
// Created by Gus Adi on 24/05/21.
//
import SwiftUI
import Kingfisher
struct BukuCell: View {
var judulBuku = "test"
var coverImg = "covers%2Fada-apa-dengan-28.jpg?download=false"
var body: some View {
let url = "https://cabaca.id:8443/api/v2/files/\(coverImg)&api_key=32ded42cfffb77dee86a29f43d36a3641849d4b5904aade9a79e9aa6cd5b5948"
HStack {
KFImage(URL(string: url))
.resizable()
.loadImmediately()
.loadDiskFileSynchronously()
.cacheMemoryOnly()
.fade(duration: 0.5)
.onProgress { receivedSize, totalSize in }
.onSuccess { result in }
.onFailure { error in }
.frame(width: 80, height: 100)
.cornerRadius(15)
Text(judulBuku)
.font(.system(size: 22))
Spacer()
Image(systemName: "chevron.right")
}
.padding()
.padding(.vertical)
.background(Color(.white))
.cornerRadius(20)
.shadow(color: Color.black.opacity(0.1), radius: 10, x: 0.0, y: 4)
}
}
struct BukuCell_Previews: PreviewProvider {
static var previews: some View {
BukuCell(judulBuku: "test", coverImg: "covers%2Fada-apa-dengan-28.jpg?download=false")
}
}
| true
|
77e4327e49e9f9797a8e29cd8fbf509fdc624727
|
Swift
|
KevinNatera/Unit4Assignment2
|
/Unit4Assignment2/Views/WeatherCollectionViewCell.swift
|
UTF-8
| 720
| 2.9375
| 3
|
[] |
no_license
|
//
// WeatherCollectionViewCell.swift
// Unit4Assignment2
//
// Created by Kevin Natera on 10/9/19.
// Copyright © 2019 Kevin Natera. All rights reserved.
//
import UIKit
class WeatherCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var imageOutlet: UIImageView!
@IBOutlet weak var highLabel: UILabel!
@IBOutlet weak var lowLabel: UILabel!
func configureCell(weather: Weather ) {
highLabel.text = "High: \(weather.temperatureHigh)"
lowLabel.text = "Low: \(weather.temperatureLow)"
dateLabel.text = weather.date.replacingOccurrences(of: "-", with: " ")
imageOutlet.image = UIImage(named: weather.icon )
}
}
| true
|
fd20dded30cca81acca501401386a5a8345e1ee6
|
Swift
|
Anhtastic/CrackingTheCodingInterViewInSwift
|
/Ch2.LinkedList/P2_02_Kth_To_Last.playground/Contents.swift
|
UTF-8
| 2,937
| 4.28125
| 4
|
[] |
no_license
|
//: Playground - noun: a place where people can play
import UIKit
// Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list.
class Node<T> {
var next: Node<T>?
var value: T
init(value: T) {
self.value = value
}
var description: String {
var node: Node<T>?
node = self
var rval = "["
while node != nil {
rval += "\(node!.value) -> "
node = node?.next
}
return rval + "]"
}
}
class LinkedList<T>: CustomStringConvertible {
private var head: Node<T>?
private var last: Node<T>? {
var node = head
while node?.next != nil {
node = node?.next
}
return node
}
func insert(value: T) {
if let last = last {
last.next = Node(value: value)
} else {
head = Node(value: value)
}
}
// Recursive Soln
private func kthToLastRecursive(node: Node<T>?, k: Int, i: inout Int) -> Node<T>? {
if node == nil { return nil }
let nextNode = kthToLastRecursive(node: node?.next, k: k, i: &i)
i += 1
if i == k { return node }
return nextNode
}
func kthToLastRecursive(k: Int) -> Node<T>? {
var i = 0
return kthToLastRecursive(node: head, k: k, i: &i)
}
// Iterative Soln
func kthToLastIterative(k: Int) -> Node<T>? {
var current = head
var runner = head
for _ in 0 ..< k {
if runner == nil { return nil }
runner = runner?.next
}
while runner != nil {
current = current?.next
runner = runner?.next
}
return current
}
var description: String {
var rval = "["
var node = head
while node != nil {
rval += "\(node!.value) -> "
node = node?.next
}
return rval + "]"
}
}
let list = LinkedList<String>()
list.insert(value: "A")
list.insert(value: "B")
list.insert(value: "C")
list.insert(value: "D")
list.insert(value: "E")
list.insert(value: "F")
list.kthToLastRecursive(k: 0)?.description
list.kthToLastRecursive(k: 1)?.description
list.kthToLastRecursive(k: 2)?.description
list.kthToLastRecursive(k: 3)?.description
list.kthToLastRecursive(k: 4)?.description
list.kthToLastRecursive(k: 5)?.description
list.kthToLastRecursive(k: 6)?.description
list.kthToLastRecursive(k: 7)?.description
list.kthToLastIterative(k: 0)?.description
list.kthToLastIterative(k: 1)?.description
list.kthToLastIterative(k: 2)?.description
list.kthToLastIterative(k: 3)?.description
list.kthToLastIterative(k: 4)?.description
list.kthToLastIterative(k: 5)?.description
list.kthToLastIterative(k: 6)?.description
list.kthToLastIterative(k: 7)?.description
| true
|
c054508c56ef7d64fa01ae8805095ec82a13a7cf
|
Swift
|
NobleMat/The-Bourne-Challenge
|
/TheBourneChallenge/MovieDetail/View/MovieDetailViewController.swift
|
UTF-8
| 2,525
| 2.671875
| 3
|
[] |
no_license
|
import Kingfisher
import UIKit
final class MovieDetailViewController: UIViewController {
// MARK: - Properties
// MARK: IBOutlets
@IBOutlet private var movieImageView: UIImageView!
@IBOutlet private var movieTitleLabel: UILabel! {
didSet {
movieTitleLabel.font = .semiBoldFont(with: 21)
movieTitleLabel.addAccessibility(using: .title1)
}
}
@IBOutlet private var movieReleaseDateLabel: UILabel! {
didSet {
movieReleaseDateLabel.font = .regularFont(with: 16)
movieReleaseDateLabel.addAccessibility(using: .body)
}
}
@IBOutlet private var movieRatingLabel: UILabel! {
didSet {
movieRatingLabel.font = .lightFont(with: 16)
movieRatingLabel.addAccessibility(using: .body)
}
}
@IBOutlet private var contentView: UIView!
@IBOutlet private var imageContainerView: UIView!
// MARK: Public
var presenter: MovieDetailPresenting!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
assert(presenter != nil, "MovieDetailPresenter should be present")
view.backgroundColor = .viewBackground
contentView.backgroundColor = .cellBackground
navigationItem.largeTitleDisplayMode = .never
navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
navigationItem.leftItemsSupplementBackButton = true
presenter.displayDidLoad()
}
}
// MARK: - Conformance
// MARK: MovieDetailDisplaying
extension MovieDetailViewController: MovieDetailDisplaying {
func set(title: String) {
self.title = title
}
func set(title: String, releaseDate: String) {
movieTitleLabel.text = title
movieReleaseDateLabel.isHidden = false
movieReleaseDateLabel.text = releaseDate
}
func set(rating: String) {
movieRatingLabel.isHidden = false
movieRatingLabel.text = rating
}
func hideRating() {
movieRatingLabel.isHidden = true
}
func set(imageUrl: URL) {
imageContainerView.isHidden = false
movieImageView.kf.setImage(with: imageUrl)
}
func hideImage() {
imageContainerView.isHidden = true
}
func set(error: String) {
movieTitleLabel.text = error
[
imageContainerView,
movieRatingLabel,
movieReleaseDateLabel,
].forEach {
$0?.isHidden = true
}
}
}
| true
|
c6325f7d35a8de097e97d8796da00506d25cbbc1
|
Swift
|
Santana-Says/ios-sprint-challenge-pokedex
|
/Pokedex/Pokedex/Controllers/PokeController.swift
|
UTF-8
| 1,484
| 3.296875
| 3
|
[] |
no_license
|
//
// PokeController.swift
// Pokedex
//
// Created by Jeffrey Santana on 8/9/19.
// Copyright © 2019 Lambda. All rights reserved.
//
import Foundation
class PokeController {
private let baseURL = URL(string: "https://pokeapi.co/api/v2/")!
private(set) var myPokemon = [Pokemon]()
func add(pokemon: Pokemon) {
if !myPokemon.contains(pokemon) {
myPokemon.append(pokemon)
}
}
func removePokemon(at index: Int) {
myPokemon.remove(at: index)
}
func sortPokemon(by sorting: SortBy) {
switch sorting {
case .id:
myPokemon.sort(by: {$0.id < $1.id})
case .name:
myPokemon.sort(by: {$0.name < $1.name})
}
}
func getPokemon(by searchTerm: String, completion: @escaping (Result<Pokemon, NetworkError>) -> Void) {
let pokeURL = baseURL.appendingPathComponent("pokemon/\(searchTerm.lowercased())")
let request = URLRequest(url: pokeURL)
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
NSLog(error.localizedDescription)
completion(.failure(.other(error)))
return
}
guard let data = data else {
NSLog("Data is empty")
completion(.failure(.noData))
return
}
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let pokemon = try decoder.decode(Pokemon.self, from: data)
completion(.success(pokemon))
} catch {
NSLog("Trouble Decoding")
completion(.failure(.notDecoding))
}
}.resume()
}
}
| true
|
d1da7a546b2648caaac622b530d230d4fa6def9f
|
Swift
|
Jamaal51/SwiftProgress
|
/SwiftLearning/Lynda Exercise Files/Ch06/06-09 UsingIfCaseAndForCase.playground/Contents.swift
|
UTF-8
| 709
| 4.125
| 4
|
[] |
no_license
|
//: ## Using If-Case & For-Case
enum Number {
case Integer(Int)
case FloatingPoint(Double)
case Text(String)
}
let someNumber = Number.FloatingPoint(12.34)
switch someNumber {
case .Integer(let n):
break
case .FloatingPoint(let n):
print(n)
case .Text(let n):
break
}
let someAges: [Number] = [.Integer(19), .FloatingPoint(20.99), .Text("Twenty-something")]
for age in someAges {
switch age {
case .Integer(let a):
print(a)
default:
break
}
}
let currentVolume: Int? = 9
// Optional binding
if let volume = currentVolume where volume < 16 {
print("Turn it up!")
}
let optionalNumbers: [Number?] = [nil, .FloatingPoint(50.0), nil, .Integer(37), nil, .Integer(45)]
| true
|
b4dccf3b6b2cc7c14ac4a6ff8d89bb46af2323b8
|
Swift
|
kye007/Ricky
|
/Morty-Core/Morty/Extensions/JSONDecoder.swift
|
UTF-8
| 791
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
//
// JSONDecoder.swift
// Morty
//
// Created by George Kye on 2019-07-04.
// Copyright © 2019 georgekye. All rights reserved.
//
import Foundation
public extension JSONDecoder {
var `default`: JSONDecoder {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(Formatter.iso8601)
return decoder
}
}
extension Formatter {
static let iso8601: DateFormatter = {
//https://stackoverflow.com/a/47601082
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: .iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
return formatter
}()
}
| true
|
912a76a7db5a8bbfef01070444864e8a03007691
|
Swift
|
feidora/Arsa-MC1
|
/Arsa MC1/Main Page/BreakfastCollectionViewCell.swift
|
UTF-8
| 1,629
| 2.65625
| 3
|
[] |
no_license
|
//
// BreakfastCollectionViewCell.swift
// Arsa MC1
//
// Created by Zhafira Millenia on 12/04/20.
// Copyright © 2020 Feidora Nadia Putri. All rights reserved.
//
import UIKit
protocol MenuCellDelegate {
func didAddMenuToMainPage(menu: String)
}
class BreakfastCollectionViewCell: UICollectionViewCell {
var delegate: MenuCellDelegate?
var tipeMakanan: Makanan!
@IBOutlet weak var breakfastImage: UIImageView!
@IBOutlet weak var breakfastFoodName: UILabel!
@IBOutlet weak var breakfastFoodCalories: UILabel!
@IBOutlet weak var buttonAdd: UIButton!
@IBAction func buttonAdd(_ sender: Any) {
delegate?.didAddMenuToMainPage(menu: tipeMakanan.breakfastFoodName)
}
//
// var tipeMakanan = [Makanan]()
// var category: String = ""
//
// func initMakanan(category: Category) {
// self.navigationItem.title = category.mealsType
// tipeMakanan = getSuggestionMenu(forCategoryTitle: category.mealsType)
// self.category = category.mealsType.lowercased()
// }
//
// func getSuggestionMenu(forCategoryTitle title:String) -> [Makanan] {
// switch title {
// case "Breakfast":
// return menuPagi
// case "Lunch":
// return menuSiang
// case "Dinner":
// return menuMalam
// default:
// return menuPagi
// }
//
}
| true
|
286d2a0bb24498dbc3554105dbe5a763f3aa0c6c
|
Swift
|
niceagency/Base
|
/Base/RequestBehavior.swift
|
UTF-8
| 1,883
| 3.15625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// RequestBehavior.swift
// NABase
//
// Created by Wain on 31/01/2017.
// Copyright © 2017 Nice Agency. All rights reserved.
//
import Foundation
public protocol RequestBehavior {
func modify(urlComponents: URLComponents) -> URLComponents
func modify(planned request: URLRequest) -> URLRequest
func before(sending request: URLRequest)
func after(completion response: URLResponse?)
func after(failure: Error?, retry: () -> Void)
}
public extension RequestBehavior {
func modify(urlComponents: URLComponents) -> URLComponents { return urlComponents }
func modify(planned request: URLRequest) -> URLRequest { return request }
func before(sending: URLRequest) { }
func after(completion: URLResponse?) { }
func after(failure: Error?, retry: () -> Void) { }
func adding(_ behavior: RequestBehavior) -> RequestBehavior {
return CompositeRequestBehavior(behaviors: [self, behavior])
}
}
struct EmptyRequestBehavior: RequestBehavior {
init() {}
}
private struct CompositeRequestBehavior: RequestBehavior {
let behaviors: [RequestBehavior]
init(behaviors: [RequestBehavior]) {
self.behaviors = behaviors
}
func modify(planned request: URLRequest) -> URLRequest {
var request = request
behaviors.forEach {
request = $0.modify(planned: request)
}
return request
}
func before(sending request: URLRequest) {
behaviors.forEach {
$0.before(sending: request)
}
}
func after(completion response: URLResponse?) {
behaviors.forEach {
$0.after(completion: response)
}
}
func after(failure: Error?, retry: () -> Void) {
behaviors.forEach {
$0.after(failure: failure, retry: retry)
}
}
}
| true
|
be9d12254280c93f192994aca4c1095dd2314a44
|
Swift
|
thedonat/Songs
|
/SongBox/SongBox/Scenes/SongList/SongListContracts.swift
|
UTF-8
| 637
| 2.8125
| 3
|
[] |
no_license
|
//
// SongListContracts.swift
// SongBox
//
// Created by Burak Donat on 7.10.2020.
// Copyright © 2020 Burak Donat. All rights reserved.
//
import SongBoxAPI
protocol SongListViewModelProtocol { //view controllerin istekleri
var delegate: SongListViewModelDelegate? { get set }
func loadSongs()
func selectSong(at index: Int)
}
protocol SongListViewModelDelegate: class { //view modelden donen outputlar
func handleViewModelOutput(_ output: SongListViewModelOutput)
}
enum SongListViewModelOutput: Equatable { //view modelin outputlarini tasarliyoruz.
case updateTitle(String)
case showSongList(result: [Song])
}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.