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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e7a1e3c5a128587943bbefccb657e4cffc63cb02
|
Swift
|
JohannesGHeinke/Ruler
|
/Ruler/New World Model Test/Undirected Graph.swift
|
UTF-8
| 10,568
| 3.03125
| 3
|
[] |
no_license
|
//
// UndirectedGraph.swift
// Ruler
//
// Created by Johannes Heinke Business on 27.09.18.
// Copyright © 2018 Mikavaa. All rights reserved.
//
import Foundation
/*
internal struct UndirectedGraph<BranchValue: Equatable & AnyObject , EdgeValue: Equatable & AnyObject> {
private var branches: [(value: BranchValue, connections: [(Int, Bool)])]
private var edges = [(value: EdgeValue, first: Int, second: Int)].init()
init(firstBranchValue: BranchValue) {
self.branches = [(firstBranchValue, [(Int, Bool)].init())]
}
//: Wird ersetzt wenn branches durch B-Tree ersetzt wird --> B-Tree hat eigene Search Funktion
private func searchForBranch(with value: BranchValue) -> Int? {
return self.branches.firstIndex(where: { (branch) -> Bool in
return branch.value === value
})
}
internal mutating func insertConnection(from startValue: BranchValue, with edgeValue: EdgeValue, to endValue: BranchValue) -> UndirectedGraph? {
if let knownStart = self.searchForBranch(with: startValue) {
guard let knownEnd = self.searchForBranch(with: endValue) else {
let edgeIndex = self.edges.count
self.edges.append((edgeValue, knownStart, self.branches.count))
self.branches.append((endValue, [(edgeIndex, false)]))
self.branches[knownStart].connections.append((edgeIndex, true))
return nil
}
let edgeIndex = self.edges.count
self.branches[knownStart].connections.append((edgeIndex, true))
self.branches[knownEnd].connections.append((edgeIndex, false))
self.edges.append((edgeValue, knownStart, knownEnd))
return nil
} else {
guard let knownEnd = self.searchForBranch(with: endValue) else {
var newGraph = UndirectedGraph.init(firstBranchValue: startValue)
_ = newGraph.insertConnection(from: startValue, with: edgeValue, to: endValue)
return newGraph
}
/*
var startBranch = Branch.init(value: startValue)
let edgeIndex = self.edges.count
startBranch.connections.append((edgeIndex, true))
let edge = Edge.init(first: self.branches.count, value: edgeValue, second: knownEnd)
self.branches.append(startBranch)
self.edges.append(edge)
self.branches[knownEnd].connections.append((edgeIndex, false))*/
return nil
}
}
internal mutating func insertConnection2(from startBranch: BranchValue, with line: EdgeValue, to endBranch: BranchValue) -> UndirectedGraph2<BranchValue, EdgeValue>? {
if let knownStart = self.searchForBranch(with: startBranch) {
guard let knownEnd = self.searchForBranch(with: endBranch) else {
let endBranchIndex = self.edges.count
let edgeIndex = self.edges.count
precondition(true)
self.edges.append((line, knownStart, endBranchIndex))
self.branches[knownStart].connections.append((edgeIndex, true))
precondition(true)
self.branches.append((endBranch, [(edgeIndex, false)]))
return nil
}
let edgeIndex = self.edges.count
precondition(true)
self.edges.append((line, knownStart, knownEnd))
self.branches[knownStart].connections.append((edgeIndex, true))
self.branches[knownEnd].connections.append((edgeIndex, false))
return nil
} else {
guard let knownEnd = self.searchForBranch(with: endBranch) else {
var newGraph = UndirectedGraph2<BranchValue,EdgeValue>.init(branch: startBranch)
_ = newGraph.insertConnection(from: startBranch, with: line, to: endBranch)
return newGraph
}
let edgeIndex = self.edges.count
self.edges.append((line, self.branches.count, knownEnd))
self.branches[knownEnd].connections.append((edgeIndex, false))
self.branches.append((startBranch, [(edgeIndex, true)]))
return nil
}
}
internal struct BranchWorker {
private let branchIndex: Int
}
private struct Branch {
private let value: BranchValue
private var connections = Array<(Int, first: Bool)>.init()
/*
fileprivate static func << (lhs: Branch, rhs: Branch) -> Bool {
return lhs.value << rhs.value
}
fileprivate static func == (lhs: Branch, rhs: Branch) -> Bool {
return lhs.value === rhs.value
}*/
init(value: BranchValue) {
self.value = value
}
}
private struct Edge {
fileprivate let first: Int
fileprivate let value: EdgeValue
fileprivate let second: Int
/*
fileprivate static func << (lhs: Edge, rhs: Edge) -> Bool {
return lhs.value << rhs.value
}
fileprivate static func == (lhs: Edge, rhs: Edge) -> Bool {
return lhs.value === rhs.value
}*/
init(first: Int, value: EdgeValue, second: Int) {
self.first = first
self.value = value
self.second = second
}
}
}
*/
internal final class UndirectedGraph4<BranchValue: Equatable & AnyObject, EdgeValue: Equatable>: CustomStringConvertible {
private final var branches: [(value: BranchValue, connections: [(index: Int, first: Bool)])]
private final var edges = [(value: EdgeValue, first: Int, second: Int)].init()
internal var description: String {
return "\(self.branches[0].connections.count)"
}
init(branch: BranchValue) {
self.branches = [(branch, [(Int, Bool)].init())]
}
private final func searchForBranch(with value: BranchValue) -> Int? {
return self.branches.firstIndex(where: { (arg) -> Bool in
let (valueTmp, _) = arg
return valueTmp === value
})
}
private func searchForEdge(with check: (_ value: EdgeValue, _ first: Int, _ second: Int) -> Bool) -> Int? {
return self.edges.firstIndex(where: { (edge) -> Bool in
return check(edge.value, edge.first, edge.second)
})
}
//: Mittels FastInsert ist hier noch Luft nach oben
internal final func insertConnection(from startBranch: BranchValue, with line: EdgeValue, to endBranch: BranchValue) -> UndirectedGraph2<BranchValue, EdgeValue>? {
if let knownStart = self.searchForBranch(with: startBranch) {
guard let knownEnd = self.searchForBranch(with: endBranch) else {
let endBranchIndex = self.edges.count
let edgeIndex = self.edges.count
precondition(true)
self.edges.append((line, knownStart, endBranchIndex))
self.branches[knownStart].connections.append((edgeIndex, true))
precondition(true)
self.branches.append((endBranch, [(edgeIndex, false)]))
return nil
}
let edgeIndex = self.edges.count
precondition(true)
self.edges.append((line, knownStart, knownEnd))
self.branches[knownStart].connections.append((edgeIndex, true))
self.branches[knownEnd].connections.append((edgeIndex, false))
return nil
} else {
guard let knownEnd = self.searchForBranch(with: endBranch) else {
var newGraph = UndirectedGraph2<BranchValue,EdgeValue>.init(branch: startBranch)
_ = newGraph.insertConnection(from: startBranch, with: line, to: endBranch)
return newGraph
}
let edgeIndex = self.edges.count
self.edges.append((line, self.branches.count, knownEnd))
self.branches[knownEnd].connections.append((edgeIndex, false))
self.branches.append((startBranch, [(edgeIndex, true)]))
return nil
}
}
}
/*
internal final class UndirectedGraph<BranchValue: FastComparable, EdgeValue: FastComparable>: CustomStringConvertible {
private final var branches: ContiguousArray<(value: BranchValue, connections: ContiguousArray<(index: Int, first: Bool)>)>
private final var edges = ContiguousArray<(first: Int, value: EdgeValue, second: Int)>.init()
internal var description: String {
return "\(self.branches.count)"
}
init(firstBranchValue: BranchValue) {
self.branches = [(firstBranchValue, connections: ContiguousArray<(index: Int, first: Bool)>.init())]
}
private final func searchForBranch(with value: BranchValue) -> Int? {
return self.branches.firstIndex(where: { (branchValue, _) -> Bool in
return branchValue == value
})
}
internal final func insertConnection(from startValue: BranchValue, with edgeValue: EdgeValue, to endValue: BranchValue) -> UndirectedGraph? {
if let knownStart = self.searchForBranch(with: startValue) {
guard let knownEnd = self.searchForBranch(with: endValue) else {
let edgeIndex = self.edges.count
self.edges.append((knownStart, edgeValue, self.branches.count))
self.branches.append((endValue, [(edgeIndex, false)]))
self.branches[knownStart].connections.append((edgeIndex, true))
return nil
}
let edgeIndex = self.edges.count
self.edges.append((knownStart, edgeValue, knownEnd))
self.branches[knownEnd].connections.append((edgeIndex, false))
self.branches[knownStart].connections.append((edgeIndex, true))
return nil
} else {
guard let knownEnd = self.searchForBranch(with: endValue) else {
let newGraph = UndirectedGraph.init(firstBranchValue: startValue)
_ = newGraph.insertConnection(from: startValue, with: edgeValue, to: endValue)
return newGraph
}
let edgeIndex = self.edges.count
self.edges.append((self.branches.count, edgeValue, knownEnd))
self.branches.append((startValue, [(edgeIndex, true)]))
self.branches[knownEnd].connections.append((edgeIndex, false))
return nil
}
}
}
*/
| true
|
4dc8139a4131631ba3850d7167a8f1ea6b72732e
|
Swift
|
Pigarciag/CodingTest
|
/MyApp/src/modules/ItemDetail/ItemDetailInteractor.swift
|
UTF-8
| 1,096
| 2.515625
| 3
|
[] |
no_license
|
//
// ItemDetailInteractor.swift
// MyApp
//
// Created by Eloi Guzmán Cerón on 21/12/16.
// Copyright © 2016 Worldline. All rights reserved.
//
import Foundation
// MARK: - Protocol to be defined at Interactor
protocol ItemDetailRequestHandler: class {
// func handle______Request()
func requestPOI() -> POIEntity?
func requestPOIDetails( _ completion: @escaping ( _ entity: GetPOIEntity) -> Void)
}
class ItemDetailInteractor: NSObject, ItemDetailRequestHandler {
weak var presenter: ItemDetailResponseHandler!
let itemId: POIIdentifier
init ( _ itemId: POIIdentifier) {
self.itemId = itemId
}
// MARK: ItemDetailInteractorInterface
func requestPOI() -> POIEntity? {
let worker = SharedContainer().resolved(POIsWorker.self)
return worker.queryGetPOI(itemId)
}
func requestPOIDetails( _ completion: @escaping ( _ entity: GetPOIEntity) -> Void) {
let worker = SharedContainer().resolved(POIsWorker.self)
worker.requestGetPOI(itemId) { (entity: GetPOIEntity) in
completion(entity)
}
}
}
| true
|
6c135750c776ea62c7c3a93f21cf4b5851ce1b9e
|
Swift
|
otto-schnurr/AdventOfCode
|
/2022/Day06.swift
|
UTF-8
| 813
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env swift sh
// A solution for https://adventofcode.com/2022/day/6
//
// MIT License
// https://github.com/otto-schnurr/AdventOfCode/blob/main/LICENSE
// Copyright © 2022 Otto Schnurr
import Algorithms // https://github.com/apple/swift-algorithms
struct StandardInput: Sequence, IteratorProtocol {
func next() -> String? { return readLine() }
}
func markerEnd(for signal: String, markerLength: Int) -> Int {
return Array(signal.windows(ofCount: markerLength))
.firstIndex { Set($0).count == markerLength }! + markerLength
}
let signals = StandardInput().compactMap { $0 }
let part1 = signals.map { markerEnd(for: $0, markerLength: 4) }.reduce(0, +)
let part2 = signals.map { markerEnd(for: $0, markerLength: 14) }.reduce(0, +)
print("part 1 : \(part1)")
print("part 2 : \(part2)")
| true
|
d42bd074ebd22c3fad1de7774f9b7baa2554fcd0
|
Swift
|
dylane1/OnTheMap
|
/On The Map/Extensions.swift
|
UTF-8
| 1,927
| 3.140625
| 3
|
[] |
no_license
|
//
// Extensions.swift
// On The Map
//
// Created by Dylan Edwards on 5/25/16.
// Copyright © 2016 Slinging Pixels Media. All rights reserved.
//
import MapKit
import UIKit
//MARK: - String
extension String {
var isEmail: Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,20}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
var safariOpenableURL: URL? {
/// Remove whitespace
let trimmedString = self.trimmingCharacters( in: CharacterSet.whitespacesAndNewlines)
guard var url = URL(string: trimmedString) else {
return nil
}
/// Test for valid scheme
if !(["http", "https"].contains(url.scheme?.lowercased())) {
let appendedLink = "http://" + trimmedString
url = URL(string: appendedLink)!
}
return url
}
}
//MARK: - UIImage
extension UIImage {
enum AssetIdentifier: String {
case Map_iPhone4s, Map_iPhone5, Map_iPhone6, Map_iPhone6Plus
}
convenience init!(assetIdentifier: AssetIdentifier) {
self.init(named: assetIdentifier.rawValue)
}
}
//MARK: - Reusable Views
/**
Adapted from Natasha "The Robot"'s WWDC 2016 POP talk:
https://realm.io/news/appbuilders-natasha-muraschev-practical-protocol-oriented-programming
*/
extension UITableViewCell: ReusableView { }
extension MKAnnotationView: ReusableView { }
//MARK: - UITableView
extension UITableView {
func dequeueReusableCell<T: UITableViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = self.dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("No way, Jose... could not dequeue cell w/ identifier: \(T.reuseIdentifier)")
}
return cell
}
}
| true
|
a62a35c8cd610e7435db32d5d2fc9f6ea9f0b924
|
Swift
|
InLefter/airmaster
|
/airmaster/ChartValueFormatter.swift
|
UTF-8
| 613
| 2.578125
| 3
|
[] |
no_license
|
//
// ChartValueFormatter.swift
// airmaster
//
// Created by Howie on 2017/5/28.
// Copyright © 2017年 Howie. All rights reserved.
//
import Foundation
import Charts
public class ChartValueFormatter: NSObject, IValueFormatter {
private var mFormat: NumberFormatter!
public override init() {
mFormat = NumberFormatter()
mFormat.numberStyle = .none
}
public func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
return (mFormat.number(from: String(value))?.description)!
}
}
| true
|
4cb74adb19d8ea791637e89f736edf12bd38bb91
|
Swift
|
gravey/DataValidator
|
/DataValidator/DataValidator/Validator/Validator.swift
|
UTF-8
| 2,412
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
//
// Validatables.swift
// DataValidator
//
// Created by Richard Gravenor on 18/04/2018.
// Copyright © 2018 Luminous Squares Ltd. All rights reserved.
//
import Foundation
public protocol ValidationError: Error {}
public enum ValidationResponse {
case success
case fail
}
public protocol Validatable {
associatedtype T
typealias Validation = (T?) -> (ValidationError?)
typealias ValidationSuccess = (T?) -> ()
typealias ValidationFail = ([ValidationError]) -> ()
func validate(_ data: T?, using validations: [Validation], success: ValidationSuccess?, fail: ValidationFail?)
func validate(_ data: T?, using validation: @escaping Validation, success: ValidationSuccess?, fail: ValidationFail?)
}
public protocol ValidationPerformer {
typealias PerformanceCompletion = (ValidationResponse) -> ()
func perform(continueAfterErrors: Bool, completed: PerformanceCompletion?)
}
public class Validator<V>: Validatable, ValidationPerformer {
public typealias T = V
private typealias ValidationWrapper = () -> (ValidationResponse)
private var wrappers: [ValidationWrapper] = []
public init() {}
public func validate(_ data: V?, using validation: @escaping Validation, success: ValidationSuccess? = nil, fail: ValidationFail? = nil) {
return self.validate(data, using: [validation], success: success, fail: fail)
}
public func validate(_ data: V?, using validations: [Validation], success: ValidationSuccess? = nil, fail: ValidationFail? = nil) {
let wrapper: ValidationWrapper = {
let errors = validations.compactMap {
return $0(data)
}
guard errors.isEmpty else {
fail?(errors)
return ValidationResponse.fail
}
success?(data)
return ValidationResponse.success
}
wrappers.append(wrapper)
}
public func perform(continueAfterErrors: Bool = true, completed: PerformanceCompletion?) {
var failures: [ValidationResponse] = []
for wrapper in wrappers {
let result = wrapper()
if case ValidationResponse.fail = result {
failures.append(result)
if !continueAfterErrors {
completed?(ValidationResponse.fail)
return
}
}
}
guard failures.isEmpty else {
completed?(ValidationResponse.fail)
return
}
completed?(ValidationResponse.success)
}
}
| true
|
9d684dad486e76d4f06b7ffd440351a8f6433586
|
Swift
|
charleyfromage/mvp-demo
|
/MVP/MVP/Scenes/TeamsList/TeamsListPresenter.swift
|
UTF-8
| 1,010
| 2.53125
| 3
|
[] |
no_license
|
//
// TeamsListPresenter.swift
// MVP
//
// Created by Fromage Charley on 24/10/2019.
// Copyright © 2019 Voodoo Coding. All rights reserved.
//
import Foundation
class TeamsListPresenter: BasePresenter<TeamsListView> {
var teams = [Team]()
private let service = SportDBService()
func fetchTeams(for country: String?) {
guard let country = country, country != "" else {
teams.removeAll()
view?.updateList()
return
}
service.getTeamsList(for: country) { [weak self] teams, error in
guard let teams = teams else { return }
self?.teams = teams.list
self?.view?.updateList()
}
}
func cellSelected(for row: Int) {
let selectedTeam = teams[row]
let parameters = [TeamDetailsPresenter.teamKey: selectedTeam]
let context = RouteContext(with: parameters)
view?.openChildScreen(.teamDetailsView, fromStoryboard: .main, withContext: context)
}
}
| true
|
eae6c0fe9f0cdaeed2a4d1f5749ab8b9bc77ea2e
|
Swift
|
coxy1989/soundarama_open_source
|
/Soundarama/Soundarama/SocketEndpoint.swift
|
UTF-8
| 1,714
| 2.6875
| 3
|
[] |
no_license
|
//
// Endpoint.swift
// Soundarama
//
// Created by Jamie Cox on 25/01/2016.
// Copyright © 2016 Touchpress Ltd. All rights reserved.
//
/*
import CocoaAsyncSocket
class SocketEndpoint: NSObject, Endpoint {
//weak var connectionDelegate: ConnectableDelegate!
weak var readableDelegate: ReadableDelegate!
weak var writeableDelegate: WriteableDelegate?
static let portTCP: UInt16 = 6565
static let portUDP: UInt16 = 6568
lazy var socket: AsyncSocket = {
let s = AsyncSocket()
s.setDelegate(self)
return s
}()
}
/*
extension SocketEndpoint: Connectable {
func connect() {
/* Abstract */
assert(false, "This is an abstract method")
}
func disconnect() {
/* Abstract */
assert(false, "This is an abstract method")
}
}
*/
extension SocketEndpoint: Readable {
func readData(terminator: NSData) {
/* Abstract */
assert(false, "This is an abstract method")
}
func readData(terminator: NSData, address: Address) {
/* Abstract */
assert(false, "This is an abstract method")
}
}
extension SocketEndpoint: Writeable {
func writeData(data: NSData) {
socket.writeData(data, withTimeout: -1, tag: 0)
writeableDelegate?.didWriteData()
}
func writeData(data: NSData, address: Address) { /* Abstract */ }
}
extension SocketEndpoint: AsyncSocketDelegate {
func onSocket(sock: AsyncSocket!, didReadData data: NSData!, withTag tag: Int) {
readableDelegate.didReadData(data, address: sock.connectedHost())
}
}
*/
| true
|
d6c6a5d11b1093248c4172bff730e27f60d8b713
|
Swift
|
rolisanchez/advent-of-code-2020
|
/Day14/1-bitmask-initialization.swift
|
UTF-8
| 2,632
| 3.296875
| 3
|
[] |
no_license
|
import Foundation
let filepath = "./input.txt"
// let filepath = "./testinput.txt"
func pad(binary : String, toSize: Int) -> String {
var padded = binary
for _ in 0..<(toSize - binary.count) {
padded = "0" + padded
}
return padded
}
do {
let start = DispatchTime.now().uptimeNanoseconds
if let contents = try? String(contentsOfFile: filepath) {
let lines = contents.components(separatedBy: "\n")
var currentMask = ""
var memoryContents = [Int:Int]() // ex: memoryContents[8] = 101
for line in lines {
let lineComponents = line.components(separatedBy: "=")
let command = lineComponents[0].trimmingCharacters(in: .whitespacesAndNewlines)
let value = lineComponents[1].trimmingCharacters(in: .whitespacesAndNewlines)
if command == "mask" {
currentMask = value
} else { // ex: mem[5201]
let memAddress = Int(command.components(separatedBy: "[")[1].components(separatedBy: "]")[0])!
var binaryVal = String(Int(value)!, radix: 2)
binaryVal = pad(binary: binaryVal, toSize: 36)
// Rules:
// The current bitmask is applied to values immediately before they are written to memory:
// a 0 or 1 overwrites the corresponding bit in the value, while an X leaves the bit in the value unchanged.
// var modifiedMask = currentMask
var modifiedMask = ""
for index in 0..<currentMask.count {
let charMask = currentMask[currentMask.index(currentMask.startIndex, offsetBy: index)]
let charVal = binaryVal[binaryVal.index(binaryVal.startIndex, offsetBy: index)]
if charMask == "X" { // X leaves value unchanged
// modifiedMask[modifiedMask.index(modifiedMask.startIndex, offsetBy: index)] = charVal
modifiedMask += String(charVal)
} else {
// modifiedMask[modifiedMask.index(modifiedMask.startIndex, offsetBy: index)] = charMask
modifiedMask += String(charMask)
}
}
memoryContents[memAddress] = Int(modifiedMask, radix: 2)
}
}
print("Result: ", memoryContents.values.reduce(0){$0 + $1})
let end = DispatchTime.now().uptimeNanoseconds
print("Time elapsed: \((end-start)/1_000)μs")
} else {
fatalError("Could not open file")
}
}
| true
|
7c075f1292e234d4b1e0dfac0d7664daa2bbe27a
|
Swift
|
discobeetlesoftware/PokerKit
|
/Sources/PokerKit/Core/Evaluation/HighHandEvaluator.swift
|
UTF-8
| 2,123
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
//
// Created on 7/28/16.
//
public class HighHandEvaluator: HandEvaluator {
let configuration: HandEvaluatorConfiguration
public required init(configuration: HandEvaluatorConfiguration) {
self.configuration = configuration
}
public func evaluate(_ cards: Hand) -> HandEvaluationResult {
let model = HandEvaluationModel(withCards: cards)
var analysis = HighHandAnalysis(model)
if let result = analysis.fiveOfAKindResult() { return result }
if let result = analysis.straightFlushResult() { return result }
if let result = analysis.fourOfAKindResult() { return result }
if let result = analysis.fullHouseResult() { return result }
if let result = analysis.flushResult() { return result }
if let result = analysis.straightResult() { return result }
if let result = analysis.threeOfAKindResult() { return result }
if let result = analysis.twoPairResult() { return result }
if let result = analysis.pairResult() { return result }
return analysis.highCardResult()
}
open func evaluateHand(_ hand: Hand) -> [HandEvaluationResult] {
let model = HandEvaluationModel(withCards: hand)
var analysis = HighHandAnalysis(model)
var results: [HandEvaluationResult] = []
if let result = analysis.fiveOfAKindResult() { results.append(result) }
if let result = analysis.straightFlushResult() { results.append(result) }
if let result = analysis.fourOfAKindResult() { results.append(result) }
if let result = analysis.fullHouseResult() { results.append(result) }
if let result = analysis.flushResult() { results.append(result) }
if let result = analysis.straightResult() { results.append(result) }
if let result = analysis.threeOfAKindResult() { results.append(result) }
if let result = analysis.twoPairResult() { results.append(result) }
if let result = analysis.pairResult() { results.append(result) }
results.append(analysis.highCardResult())
return results
}
}
| true
|
ce77c43d74abc01e26f7053f383bf0a1a8400a20
|
Swift
|
mostafaelshazly9/Social-Media
|
/Social Media/Controllers/MessageManager.swift
|
UTF-8
| 2,329
| 2.859375
| 3
|
[] |
no_license
|
//
// MessageManager.swift
// Social Media
//
// Created by Mostafa Elshazly on 11/30/19.
// Copyright © 2019 Mostafa Elshazly. All rights reserved.
//
import Foundation
import Firebase
import FirebaseDatabase
let messageRef = Database.database().reference(withPath: "messages")
class MessageManager:NSObject{
class func sendMessage(to receiver:String, messageBody:String){
guard let sender = Auth.auth().currentUser?.email else { return }
let uuid = UUID().uuidString
let dict = [
"id": uuid,
"sender": sender,
"receiver":receiver,
"messageBody":messageBody,
"date": ServerValue.timestamp(),
] as [String : Any]
messageRef.child("\(Date())---\(uuid)").setValue(dict)
}
class func getMessagesBetween(_ otherPerson:String, completion: @escaping (_ messages:[Message],_ error:MessagesError?)->Void){
messageRef.observe(.value, with: { snapshot in
if snapshot.exists() == false { return }
guard let userEmail = Auth.auth().currentUser?.email else { return }
var newMessages = [Message]()
for child in snapshot.children{
let message = (child as! DataSnapshot).value as! [String: Any]
if ((message["sender"] as! String == otherPerson) &&
(message["receiver"] as! String == userEmail)) ||
((message["sender"] as! String == userEmail) &&
(message["receiver"] as! String == otherPerson))
{
let newMessage = Message(id: message["id"] as! String,
sender: message["sender"] as! String,
receiver: message["receiver"] as! String,
messageBody: message["messageBody"] as! String,
date: Double(truncating: message["date"] as! NSNumber))
newMessages.append(newMessage)
}
}
var error:MessagesError?
if newMessages.isEmpty{
error = MessagesError.noMessages
}
completion(newMessages.reversed(), error)
})
}
}
| true
|
f2e1c70a74135923222331cf1ed33ca7f52aeb7f
|
Swift
|
ShabanKamell/HandyX
|
/Data/Data/Mapper.swift
|
UTF-8
| 1,579
| 2.796875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Created by mac on 11/25/19.
// Copyright (c) 2019 sha. All rights reserved.
//
import Foundation
public protocol Mapper {
associatedtype I
associatedtype O
func map(_ input: I) -> O
}
public protocol ListMapperProtocol {
associatedtype I
associatedtype O
func map(_ input: [I]) -> [O]
}
public struct ListMapper<M: Mapper>: ListMapperProtocol {
public typealias I = M.I
public typealias O = M.O
private let mapper: M
public init(_ mapper: M) {
self.mapper = mapper
}
public func map(_ input: [M.I]) -> [M.O] {
input.map { mapper.map($0) }
}
}
public protocol NullableInputListMapperProtocol {
associatedtype I
associatedtype O
func map(_ input: [I]?) -> [O]
}
public struct NullableInputListMapper<M: Mapper>: NullableInputListMapperProtocol {
public typealias I = M.I
public typealias O = M.O
private let mapper: M
public init(_ mapper: M) {
self.mapper = mapper
}
public func map(_ input: [M.I]?) -> [M.O] {
input?.map { mapper.map($0) } ?? []
}
}
public protocol NullableOutputListMapperProtocol {
associatedtype I
associatedtype O
func map(_ input: [I]) -> [O]?
}
public struct NullableOutputListMapper<M: Mapper>: NullableOutputListMapperProtocol {
public typealias I = M.I
public typealias O = M.O
private let mapper: M
public init(_ mapper: M) {
self.mapper = mapper
}
public func map(_ input: [M.I]) -> [M.O]? {
input.isEmpty ? nil : input.map { mapper.map($0) }
}
}
| true
|
0cd01ddd38a34af09c6d59e45ef6d189eaaec4d3
|
Swift
|
krokonox/Weather-App
|
/Weather App/Views/Cells/VerticalHourlyWeatherCollectionCell.swift
|
UTF-8
| 2,638
| 2.75
| 3
|
[] |
no_license
|
//
// VerticalHourlyWeatherCollectionCell.swift
// Weather App
//
// Created by Admin on 01/06/2020.
// Copyright © 2020 Admin. All rights reserved.
//
import UIKit
import SnapKit
class VerticalHourlyWeatherCollectionCell: DataSourceCell {
lazy var hourLabel: WhiteLabel = {
let hour = WhiteLabel()
hour.font = UIFont.systemFont(ofSize: 13)
return hour
}()
lazy var temperatureLabel: WhiteLabel = {
let temperature = WhiteLabel()
temperature.font = UIFont.systemFont(ofSize: 14)
return temperature
}()
lazy var humidityLabel: WhiteLabel = {
let humidity = WhiteLabel()
humidity.font = UIFont.systemFont(ofSize: 11, weight: .light)
return humidity
}()
lazy var weatherIcon: UIImageView = {
let icon = UIImageView()
return icon
}()
override var dataSourceItem: Any? {
didSet {
guard let item = dataSourceItem as? HourlyWeatherViewModel else { return }
self.set(weather: item)
}
}
override func setupUI() {
super.setupUI()
self.addSubview(hourLabel)
self.addSubview(humidityLabel)
self.addSubview(weatherIcon)
self.addSubview(temperatureLabel)
self.setupConstraints()
}
private func setupConstraints() {
self.hourLabel.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.centerX.equalToSuperview()
// make.bottom.equalTo(humidityLabel.snp.top).offset(7)
}
self.humidityLabel.snp.makeConstraints { (make) in
make.top.equalTo(hourLabel.snp.bottom).offset(5)
// make.bottom.equalTo(weatherIcon.snp.top).offset(10)
make.centerX.equalToSuperview()
}
self.weatherIcon.snp.makeConstraints { (make) in
// make.height.width.equalTo(9)
make.top.equalTo(humidityLabel.snp.bottom).offset(15)
make.centerX.equalToSuperview()
//make.bottom.equalTo(temperatureLabel.snp.top).inset(15)
}
self.temperatureLabel.snp.makeConstraints { (make) in
//make.top.equalTo(weatherIcon.snp.bottom).offset(15)
make.centerX.equalToSuperview()
make.bottom.equalToSuperview()
}
}
private func set(weather: HourlyWeatherViewModel) {
hourLabel.text = weather.hour
temperatureLabel.text = weather.temperature
weatherIcon.image = weather.icon
humidityLabel.text = weather.humidity
}
}
| true
|
3eff50d51d5705d1c900b337cc6946e782618e78
|
Swift
|
AsioOtus/SterileCrypto
|
/SterileCrypto/SterileCrypto/Source/Math/Math.swift
|
UTF-8
| 2,875
| 3.234375
| 3
|
[] |
no_license
|
import BigInt
struct Math { }
extension Math {
struct Parameters {
static let minimalPrimeNumber = 3
static let minimalPrimeNumberSize = 2
static let theOnlyEvenPrimeNumber = 2
}
}
extension Math {
static func isCoprime (_ a: BigInt, _ b: BigInt) -> Bool {
return _isCoprime(a, b)
}
static func isCoprime (_ a: BigUInt, _ b: BigInt) -> Bool {
let a = BigInt(a)
return _isCoprime(a, b)
}
static func isCoprime (_ a: BigInt, _ b: BigUInt) -> Bool {
let b = BigInt(b)
return _isCoprime(a, b)
}
static func isCoprime (_ a: BigUInt, _ b: BigUInt) -> Bool {
let a = BigInt(a)
let b = BigInt(b)
return _isCoprime(a, b)
}
private static func _isCoprime (_ a: BigInt, _ b: BigInt) -> Bool {
let isRelativelyPrime = a.greatestCommonDivisor(with: b) == 1
return isRelativelyPrime
}
}
extension Math {
static func gcd (_ a: BigInt, _ b: BigInt) -> BigInt {
return b != 0 ? gcd(b, a % b) : a
}
static func lcm (_ a: BigInt, _ b: BigInt) -> BigInt {
return a * b / gcd(a, b)
}
static func exgcd (_ a: BigUInt, _ b: BigUInt) -> (BigUInt, BigUInt, BigUInt) {
guard b != 0 else { return (a, 1, 0) }
let (d, kA, kB) = exgcd(b, a % b)
return (d, kB, kA - kB * (a / b))
}
static func inverseElement (_ a: BigUInt, _ m: BigUInt) -> BigUInt? {
let (d, kA, _) = exgcd(a, m)
let inverseElementValue = d == 1 ? (kA % m + m) % m : nil
return inverseElementValue
}
}
extension Math {
static func generatePrimeNumber (size: UInt) throws -> BigUInt {
guard size > Parameters.minimalPrimeNumberSize else { throw Math.Errors.PrimeNumberGeneration.tooSmallBoundSize(size: size) }
let generatedNumber = generatePrimeNumber(with: { BigUInt.randomInteger(withExactWidth: Int(size)) })
return generatedNumber
}
static func generatePrimeNumber (lessThan predeterminedNumber: BigUInt) throws -> BigUInt {
guard predeterminedNumber < Parameters.minimalPrimeNumber else { throw Math.Errors.PrimeNumberGeneration.tooSmallBoundNumber(number: predeterminedNumber) }
let generatedNumber = generatePrimeNumber(with: { BigUInt.randomInteger(lessThan: predeterminedNumber) })
return generatedNumber
}
private static func generatePrimeNumber (with generationFunction: () -> (BigUInt)) -> BigUInt {
while true {
let randomNumber = generationFunction()
if isPrime(randomNumber) {
return randomNumber
}
}
}
private static func isPrime (_ number: BigUInt) -> Bool {
guard number != Parameters.theOnlyEvenPrimeNumber else { return true }
let number = number | 1
let isPrime = number.isPrime()
return isPrime
}
}
extension Math {
static func isPrimitiveRoot (_ g: BigUInt, of m: BigUInt) -> Bool {
guard g.power(m - 1, modulus: m) == 1 else { return false}
for i in 1..<(m - 1) {
guard g.power(i, modulus: m) != 1 else { return false }
}
return true
}
}
| true
|
f3832f78f8399b3dc7af6faf09bcd0bf8219c8f6
|
Swift
|
pgbo/SectionReading
|
/SectionReading/View/CircularButton.swift
|
UTF-8
| 576
| 2.84375
| 3
|
[] |
no_license
|
//
// CircularButton.swift
// SectionReading
//
// Created by guangbo on 15/11/5.
// Copyright © 2015年 pengguangbo. All rights reserved.
//
import UIKit
/// 圆形按钮
class CircularButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
let frame = self.frame
self.layer.cornerRadius = fmax(frame.width, frame.height)/2
self.layer.shadowOpacity = 0.5
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowRadius = 1.0
self.layer.masksToBounds = true
}
}
| true
|
4e5af29a462d0969b605dccc1075b38d09b1841a
|
Swift
|
gugu-wq/BeverageDB
|
/BeverageDB/View Controllers/Onboarding/Service/NavigationManager.swift
|
UTF-8
| 1,028
| 2.84375
| 3
|
[] |
no_license
|
//
// NavigationManager.swift
// BeverageDB
//
// Created by Gugu Ndaba on 2021/08/06.
//
import Foundation
import UIKit
class NavigationManager {
enum Screen {
case onboarding
case home
}
func show(screen: Screen, inController: UIViewController) {
var viewController: UIViewController!
switch screen {
case .onboarding:
viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "OnboardingVC")
case .home:
viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "HomeTabBar")
}
if let sceneDelegate = inController.view.window?.windowScene?.delegate as? SceneDelegate, let window = sceneDelegate.window {
window.rootViewController = viewController
UIView.transition(with: window, duration: 0.5, options: .transitionCrossDissolve, animations: nil, completion: nil)
}
}
}
| true
|
934c19e7315dd1c4c1d34d4996343674378b00aa
|
Swift
|
renatomateusx/Koombea-Company-Challenge
|
/KoombeaChallengeTest/Home/View/TableCells/ThreeImagesViewCell.swift
|
UTF-8
| 2,617
| 2.78125
| 3
|
[] |
no_license
|
//
// ThreeImagesViewCell.swift
// KoombeaChallengeTest
//
// Created by Renato Mateus on 27/09/21.
//
import UIKit
protocol ThreeImagesViewCellDelegate: AnyObject {
func didThreeImagesTapped(image: UIImage)
}
class ThreeImagesViewCell: UITableViewCell {
// MARK: - Identifier
static let identifier: String = "ThreeImagesViewCell"
// MARK: - Outlets
@IBOutlet weak var postDateLabel: UILabel!
@IBOutlet weak var postImageView: UIImageView!
@IBOutlet weak var firstImageView: UIImageView!
@IBOutlet weak var secondImageView: UIImageView!
// MARK: - Private Properties
weak var delegate: ThreeImagesViewCellDelegate?
private var post: Post? {
didSet {
setupData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
// MARK: - Setup Data
extension ThreeImagesViewCell {
func setupData() {
let date = Date()
if let postedDate = self.post?.date {
self.postDateLabel.text = date.getDate(dateString: postedDate)
}
if let imagePic = self.post?.pics[0],
let url = URL(string: imagePic) {
self.postImageView.kf.setImage(with: url)
self.configureImageTapped(self.postImageView)
}
if let imagePic2 = self.post?.pics[2],
let url = URL(string: imagePic2) {
self.firstImageView.kf.setImage(with: url)
self.configureImageTapped(self.firstImageView)
}
if let imagePic3 = self.post?.pics[2],
let url = URL(string: imagePic3) {
self.secondImageView.kf.setImage(with: url)
self.configureImageTapped(self.secondImageView)
}
}
}
// MARK: - Cell Configuration
extension ThreeImagesViewCell {
func configure(with post: Post) {
self.post = post
}
func configureImageTapped(_ imageView: UIImageView) {
let tap = UITapGestureRecognizer(target: self,
action: #selector(didTappedImage(tapGesture:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tap)
}
}
// MARK: - Actions
extension ThreeImagesViewCell {
@objc func didTappedImage(tapGesture: UITapGestureRecognizer) {
let imageView = tapGesture.view as! UIImageView
if let image = imageView.image {
self.delegate?.didThreeImagesTapped(image: image)
}
}
}
| true
|
ec4fd9c785ec9f54eb6eaf60301fe7a9c244e101
|
Swift
|
kcamp92/Foursquare-Map-Project
|
/Foursquare-Map-Project/Views/listCell.swift
|
UTF-8
| 3,422
| 2.59375
| 3
|
[] |
no_license
|
//
// listCell.swift
// Foursquare-Map-Project
//
// Created by Krystal Campbell on 11/12/19.
// Copyright © 2019 Krystal Campbell. All rights reserved.
//
import UIKit
class listCell: UITableViewCell {
lazy var foodCatImage: UIImageView = {
let iv = UIImageView()
iv.clipsToBounds = true
iv.contentMode = .scaleToFill
iv.backgroundColor = .systemIndigo
return iv
}()
lazy var venueLabel:UILabel = {
let label = UILabel()
label.textAlignment = .center
label.font = UIFont(name: "Marker Felt", size: 20.0)
label.textColor = .black
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.layer.cornerRadius = 20
// label.isHidden = true
label.backgroundColor = .clear
return label
}()
lazy var catLabel:UILabel = {
let label = UILabel()
label.textAlignment = .center
label.font = UIFont(name: "Marker Felt", size: 20.0)
label.textColor = .black
label.textAlignment = .center
label.adjustsFontSizeToFitWidth = true
label.layer.cornerRadius = 20
//label.isHidden = true
label.backgroundColor = .clear
return label
}()
// MARK: - Initializers
override func awakeFromNib() {
super.awakeFromNib()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style:style, reuseIdentifier: reuseIdentifier)
addSubviews()
setupConstraints()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Private Methods
private func addSubviews() {
contentView.addSubview(foodCatImage)
contentView.addSubview(venueLabel)
contentView.addSubview(catLabel)
}
private func setupConstraints() {
foodCatImage.translatesAutoresizingMaskIntoConstraints = false
foodCatImage.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = true
foodCatImage.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 5).isActive = true
foodCatImage.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -5).isActive = true
foodCatImage.widthAnchor.constraint(equalTo: self.foodCatImage.heightAnchor).isActive = true
venueLabel.translatesAutoresizingMaskIntoConstraints = false
venueLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true
venueLabel.leadingAnchor.constraint(equalTo: self.foodCatImage.trailingAnchor, constant: 10).isActive = true
venueLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true
venueLabel.widthAnchor.constraint(equalToConstant: 200).isActive = true
catLabel.translatesAutoresizingMaskIntoConstraints = false
catLabel.topAnchor.constraint(equalTo: venueLabel.bottomAnchor, constant: 10).isActive = true
catLabel.leadingAnchor.constraint(equalTo: self.foodCatImage.trailingAnchor, constant: 10).isActive = true
catLabel.heightAnchor.constraint(equalTo: self.venueLabel.heightAnchor).isActive = true
catLabel.widthAnchor.constraint(equalTo: self.venueLabel.widthAnchor).isActive = true
}
}
| true
|
b3eee8797979120255bfdbe7016580042df4143b
|
Swift
|
Modeso/ModesoWheel
|
/ModesoWheel/ModesoWheel/Sources/UIView+Extension.swift
|
UTF-8
| 711
| 2.59375
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// UIView+Extension.swift
// Break Even
//
// Created by Reem Hesham on 12/18/17.
// Copyright © 2017 Modeso. All rights reserved.
//
import UIKit
extension UIView {
/** LoadFromNib Method
Load the UIView from the .xib file using the Bundle and nib name
*/
@discardableResult func loadFromNib < T: UIView >() -> T? {
guard let view = Bundle(for: self.classForCoder).loadNibNamed(String(describing: type(of: self)), owner: self, options: nil)?[0] as? T else {
return nil
}
view.frame = bounds
self.addSubview(view)
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
return view
}
}
| true
|
a312dedb246f003c9ecdf8855e1ea819d492cd18
|
Swift
|
sanjib/On-the-Map
|
/On The Map/Models/AllStudents.swift
|
UTF-8
| 1,501
| 2.921875
| 3
|
[] |
no_license
|
//
// AllStudents.swift
// On The Map
//
// Created by Sanjib Ahmad on 6/10/15.
// Copyright (c) 2015 Object Coder. All rights reserved.
//
import Foundation
class AllStudents: NSObject {
static var collection = [Student]()
static var reloadInProgress = false
static func reload(completionHandler: (errorString: String?) -> Void) {
reloadInProgress = true
// Stop all NSURLSession tasks
NSURLSession.sharedSession().getTasksWithCompletionHandler() { dataTasks, uploadTasks, downloadTasks in
for dataTask in dataTasks {
dataTask.cancel()
}
}
NSURLSession.sharedSession().invalidateAndCancel()
collection = [Student]()
ParseClient.sharedInstance().getStudentLocations() { students, errorString in
if errorString != nil {
completionHandler(errorString: errorString)
} else {
self.collection = students!
self.sortByFirstName()
self.reloadInProgress = false
completionHandler(errorString: nil)
}
}
}
static func addStudent(student: Student) {
collection.append(student)
sortByFirstName()
}
// Should be reset when user logs out
static func reset() {
collection = [Student]()
}
private static func sortByFirstName() {
collection.sortInPlace({ $0.firstName < $1.firstName })
}
}
| true
|
6e4ba968953a2ca0a531bcabfa0156df434313e8
|
Swift
|
DiwakarThapa/swift-tutorials
|
/API TableView /API TableView Call.swift
|
UTF-8
| 3,464
| 3.46875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Simple URL Session call to update a TableView from the Swapi.co api
//
// Created by Laurie Gray on 02/08/2017.
import UIKit
class ViewController: UITableViewController {
// Tweak this URL for lots of different fun results
let url: String = "https://swapi.co/api/people/1/"
// Declare an array upfront - it could hold anthying: Int, String, Arrays or Dictionaries
var filmArray:[String] = []
override func viewDidLoad() {
super.viewDidLoad()
// You need to register a cell class to work with custom cells
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
// Don't forget to notify the tableView we'll provide the data and delegate method implementations
tableView.delegate = self
tableView.dataSource = self
// Get 'dat DATA!
loadAPIData(fromURL: url)
}
// We'll take a String for convenience
func loadAPIData(fromURL url:String) {
// Cast the String to a URL
guard let URL = URL(string: url) else {
print("Sort your URL String")
return
}
// 3 things - Request, Config, Session
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration)
let request = URLRequest(url: URL)
//Perform the data task and connect to the web
let dataTask = session.dataTask(with: request) { (data, response, error) in
// This can fail so we need to use a do-catch block
do {
if let data = data {
// Cast the result as ["x":Int, "y":[String], "z":[String:Int]]
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any]
// Itterate and append to the array
if let films = json!["films"] as? [String] {
for film in films {
self.filmArray.append(film)
}
}
}
// Upload the tableView with new data as by this point it thinks it has loaded all of the data
// Do it asynchronously
DispatchQueue.main.async {
self.tableView.reloadData()
}
} catch let error {
print(error.localizedDescription)
}
}
// URLSession Tasks are initialised in a paused state by default, so let us begin...
dataTask.resume()
}
}
// MARK: TableView delegate method implementation
extension ViewController {
// How many sections will there be?
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// How many rows in each section?
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filmArray.count
}
// Get the cell ready, prepped and dislaying
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = filmArray[indexPath.row]
return cell
}
}
| true
|
58e96ac33c864fe692ef6cd62cce2b3588455c29
|
Swift
|
DangTrungdev113999/learn-swiftUi
|
/Swift/OptionalChanning.swift
|
UTF-8
| 501
| 3.5625
| 4
|
[] |
no_license
|
class User {
var name: String
var readingBook: Book?
int(name: String) {
self.name = name
}
}
class Book {
var numberOfPages = 1000
}
var mrTrung = User(name: "Dang The Trung")
mrTrung.readingBook = Book()
if let numberOfPages = mrTrung.readingBook?.numberOfPages {
print("Book of ")
} else {
print("Failded to get number of page")
}
var testScores = [
"Hoang" : [60, 70, 80],
"Alex" : [79, 94, 81]
]
testScores["Hoang"]?[0] = 99
testScores["Alex"]?[0] += 1
| true
|
0ff2639c34b0e2ebde55adc26b75f324f97ad50f
|
Swift
|
musyasyugyo/SelfStudy
|
/algorithm/algorithm/src/controller/Business/BusinessInformationView.swift
|
UTF-8
| 5,205
| 2.875
| 3
|
[] |
no_license
|
//
// BusinessInformationView.swift
// algorithm
//
// Created by Minako Tanaka on 2021/03/21.
//
import UIKit
protocol MainViewDelegate: class {
}
class BusinessInformationView: UIView{
//MARK: delegate
public weak var delegate: MainViewDelegate? = nil
//-------------------------------------------------------------//
// MARK: 変数定義
//-------------------------------------------------------------//
@IBOutlet weak var mainScrollView: UIScrollView!
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var businessLabel: UITextView!
@IBOutlet weak var pagingScrollView: UIScrollView!
// 1. ページ数
let pageCount = 3
// 3. StackViewの作成
let contentView = UIStackView()
let businessImage = ["Software", "Hardware", "Substrate"]
let business: [String] = ["software".localized, "hardware".localized, "substrate".localized]
let businessOverview: [String] = ["softwareOverview".localized, "hardwareOverview".localized, "substrateOverview".localized]
//-------------------------------------------------------------//
// MARK: ライフサイクル
//-------------------------------------------------------------//
override init(frame: CGRect) {
super.init(frame: frame)
self.loadNib()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
self.loadNib()
}
func loadNib() {
guard let view = Bundle.main.loadNibNamed("BusinessInformationView", owner: self, options: nil)?.first as? UIView else {
return
}
view.frame = self.frame
self.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
let views = ["subView": view]
self.addConstraints (
NSLayoutConstraint.constraints(
withVisualFormat: "V:|[subView]|",
options:NSLayoutConstraint.FormatOptions(rawValue: 0),
metrics: nil,
views: views
)
)
self.addConstraints (
NSLayoutConstraint.constraints(
withVisualFormat: "H:|[subView]|",
options:NSLayoutConstraint.FormatOptions(rawValue: 0),
metrics: nil,
views: views
)
)
//init
self.initialize()
}
//-------------------------------------------------------------//
// MARK: init
//-------------------------------------------------------------//
private func initialize() {
//初期化処理
self.contentViewLoad()
}
//-------------------------------------------------------------//
// MARK: functions
//-------------------------------------------------------------//
func contentViewLoad() {
// 3.
//以下のようにすると横向きのページングとして使用することができ、追加されたページのレイアウトもStack Viewが揃えてくれる
// 以下のプロパティの説明は、https://qiita.com/tasanobu/items/6908c956b758547ccf6c を参照
contentView.spacing = 0.0
contentView.axis = .horizontal
contentView.alignment = .fill
contentView.distribution = .fillEqually
pagingScrollView.addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
// Top Bottom Leading TrailingはすべてScroll Viewに合わせる
contentView.topAnchor.constraint(equalTo: pagingScrollView.topAnchor),
contentView.leadingAnchor.constraint(equalTo: pagingScrollView.leadingAnchor),
contentView.bottomAnchor.constraint(equalTo: pagingScrollView.bottomAnchor),
contentView.trailingAnchor.constraint(equalTo: pagingScrollView.trailingAnchor),
// HeightはpagingScrollViewに合わせる。
contentView.heightAnchor.constraint(equalTo: pagingScrollView.heightAnchor),
// WidthはpagingScrollView.widthAnchor x ページ数
contentView.widthAnchor.constraint(equalTo: pagingScrollView.widthAnchor, multiplier: CGFloat(pageCount))
])
let businessDataArray: [[String]] = [
["1", "software".localized, "softwareOverview".localized],
["2", "hardware".localized, "hardwareOverview".localized],
["3", "substrate".localized, "substrateOverview".localized],
]
let firstView = InfoContents(businessDataArray: businessDataArray[0])
// Stack Viewへの追加なのでaddArrangedSubview
contentView.addArrangedSubview(firstView)
let secondView = InfoContents(businessDataArray: businessDataArray[1])
contentView.addArrangedSubview(secondView)
let therdView = InfoContents(businessDataArray: businessDataArray[2])
contentView.addArrangedSubview(therdView)
}
//-------------------------------------------------------------//
// MARK: delegate
//-------------------------------------------------------------//
}
| true
|
7412d2243f9f413829ecb59eedacb61708c214ee
|
Swift
|
QKKQQK/Yatzee-Dice
|
/YaDice/ForceTouchGestureRecongnizer.swift
|
UTF-8
| 1,743
| 2.796875
| 3
|
[] |
no_license
|
//
// forceTouchGestureRecongnizer.swift
// YaDice
//
// Created by Qiankang Zhou on 7/27/17.
// Copyright © 2017 Qiankang Zhou. All rights reserved.
//
import UIKit.UIGestureRecognizerSubclass
class ForceTouchGestureRecognizer: UIGestureRecognizer {
let threshold: CGFloat
private var forceTouch: Bool = false
init(target: AnyObject?, action: Selector, threshold: CGFloat) {
self.threshold = threshold
super.init(target: target, action: action)
}
override func touchesBegan(_ touches: Set<UITouch>, with: UIEvent)
{
if let touch = touches.first
{
handleTouch(touch: touch)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with: UIEvent)
{
if let touch = touches.first
{
handleTouch(touch: touch)
}
}
override func touchesEnded(_ touches: Set<UITouch>, with: UIEvent)
{
super.touchesEnded(touches, with: with)
state = self.forceTouch ? UIGestureRecognizerState.ended : UIGestureRecognizerState.failed
self.forceTouch = false
}
private func handleTouch(touch: UITouch)
{
guard touch.force != 0 && touch.maximumPossibleForce != 0 else
{
return
}
if !self.forceTouch && (touch.force / touch.maximumPossibleForce) >= self.threshold
{
state = UIGestureRecognizerState.began
self.forceTouch = true
}
else if self.forceTouch && (touch.force / touch.maximumPossibleForce) < self.threshold
{
state = UIGestureRecognizerState.ended
self.forceTouch = false
}
}
}
| true
|
4c6b8b00b139a0c31f18fdd6bc0eef8387248599
|
Swift
|
Catterwaul/HemiprocneMystacea
|
/Sources/HM/Swift/extension/Collection/Type-erased/AnyIterator.swift
|
UTF-8
| 631
| 3.203125
| 3
|
[] |
no_license
|
public extension AnyIterator {
/// Use when `AnyIterator` is required / `UnfoldSequence` can't be used.
init<State>(
state: State,
_ getNext: @escaping (inout State) -> Element?
) {
var state = state
self.init { getNext(&state) }
}
/// Process iterations with a closure.
/// - Parameters:
/// - processNext: Executes with every iteration.
init(
_ sequence: some Sequence<Element>,
processNext: @escaping (Element?) -> Void
) {
self.init(state: sequence.makeIterator()) { iterator -> Element? in
let next = iterator.next()
processNext(next)
return next
}
}
}
| true
|
e8b0b7d0f91212f1404b67abaf429cb287fb322d
|
Swift
|
RudenkoElizabeth/pw-application
|
/pw-application/View/LoginViewController.swift
|
UTF-8
| 1,752
| 2.53125
| 3
|
[] |
no_license
|
//
// LoginViewController.swift
// pw-application
//
// Created by Elizabeth Rudenko on 29.03.2018.
// Copyright © 2018 Elizabeth Rudenko. All rights reserved.
//
import UIKit
import MBProgressHUD
class LoginViewController: UIViewController, UITextFieldDelegate {
//UI elements
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var registrationButton: UIButton!
let viewModel = AuthViewModel()
override func viewDidLoad() {
super.viewDidLoad()
viewModel.delegate = self
//set keyboard type
emailTextField.keyboardType = UIKeyboardType.emailAddress
}
//return button on keyboard
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
emailTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
return true
}
@IBAction func loginButtonTapped() {
guard let email = emailTextField.text,
let password = passwordTextField.text else { return }
//wait for response
MBProgressHUD.showAdded(to: self.view, animated: true)
viewModel.tryAuthBy(email: email, andPassword: password)
}
}
extension LoginViewController: AuthViewModelDelegate {
func succeessAuth() {
MBProgressHUD.hide(for: self.view, animated: true)
//open profile view controller
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.setViewController()
}
func errorAuth(_ errorText: String) {
MBProgressHUD.hide(for: self.view, animated: true)
AlertHelper().messageAlert(stringMessage: errorText, vc: self)
}
}
| true
|
5369037823cfb662982fce6bbf4f8e983e59871c
|
Swift
|
klee8880/GarageMaster
|
/GarageMaster/Views/FuelingViewController.swift
|
UTF-8
| 4,309
| 2.734375
| 3
|
[] |
no_license
|
//
// FuelingViewController.swift
// GarageMaster
//
// Created by Steven Lee on 3/3/20.
// Copyright © 2020 Kevin Lee. All rights reserved.
//
import UIKit
//MARK: - Table Cell
class UIFuelingCell: UITableViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var costLabel: UILabel!
@IBOutlet weak var volumeLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
class FuelingViewController: UITableViewController {
var detail: VehicleData?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int { return 1 }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let detail = self.detail { return detail.fueling.count }
else{ return 0 }
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "fuelingData", for: indexPath) as! UIFuelingCell
// Configure the cell...
if let fueling = self.detail?.fueling[indexPath.row] {
if let price = fueling.price{
cell.costLabel.text = "$\(price)"
}
if let date = fueling.date{
let df = DateFormatter()
df.dateFormat = "dd/mm/yy"
cell.dateLabel.text = df.string(for: date)
}
if let volume = fueling.volume{
var tag = ""
switch detail!.type{
case.petroleum:
tag = "Gal"
break;
case.diesel:
tag = "Gal"
break;
case.electric:
tag = "Mwh"
break;
default:
break;
}
cell.volumeLabel.text = "\(volume) " + tag
}
}
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
1fdc0586d7481b1e95663f4ca079c6eda42f9960
|
Swift
|
sassiwalid/femininbio
|
/FeminBio/Controllers/ArticlesDetailsViewControllers.swift
|
UTF-8
| 1,841
| 2.90625
| 3
|
[] |
no_license
|
//
// ArticlesDetailsViewControllers.swift
// FeminBio
//
// Created by Walid Sassi on 10/02/2018.
// Copyright © 2018 Walid Sassi. All rights reserved.
//
import UIKit
import Alamofire
class ArticlesDetailsViewControllers: UIViewController {
var article: Article? = nil
//MARK: Outlets
@IBOutlet weak var articleDateLabel: UILabel!
@IBOutlet weak var articleAuthorLabel: UILabel!
@IBOutlet weak var articleDetailsLabel: UILabel!
@IBOutlet weak var articleTitleLabel: UILabel!
@IBOutlet weak var ArticleImageView: UIImageView!
convenience init (article:Article){
self.init()
self.article = article
}
override func viewDidLoad() {
super.viewDidLoad()
initData()
DownloadImage(imageLink: (self.article?.image.link)!)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func initData(){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-YYYY"
dateFormatter.locale = Locale(identifier: "fr_FR")
dateFormatter.timeStyle = DateFormatter.Style.none
dateFormatter.dateStyle = DateFormatter.Style.medium
self.articleDateLabel.text = dateFormatter.string(from: (article?.date)!)
self.articleAuthorLabel.text = article?.author.name
self.articleTitleLabel.text = article?.title
self.articleDetailsLabel.text = article?.description
}
func DownloadImage(imageLink:String){
Alamofire.request(imageLink)
.response { response in
guard let imageData = response.data else {
print("Could not get image from image URL returned in search results")
return
}
self.ArticleImageView.image = UIImage(data: imageData)
}
}
}
| true
|
3076399082cfc190c12fbef33d9bf8f4a9416471
|
Swift
|
bsniped/TestGitHubProduce
|
/TestGitHubProduce/ViewController.swift
|
UTF-8
| 957
| 2.75
| 3
|
[] |
no_license
|
//
// ViewController.swift
// TestGitHubProduce
//
// Created by Tyler Boston on 5/1/21.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
func printFromF1() {
print("Hello World, this is code from a featurebranch")
print("Modifications by SomeRando22@hotmail.com")
print("Modification by who? w/o conflicting code")
print("modification by Tylyr w/o conflicting code x 2, also a new addition to this line as referenced in line 19 ")
print("last modification by Tyler w/ conflicting code on line 17 and 18")
}
func printFromF2() {
print("Hello Ya Filthy Animals, this is code from F2 that will be merged into the mainline, and merged into featurebranch1 to determine what it's like to work side by side with continuous integrators")
}
}
}
| true
|
0c75c6efadd8b8977e461292b9179946edc8ef4f
|
Swift
|
udotneb/GymMe
|
/GymMe/Create Workout/LogWorkout/ExcerciseView.swift
|
UTF-8
| 6,761
| 2.671875
| 3
|
[] |
no_license
|
//
// ExcerciseView.swift
// GymMe
//
// Created by Benjamin Ulrich on 10/22/19.
// Copyright © 2019 Benjamin Ulrich. All rights reserved.
//
import UIKit
class ExcerciseView: UIView {
private var excerciseName: String
// sizing constants
private let excerciseNameLabelHeight = 25
private let excerciseSetNamesViewHeight = 25
private let excerciseSetViewHeight = 40
private let addSetButtonHeight = 40
// view components
private let excerciseSetNamesView = ExcerciseSetNamesView()
private var excerciseSetViewLst: [ExcercseSetView] = [ExcercseSetView(setNumber: 1)]
private let addSetButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: #selector(addSetButtonPressed), for: .touchUpInside)
button.backgroundColor = .clear
button.setTitleColor(.black, for: .normal)
button.setTitle("+ Add Set", for: .normal)
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor
return button
}()
private let excerciseNameLabel: UILabel = {
let label = UILabel()
label.textColor = UIColor(red:0.20, green:0.60, blue:0.86, alpha:1.0)
return label
}()
private var constraintLst: [NSLayoutConstraint] = [] // for updateAnchors
init(excerciseName: String) {
self.excerciseName = excerciseName
super.init(frame: UIScreen.main.bounds)
excerciseNameLabel.text = self.excerciseName
updateAnchors()
}
private func updateAnchors() {
// Removes all constraints, then re adds them, also updates this views heightAnchor
// Use: Adding and removing excercise sets requires breaking constraints and then readding them in another order
// deactivate all constraints
for constraint in constraintLst {
constraint.isActive = false
}
constraintLst = []
// add all new constraints to constraintLst
if !excerciseNameLabel.isDescendant(of: self) {
self.addSubview(excerciseNameLabel)
}
excerciseNameLabel.translatesAutoresizingMaskIntoConstraints = false
constraintLst.append(excerciseNameLabel.leftAnchor.constraint(equalTo: self.leftAnchor))
constraintLst.append(excerciseNameLabel.topAnchor.constraint(equalTo: self.topAnchor))
constraintLst.append(excerciseNameLabel.rightAnchor.constraint(equalTo: self.rightAnchor))
constraintLst.append(excerciseNameLabel.heightAnchor.constraint(equalToConstant: CGFloat(excerciseNameLabelHeight)))
if !excerciseSetNamesView.isDescendant(of: self) {
self.addSubview(excerciseSetNamesView)
}
excerciseSetNamesView.translatesAutoresizingMaskIntoConstraints = false
constraintLst.append(excerciseSetNamesView.topAnchor.constraint(equalTo: excerciseNameLabel.bottomAnchor, constant: 10))
constraintLst.append(excerciseSetNamesView.leftAnchor.constraint(equalTo: self.leftAnchor))
constraintLst.append(excerciseSetNamesView.rightAnchor.constraint(equalTo: self.rightAnchor))
constraintLst.append(excerciseSetNamesView.heightAnchor.constraint(equalToConstant: CGFloat(excerciseSetNamesViewHeight)))
for i in 0..<excerciseSetViewLst.count {
let workoutSet = excerciseSetViewLst[i]
workoutSet.translatesAutoresizingMaskIntoConstraints = false
if !workoutSet.isDescendant(of: self) {
self.addSubview(workoutSet)
}
if i == 0 { // set to excerciseSetNamesView
constraintLst.append(workoutSet.topAnchor.constraint(equalTo: excerciseSetNamesView.bottomAnchor))
} else { // set to previous excerciseSetView
constraintLst.append(workoutSet.topAnchor.constraint(equalTo: excerciseSetViewLst[i-1].bottomAnchor, constant:5))
}
constraintLst.append(workoutSet.leftAnchor.constraint(equalTo: self.leftAnchor))
constraintLst.append(workoutSet.rightAnchor.constraint(equalTo: self.rightAnchor))
constraintLst.append(workoutSet.heightAnchor.constraint(equalToConstant: CGFloat(excerciseSetViewHeight)))
}
if !addSetButton.isDescendant(of: self) {
self.addSubview(addSetButton)
}
addSetButton.translatesAutoresizingMaskIntoConstraints = false
constraintLst.append(addSetButton.topAnchor.constraint(equalTo: excerciseSetViewLst[excerciseSetViewLst.count - 1].bottomAnchor, constant: 10))
constraintLst.append(addSetButton.leftAnchor.constraint(equalTo: self.leftAnchor))
constraintLst.append(addSetButton.rightAnchor.constraint(equalTo: self.rightAnchor))
constraintLst.append(addSetButton.heightAnchor.constraint(equalToConstant: CGFloat(addSetButtonHeight)))
// add new height constraint
let newHeight = excerciseNameLabelHeight + excerciseSetNamesViewHeight + excerciseSetViewLst.count * (excerciseSetViewHeight + 5) + addSetButtonHeight + 20
constraintLst.append(self.heightAnchor.constraint(equalToConstant: CGFloat(newHeight)))
// activate all constraints
for constraint in constraintLst {
constraint.isActive = true
}
}
@objc private func addSetButtonPressed(sender: UIButton!) {
addNewSet()
}
private func addNewSet() {
// adds a new ExcerciseSetView to the UI, copys over the previous weight and reps
// excerciseSetViewLst must always be atleast length one
let previousWeight = excerciseSetViewLst[excerciseSetViewLst.count - 1].getWeight()
let previousReps = excerciseSetViewLst[excerciseSetViewLst.count - 1].getReps()
let newWorkoutSet = ExcercseSetView(setNumber: excerciseSetViewLst.count + 1,
previousWeight: previousWeight,
previousReps: previousReps)
excerciseSetViewLst.append(newWorkoutSet)
updateAnchors()
}
required init?(coder aDecoder: NSCoder) {
self.excerciseName = ""
super.init(coder: aDecoder)
}
func getExcerciseStruct() -> Excercise? {
var lstSets: [ExcerciseSet] = []
for w in excerciseSetViewLst {
if let excerciseSet = w.getExcerciseSetStruct() {
lstSets.append(excerciseSet)
}
}
if lstSets.count > 0 {
return Excercise(lstSets: lstSets,
excerciseName: self.excerciseName)
}
return nil
}
}
| true
|
c592983d9ebb8f54d9c1bad88b1191653030629e
|
Swift
|
LesC1210/ParseChat
|
/ParseChat/ChatViewController.swift
|
UTF-8
| 3,568
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// ChatViewController.swift
// ParseChat
//
// Created by Leslie on 10/24/18.
// Copyright © 2018 Leslie . All rights reserved.
//
import UIKit
import Parse
class ChatViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var chatTableView: UITableView!
@IBOutlet weak var messageTextField: UITextField!
var messages: [PFObject]?
@IBAction func onSend(_ sender: Any) {
let message = PFObject(className: "Message")
print ("sending message")
print (messageTextField.text ?? "Nothing")
if messageTextField.text != "" {
message["text"] = messageTextField.text
message["user"] = PFUser.current()
message.saveInBackground(block: {(success: Bool?, error: Error?) in
if success == true {
print ("message sent")
}
else {
print ("message not sent")
}
})
}
messageTextField.text = ""
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let message = self.messages {
return message.count
}
return 0
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
chatTableView.delegate = self
chatTableView.dataSource = self
// Auto size row height based on cell autolayout constraints
chatTableView.rowHeight = UITableView.automaticDimension
// Provide an estimated row height. Used for calculating scroll indicator
chatTableView.estimatedRowHeight = 50
//chatTableView.separatorStyle = .none
Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ChatViewController.onTimer), userInfo: nil, repeats: true)
}
@objc func onTimer() {
let query = PFQuery(className:"Message")
query.whereKeyExists("text").includeKey("user")
query.order(byDescending: "createdAt")
query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) -> Void in
if error == nil {
// The find succeeded.
self.messages = objects
self.chatTableView.reloadData()
} else {
// Log details of the failure
print("<><><><>Error: \(error?.localizedDescription)")
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ChatCell", for: indexPath) as! ChatCell
cell.messages = (self.messages?[indexPath.row])!
if let user = cell.messages["user"] as? PFUser {
// User found! update username label with username
cell.userLabel.text = user.username
} else {
// No user found, set default username
cell.userLabel.text = "🤖"
}
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
| true
|
d3bedb56feb580343da01c815a3c35a0b271992d
|
Swift
|
pavangandhi/iOS-8-Swift-Programming
|
/chapter-cloud/Creating and Managing Folders for Apps in iCloud/Creating and Managing Folders for Apps in iCloud/AppDelegate.swift
|
UTF-8
| 5,199
| 3.125
| 3
|
[] |
no_license
|
//
// AppDelegate.swift
// Creating and Managing Folders for Apps in iCloud
//
// Created by Vandad Nahavandipoor on 7/11/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at vandad.np@gmail.com
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
/* 1 */
//import UIKit
//
//@UIApplicationMain
//class AppDelegate: UIResponder, UIApplicationDelegate {
//
// var window: UIWindow?
// let fileManager = NSFileManager()
// var documentsDirectory: String?
//
// func doesDocumentsDirectoryExist() -> Bool{
// var isDirectory = false as ObjCBool
//
// if let directory = documentsDirectory{
// if fileManager.fileExistsAtPath(directory,
// isDirectory: &isDirectory){
// if isDirectory{
// return true
// }
// }
// }
//
// return false
// }
//
// func createDocumentsDirectory(){
// print("Must create the directory.")
//
// var directoryCreationError: NSError?
//
// if let directory = documentsDirectory{
// do {
// try fileManager.createDirectoryAtPath(directory,
// withIntermediateDirectories:true,
// attributes:nil)
// print("Successfully created the folder")
// } catch let error1 as NSError {
// directoryCreationError = error1
// if let error = directoryCreationError{
// print("Failed to create the folder with error = \(error)")
// }
// }
// } else {
// print("The directory was nil")
// }
//
// }
//
// func application(application: UIApplication,
// didFinishLaunchingWithOptions launchOptions:
// [NSObject : AnyObject]?) -> Bool {
//
// let containerURL =
// fileManager.URLForUbiquityContainerIdentifier(nil)
//
// documentsDirectory =
// containerURL!.path!.stringByAppendingPathComponent("Documents")
//
// if doesDocumentsDirectoryExist(){
// print("This folder already exists.")
// } else {
// createDocumentsDirectory()
// }
//
// return true
// }
//
//}
//
/* 2 */
import UIKit
import CloudKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let fileManager = NSFileManager()
var documentsDirectory: String?
func storeFile(){
print("Storing a file in the directory...")
if let _ = documentsDirectory{
let path =
documentsDirectory!.stringByAppendingPathComponent("File.txt")
var writingError: NSError?
do {
try "Hello, World!".writeToFile(path,
atomically: true,
encoding: NSUTF8StringEncoding)
print("Successfully saved the file")
} catch let error1 as NSError {
writingError = error1
if let error = writingError{
print("An error occurred while writing the file = \(error)")
}
}
} else {
print("The directory was nil")
}
}
func doesDocumentsDirectoryExist() -> Bool{
var isDirectory = false as ObjCBool
if let directory = documentsDirectory{
if fileManager.fileExistsAtPath(directory,
isDirectory: &isDirectory){
if isDirectory{
return true
}
}
}
return false
}
func createDocumentsDirectory(){
print("Must create the directory.")
var directoryCreationError: NSError?
if let directory = documentsDirectory{
do {
try fileManager.createDirectoryAtPath(directory,
withIntermediateDirectories:true,
attributes:nil)
print("Successfully created the folder")
/* Now store the file */
storeFile()
} catch let error1 as NSError {
directoryCreationError = error1
if let error = directoryCreationError{
print("Failed to create the folder with error = \(error)")
}
}
} else {
print("The directory was nil")
}
}
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[NSObject : AnyObject]?) -> Bool {
let containerURL =
fileManager.URLForUbiquityContainerIdentifier(nil)
documentsDirectory =
containerURL!.path!.stringByAppendingPathComponent("Documents")
if doesDocumentsDirectoryExist(){
print("This folder already exists.")
/* Now store the file */
storeFile()
} else {
createDocumentsDirectory()
}
return true
}
}
| true
|
11b18403deb5e278cdf5e4abd83b32588dc9e92b
|
Swift
|
Iwark/cclt-ios
|
/cclt/app/views/SummaryContents/SourceLabel.swift
|
UTF-8
| 1,042
| 2.578125
| 3
|
[] |
no_license
|
//
// SourceLabel.swift
// cclt
//
// Created by Kohei Iwasaki on 1/16/15.
// Copyright (c) 2015 Donuts. All rights reserved.
//
import UIKit
class SourceLabel: UILabel {
init(frame: CGRect, text: String, target: AnyObject, action: Selector) {
super.init(frame: frame)
self.text = "出典: " + text
self.textColor = Settings.Colors.sourceLinkColor
self.font = Settings.Fonts.minimumFont
let tapGesture = UITapGestureRecognizer(target: target, action: action)
self.addGestureRecognizer(tapGesture)
self.userInteractionEnabled = true
self.sizeToFit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let color = self.backgroundColor
self.backgroundColor = Settings.Colors.tappedColor
SwiftDispatch.after(0.2) {
() in
self.backgroundColor = color
}
}
}
| true
|
bac7356b86d8643829e388ca5d528ab03fb2bfa0
|
Swift
|
jakecast/wwdc-podcaster-macos
|
/wwdc-podcaster/config.swift
|
UTF-8
| 2,195
| 2.53125
| 3
|
[] |
no_license
|
import Foundation
internal struct Config {
internal let wwdcSessionInfoFile = Process.arguments.last ?? "null"
internal let wwdcSessionInfoURL = "https://raw.githubusercontent.com/jakecast/WWDC-Session-Podcast-Generator/master/data/sessions.json"
internal let feedAuthor = "Apple Developer Center"
internal let feedDirectory = "Desktop"
internal let feedYears = ["2011", "2012", "2013", "2014", "2015", ]
private let feedDescription = "WWDC %%%% Session Videos - Apple Developer"
private let feedFileName = "wwdc-%%%%.rss"
private let feedLink = "https://developer.apple.com/videos/wwdc/%%%%/"
private let feedTitle = "WWDC %%%% Session Videos - Apple Developer"
private let feedImages = [
"2011": "https://raw.githubusercontent.com/jakecast/WWDC-Session-Podcast-Generator/master/data/wwdc-2011.png",
"2012": "https://raw.githubusercontent.com/jakecast/WWDC-Session-Podcast-Generator/master/data/wwdc-2012.png",
"2013": "https://raw.githubusercontent.com/jakecast/WWDC-Session-Podcast-Generator/master/data/wwdc-2013.png",
"2014": "https://raw.githubusercontent.com/jakecast/WWDC-Session-Podcast-Generator/master/data/wwdc-2014.png",
"2015": "https://raw.githubusercontent.com/jakecast/WWDC-Session-Podcast-Generator/master/data/wwdc-2015.png",
]
internal func getFeedFileName(year: String) -> String {
return self.getFeedString(self.feedFileName, year: year)
}
internal func getFeedTitle(year: String) -> String {
return self.getFeedString(self.feedTitle, year: year)
}
internal func getFeedDescription(year: String) -> String {
return self.getFeedString(self.feedDescription, year: year)
}
internal func getFeedLink(year: String) -> String {
return self.getFeedString(self.feedLink, year: year)
}
internal func getFeedImage(year: String) -> String {
return self.feedImages[year]!
}
private func getFeedString(baseString: String, year: String) -> String {
return baseString.stringByReplacingOccurrencesOfString("%%%%", withString: year)
}
}
internal let config = Config()
| true
|
8ba27644a918c7fc37228d8b292e82ee0df0afef
|
Swift
|
JonnyBeeGod/RestorableCountdown
|
/Sources/RestorableCountdown/CountdownConfiguration.swift
|
UTF-8
| 1,352
| 3.296875
| 3
|
[
"MIT"
] |
permissive
|
//
// CountdownConfiguration.swift
// RestorableBackgroundTimer
//
// Created by Jonas Reichert on 23.12.19.
//
import Foundation
public protocol CountdownConfigurable {
var fireInterval: TimeInterval { get }
var tolerance: Double { get }
var maxCountdownDuration: TimeInterval { get }
var minCountdownDuration: TimeInterval { get }
var countdownDuration: TimeInterval { get }
}
public struct CountdownConfiguration: CountdownConfigurable {
public let fireInterval: TimeInterval
public let tolerance: Double
public let maxCountdownDuration: TimeInterval
public let minCountdownDuration: TimeInterval
public let countdownDuration: TimeInterval
public init(fireInterval: TimeInterval = 0.1, tolerance: Double = 0.05, maxCountdownDuration: TimeInterval = 30 * 60, minCountdownDuration: TimeInterval = 15, defaultCountdownDuration: TimeInterval = 90) {
assert(minCountdownDuration <= defaultCountdownDuration && defaultCountdownDuration <= maxCountdownDuration, "invalid input. make sure your countdownDuration is between min and max duration")
self.fireInterval = fireInterval
self.tolerance = tolerance
self.maxCountdownDuration = maxCountdownDuration
self.minCountdownDuration = minCountdownDuration
self.countdownDuration = defaultCountdownDuration
}
}
| true
|
da9727264eab27d75afc58e1d48aa3f97ebba521
|
Swift
|
rbozdag/BinarySearchTree
|
/RBBinarySearchTreeTests/BinarySearchTreeTests.swift
|
UTF-8
| 3,306
| 2.671875
| 3
|
[] |
no_license
|
//
// RBBinarySearchTreeTests.swift
// RBBinarySearchTreeTests
//
// Created by Rahmi on 3.01.2019.
// Copyright © 2019 rbozdag. All rights reserved.
//
import XCTest
@testable import RBBinarySearchTree
class BinarySearchTreeTests: XCTestCase {
func testTreeHeight() {
let tree = BinarySearchTree<Int>()
XCTAssertEqual(tree.height, 0)
tree.insert(50)
XCTAssertEqual(tree.height, 1)
tree.insert(60)
XCTAssertEqual(tree.height, 2)
tree.insert(70)
XCTAssertEqual(tree.height, 3)
tree.insert(80)
XCTAssertEqual(tree.height, 4)
tree.insert(40)
XCTAssertEqual(tree.height, 4)
tree.insert(30)
XCTAssertEqual(tree.height, 4)
tree.insert(20)
XCTAssertEqual(tree.height, 4)
tree.insert(10)
XCTAssertEqual(tree.height, 5)
tree.insert(5)
XCTAssertEqual(tree.height, 6)
tree.insert(90)
XCTAssertEqual(tree.height, 6)
tree.insert(100)
XCTAssertEqual(tree.height, 6)
tree.insert(110)
XCTAssertEqual(tree.height, 7)
tree.insert(120)
XCTAssertEqual(tree.height, 8)
}
func testTreeMaxDepth() {
let tree = BinarySearchTree<Int>()
XCTAssertEqual(tree.maxDepth, 0)
tree.insert(50)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(60)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(70)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(80)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(40)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(30)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(20)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(10)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(5)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(90)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(100)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(110)
XCTAssertEqual(tree.maxDepth, tree.height)
tree.insert(120)
XCTAssertEqual(tree.maxDepth, tree.height)
}
func testTreeMinDepth() {
let tree = BinarySearchTree<Int>()
XCTAssertEqual(tree.minDepth, 0)
tree.insert(50)
XCTAssertEqual(tree.minDepth, 1)
tree.insert(60)
XCTAssertEqual(tree.minDepth, 2)
tree.insert(70)
XCTAssertEqual(tree.minDepth, 3)
tree.insert(80)
XCTAssertEqual(tree.minDepth, 4)
tree.insert(40)
XCTAssertEqual(tree.minDepth, 2)
tree.insert(30)
XCTAssertEqual(tree.minDepth, 3)
tree.insert(20)
XCTAssertEqual(tree.minDepth, 4)
tree.insert(10)
XCTAssertEqual(tree.minDepth, 4)
tree.insert(5)
XCTAssertEqual(tree.minDepth, 4)
tree.insert(90)
XCTAssertEqual(tree.minDepth, 5)
tree.insert(100)
XCTAssertEqual(tree.minDepth, 6)
tree.insert(110)
XCTAssertEqual(tree.minDepth, 6)
tree.insert(120)
XCTAssertEqual(tree.minDepth, 6)
}
}
| true
|
26bf4e5feab2e036a20fb218fe794804f7d4a42e
|
Swift
|
TraceTschidaUT/cs329e
|
/TschidaTrace-hw5/TschidaTrace-hw5/Assets.xcassets/DbContext.swift
|
UTF-8
| 2,554
| 2.953125
| 3
|
[] |
no_license
|
//
// DbContext.swift
// TschidaTrace-hw5
//
// Created by user135456 on 2/19/18.
// Copyright © 2018 tracetschida_cs329. All rights reserved.
//
import Foundation
import CoreData
import UIKit
class DbContext {
// Initalize an array of managed objects
init() {
// Core Data object
people = [NSManagedObject]()
// Load all of the people
self.getAllPeople()
}
// Properties
public var people: [NSManagedObject]
// Functions
func savePerson (firstName: String, lastName: String, state: String, politicalParty: String){
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
// Create Entity we want to save the new person into
let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)
// Grab a new person of the entity listed above and insert it into the managed context
let person = NSManagedObject(entity: entity! , insertInto: managedContext)
// Set the values
person.setValue(firstName, forKey: "firstName")
person.setValue(lastName, forKey: "lastName")
person.setValue(state, forKey: "state")
person.setValue(politicalParty, forKey: "politicalParty")
// Commit the changes
do {
try managedContext.save()
}
catch {
let nserror = error as NSError
print("Unresolved error \(nserror), \(nserror.userInfo)")
}
// Add the new entity to our array of managed objects
people.append(person)
}
func getAllPeople() {
// Get access to the app delegate
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
// Get the managed context from the delegeate
// Managed context was created as delegate because of the Core Data check box
let managedContext = appDelegate.persistentContainer.viewContext
// Fetch the Core Data for the Person entity
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person")
do {
people = try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
}
| true
|
47de6012e9a72e45833ea8dd5f093cc19369ce78
|
Swift
|
ravelasquez99/HDIL
|
/HDIL/HDIL/SavedPicturesVC.swift
|
UTF-8
| 1,369
| 2.515625
| 3
|
[] |
no_license
|
//
// SavedPicturesVC.swift
// HDIL
//
// Created by Richard Velazquez on 5/30/16.
// Copyright © 2016 Ricky. All rights reserved.
//
import UIKit
class SavedPicturesVC: UIViewController, UITableViewDelegate, UITableViewDataSource,SavedPictureCellDelegate {
var pictures : NSMutableArray?
var selectedImage : UIImage?
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (self.pictures?.count)!
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("PictureCell") as! SavedPictureCell
let cellPicture = self.pictures?.objectAtIndex(indexPath.row) as! Picture
let imageData = cellPicture.binary
cell.pictureView.image = UIImage(data: imageData!)
cell.analyzeButton.enabled = true
cell.delegate = self
return cell
}
func userDidRequestAnalysisOnImgae(image: UIImage) {
print("delegte hit")
self.selectedImage = image
self.performSegueWithIdentifier("unwind", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "unwind" {
let destVC = segue.destinationViewController as! HomeVC
destVC.selectedImage = self.selectedImage
destVC.didSelectImage = true
}
}
}
| true
|
d634a0aa0aca6998a92fd616c222dd44cd0986e1
|
Swift
|
AndresLeonardoMartinez/Academy
|
/HeroesApp/HeroesApp/Models/Creator.swift
|
UTF-8
| 5,445
| 2.6875
| 3
|
[] |
no_license
|
import Foundation
import CoreData
class ResponseCreator: NSManagedObject, Decodable, CodableHasContextChecker , EntityNameable {
static func entityName() -> String {
return "ResponseCreator"
}
@NSManaged var code: Int32
@NSManaged var status: String
@NSManaged var data: DataClassCreator
enum CodingKeys: String, CodingKey{
case code
case status
case data
}
required convenience init(from decoder: Decoder) throws {
guard let ent = ResponseHeroes.hasValidContext(decoder: decoder, entityName: "ResponseCreator") else {
fatalError("Failed to decode Subject!")
}
self.init(entity: ent.0, insertInto: ent.1)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.code = try container.decode(Int32.self, forKey: .code)
self.status = try container.decode(String.self, forKey: .status)
self.data = try container.decode(DataClassCreator.self, forKey: .data)
}
}
class DataClassCreator: NSManagedObject, Decodable, CodableHasContextChecker {
@NSManaged var offset, limit, total, count: Int32
@NSManaged var results: Set<Creator>
enum CodingKeys: String, CodingKey{
case offset
case limit
case total
case count
case results
}
required convenience init(from decoder: Decoder) throws {
guard let ent = DataClassHeroes.hasValidContext(decoder: decoder, entityName: "DataClassCreator") else {
fatalError("Failed to decode Subject!")
}
self.init(entity: ent.0, insertInto: ent.1)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.offset = try container.decode(Int32.self, forKey: .offset)
self.limit = try container.decode(Int32.self, forKey: .limit)
self.total = try container.decode(Int32.self, forKey: .total)
self.count = try container.decode(Int32.self, forKey: .count)
self.results = try container.decode(Set<Creator>.self, forKey: .results)
}
}
class Creator: NSManagedObject, Decodable, CodableHasContextChecker {
@NSManaged var id: Int32
@NSManaged var fullName: String
@NSManaged var thumbnail: Thumbnail
@NSManaged var urls: Set<URLElement>
enum CodingKeys: String, CodingKey{
case id
case fullName
case thumbnail
case urls
}
required convenience init(from decoder: Decoder) throws {
guard let ent = DataClassHeroes.hasValidContext(decoder: decoder, entityName: "Creator") else {
fatalError("Failed to decode Subject!")
}
self.init(entity: ent.0, insertInto: ent.1)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(Int32.self, forKey: .id)
self.fullName = try container.decode(String.self, forKey: .fullName)
self.thumbnail = try container.decode(Thumbnail.self, forKey: .thumbnail)
self.urls = try container.decode(Set<URLElement>.self, forKey: .urls)
}
}
//struct Comics: NSManagedObject, Decodable, CodableHasContextChecker {
// @NSManaged var available: Int32
// @NSManaged var collectionURI: String
// @NSManaged var items: [ComicsItem]
// @NSManaged var returned: Int32
//}
//struct ComicsItem: NSManagedObject, Decodable, CodableHasContextChecker {
// @NSManaged var resourceURI: String
// @NSManaged var name: String
//}
//
//struct Stories: NSManagedObject, Decodable, CodableHasContextChecker {
// @NSManaged var available: Int32
// @NSManaged var collectionURI: String
// @NSManaged var items: [StoriesItem]
// @NSManaged var returned: Int32
//}
//
//struct StoriesItem: NSManagedObject, Decodable, CodableHasContextChecker {
// @NSManaged var resourceURI: String
// @NSManaged var name: String
// @NSManaged var type: ItemType
//}
//
//enum ItemType: String, Codable {
// case cover = "cover"
// case empty = ""
// case interiorStory = "interiorStory"
// case pinup
// case unknown
//}
//extension ItemType {
// public init(from decoder: Decoder) throws {
// self = try ItemType(rawValue: decoder.singleValueContainer().decode(String.self)) ?? .unknown
// }
//}
class Thumbnail: NSManagedObject, Codable, CodableHasContextChecker {
@NSManaged var path: String
@NSManaged var thumbnailExtension: String
enum CodingKeys: String, CodingKey {
case path
case thumbnailExtension = "extension"
}
required convenience init(from decoder: Decoder) throws {
guard let ent = Thumbnail.hasValidContext(decoder: decoder, entityName: "Thumbnail") else {
fatalError("Failed to decode Subject!")
}
self.init(entity: ent.0, insertInto: ent.1)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.path = try container.decode(String.self, forKey: .path)
self.thumbnailExtension = try container.decode(String.self, forKey: .thumbnailExtension)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(path, forKey: .path)
try container.encode(thumbnailExtension, forKey: .thumbnailExtension)
}
}
//enum Extension: String, Codable {
// case jpg
// case gif
// case png
//}
| true
|
34780e7f168980138d6402ae1f5e82f3b9df0bde
|
Swift
|
IvoKroon/beetle
|
/App/beetle/ViewController.swift
|
UTF-8
| 4,477
| 2.703125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// beetle
//
// Created by ivo kroon on 09/04/2018.
// Copyright © 2018 ivo kroon. All rights reserved.
//
import UIKit
import RealmSwift
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var currentLocation:CLLocation? = nil
// var homeLocation:CLLocation = CLLocation(latitude: 51.7640462, longitude: 4.1480324)
var homeLocation:CLLocation = CLLocation(latitude: 51.753242, longitude: 4.162058)
var home:Bool = false
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var statusView: UIView!
@IBOutlet weak var firstNameLabel: UILabel!
@IBOutlet weak var lastNameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
self.locationManager.delegate = self
self.locationManager.requestAlwaysAuthorization()
self.startReceivingSignificantLocationChanges()
}
override func viewDidLoad() {
super.viewDidLoad()
self.statusView.layer.cornerRadius = 10
self.statusView.backgroundColor = ColorHelper(
red:34.0,
green:139.0,
blue:34.0)
let realm = try! Realm()
let user = realm.objects(User.self)
if !user.isEmpty {
let userData = user[0] as User
self.emailLabel.text = userData.email
self.firstNameLabel.text = userData.firstName
self.lastNameLabel.text = userData.lastName
}
}
// LET'S CHECK WHAT THE USER WANTS.
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("AUTH");
print(status);
switch status {
case CLAuthorizationStatus.denied:
print("USER DENIED")
break;
case CLAuthorizationStatus.authorizedWhenInUse:
print("WHEN IN USE")
startReceivingSignificantLocationChanges()
case CLAuthorizationStatus.authorizedAlways:
print("ALWAY")
startReceivingSignificantLocationChanges()
default:
print("ERROR")
}
}
func startReceivingSignificantLocationChanges (){
let authorizationStatus = CLLocationManager.authorizationStatus()
if authorizationStatus != .authorizedAlways {
print("NO AUTHORIZATION")
// User has not authorized access to location information.
return
}
if !CLLocationManager.significantLocationChangeMonitoringAvailable() {
// The service is not available.
print("ERROR")
return
}
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
self.locationManager.distanceFilter = 100.0
self.locationManager.startUpdatingLocation()
}
// CHECK
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.currentLocation = locations.last!
let distance = self.currentLocation?.distance(from: self.homeLocation)
// IF DISTANCE IS NEAR HOME WE ARE HOME ELS WE ARE LEAVING HOME
if(Double(distance!) < 500.0 && !self.home){
// SHOW NOTIFICATION
self.home = true;
self.statusLabel.text = "Status: HOME"
self.statusView.backgroundColor = ColorHelper(
red:34.0,
green:139.0,
blue:34.0)
}else if(Double(distance!) < 500.0){
print("Still HERE")
}else{
print("LEAVING HOME")
self.home = false;
self.statusLabel.text = "Status: OUT"
self.statusView.backgroundColor = ColorHelper(
red:255.0,
green:0.0,
blue:0.0)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("error")
if let error = error as? CLError, error.code == .denied {
// Location updates are not authorized.
manager.stopMonitoringSignificantLocationChanges()
return
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
6959485bb1924993008387d415a0fdf746ba3a55
|
Swift
|
jpladuguie/TopScorer
|
/Footballers/tabBarController.swift
|
UTF-8
| 2,526
| 2.75
| 3
|
[] |
no_license
|
import UIKit
import SlidingTabBar
// Tab bar controller class.
// Uses a custom tab bar from the SlidingTabBar library.
class tabBarController: UITabBarController, SlidingTabBarDataSource, SlidingTabBarDelegate, UITabBarControllerDelegate {
// Custom tab bar.
var tabBarView: SlidingTabBar!
var fromIndex: Int!
var toIndex: Int!
override func viewDidLoad() {
super.viewDidLoad()
// Hide the original tab bar.
self.tabBar.isHidden = true
// Start at 0, i.e. home view.
self.selectedIndex = 0
self.delegate = self
// Increase the tab bar height.
var frame: CGRect = self.tabBar.frame
frame.origin.y -= 11
frame.size.height += 11
// Create the custom tab bar.
tabBarView = SlidingTabBar(frame: frame, initialTabBarItemIndex: self.selectedIndex)
// Set the tab bar colour.
tabBarView.tabBarBackgroundColor = darkGrey
tabBarView.tabBarItemTintColor = UIColor.gray
tabBarView.selectedTabBarItemTintColor = UIColor.white
tabBarView.selectedTabBarItemColors = [lightGrey, lightGrey, lightGrey]
// Set the animation duration.
tabBarView.slideAnimationDuration = 0.3
// Set up anything else to do with the tab bar.
tabBarView.datasource = self
tabBarView.delegate = self
tabBarView.setup()
// Add the tab bar to view.
self.view.addSubview(tabBarView)
}
// MARK: - SlidingTabBarDataSource
func tabBarItemsInSlidingTabBar(tabBarView: SlidingTabBar) -> [UITabBarItem] {
return tabBar.items!
}
// MARK: - SlidingTabBarDelegate
func didSelectViewController(tabBarView: SlidingTabBar, atIndex index: Int, from: Int) {
self.fromIndex = from
self.toIndex = index
self.selectedIndex = index
}
// MARK: - UITabBarControllerDelegate
func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return SlidingTabAnimatedTransitioning(transitionDuration: 0.3, direction: .Both,
fromIndex: self.fromIndex, toIndex: self.toIndex)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
fe52d65ba2c64c67113fd60b93422cacbbb0ef30
|
Swift
|
FirstZverev/TestWeather
|
/TestWeather/TestWeather/VIewModel/ViewModelWeather.swift
|
UTF-8
| 1,621
| 2.703125
| 3
|
[] |
no_license
|
//
// ModelView.swift
// TestWeather
//
// Created by Володя Зверев on 01.03.2021.
//
import Foundation
class ViewModelWeather {
var coordinators: [Coordinator] = [
Coordinator(id: 0, name: "Казань", lat: 55.7887, lot: 49.1221),
Coordinator(id: 1, name: "Москва", lat: 55.75222, lot: 37.61556),
Coordinator(id: 2, name: "Краснодар", lat: 45.04484, lot: 38.97603),
Coordinator(id: 3, name: "Киров", lat: 58.603591, lot: 49.668014),
Coordinator(id: 4, name: "Альмевск", lat: 54.901383, lot: 52.297113),
Coordinator(id: 5, name: "Сочи", lat: 43.585472, lot: 39.723089),
Coordinator(id: 6, name: "Владикавказ", lat: 43.024616, lot: 44.681762),
Coordinator(id: 7, name: "Гелинджик", lat: 37.737716, lot: 30.445711),
Coordinator(id: 8, name: "Санкт-Петербург", lat: 59.938951, lot: 30.315635),
Coordinator(id: 9, name: "Владимир", lat: 56.129057, lot: 40.406635),
]
var modelWeather: [ModelWeather] = []
var modelWeatherSearching: [ModelWeather] = []
// var cityName = ["Казань","Москва","Санкт-Петербург","Ульяновск","Краснодар","Киров","Владивосток","Орёл","Зеленодольск","Альметевск"]
var yandexModel: YandexModel?
}
struct Coordinator {
let id: Int
let name: String
let lat: Double
let lot: Double
}
struct ModelWeather {
let id: Int
let name: String
let temp: Int
let state: String
let model: YandexModel?
}
| true
|
77406ebf8f97f0aa4243c68762d65d5344d40109
|
Swift
|
BruceKhin/Restaurant_IOS_SWIFT_OBJC
|
/Swift/Restaurant/Classes/Cells/ReservationLocationTableViewCell.swift
|
UTF-8
| 1,934
| 2.609375
| 3
|
[] |
no_license
|
//
// ReservationLocationTableViewCell.swift
// Restaurant
//
// Created by AppsFoundation on 8/27/15.
// Copyright © 2015 AppsFoundation. All rights reserved.
//
import UIKit
class ReservationLocationTableViewCell: UITableViewCell {
@IBOutlet weak var locationLabel: UILabel?
@IBOutlet weak var distanceLabel: UILabel?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
// MARK: - Actions
@IBAction func leftSwipe(_ sender: AnyObject) {
print("Previous location")
previousLocation()
}
@IBAction func rightSwipe(_ sender: AnyObject) {
print("Next location")
nextLocation()
}
@IBAction func onPreviosLocation(_ sender: AnyObject) {
print("Previous location")
previousLocation()
distanceLabel?.text = "2,5 Mi"
locationLabel?.text = "21th St & Silent Rd\n(345)123-0987\nPhoenix,AZ 42200"
}
@IBAction func onNextLocation(_ sender: AnyObject) {
print("Next location")
nextLocation()
distanceLabel?.text = "2,5 Mi"
locationLabel?.text = "21th St & Silent Rd\n(345)123-0987\nPhoenix,AZ 42200"
}
// MARK: Private Methods
private func previousLocation() {
UIView.animate(withDuration: 0.2) { () -> Void in
self.locationLabel?.alpha = 0.0
}
UIView.animate(withDuration: 0.1) { () -> Void in
self.locationLabel?.alpha = 1.0
}
}
private func nextLocation() {
UIView.animate(withDuration: 0.2) { () -> Void in
self.locationLabel?.alpha = 0.0
}
UIView.animate(withDuration: 0.1) { () -> Void in
self.locationLabel?.alpha = 1.0
}
}
}
| true
|
d6228f8dd923846d31f9a368300a1ab82de878bb
|
Swift
|
bigsnickers/DPActivityIndicatorView
|
/DPActivityIndicatorView/Source/Content Views/Native/DPActivityIndicatorNativeContentView.swift
|
UTF-8
| 870
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//
// DPActivityIndicatorNativeContentView.swift
// DPActivityIndicatorExample
//
// Created by Dennis Pashkov on 4/15/16.
// Copyright © 2016 Dennis Pashkov. All rights reserved.
//
import UIKit
internal class DPActivityIndicatorNativeContentView: DPActivityIndicatorContentView {
@IBOutlet private weak var nativeActivityIndicator: UIActivityIndicatorView?
}
extension DPActivityIndicatorNativeContentView {
override func startAnimation() {
nativeActivityIndicator?.startAnimating()
}
override func stopAnimation() {
nativeActivityIndicator?.stopAnimating()
}
override func isAnimating() -> Bool {
if nativeActivityIndicator == nil {
return false
}
else {
return nativeActivityIndicator!.isAnimating()
}
}
}
| true
|
1a024bbafaca618fe89bf1503bc1e391e8316d10
|
Swift
|
kunhwiko/swiftris
|
/Tetris/Game/GamePieces.swift
|
UTF-8
| 11,044
| 3.46875
| 3
|
[] |
no_license
|
//
// GamePieces.swift
// Tetris
//
// Created by Kun Hwi Ko on 6/21/20.
// Copyright © 2020 Kun Hwi Ko. All rights reserved.
//
import SwiftUI
// Block is a single square that makes up a tetris piece
struct Block {
var blockType : String
var color : Color
}
struct BlockPosition {
var row:Int
var column:Int
}
// TetrisPiece is an entire tetromino made up of 4 blocks
struct TetrisPiece {
var startPos: BlockPosition
var blockType : String
var color : Color {return TetrisPiece.getColors(blockType: self.blockType)}
var blocks : [BlockPosition] {return TetrisPiece.getBlocks(blockType: self.blockType, rotation: self.rotation)}
var rotation : Int
func move(row:Int, column:Int) -> TetrisPiece{
let newPos = BlockPosition(row:startPos.row+row, column:startPos.column+column)
return TetrisPiece(startPos:newPos, blockType: blockType, rotation: rotation)
}
func rotate(clockwise: Bool) -> TetrisPiece{
return TetrisPiece(startPos: startPos, blockType: blockType, rotation: rotation + (clockwise ? -1: 1))
}
func kick(clockwise: Bool) -> [BlockPosition]{
return TetrisPiece.getKicks(blockType: blockType, rotation: rotation, clockwise: clockwise)
}
// we make the following functions 'functions of the struct' and not 'functions of an instance of struct'
static func getRandomType() -> String{
let type = ["I","O","T","S","Z","J","L"]
return type.randomElement()!
}
static func getBlocks(blockType: String, rotation: Int = 0) -> [BlockPosition] {
let allBlocks = getAllBlocks(blockType: blockType)
var index = rotation % allBlocks.count
if index < 0 {index += allBlocks.count}
return allBlocks[index]
}
// these are the block positions in all their rotated forms
static func getAllBlocks(blockType: String) -> [[BlockPosition]] {
switch blockType {
case "I":
return [[BlockPosition(row: 0, column: -1), BlockPosition(row: 0, column: 0),
BlockPosition(row: 0, column: 1), BlockPosition(row: 0, column: 2)],
[BlockPosition(row: -1, column: 1), BlockPosition(row: 0, column: 1),
BlockPosition(row: 1, column: 1), BlockPosition(row: -2, column: 1)],
[BlockPosition(row: -1, column: -1),BlockPosition(row: -1, column: 0),
BlockPosition(row: -1, column: 1), BlockPosition(row: -1, column: 2)],
[BlockPosition(row: -1, column: 0), BlockPosition(row: 0, column: 0),
BlockPosition(row: 1, column: 0), BlockPosition(row: -2, column: 0)]]
case "O":
return [[BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: 1),
BlockPosition(row: 1, column: 1), BlockPosition(row: 1, column: 0)]]
case "T":
return [[BlockPosition(row: 0, column: -1), BlockPosition(row: 0, column: 0),
BlockPosition(row: 0, column: 1), BlockPosition(row: 1, column: 0)],
[BlockPosition(row: -1, column: 0), BlockPosition(row: 0, column: 0),
BlockPosition(row: 0, column: 1), BlockPosition(row: 1, column: 0)],
[BlockPosition(row: 0, column: -1), BlockPosition(row: 0, column: 0),
BlockPosition(row: 0, column: 1), BlockPosition(row: -1, column: 0)],
[BlockPosition(row: 0, column: -1), BlockPosition(row: 0, column: 0),
BlockPosition(row: 1, column: 0), BlockPosition(row: -1, column: 0)]]
case "S":
return [[BlockPosition(row: 1, column: -1), BlockPosition(row: 1, column: 0),
BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: 1)],
[BlockPosition(row: 1, column: 1), BlockPosition(row: 0, column: 1),
BlockPosition(row: 0, column: 0), BlockPosition(row: -1, column: 0)],
[BlockPosition(row: 0, column: -1), BlockPosition(row: 0, column: 0),
BlockPosition(row: -1, column: 0), BlockPosition(row: -1, column: 1)],
[BlockPosition(row: 1, column: 0), BlockPosition(row: 0, column: 0),
BlockPosition(row: 0, column: -1), BlockPosition(row: -1, column: -1)]]
case "Z":
return [[BlockPosition(row: 0, column: -1), BlockPosition(row: 0, column: 0),
BlockPosition(row: 1, column: 0), BlockPosition(row: 1, column: 1)],
[BlockPosition(row: 1, column: 0), BlockPosition(row: 0, column: 0),
BlockPosition(row: 0, column: 1), BlockPosition(row: -1, column: 1)],
[BlockPosition(row: 0, column: 1), BlockPosition(row: 0, column: 0),
BlockPosition(row: -1, column: 0), BlockPosition(row: -1, column: -1)],
[BlockPosition(row: 1, column: -1), BlockPosition(row: 0, column: -1),
BlockPosition(row: 0, column: 0), BlockPosition(row: -1, column: 0)]]
case "J":
return [[BlockPosition(row: 0, column: -1), BlockPosition(row: 0, column: 0),
BlockPosition(row: 0, column: 1), BlockPosition(row: 1, column: 1)],
[BlockPosition(row: 1, column: 0), BlockPosition(row: 0, column: 0),
BlockPosition(row: -1, column: 0), BlockPosition(row: -1, column: 1)],
[BlockPosition(row: 0, column: -1), BlockPosition(row: 0, column: 0),
BlockPosition(row: 0, column: 1), BlockPosition(row: -1, column: -1)],
[BlockPosition(row: 1, column: 0), BlockPosition(row: 0, column: 0),
BlockPosition(row: -1, column: 0), BlockPosition(row: 1, column: -1)]]
case "L":
return [[BlockPosition(row: 1, column: -1), BlockPosition(row: 0, column: -1),
BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: 1)],
[BlockPosition(row: 1, column: 0), BlockPosition(row: 0, column: 0),
BlockPosition(row: -1, column: 0), BlockPosition(row: 1, column: 1)],
[BlockPosition(row: -1, column: 1), BlockPosition(row: 0, column: -1),
BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: 1)],
[BlockPosition(row: 1, column: 0), BlockPosition(row: 0, column: 0),
BlockPosition(row: -1, column: 0), BlockPosition(row: -1, column: -1)]]
default:
return [[BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: 0),
BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: 0)]]
}
}
// wall kicks are essential to rotate pieces when along the walls
static func getKicks(blockType: String, rotation: Int, clockwise: Bool) -> [BlockPosition] {
let rotationCount = getAllBlocks(blockType: blockType).count
var index = rotation % rotationCount
if index < 0 {index += rotationCount}
var kicks = getAllKicks(blockType: blockType)[index]
if clockwise == false{
var counterKicks: [BlockPosition] = []
for kick in kicks {
counterKicks.append(BlockPosition(row: -1*kick.row, column: -1*kick.column))
}
kicks = counterKicks
}
return kicks
}
static func getAllKicks(blockType: String) -> [[BlockPosition]] {
switch blockType {
case "O":
return [[BlockPosition(row: 0, column: 0)]]
case "I":
return [[BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: -2), BlockPosition(row: 0, column: 1),
BlockPosition(row: -1, column: -2), BlockPosition(row: 2, column: -1)],
[BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: -1), BlockPosition(row: 0, column: 2),
BlockPosition(row: 2, column: -1), BlockPosition(row: -1, column: 2)],
[BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: 2), BlockPosition(row: 0, column: -1),
BlockPosition(row: 1, column: 2), BlockPosition(row: -2, column: -1)],
[BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: 1), BlockPosition(row: 0, column: -2),
BlockPosition(row: -2, column: 1), BlockPosition(row: 1, column: -2)]
]
default:
return [[BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: -1), BlockPosition(row: 1, column: -1),
BlockPosition(row: 0, column: -2), BlockPosition(row: -2, column: -1)],
[BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: 1), BlockPosition(row: -1, column: 1),
BlockPosition(row: 2, column: 0), BlockPosition(row: 1, column: 2)],
[BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: 1), BlockPosition(row: 1, column: 1),
BlockPosition(row: -2, column: 0), BlockPosition(row: -2, column: 1)],
[BlockPosition(row: 0, column: 0), BlockPosition(row: 0, column: -1), BlockPosition(row: -1, column: -1),
BlockPosition(row: 2, column: 0), BlockPosition(row: 2, column: -1)]
]
}
}
static func getColors(blockType: String) -> Color {
switch blockType {
case "I":
return .customCyan
case "O":
return .yellow
case "T":
return .purple
case "S":
return .green
case "Z":
return .red
case "J":
return .blue
case "L":
return .orange
default:
return .customBoardColor
}
}
static func getShadowColors(blockType: String) -> Color {
switch blockType {
case "I":
return .customShadowCyan
case "O":
return .customShadowYellow
case "T":
return .customShadowPurple
case "S":
return .customShadowGreen
case "Z":
return .customShadowRed
case "J":
return .customShadowBlue
case "L":
return .customShadowOrange
default:
return .customBoardColor
}
}
static func createNewPiece(row: Int, column: Int) -> TetrisPiece {
let blockType = getRandomType()
var origin:BlockPosition
if blockType == "Z" {
origin = BlockPosition(row: 1, column: (column-1)/2)
} else {
origin = BlockPosition(row: 0, column: (column-1)/2)
}
return TetrisPiece(startPos: origin, blockType: blockType, rotation: 0)
}
}
| true
|
9f5c444ea04ad4939ca206fa040d25b121fa33d3
|
Swift
|
rbukovansky/SwiftCLI
|
/Tests/SwiftCLITests/Fixtures.swift
|
UTF-8
| 4,454
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// SwiftCLITests.swift
// SwiftCLITests
//
// Created by Jake Heiser on 6/28/16.
// Copyright (c) 2016 jakeheis. All rights reserved.
//
import SwiftCLI
class TestCommand: Command {
let name = "test"
let shortDescription = "A command to test stuff"
var executionString = ""
let testName = Parameter()
let testerName = OptionalParameter()
let silent = Flag("-s", "--silent", description: "Silence all test output")
let times = Key<Int>("-t", "--times", description: "Number of times to run the test")
let completion: ((_ executionString: String) -> ())?
init(completion: ((_ executionString: String) -> ())? = nil) {
self.completion = completion
}
func execute() throws {
executionString = "\(testerName.value ?? "defaultTester") will test \(testName.value), \(times.value ?? 1) times"
if silent.value {
executionString += ", silently"
}
if verbose.value {
executionString += ", verbosely"
}
completion?(executionString)
}
}
class TestInheritedCommand: TestCommand {
let verbose = Flag("-v", "--verbose", description: "Show more output information")
}
// MARK: -
let alphaCmd = AlphaCmd()
let betaCmd = BetaCmd()
let charlieCmd = CharlieCmd()
let deltaCmd = DeltaCmd()
class AlphaCmd: Command {
let name = "alpha"
let shortDescription = "The alpha command"
fileprivate init() {}
func execute() throws {}
}
class BetaCmd: Command {
let name = "beta"
let shortDescription = "A beta command"
fileprivate init() {}
func execute() throws {}
}
class CharlieCmd: Command {
let name = "charlie"
let shortDescription = "A beta command"
fileprivate init() {}
func execute() throws {}
}
class DeltaCmd: Command {
let name = "delta"
let shortDescription = "A beta command"
fileprivate init() {}
func execute() throws {}
}
class EmptyCmd: Command {
let name = "req"
func execute() throws {}
}
class Req1Cmd: EmptyCmd {
let req1 = Parameter()
}
class Opt1Cmd: EmptyCmd {
let opt1 = OptionalParameter()
}
class Req2Cmd: EmptyCmd {
let req1 = Parameter()
let req2 = Parameter()
}
class Opt2Cmd: EmptyCmd {
let opt1 = OptionalParameter()
let opt2 = OptionalParameter()
}
class Opt2InhCmd: Opt2Cmd {
let opt3 = OptionalParameter()
}
class ReqCollectedCmd: EmptyCmd {
let req1 = CollectedParameter()
}
class OptCollectedCmd: EmptyCmd {
let opt1 = OptionalCollectedParameter()
}
class Req2CollectedCmd: EmptyCmd {
let req1 = Parameter()
let req2 = CollectedParameter()
}
class Opt2CollectedCmd: EmptyCmd {
let opt1 = OptionalParameter()
let opt2 = OptionalCollectedParameter()
}
class Req2Opt2Cmd: EmptyCmd {
let req1 = Parameter()
let req2 = Parameter()
let opt1 = OptionalParameter()
let opt2 = OptionalParameter()
}
// MARK: -
let midGroup = MidGroup()
let intraGroup = IntraGroup()
class MidGroup: CommandGroup {
let name = "mid"
let shortDescription = "The mid level of commands"
let children: [Routable] = [alphaCmd, betaCmd]
fileprivate init() {}
}
class IntraGroup: CommandGroup {
let name = "intra"
let shortDescription = "The intra level of commands"
let children: [Routable] = [charlieCmd, deltaCmd]
fileprivate init() {}
}
// MARK: -
class OptionCmd: Command {
let name = "cmd"
let shortDescription = ""
var helpFlag: Flag? = nil
func execute() throws {}
}
class FlagCmd: OptionCmd {
let flag = Flag("-a", "--alpha")
}
class KeyCmd: OptionCmd {
let key = Key<String>("-a", "--alpha")
}
class DoubleFlagCmd: OptionCmd {
let alpha = Flag("-a", "--alpha")
let beta = Flag("-b", "--beta")
}
class DoubleKeyCmd: OptionCmd {
let alpha = Key<String>("-a", "--alpha")
let beta = Key<String>("-b", "--beta")
}
class FlagKeyCmd: OptionCmd {
let alpha = Flag("-a", "--alpha")
let beta = Key<String>("-b", "--beta")
}
class IntKeyCmd: OptionCmd {
let alpha = Key<Int>("-a", "--alpha")
}
class ExactlyOneCmd: Command {
let name = "cmd"
let shortDescription = ""
var helpFlag: Flag? = nil
func execute() throws {}
let alpha = Flag("-a", "--alpha")
let beta = Flag("-b", "--beta")
let optionGroups: [OptionGroup]
init() {
optionGroups = [OptionGroup(options: [alpha, beta], restriction: .exactlyOne)]
}
}
| true
|
524dd8a1bb4f7a9d8e05d930cfdcaed33d794baa
|
Swift
|
nguyenvhung9420/WorldAirQualityReportAssignment
|
/WorldAirQualityReportAssignment/Models/PieceOfInformation.swift
|
UTF-8
| 2,280
| 3.28125
| 3
|
[] |
no_license
|
//
// PieceOfInformation.swift
// WeatherWithNAB
//
// Created by Hung Nguyen on 8/28/21.
//
import Foundation
import Combine
import ObjectMapper
class Country: Mappable {
var name: String = ""
init() {}
required init?(map: Map) {}
func mapping(map: Map) {
name <- map["country"]
}
}
class City: Mappable {
var name: String = ""
init() {}
required init?(map: Map) {}
func mapping(map: Map) {
name <- map["city"]
}
}
class CountryState: Mappable {
var name: String = ""
init() {}
required init?(map: Map) {}
func mapping(map: Map) {
name <- map["state"]
}
}
//class City: Mappable {
// var dt: Int?
// var dateInterval: Int?
// var avgTemp: Temperature? // always in Celsius
// var pressure: Int = 1
// var humid: Double = 0.0
// var description: String?
// var icon: String = ""
//
// init() {}
//
// required init?(map: Map) {}
//
// func mapping(map: Map) {
// dt <- map["dt"]
// description <- map["weather.0.description"]
// icon <- map["weather.0.icon"]
// avgTemp <- map["temp"]
// pressure <- map["pressure"]
// humid <- map["humidity"]
// dateInterval <- map["dt"]
// }
//
// var id: String {
// guard let dt = self.dt else {
// return ""
// }
// return String(describing: dt)
// }
//
// var date: Date {
// let date = Date(timeIntervalSince1970: Double(self.dateInterval ?? 0))
// return date
// }
//
// var dateString: String {
// let formatter = DateFormatter()
// formatter.dateFormat = "EEE, dd MMM, yyyy"
// return formatter.string(from: self.date)
// }
//
// var averageTempString: String {
// return String(format: "%.2f°C", self.avgTemp?.day ?? 0.0)
// }
//}
class Temperature: Mappable {
var day: Double?
var min: Double?
var max: Double?
var night: Double?
var morning: Double?
init() {}
required init?(map: Map) {}
// Mappable
func mapping(map: Map) {
day <- map["day"]
min <- map["min"]
max <- map["max"]
night <- map["night"]
morning <- map["morn"]
}
}
| true
|
77aaaad888d354e9c4ef1067bb1da00868db848b
|
Swift
|
smolyakovroma/MLCoreExample
|
/MLCoreExample/ViewController.swift
|
UTF-8
| 3,038
| 2.578125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// MLCoreExample
//
// Created by Роман Смоляков on 03/11/2018.
// Copyright © 2018 Роман Смоляков. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var labelCategory: UILabel!
@IBOutlet weak var img1: UIImageView!
@IBOutlet weak var img2: UIImageView!
@IBOutlet weak var img3: UIImageView!
let model = GoogLeNetPlaces()
override func viewDidLoad() {
super.viewDidLoad()
var tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
img1.isUserInteractionEnabled = true
img1.addGestureRecognizer(tapGestureRecognizer)
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
img2.isUserInteractionEnabled = true
img2.addGestureRecognizer(tapGestureRecognizer)
tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
img3.isUserInteractionEnabled = true
img3.addGestureRecognizer(tapGestureRecognizer)
}
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let imageView = tapGestureRecognizer.view as? UIImageView
if let imageToAnalyse = imageView?.image {
let scaledImage = scaleImage(image: imageToAnalyse, toSize: CGSize(width: 224, height: 224))
if let sceneLabelString = sceneLabel(forImage: scaledImage) {
labelCategory.text = sceneLabelString
}
}
}
// @objc func imageTapped(sender: UITapGestureRecognizer) {
// let imageView = sender.view as? UIImageView
//
// if let imageToAnalyse = imageView?.image {
// if let sceneLabelString = sceneLabel(forImage: imageToAnalyse) {
// labelCategory.text = sceneLabelString
// }
// }
// }
func sceneLabel (forImage image: UIImage) -> String? {
if let pixelBuffer = ImageProcessor.pixelBuffer(forImage: image.cgImage!) {
guard let scene = try? model.prediction(sceneImage: pixelBuffer)
else {fatalError("Unexpected runtime error!")}
return scene.sceneLabel
}
return nil
}
func scaleImage(image: UIImage, toSize size: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 1.0)
image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
extension UIImage {
convenience init(view: UIView) {
UIGraphicsBeginImageContext(view.frame.size)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(cgImage: image!.cgImage!)
}
}
| true
|
75cc05946d18e1d74736c07a2d8373aaa904a9b1
|
Swift
|
LiuLongyang0305/LeetCode
|
/swift/Tree/1448_CountGoodNodesInBinaryTree.swift
|
UTF-8
| 733
| 3.46875
| 3
|
[] |
no_license
|
// https://leetcode.com/problems/count-good-nodes-in-binary-tree/
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init(_ val: Int) {
self.val = val
self.left = nil
self.right = nil
}
}
class Solution {
func goodNodes(_ root: TreeNode?) -> Int {
var ans = 0
func dfs(_ node: TreeNode?, _ maxValue: Int) {
guard let n = node else {
return
}
if n.val >= maxValue {
ans += 1
}
dfs(n.left, max(maxValue, n.val))
dfs(n.right, max(maxValue, n.val))
}
dfs(root, Int.min)
return ans
}
}
| true
|
3f012bf2fac2cf3295961ce274cd9794d9b300a9
|
Swift
|
PabloRb2X/CVChallegeG
|
/CVChallenge/Views/LoadingView.swift
|
UTF-8
| 811
| 2.5625
| 3
|
[] |
no_license
|
//
// LoadingView.swift
// CVChallenge
//
// Created by Pablo Ramirez on 7/10/19.
// Copyright © 2019 Pablo Ramirez. All rights reserved.
//
import Foundation
import UIKit
class LoadingView: UIView {
@IBOutlet weak var loadingView: UIView!
@IBOutlet weak var textAlert: UILabel!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init (frame : CGRect) {
super.init(frame : frame)
setup()
}
private func setup() {
let view = Bundle.main.loadNibNamed("LoadingView", owner: self, options: nil)?[0] as! UIView
addSubview(view)
view.frame = self.bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
loadingView.layer.cornerRadius = 10
}
}
| true
|
690526df7ce5b97c7af22bde414e1c2b1da4a016
|
Swift
|
prakashini/FlickerAPIImageSearch
|
/FlickrPhotoSearch/FlickrPhotoSearch/Model/FlickrPhotoParent.swift
|
UTF-8
| 612
| 2.53125
| 3
|
[] |
no_license
|
//
// FlickrPhotoParentObj.swift
// FlickrPhotoSearch
//
// Created by LHUser on 17/12/18.
// Copyright © 2018 Prakashini Pattabiraman. All rights reserved.
//
import Foundation
struct FlickrPhotoParent {
var pageNumber : Int?
var noOfPages : Int?
init (_ dictionary: [String: Any]) {
self.pageNumber = dictionary["page"] as? Int ?? 0
self.noOfPages = dictionary["pages"] as? Int ?? 0
}
func storePageDetailsToUserDefaults(){
UserDefaults.standard.set(self.pageNumber, forKey: "page")
UserDefaults.standard.set(self.noOfPages, forKey: "pages")
}
}
| true
|
df0e7ddaf7cdb5f8c98335233afb766d5ce7bab4
|
Swift
|
ryan-lewin/referencer
|
/referencer/SpiderDetailView.swift
|
UTF-8
| 1,800
| 2.921875
| 3
|
[] |
no_license
|
//
// SpiderDetailView.swift
// referencer
//
// Created by Ryan Lewin on 15/3/20.
// Copyright © 2020 Ryan Lewin. All rights reserved.
//
import SwiftUI
struct SpiderDetailView: View {
@ObservedObject var spider: Spider
var body: some View {
VStack(alignment: .center) {
Text("Notes")
.font(.title)
TextField("Enter text", text: $spider.note)
.border(Color.gray)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
spider.getImg(url: spider.picURL)
.resizable()
.aspectRatio(contentMode: .fit)
.padding(.bottom)
VStack() {
TextField("Enter name", text: $spider.name)
.font(.title)
TextField("Enter scientific name", text: $spider.scientificName)
.font(.headline)
HStack(alignment: .center) {
Text("Genus:")
.fontWeight(.bold)
TextField("Enter genus", text: $spider.genus)
}
HStack(alignment: .center) {
Text("Family")
.fontWeight(.bold)
TextField("Enter family", text: $spider.family)
}
HStack() {
Text("Danger Level")
.fontWeight(.bold)
TextField("Enter danger level", text: $spider.dangerLevel)
}
HStack() {
Text("Image URL")
.fontWeight(.bold)
TextField("Enter Url", text: $spider.picURL)
}
}.padding()
Spacer()
}
}
}
| true
|
8144488107b8670398499dac55200f5726da2e35
|
Swift
|
sp55/Starter
|
/Starter/Classes/View/SNNavigationBar.swift
|
UTF-8
| 2,190
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
//
// SNNavigationBar.swift
// ShowNow
//
// Created by apple on 2019/6/6.
// Copyright © 2019 apple. All rights reserved.
//自定义导航条
import UIKit
import SnapKit
class SNNavigationBar: UIView {
var titleLabel:UILabel!//标题
var seperatorLine:UILabel!//分割线
var backgroundView:UIView!//背景view
var backBtn:UIButton!//返回按钮
var backActionBlock:(()->())?
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}
func setupViews() {
backgroundView = UIView.init()
titleLabel = UILabel.init()
titleLabel.backgroundColor = UIColor.blue;
titleLabel.text = "标题"
titleLabel.textAlignment = NSTextAlignment.center
seperatorLine = UILabel.init()
seperatorLine.backgroundColor = UIColor.yellow
backBtn = UIButton.init()
backBtn.setTitle("返回", for: .normal)
backBtn.tag = 1
backBtn.backgroundColor=UIColor.black
backBtn.addTarget(self, action: #selector(backAction), for: .touchUpInside);
self.addSubview(backgroundView)
backgroundView.addSubview(titleLabel);
backgroundView.addSubview(backBtn);
backgroundView.addSubview(seperatorLine);
}
//按钮点击事件
@objc func backAction(sender: UIButton) {
print(sender.tag)
backActionBlock?()
}
override func layoutSubviews() {
backgroundView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
titleLabel.snp.makeConstraints { (make) in
make.centerX.equalTo(backgroundView)
make.height.equalTo(backgroundView)
make.width.equalTo(150)
}
seperatorLine.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(0)
make.height.equalTo(3.5);
}
backBtn.snp.makeConstraints { (make) in
make.top.left.bottom.equalTo(0);
make.width.equalTo(80);
}
}
}
| true
|
244a57679b39243d567d2bbf9ceee777ad7b4db8
|
Swift
|
macben/PaperSwift
|
/PaperSwift/PaperSwift/CollectionViewLargeLayout.swift
|
UTF-8
| 2,758
| 2.875
| 3
|
[] |
no_license
|
//
// CollectionViewLargeLayout.swift
// MacBen
//
// Created by ben on 24/10/2014.
// Copyright (c) 2014 meteomodem. All rights reserved.
//
import Foundation
import UIKit
class CollectionViewLargeLayout: UICollectionViewFlowLayout {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init() {
super.init();
self.itemSize = CGSizeMake(CGRectGetWidth(UIScreen.mainScreen().bounds), CGRectGetHeight(UIScreen.mainScreen().bounds))
self.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
self.minimumInteritemSpacing = 10.0
self.minimumLineSpacing = 4.0
self.scrollDirection = UICollectionViewScrollDirection.Horizontal
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
println("proposedContentOffset.x = \(proposedContentOffset.x) \t proposedContentOffset.y = \(proposedContentOffset.y)")
println("velocity.x = \(velocity.x) \t velocity.y = \(velocity.y)")
var offsetAdjustment: CGFloat = CGFloat.max
var horizontalCenter: CGFloat = proposedContentOffset.x + (CGRectGetWidth(self.collectionView!.bounds) / 2.0)
var targetRect: CGRect = CGRectMake(proposedContentOffset.x, 0.0, self.collectionView!.bounds.size.width, self.collectionView!.bounds.size.height)
var layoutAttrArr : Array<AnyObject>! = layoutAttributesForElementsInRect(targetRect)
for layoutAttributes in layoutAttrArr {
println("lol");
if ((layoutAttributes as UICollectionViewLayoutAttributes).representedElementCategory != UICollectionElementCategory.Cell) {
println("ok");
continue; // skip headers
}
var itemHorizontalCenter: CGFloat = (layoutAttributes as UICollectionViewLayoutAttributes).center.x;
println("itemHorizontalCenter = \(itemHorizontalCenter)")
if (abs(itemHorizontalCenter - horizontalCenter) < abs(offsetAdjustment)) {
offsetAdjustment = itemHorizontalCenter - horizontalCenter;
println("offsetAdjustment = \(offsetAdjustment)")
(layoutAttributes as UICollectionViewLayoutAttributes).alpha = 0;
}
}
println("proposedContentOffset.x = \(proposedContentOffset.x)\toffsetAdjustment = \(offsetAdjustment)\tproposedContentOffset.y = \(proposedContentOffset.y)")
return CGPointMake(proposedContentOffset.x + offsetAdjustment, proposedContentOffset.y);
}
}
| true
|
965c4ddbbbaf05f8fdebb209f54ca1b019610db2
|
Swift
|
PieterVandendriessche/Bachelorproef-HoGent
|
/code/iOS/largerText/largerText/ViewController.swift
|
UTF-8
| 727
| 2.8125
| 3
|
[] |
no_license
|
//
// ViewController.swift
// largerText
//
// Created by Pieter Vandendriessche on 01/05/2019.
// Copyright © 2019 Pieter Vandendriessche. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var arialLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//Ophalen van lettertype
var lettertypeVanLabel = arialLabel.font!
//Schalen van bestaande lettertype
var geschaaldLettertype = UIFontMetrics(forTextStyle: .body).scaledFont(for: lettertypeVanLabel)
arialLabel.font = geschaaldLettertype
//Reageren op aanpassingen in schaal (Dynamic type)
arialLabel.adjustsFontForContentSizeCategory = true
}
}
| true
|
2bbf5089881af3d5d6dffd00de476c68efced6a2
|
Swift
|
Falikor/Ihungry
|
/Ihungry/ViewControllers/HomeViewController.swift
|
UTF-8
| 4,817
| 2.890625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// Ihungry
//
// Created by Татьяна Татьяна on 09.06.2021.
//
import UIKit
class HomeViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var homeImag: UIImageView!
@IBOutlet weak var tameCount: UILabel!
@IBOutlet weak var typeFasting: UIPickerView!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var restartButton: UIButton!
private var timer: Timer?
private var durationTime = 0
var answers: [Answer] = []
override func viewDidLoad() {
super.viewDidLoad()
startButton.addTarget(self, action: #selector(startButtonTapped), for: .touchUpInside)
restartButton.isHidden = true
typeFasting.dataSource = self
typeFasting.delegate = self
let letNowYouType = resultTestOfTypeFasting()
updateUI(myType: letNowYouType)
}
@objc func startButtonTapped() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countdown), userInfo: nil, repeats: true)
}
@IBAction func countdown(_ sender: UIButton) {
timerFasting()
}
@IBAction func restartTimer(_ sender: UIButton) {
startButton.isHidden = false
typeFasting.isHidden = false
timer?.invalidate()
restartButton.isHidden = true
}
}
extension HomeViewController {
private func timerFasting() {
startButton.isHidden = true
typeFasting.isHidden = true
restartButton.isHidden = false
durationTime -= 1
var hour = String(durationTime / 3600)
var minutes = String((durationTime % 3600) / 60)
var seconds = String((durationTime % 3600) % 60)
hour = vluesSmolTen(number: hour)
minutes = vluesSmolTen(number: minutes)
seconds = vluesSmolTen(number: seconds)
tameCount.text = hour + ":" + minutes + ":" + seconds
if durationTime == 0 {
timer?.invalidate()
}
}
private func vluesSmolTen(number: String) -> String {
var newNumber = number
if (Int(number) ?? 0) < 10 {
newNumber = String("0" + String(number))
}
return newNumber
}
}
extension HomeViewController {
internal func numberOfComponents(in pickerView: UIPickerView) -> Int {
1
}
internal func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return 4
}
}
extension HomeViewController {
internal func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch row {
case 0:
durationTime = TypeOfFasting.hour6.rawValue
return TypeOfFasting.hour6.definition
case 1:
durationTime = TypeOfFasting.hour8.rawValue
return TypeOfFasting.hour8.definition
case 2:
durationTime = TypeOfFasting.hour12.rawValue
return TypeOfFasting.hour12.definition
case 3:
durationTime = TypeOfFasting.hour24.rawValue
return TypeOfFasting.hour24.definition
default:
print("mistake")
}
return ""
}
}
extension HomeViewController {
private func resultTestOfTypeFasting() -> TypeOfFasting? {
var frequncyOfType: [TypeOfFasting: Int] = [:]
let fastingTypes = answers.map {$0.type}
for fastingType in fastingTypes {
if let fastingTypeCount = frequncyOfType[fastingType] {
frequncyOfType.updateValue(fastingTypeCount + 1, forKey: fastingType)
} else {
frequncyOfType[fastingType] = 1
}
}
let sortedFrequncyOfType = frequncyOfType.sorted {$0.value > $1.value}
guard let mostFrequencyTypeOfFasting = sortedFrequncyOfType.first?.key else {return nil}
return mostFrequencyTypeOfFasting
}
private func updateUI(myType: TypeOfFasting?) {
if myType == nil {
tameCount.text = "00:00:00"
} else {
tameCount.text = "Вам подходит - \(myType?.definition ?? "")"
switch myType {
case .hour24:
typeFasting.selectRow(3, inComponent: 0, animated: true)
case .hour12:
typeFasting.selectRow(2, inComponent: 0, animated: true)
case .hour8:
typeFasting.selectRow(1, inComponent: 0, animated: true)
case .hour6:
typeFasting.selectRow(0, inComponent: 0, animated: true)
case .none:
typeFasting.selectRow(0, inComponent: 0, animated: true)
}
}
}
}
| true
|
24fbdc47858587f7e076af02c28462d0a0431adc
|
Swift
|
bourvill/blog
|
/Sources/Blog/Model/App.swift
|
UTF-8
| 1,407
| 2.671875
| 3
|
[] |
no_license
|
import Foundation
enum App: CaseIterable {
case barista
case mazout
case reefBuddy
case wallabag
case dlm
var name: String {
switch self {
case .barista:
return "Barista - Caffeine Tracker"
case .mazout:
return "Mazout'"
case .reefBuddy:
return "Reef buddy"
case .wallabag:
return "Wallabag"
case .dlm:
return "Deviner le mot"
}
}
var url: String {
switch self {
case .barista:
return "https://apple.co/3oxhXJe"
case .mazout:
return "https://apps.apple.com/us/app/id1442054061"
case .reefBuddy:
return "https://apps.apple.com/fr/app/reef-buddy/id1593580822"
case .wallabag:
return "https://apps.apple.com/us/app/wallabag-2-official/id1170800946?l=fr&ls=1"
case .dlm:
return "https://apps.apple.com/us/app/deviner-le-mot/id986540981?l=fr&ls=1"
}
}
var img: String {
switch self {
case .barista:
return "/img/apps/barista.jpg"
case .mazout:
return "/img/apps/mazout.png"
case .reefBuddy:
return "/img/apps/reefbuddy.png"
case .wallabag:
return "/img/apps/wallabag.png"
case .dlm:
return "/img/apps/dlm.jpg"
}
}
}
| true
|
e5b838591800e02bfe2c1a5aafdf6677e5f21c9a
|
Swift
|
chrispix/swift-poloniex-portfolio
|
/Sources/poloniex/KeyLoader.swift
|
UTF-8
| 863
| 3
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public struct APIKeys {
let key: String
let secret: String
}
public struct KeyLoader {
public static func loadKeys(_ path: String) -> APIKeys? {
guard let data = FileManager.default.contents(atPath: path) else {
print("Couldn't load keys JSON file")
return nil
}
do {
let dict: [String: AnyObject] = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as! [String: AnyObject]
guard let apiKey = dict["API_KEY"] as? String, let secret = dict["API_SECRET"] as? String else {
print("Couldn't find keys in JSON file")
return nil
}
return APIKeys(key: apiKey, secret: secret)
} catch {
print("Couldn't parse keys JSON file")
return nil
}
}
}
| true
|
d80cc910d063ede38a6c4e0116ec73f23b3b2d0b
|
Swift
|
brandonrich/roamer
|
/Roamer/Destination.swift
|
UTF-8
| 441
| 3.03125
| 3
|
[] |
no_license
|
//
// Destination.swift
// Roamer
//
// Created by Brandon Rich2 on 2/9/16.
// Copyright © 2016 Infinite Donuts. All rights reserved.
//
import Foundation
class Destination {
var name : String = ""
var tours : [Tour] = []
var imageName = ""
func addTour( tour: Tour ) {
tours.append(tour)
}
init( name: String, imageName: String ){
self.name = name
self.imageName = imageName
}
}
| true
|
6af939ad3e5f843c9c9a0c1e936ea46e01186c69
|
Swift
|
alexazv/Events-iOS
|
/Events-iOS/View/EventTableViewCell.swift
|
UTF-8
| 1,210
| 2.625
| 3
|
[] |
no_license
|
//
// EventTableViewCell.swift
// Events-iOS
//
// Created by Alexandre Azevedo on 21/01/21.
//
import AlamofireImage
import UIKit
class EventTableViewCell: UITableViewCell {
@IBOutlet weak var eventImage: UIImageView?
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var date: UILabel?
@IBOutlet weak var containerView: UIView?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setup(_ event: Event?) {
guard let event = event else {
return
}
titleLabel?.text = event.title
date?.text = event.dateString
if let url = event.imageUrl {
eventImage?.af.setImage(withURL: url)
}
setupContainerView()
selectionStyle = .none
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
private func setupContainerView() {
containerView?.layer.shadowOpacity = 0.5
containerView?.layer.shadowOffset = CGSize(width: 3, height: 3)
containerView?.layer.shadowRadius = 8.0
containerView?.layer.shadowColor = UIColor.systemGray.cgColor
}
}
| true
|
50305b1de82df67e6ceab61074d6e63af3beb65c
|
Swift
|
radyslavkrechet/BNMovies
|
/App/Source/Modules/Main/SimilarMovies/SimilarMoviesDataSource.swift
|
UTF-8
| 1,319
| 2.96875
| 3
|
[] |
no_license
|
//
// SimilarMoviesDataSource.swift
// Movies
//
// Created by Radyslav Krechet on 9/6/19.
// Copyright © 2020 Radyslav Krechet. All rights reserved.
//
import Domain
protocol SimilarMoviesDataSourceProtocol: ListCollectionDataSourceProtocol where Item == Movie {}
class SimilarMoviesDataSource: NSObject, SimilarMoviesDataSourceProtocol {
var userDidSelectItem: ((Movie) -> Void)?
private var items = [Movie]()
func populate(with items: [Movie]) {
self.items = items
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let movie = items[indexPath.row]
let cell: SimilarMovieCollectionViewCell = collectionView.dequeueReusableCellForIndexPath(indexPath)
cell.populate(with: movie)
return cell
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
let movie = items[indexPath.row]
userDidSelectItem?(movie)
}
}
| true
|
2349199f2ff4c242a2042a281c84e113c173c497
|
Swift
|
bleeckerj/UILabel-FormattedText
|
/UILabel+FormattedText.swift
|
UTF-8
| 9,127
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//
// UILabel+FormattedText.swift
// UILabel+FormattedText
//
// Created by João Costa on 16/09/15.
//
//
import Foundation
import UIKit
extension UILabel {
func fullRange() -> NSRange {
return NSMakeRange(0, (text ?? "").characters.count)
}
// MARK: Range Formatter
func setTextColor(color: UIColor, range: NSRange?) {
guard let range = range else { return }
let text = mutableAttributedString()
text.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
attributedText = text
}
func setFont(font: UIFont, range: NSRange?) {
guard let range = range else { return }
let text = mutableAttributedString()
text.addAttribute(NSFontAttributeName, value: font, range: range)
attributedText = text
}
func setTextUnderline(color: UIColor, range: NSRange?) {
setTextUnderline(color: color, range: range, byWord: false)
}
func setTextUnderline(color: UIColor, range: NSRange?, byWord: Bool) {
guard let range = range else { return }
let text = mutableAttributedString()
var style = NSUnderlineStyle.styleSingle.rawValue
if byWord { style = style | NSUnderlineStyle.byWord.rawValue }
text.addAttribute(NSUnderlineStyleAttributeName, value: NSNumber(value: style), range: range)
text.addAttribute(NSUnderlineColorAttributeName, value: color, range: range)
attributedText = text
}
func setTextWithoutUnderline(range: NSRange?) {
guard let range = range else { return }
let text = mutableAttributedString()
text.removeAttribute(NSUnderlineStyleAttributeName, range: range)
attributedText = text
}
// MARK: String Formatter
func rangeOf(string: String) -> NSRange? {
let range = NSString(string: text ?? "").range(of: string)
return range.location != NSNotFound ? range : nil
}
func setTextColor(color: UIColor, string: String) {
setTextColor(color: color, range: rangeOf(string: string))
}
func setFont(font: UIFont, string: String) {
setFont(font: font, range: rangeOf(string: string))
}
func setTextUnderline(color: UIColor, string: String) {
setTextUnderline(color: color, range: rangeOf(string: string))
}
func setTextUnderline(color: UIColor, string: String, byWord: Bool) {
setTextUnderline(color: color, range: rangeOf(string: string), byWord: byWord)
}
func setTextWithoutUnderline(string: String) {
setTextWithoutUnderline(range: rangeOf(string: string))
}
// MARK: After Formatter
func rangeAfter(string: String) -> NSRange? {
guard var range = rangeOf(string: string) else { return nil }
range.location = range.location + range.length
range.length = text!.characters.count - range.location
return range
}
func setTextColor(color: UIColor, after: String) {
setTextColor(color: color, range: rangeAfter(string: after))
}
func setFont(font: UIFont, after: String) {
setFont(font: font, range: rangeAfter(string: after))
}
func setTextUnderline(color: UIColor, after: String) {
setTextUnderline(color: color, range: rangeAfter(string: after))
}
func setTextUnderline(color: UIColor, after: String, byWord: Bool) {
setTextUnderline(color: color, range: rangeAfter(string: after), byWord: byWord)
}
func setTextWithoutUnderline(after: String) {
setTextWithoutUnderline(range: rangeAfter(string: after))
}
// MARK: Before Formatter
func rangeBefore(string: String) -> NSRange? {
guard var range = rangeOf(string: string) else { return nil }
range.length = range.location
range.location = 0
return range
}
func setTextColor(color: UIColor, before: String) {
setTextColor(color: color, range: rangeBefore(string: before))
}
func setFont(font: UIFont, before: String) {
setFont(font: font, range: rangeBefore(string: before))
}
func setTextUnderline(color: UIColor, before: String) {
setTextUnderline(color: color, range: rangeBefore(string: before))
}
func setTextUnderline(color: UIColor, before: String, byWord: Bool) {
setTextUnderline(color: color, range: rangeBefore(string: before), byWord: byWord)
}
func setTextWithoutUnderline(before: String) {
setTextWithoutUnderline(range: rangeBefore(string: before))
}
// MARK: After & Before Formatter
func rangeAfter(after: String, before: String) -> NSRange? {
guard let rAfter = rangeAfter(string: after) else { return nil }
guard let rBefore = rangeBefore(string: before) else { return nil }
if rAfter.location < rBefore.length {
return NSMakeRange(rAfter.location, rBefore.length - rAfter.location)
}
return nil
}
func setTextColor(color: UIColor, after: String, before: String) {
setTextColor(color: color, range: rangeAfter(after: after, before: before))
}
func setFont(font: UIFont, after: String, before: String) {
setFont(font: font, range: rangeAfter(after: after, before: before))
}
func setTextUnderline(color: UIColor, after: String, before: String) {
setTextUnderline(color: color, range: rangeAfter(after: after, before: before))
}
func setTextUnderline(color: UIColor, after: String, before: String, byWord: Bool) {
setTextUnderline(color: color, range: rangeAfter(after: after, before: before), byWord: byWord)
}
func setTextWithoutUnderline(after: String, before: String) {
setTextWithoutUnderline(range: rangeAfter(after: after, before: before))
}
// MARK: From Formatter
func rangeFrom(string: String) -> NSRange? {
guard var range = rangeOf(string: string) else { return nil }
range.length = text!.characters.count - range.location
return range
}
func setTextColor(color: UIColor, from: String) {
setTextColor(color: color, range: rangeFrom(string: from))
}
func setFont(font: UIFont, from: String) {
setFont(font: font, range: rangeFrom(string: from))
}
func setTextUnderline(color: UIColor, from: String) {
setTextUnderline(color: color, range: rangeFrom(string: from))
}
func setTextUnderline(color: UIColor, from: String, byWord: Bool) {
setTextUnderline(color: color, range: rangeFrom(string: from), byWord: byWord)
}
func setTextWithoutUnderline(from: String) {
setTextWithoutUnderline(range: rangeFrom(string: from))
}
// MARK: To Formatter
func rangeTo(string: String) -> NSRange? {
guard var range = rangeOf(string: string) else { return nil }
range.length = range.location + range.length
range.location = 0
return range
}
func setTextColor(color: UIColor, to: String) {
setTextColor(color: color, range: rangeTo(string: to))
}
func setFont(font: UIFont, to: String) {
setFont(font: font, range: rangeTo(string: to))
}
func setTextUnderline(color: UIColor, to: String) {
setTextUnderline(color: color, range: rangeTo(string: to))
}
func setTextUnderline(color: UIColor, to: String, byWord: Bool) {
setTextUnderline(color: color, range: rangeTo(string: to), byWord: byWord)
}
func setTextWithoutUnderline(to: String) {
setTextWithoutUnderline(range: rangeTo(string: to))
}
// MARK: From & To Formatter
func rangeFrom(from: String, to: String) -> NSRange? {
guard let rFrom = rangeFrom(string: from) else { return nil }
guard let rTo = rangeTo(string: to) else { return nil }
if rFrom.location < rTo.length {
return NSMakeRange(rFrom.location, rTo.length - rFrom.location)
}
return nil
}
func setTextColor(color: UIColor, from: String, to: String) {
setTextColor(color: color, range: rangeFrom(from: from, to: to))
}
func setFont(font: UIFont, from: String, to: String) {
setFont(font: font, range: rangeFrom(from: from, to: to))
}
func setTextUnderline(color: UIColor, from: String, to: String) {
setTextUnderline(color: color, range: rangeFrom(from: from, to: to))
}
func setTextUnderline(color: UIColor, from: String, to: String, byWord: Bool) {
//setTextUnderline(color: color, range: rangeFrom(from: from, to: to), byWord: byWord)
setTextUnderline(color: color, range: rangeFrom(from: from, to: to), byWord: byWord)
}
func setTextWithoutUnderline(from from: String, to: String) {
setTextWithoutUnderline(range: rangeFrom(from: from, to: to))
}
// MARK: Helpers
private func mutableAttributedString() -> NSMutableAttributedString {
if attributedText != nil {
return NSMutableAttributedString(attributedString: attributedText!)
} else {
return NSMutableAttributedString(string: text ?? "")
}
}
}
| true
|
467674e07fa8e4ae36d8f6f34757c6f0f047a63f
|
Swift
|
bcgov/InvasivesBC-iOS
|
/InvasivesBC/TypeDefinitions/Activity.swift
|
UTF-8
| 1,450
| 2.65625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Activity.swift
// InvasivesBC
//
// Created by Anissa Agahchen on 2020-08-24.
// Copyright © 2020 Government of British Columbia. All rights reserved.
//
// HOW TO QUERY FROM DEBUGGER po try Row.fetchAll(db, sql: "select * from activity")
import Foundation
import GRDB
struct Activity: Codable {
var local_id: Int64?
var activityType: String
var activitySubType: String
var deviceRequestUID: String
var date: Date
var synched: Bool
var synch_error: Bool
var synch_error_string: String
}
// SQL generation
extension Activity: TableRecord {
/// The table columns
enum Columns {
static let local_id = Column(CodingKeys.local_id)
static let activityType = Column(CodingKeys.activityType)
static let activitySubType = Column(CodingKeys.activitySubType)
static let deviceRequestUID = Column(CodingKeys.deviceRequestUID)
static let date = Column(CodingKeys.date)
static let synched = Column(CodingKeys.synched)
static let synch_error = Column(CodingKeys.synch_error)
static let synch_error_string = Column(CodingKeys.synch_error_string)
}
}
// Fetching methods
extension Activity: FetchableRecord { }
// Persistence methods
extension Activity: MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(with rowID: Int64, for column: String?) {
local_id = rowID
}
}
| true
|
569456b4d39ba855551d0c9610990529d1bf6d66
|
Swift
|
lmsampson/ios-sprint1-challenge
|
/Movie List/MovieTableViewCell.swift
|
UTF-8
| 1,017
| 2.921875
| 3
|
[] |
no_license
|
//
// MovieTableViewCell.swift
// Movie List
//
// Created by Lisa Sampson on 7/27/18.
// Copyright © 2018 Lambda School. All rights reserved.
//
import UIKit
protocol MovieTableViewCellDelegate: class {
func isSeenButtonWasTapped(on cell: MovieTableViewCell)
}
class MovieTableViewCell: UITableViewCell {
private func updateViews() {
guard let movie = movie else { return }
if movie.isSeen == false {
isSeenButton.setTitle("Not Seen", for: .normal)
} else {
isSeenButton.setTitle("Seen", for: .normal)
}
movieLabel.text = movie.movie
}
@IBAction func isSeenWasTapped(_ sender: Any) {
delegate?.isSeenButtonWasTapped(on: self)
}
var movie: Movie? {
didSet {
updateViews()
}
}
weak var delegate: MovieTableViewCellDelegate?
@IBOutlet weak var movieLabel: UILabel!
@IBOutlet weak var isSeenButton: UIButton!
}
| true
|
e56d4df734b5a820e013c6196c0a89dff6d29d13
|
Swift
|
praja4267/SwiftLeetcode
|
/Project/SwiftLeetcode/SwiftLeetcode/Solutions/Easy69.swift
|
UTF-8
| 576
| 2.96875
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// Easy69.swift
// SwiftLeetcode
//
// Created by roosky on 12/29/18.
// Copyright © 2018 K W. All rights reserved.
//
/**
69. Sqrt(x)
https://leetcode.com/problems/sqrtx
time: O(LogN), binary search
space: O(1)
**/
import UIKit
class Easy69: NSObject {
func mySqrt(_ x: Int) -> Int {
var low = 0
var high = x + 1
while low < high {
let m = low + (high - low) / 2
if m * m > x {
high = m
} else {
low = m + 1
}
}
return low - 1
}
}
| true
|
56236e8ec81a702c10b7c448ce912289fc014652
|
Swift
|
TheFrenchGuy/FoodyScan
|
/FoodyScan/Settings Module/SettingsView.swift
|
UTF-8
| 1,627
| 3.140625
| 3
|
[] |
no_license
|
//
// SettingsView.swift
// FoodyScan
//
// Created by Noe De La Croix on 13/08/2020.
// Copyright © 2020 Noe De La Croix. All rights reserved.
//
import SwiftUI
struct SettingsView: View {
@Environment(\.presentationMode) var presentation
@State var showSettings:Int = 1 //So the view can toggle between 3 stats (needed as the view wont be dismissed this is a known bug so i have to display a drag down animation when the view in the back ground changes)
var body: some View {
GeometryReader { bounds in
NavigationView {
ZStack {
if self.showSettings == 1{
SettingsBlockView(showSettings: self.$showSettings) //The view the user see when he taps on the settings icon/text in the menu
}
if self.showSettings == 2{
ResetIntakeView() //When the user select to reset his daily intake a drag down animation information the user that he needs to drag down to reset his daily intake
}
if self.showSettings == 3{
LogoutView() //When the user select to log out of the application , to make the view disappeer he needs to drag down the view in the background would already have been loaded.
}
Spacer()
}
}.frame(width: bounds.size.width, height: bounds.size.height)
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
struct SettingsView_Previews: PreviewProvider {
static var previews: some View {
SettingsView()
}
}
| true
|
2ea894900c3f4e0c02919151c17c58915ebdce5e
|
Swift
|
Oxymoron1234/MY-IOS-PRojects-
|
/Quizzler-iOS13/Quizzler-iOS13/Model/Questions.swift
|
UTF-8
| 160
| 2.984375
| 3
|
[] |
no_license
|
import Foundation
struct Questions {
let ask : String
let answer : String
init(q: String, a : String) {
ask = q
answer = a
}
}
| true
|
253627609255c6319f11318a18cc0c9a8fda37cc
|
Swift
|
ok-study/algorithm
|
/m0su/algorithm.playground/Contents.swift
|
UTF-8
| 681
| 3.6875
| 4
|
[] |
no_license
|
//놀이기구의 이용료 price : 1 ≤ price ≤ 2,500, price는 자연수
//처음 가지고 있던 금액 money : 1 ≤ money ≤ 1,000,000,000, money는 자연수
//놀이기구의 이용 횟수 count : 1 ≤ count ≤ 2,500, count는 자연수
// price가 3인 놀이기구를 4번 타고 싶은 고객이 가진 현금이 20이면
// (3*1) + (3*2) + (3*3) + (3*4) = 30
// 1n+2n+...+kn = nk(k+1)/2
// 30-20은 10
import Foundation
func solution(_ price: Int, _ money: Int, _ count: Int) -> Int64 {
let totalPrice = price * (count * (count+1) / 2)
if money >= totalPrice { return 0 }
return Int64(totalPrice - money)
}
print("result: \(solution(3, 20, 4))")
| true
|
d602db48b65f84c9f1fdc828d357e46a962350d1
|
Swift
|
tanakat2020/Eng_shuffle2
|
/engwatch Extension/ComplicationController.swift
|
UTF-8
| 24,689
| 2.828125
| 3
|
[] |
no_license
|
import ClockKit
class ComplicationController: NSObject, CLKComplicationDataSource {
// MARK: - Timeline Configuration
// Define whether the app can provide future data.
func getSupportedTimeTravelDirections(for complication: CLKComplication,
withHandler handler:@escaping (CLKComplicationTimeTravelDirections) -> Void) {
// Indicate that the app can provide future timeline entries.
handler([.forward])
}
// Define how far into the future the app can provide data.
func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) {
// Indicate that the app can provide timeline entries for the next 24 hours.
handler(Date().addingTimeInterval(24.0 * 60.0 * 60.0))
}
// Define whether the complication is visible when the watch is unlocked.
func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) {
// This is potentially sensitive data. Hide it on the lock screen.
handler(.hideOnLockScreen)
}
// Return the current timeline entry.
func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) {
// Call the handler with the current timeline entry
print("log0210 getCurrentTimelineEntry")
handler(createTimelineEntry(forComplication: complication, date: Date()))
}
// Return future timeline entries.
func getTimelineEntries(for complication: CLKComplication,
after date: Date,
limit: Int,
withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) {
// handler(nil)
let fiveMinutes = 5.0 * 60.0
let twentyFourHours = 24.0 * 60.0 * 60.0
// Create an array to hold the timeline entries.
var entries = [CLKComplicationTimelineEntry]()
// Calculate the start and end dates.
var current = date.addingTimeInterval(fiveMinutes)
let endDate = date.addingTimeInterval(twentyFourHours)
let dateFormater = DateFormatter()
dateFormater.locale = Locale(identifier: "ja_JP")
dateFormater.dateFormat = "yyyy-MM-dd HH:mm:ss"
// print(current)
// print(endDate)
print("date : " + dateFormater.string(from: date))
print("current : " + dateFormater.string(from: current))
print("endDate : " + dateFormater.string(from: endDate))
print("limit: " + String(limit))
// Create a timeline entry for every five minutes from the starting time.
// Stop once you reach the limit or the end date.
// var count = 0
while (current.compare(endDate) == .orderedAscending) && (entries.count < limit) {
entries.append(createTimelineEntry(forComplication: complication, date: current))
//entries.append(createTimelineEntry(for: complication, date: current))
current = current.addingTimeInterval(fiveMinutes)
// print("count: " + String(count))
// print("current2: " + dateFormater.string(from: current))
// count = count + 1
}
// print("current2: " + dateFormater.string(from: current))
current = date.addingTimeInterval(0)
// print("current3: " + dateFormater.string(from: current))
handler(entries)
}
//https://qiita.com/MilanistaDev/items/a2325ce916f625aa1d44
func getComplicationDescriptors(handler: @escaping ([CLKComplicationDescriptor]) -> Void) {
print("getComplicationDescriptors")
let mySupportedFamilies = CLKComplicationFamily.allCases
// Create the condition descriptor.
let conditionDescriptor = CLKComplicationDescriptor(
identifier: "complication_Identifier",
displayName: "ENS-status",
supportedFamilies: mySupportedFamilies)
// Call the handler and pass an array of descriptors.
handler([conditionDescriptor])
}
private func createTimelineEntry(forComplication complication: CLKComplication, date: Date) -> CLKComplicationTimelineEntry {
// let userDefaults = UserDefaults.standard
// if let messageA = userDefaults.string(forKey: "message3") {
// //print("createTimelineEntry messageA: " + messageA)
// }
// else{
// print("createTimelineEntry No messageA")
// }
let template = getComplicationTemplate(forComplication: complication, date: date)
return CLKComplicationTimelineEntry(date: date, complicationTemplate: template)
// if let template = getComplicationTemplate(for: complication, date: date) {
// print("log0210 getCurrentTimelineEntry")
// let entry = CLKComplicationTimelineEntry(date: Date(), complicationTemplate: template)
// handler(entry)
// } else {
// handler(nil)
// }
// Get the correct template based on the complication.
// let template = createTemplate(forComplication: complication, date: date)
// Use the template and date to create a timeline entry.
// return CLKComplicationTimelineEntry(date: date, complicationTemplate: template)
}
func getComplicationTemplate(forComplication complication: CLKComplication, date: Date) -> CLKComplicationTemplate {
switch complication.family {
case .graphicCircular:
// print("graphicCircular")
return createGraphicCircleTemplate(forDate: date)
case .graphicRectangular:
// return CLKComplicationTemplateGraphicRectangularFullView(ContentView())
// print("graphicRectangular")
return createGraphicRectangularTemplate(forDate: date)
case .modularSmall:
return createModularSmallTemplate(forDate: date)
case .modularLarge:
return createModularLargeTemplate(forDate: date)
case .utilitarianSmall:
return createutilitarianSmallTemplate(forDate: date)
case .utilitarianSmallFlat:
return createutilitarianSmallTemplate(forDate: date)
case .utilitarianLarge:
return createutilitarianLargeTemplate(forDate: date)
case .circularSmall:
return createcircularSmallTemplate(forDate: date)
case .extraLarge:
return createextraLargeTemplate(forDate: date)
case .graphicCorner:
return creategraphicCornerTemplate(forDate: date)
case .graphicBezel:
return creategraphicBezelTemplate(forDate: date)
case .graphicExtraLarge:
return createGraphicExtraLargeTemplate(forDate: date)
@unknown default:
fatalError("*** Unknown Complication Family ***")
}
}
//設定する時のプレ画面
func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) {
let future = Date().addingTimeInterval(25.0 * 60.0 * 60.0)
let template = getComplicationTemplate(forComplication: complication, date: future)
handler(template)
}
private func creategraphicBezelTemplate(forDate date: Date) -> CLKComplicationTemplate {
// Create the template using the providers.
let circularTemplate = CLKComplicationTemplateGraphicCircularStackText(line1TextProvider: CLKSimpleTextProvider(text: "0.491"), line2TextProvider: CLKSimpleTextProvider(text: "0.491"))
let template = CLKComplicationTemplateGraphicBezelCircularText(circularTemplate: circularTemplate)
return template
}
private func creategraphicCornerTemplate(forDate date: Date) -> CLKComplicationTemplate {
// Create the template using the providers.
let gaugeColor = UIColor(red: 0.0, green: 167.0/255.0, blue: 219.0/255.0, alpha: 1.0)
let template = CLKComplicationTemplateGraphicCornerGaugeText(gaugeProvider: CLKSimpleGaugeProvider(style: .fill,
gaugeColor: gaugeColor,
fillFraction: 0), outerTextProvider: CLKSimpleTextProvider(text: "0.491"))
return template
}
private func createextraLargeTemplate(forDate date: Date) -> CLKComplicationTemplate {
// Create the template using the providers.
let template = CLKComplicationTemplateExtraLargeColumnsText(row1Column1TextProvider: CLKSimpleTextProvider(text: "11"), row1Column2TextProvider: CLKSimpleTextProvider(text: "11"), row2Column1TextProvider: CLKSimpleTextProvider(text: "11"), row2Column2TextProvider: CLKSimpleTextProvider(text: "11"))
template.column2Alignment = .leading
template.highlightColumn2 = false
return template
}
private func createcircularSmallTemplate(forDate date: Date) -> CLKComplicationTemplate {
// Create the template using the providers.
let template = CLKComplicationTemplateCircularSmallSimpleText(textProvider: CLKSimpleTextProvider(text: "001"))
return template
}
private func createutilitarianLargeTemplate(forDate date: Date) -> CLKComplicationTemplate {
// Create the template using the providers.
let template = CLKComplicationTemplateUtilitarianLargeFlat(textProvider: CLKSimpleTextProvider(text: "001"))
return template
}
private func createutilitarianSmallTemplate(forDate date: Date) -> CLKComplicationTemplate {
// Create the template using the providers.
let template = CLKComplicationTemplateUtilitarianSmallFlat(textProvider: CLKSimpleTextProvider(text: "001"))
return template
}
private func createModularLargeTemplate(forDate date: Date) -> CLKComplicationTemplate {
// Create the template using the providers.
let template = CLKComplicationTemplateModularLargeTable(headerTextProvider: CLKSimpleTextProvider(text: "001"), row1Column1TextProvider: CLKSimpleTextProvider(text: "001"), row1Column2TextProvider: CLKSimpleTextProvider(text: "001"), row2Column1TextProvider: CLKSimpleTextProvider(text: "001"), row2Column2TextProvider: CLKSimpleTextProvider(text: "001"))
return template
}
// Return a modular small template.
private func createModularSmallTemplate(forDate date: Date) -> CLKComplicationTemplate {
// Create the data providers.
// let mgCaffeineProvider = CLKSimpleTextProvider(text: "0.491")
// let mgUnitProvider = CLKSimpleTextProvider(text: "mg Caffeine", shortText: "mg")
//
// Create the template using the providers.
//let template = CLKComplicationTemplateModularSmallStackText()
// template.line1TextProvider = mgCaffeineProvider
// template.line2TextProvider = mgUnitProvider
let template = CLKComplicationTemplateModularSmallSimpleText(textProvider: CLKSimpleTextProvider(text: "001") )
return template
}
// Return a graphic circle template.
private func createGraphicCircleTemplate(forDate date: Date) -> CLKComplicationTemplate {
// Create the data providers.
let userDefaults = UserDefaults.standard
//削除処理
//UserDefaults.standard.removeObject(forKey: "olddate_value")
userDefaults.register(defaults: ["olddate_value" : "2021-02-16"])
//if (false) {
//if let messageA = userDefaults.string(forKey: "message3") {
if let messageA = userDefaults.string(forKey: "message3") {
// print("createGraphicCircleTemplate messageA: " + messageA)
// if dataList.count == 3 {
// let textString = "Eng_shu: " + dataList[2]
// // print("textString: ", textString)
// textTemplate.headerTextProvider = CLKSimpleTextProvider(text: textString )
// }
// else if dataList.count == 5 {
// let textString = "Eng_shu: " + dataList[4]
// // print("textString: ", textString)
// textTemplate.headerTextProvider = CLKSimpleTextProvider(text: textString )
// }
// else{
// textTemplate.headerTextProvider = CLKSimpleTextProvider(text: "Eng_shu")
// }
//改行区切りでデータを分割して配列に格納する。
var dataList:[String] = []
dataList = messageA.components(separatedBy: "\n")
// print("log0200 ComplicationController.swift dataList.count: " + String(dataList.count))
// Infograph Modular, Infographのみ
// circularTemplateの実装
// gaugeProvider, centerTextProvider が必要
//"-"区切りでデータを分割して配列に格納する。
var dataList2:[String] = []
if dataList.count == 5 {
dataList2 = dataList[4].components(separatedBy: "-")
// print("dataList2: ", dataList2[0], " dataList2[1]: ", dataList2[1])
}
else{
dataList2.append("")
dataList2.append("")
dataList2[0] = "000"
dataList2[1] = "0"
// print("dataList2: ")
// print(dataList2)
}
// centerTextProviderの実装
// let centerText = CLKSimpleTextProvider(text: dataList[4])
let centerText = CLKSimpleTextProvider(text: dataList2[0])
centerText.tintColor = .white
let bottomText = CLKSimpleTextProvider(text: "Ens")
bottomText.tintColor = .white
//dataList[4] = "999"
var value:Int = Int(dataList2[1])!
if value > 20 {
value = 20
}
if dataList2[1] == "999" {
value = 0
}
// var currentdate = ""
// currentdate = getNowClockString()
// //currentdate = "2021-03-01"
// let olddate = userDefaults.string(forKey: "olddate_value")!
// //TodaysAnswerDate = "2017-06-25"
// print("currentdate: ", currentdate, " olddate: ", olddate)
//
// //UserDefaultsがうまく動いていない? 20210216
// if currentdate != olddate {
// userDefaults.set(currentdate, forKey: "olddate_value")
// //userDefaults.set(olddate, forKey: "olddate_value")
// //同期
// userDefaults.synchronize()
// value = 0
// }
let value_f:Float = Float(Float(value)/20)
// print("value: ", value, " value_f: ", value_f)
// gaugeProviderの実装
// let gaugeColor = UIColor(red: 255/255, green: 122/255.0, blue: 50/255.0, alpha: 1.0)
let gaugeColor = UIColor(red: 0.0, green: 167.0/255.0, blue: 219.0/255.0, alpha: 1.0)
let gaugeProvider =
CLKSimpleGaugeProvider(style: .fill,
gaugeColor: gaugeColor,
fillFraction: value_f)
let circularClosedGaugeTemplate = CLKComplicationTemplateGraphicCircularOpenGaugeSimpleText(gaugeProvider: gaugeProvider, bottomTextProvider: bottomText, centerTextProvider: centerText)
return circularClosedGaugeTemplate
}
else{
print("No messageA 1")
// centerTextProviderの実装
// let centerText = CLKSimpleTextProvider(text: dataList[4])
let centerText = CLKSimpleTextProvider(text: "000")
centerText.tintColor = .white
let bottomText = CLKSimpleTextProvider(text: "Ens")
bottomText.tintColor = .white
let value_f:Float = 0
// gaugeProviderの実装
// let gaugeColor = UIColor(red: 255/255, green: 122/255.0, blue: 50/255.0, alpha: 1.0)
let gaugeColor = UIColor(red: 0.0, green: 167.0/255.0, blue: 219.0/255.0, alpha: 1.0)
let gaugeProvider =
CLKSimpleGaugeProvider(style: .fill,
gaugeColor: gaugeColor,
fillFraction: value_f)
let circularClosedGaugeTemplate = CLKComplicationTemplateGraphicCircularOpenGaugeSimpleText(gaugeProvider: gaugeProvider, bottomTextProvider: bottomText, centerTextProvider: centerText)
return circularClosedGaugeTemplate
//Coffee BreakのComplication
// // Create the data providers.
// let percentage = Float(0.0)
//
// let gaugeProvider = CLKSimpleGaugeProvider(style: .fill,
// gaugeColors: [.green, .yellow, .red],
// gaugeColorLocations: [0.0, 300.0 / 500.0, 450.0 / 500.0] as [NSNumber],
// fillFraction: percentage)
//
// let mgCaffeineProvider = CLKSimpleTextProvider(text: "test")
// let mgUnitProvider = CLKSimpleTextProvider(text: "mg Caffeine", shortText: "mg")
// // mgUnitProvider.tintColor = data.color(forCaffeineDose: data.mgCaffeine(atDate: date))
// mgUnitProvider.tintColor = .red
//
// // Create the template using the providers.
// let template = CLKComplicationTemplateGraphicCircularOpenGaugeSimpleText(gaugeProvider: gaugeProvider, bottomTextProvider: CLKSimpleTextProvider(text: "mg"), centerTextProvider: mgCaffeineProvider)
// return template
}
}
// Return a large rectangular graphic template.
private func createGraphicRectangularTemplate(forDate date: Date) -> CLKComplicationTemplate {
let userDefaults = UserDefaults.standard
// if let messageA = userDefaults.object(forKey: "message3") as? String {
if let messageA = userDefaults.string(forKey: "message3") {
print("createGraphicRectangularTemplate messageA: " + messageA)
//改行区切りでデータを分割して配列に格納する。
var dataList:[String] = []
dataList = messageA.components(separatedBy: "\n")
// dataList.removeLast()
// for i in 0...dataList.count - 1 {
// print("dataList: " + dataList[i] )
// }
// print("dataList.count: " + String(dataList.count))
var textString = ""
var textString2 = ""
if dataList.count == 3 {
textString = "Eng_shu: " + dataList[2]
// print("textString: ", textString)
}
else if dataList.count == 5 {
textString = "Eng_shu: " + dataList[4]
// print("textString: ", textString)
textString2 = dataList[2]
}
else{
textString = "Eng_shu"
}
let textTemplate = CLKComplicationTemplateGraphicRectangularStandardBody(headerTextProvider: CLKSimpleTextProvider(text: textString ), body1TextProvider: CLKSimpleTextProvider(text: dataList[0] ), body2TextProvider: CLKSimpleTextProvider(text: textString2 ))
return textTemplate
}
else{
print("No messageA 2")
let textString = "Eng_shu:000-00"
let textString2 = "test"
let textString3 = "test"
let textTemplate = CLKComplicationTemplateGraphicRectangularStandardBody(headerTextProvider: CLKSimpleTextProvider(text: textString ), body1TextProvider: CLKSimpleTextProvider(text: textString2 ), body2TextProvider: CLKSimpleTextProvider(text: textString3 ))
return textTemplate
//Coffee Breask用Complication
// // Create the data providers.
// //let imageProvider = CLKFullColorImageProvider(fullColorImage: #imageLiteral(resourceName: "CoffeeGraphicRectangular"))
// let titleTextProvider = CLKSimpleTextProvider(text: "Coffee Tracker", shortText: "Coffee")
//
// let mgCaffeineProvider = CLKSimpleTextProvider(text: "0.491")
// let mgUnitProvider = CLKSimpleTextProvider(text: "mg Caffeine", shortText: "mg")
// //mgUnitProvider.tintColor = data.color(forCaffeineDose: data.mgCaffeine(atDate: date))
// // if #available(watchOSApplicationExtension 6.0, *) {
// // _ = CLKTextProvider(format: "%@ %@", mgCaffeineProvider, mgUnitProvider)
// // } else {
// // // Fallback on earlier versions
// // }
// _ = CLKTextProvider(format: "%@ %@", mgCaffeineProvider, mgUnitProvider)
//
// let percentage = Float(min(0.491 / 500.0, 1.0))
// let gaugeProvider = CLKSimpleGaugeProvider(style: .fill,
// gaugeColors: [.green, .yellow, .red],
// gaugeColorLocations: [0.0, 300.0 / 500.0, 450.0 / 500.0] as [NSNumber],
// fillFraction: percentage)
//
// // Create the template using the providers.
// let template = CLKComplicationTemplateGraphicRectangularTextGauge(headerTextProvider: titleTextProvider, body1TextProvider: CLKSimpleTextProvider(text: "test"), gaugeProvider: gaugeProvider)
// return template
}
}
// Returns an extra large graphic template
@available(watchOSApplicationExtension 7.0, *)
private func createGraphicExtraLargeTemplate(forDate date: Date) -> CLKComplicationTemplate {
// Create the data providers.
let percentage = Float(signOf: 0.491 / 500.0, magnitudeOf: 1.0)
let gaugeProvider = CLKSimpleGaugeProvider(style: .fill,
gaugeColors: [.green, .yellow, .red],
gaugeColorLocations: [0.0, 300.0 / 500.0, 450.0 / 500.0] as [NSNumber],
fillFraction: percentage)
let mgCaffeineProvider = CLKSimpleTextProvider(text: "0.491")
return CLKComplicationTemplateGraphicExtraLargeCircularOpenGaugeSimpleText(
gaugeProvider: gaugeProvider,
bottomTextProvider: CLKSimpleTextProvider(text: "mg"),
centerTextProvider: mgCaffeineProvider)
}
// //現在時刻の取得
// func getNowClockString() -> String {
// let formatter = DateFormatter()
// //formatter.dateFormat = "yyyy-MM-dd' 'HH:mm:ss"
// formatter.dateFormat = "yyyy-MM-dd"
// let now = Date()
// return formatter.string(from: now)
// }
}
| true
|
ff23a9a74988c8e26440faf627bf37f21178ae1b
|
Swift
|
raonivaladares/adventure_ios
|
/adventure_ios/LoopGameViewController.swift
|
UTF-8
| 797
| 2.859375
| 3
|
[] |
no_license
|
import UIKit
class LoopGameViewController: UIViewController {
@IBOutlet weak var timerLabel: UILabel!
var minutes = 2
var seconds = 60
var timer = Timer()
@IBAction func startAdventureViewAction(_ sender: UIButton) {
timer = Timer.scheduledTimer(timeInterval: 1.0,
target: self,
selector: #selector(tick),
userInfo: nil,
repeats: true)
}
@objc func tick() {
timer.invalidate()
timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
}
@objc func timerAction() {
if seconds > 0 {
seconds -= 1
} else {
seconds = 59
minutes -= 1
if minutes == 0 {
timer.invalidate()
seconds = 0
}
}
timerLabel.text = "\(minutes) : \(seconds)"
}
}
| true
|
014bf162f4f990ff33091618262110daff9ad432
|
Swift
|
TrendingTechnology/network-monitor-ios
|
/NetworkMonitor/Classes/Extension/FNMAdditions.swift
|
UTF-8
| 7,355
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
//
// Copyright (c) 2020, Farfetch.
// All rights reserved.
//
// This source code is licensed under the MIT-style license found in the
// LICENSE file in the root directory of this source tree.
//
import Foundation
public extension Sequence where Iterator.Element == NSRegularExpression {
func containsMatches(in string: String,
options: NSRegularExpression.MatchingOptions = []) -> Bool {
return self.contains { regularExpression -> Bool in
return regularExpression.firstMatch(in: string,
options: options,
range: NSRange(location: 0, length: string.count)) != nil
}
}
}
public extension Sequence where Iterator.Element == String {
func computedRegularExpressions() throws -> [NSRegularExpression] {
return try self.compactMap { try NSRegularExpression(pattern: $0,
options: []) }
}
}
public extension Sequence where Iterator.Element == FNMRequestNode {
func node(for record: FNMHTTPRequestRecord) -> FNMRequestNode? {
guard let absoluteURLString = record.request.url?.absoluteString else { return nil }
return self.filter { $0.expressions.containsMatches(in: absoluteURLString) }.first
}
}
public extension Sequence where Iterator.Element == [Any] {
func allValuesHaveEqualCounts() -> Bool {
return Set(self.map { $0.count }).count == 1
}
}
public extension Array where Iterator.Element == Double {
func medianValue() -> Double? {
guard self.count != 0 else { return nil }
return self.reduce(0.0, +) / Double(self.count)
}
}
public extension NSData {
convenience init?(inputStream: InputStream,
bufferSize: Int = 4096) {
guard let data = NSMutableData(capacity: bufferSize) else { return nil }
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
inputStream.open()
while inputStream.hasBytesAvailable {
let read = inputStream.read(buffer, maxLength: bufferSize)
if read == 0 {
break
}
data.append(buffer, length: read)
}
buffer.deallocate()
inputStream.close()
self.init(data: data as Data)
}
}
public extension HTTPURLResponse {
func isSuccessful() -> Bool {
return 200...399 ~= self.statusCode
}
}
public extension NSString {
func rangesOfSubstring(_ substring: NSString) -> [NSRange] {
var ranges = [NSRange]()
var enclosingRange = NSRange(location: 0,
length: self.length)
while enclosingRange.location < self.length {
enclosingRange.length = self.length - enclosingRange.location
let foundRange = self.range(of: substring as String,
options: [.caseInsensitive],
range: enclosingRange)
if foundRange.location != NSNotFound {
enclosingRange.location = foundRange.location + foundRange.length
ranges.append(foundRange)
} else {
// no more substring to find
break
}
}
return ranges
}
}
extension Dictionary where Key == String, Value == String {
func contains(pair: (key: Key, value: Value)) -> Bool {
return self.contains { return pair.key == $0.key && pair.value == $0.value }
}
func contains(otherDictionary: [Key: Value]) -> Bool {
return otherDictionary.filter { (pair) -> Bool in return self.contains(pair: pair) == false }.count == 0
}
}
public extension Decodable {
static func decodedElements<T: Decodable>(from bundle: Bundle,
filename: String) -> [T] {
if let fileURL = bundle.url(forResource: filename,
withExtension: "json") {
do {
let JSONData = try Data(contentsOf: fileURL) as Data
let profiles = try JSONDecoder().decode([T].self,
from: JSONData)
return profiles
} catch {
print("Failed To Decode Elements With Error: \(error)")
}
}
return []
}
}
// Profile Matching
extension NSURLRequest {
enum ProfileMatchingResult {
case noDataSource
case noAvailableProfiles
case noMatchedProfiles(profileRequestMatchingResults: [FNMProfile.ProfileRequestMatchingResult])
case noAvailableProfileResponse(profile: FNMProfile)
case matchedProfileAndResponse(profile: FNMProfile, response: FNMProfileResponse)
func prettyPrinted(for request: URLRequest) -> String {
switch self {
case .noDataSource: return "❌ No dataSource for \(String(describing: request.url?.absoluteString))"
case .noAvailableProfiles: return "❌ No available profiles for \(String(describing: request.url?.absoluteString))"
case .noMatchedProfiles(let results): return "❌ No matched profile: \(results.prettyPrinted(for: request))"
case .noAvailableProfileResponse(let profile): return "❌ Matched profile but response was unavailable \(profile.request.urlPattern)"
case .matchedProfileAndResponse(let profile, let response): return "✅ Matched profile and response for \(String(describing: request.url?.absoluteString)):\n\(profile) => \(profile.request.urlPattern)\n👇\n\(String(describing: response.jsonResponse()))"
}
}
}
func profileMatchingResult(dataSource: FNMNetworkMonitorURLProtocolDataSourceProfile?) -> ProfileMatchingResult {
guard let dataSource = dataSource else {
return .noDataSource
}
guard dataSource.availableProfiles().count > 0 else {
return .noAvailableProfiles
}
let individualProfileRequestMatchingResults = dataSource.availableProfiles().map { profile -> FNMProfile.ProfileRequestMatchingResult in return profile.matches(self) }
let firstAvailableProfile = individualProfileRequestMatchingResults.compactMap { (result) -> FNMProfile? in
switch result {
case .hit(let profile, _):
return profile
default:
return nil
}
}.first
guard let availableProfile = firstAvailableProfile else {
return .noMatchedProfiles(profileRequestMatchingResults: individualProfileRequestMatchingResults)
}
let appropriateProfileResponse = availableProfile.appropriateResponse(allowable: dataSource.availableProfileResponseAllowable(),
request: self)
guard let availableProfileResponse = appropriateProfileResponse else {
return .noAvailableProfileResponse(profile: availableProfile)
}
return .matchedProfileAndResponse(profile: availableProfile,
response: availableProfileResponse)
}
}
| true
|
0695340a26d303076f85632d548c813248589d2c
|
Swift
|
kons16/labo_atte
|
/iOS/labo_atte/labo_atte/Data/Repository/GroupRepository.swift
|
UTF-8
| 1,419
| 2.859375
| 3
|
[] |
no_license
|
//
// GroupRepository.swift
// ShareTodo
//
// Created by jun on 2020/09/15.
// Copyright © 2020 jun. All rights reserved.
//
import Firebase
class GroupRepository: GroupRepositoryProtocol {
private var firestore: Firestore!
private var listener: ListenerRegistration?
init() {
self.setUpFirestore()
}
deinit {
listener?.remove()
}
func setUpFirestore() {
self.firestore = Firestore.firestore()
let settings = FirestoreSettings()
self.firestore.settings = settings
}
func fetchGroup(groupID: String) {
let documentRef = "todo/v1/groups/" + groupID
self.listener = self.firestore.document(documentRef).addSnapshotListener { (document, error) in
if let error = error {
print("Error: \(error)")
return
}
guard let document = document, document.exists else {
print("The document doesn't exist.")
return
}
do {
let groupData = try document.data(as: Group.self)
guard let group = groupData else { return }
GroupDataStore.groupDataStore.append(group: group)
} catch let error {
print("Error: \(error.localizedDescription)")
}
}
}
}
| true
|
bd722a4b685a4a9e3aff29d0912a014e9775def0
|
Swift
|
boram611/IOS_WooBoo
|
/WooBoo_Project/WooBoo_Project/Models/userUpdateModel.swift
|
UTF-8
| 1,161
| 2.734375
| 3
|
[] |
no_license
|
//
// userUpdateModel.swift
// WooBoo_Project
//
// Created by 김보람 on 2021/02/28.
//
import Foundation
class userUpdateModel: NSObject{
var urlPath = "http://127.0.0.1:8080/ios_jsp/wooboo_userUpdate.jsp?uEmail=\(Share.userID)"
func insertItems(pw: String, uImageFileName: String) -> Bool{
var result: Bool = true
let urlAdd = "&pw=\(pw)&uImageFileName=\(uImageFileName)"
urlPath = urlPath + urlAdd
print("urlPath \(urlPath)")
//한글 url encoding
urlPath = urlPath.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url){(data, response, error) in
if error != nil{
print("Failed to update data")
result = false
}else{
print("Data is update!")
result = true
}
}
task.resume()
return result
}
}//======
| true
|
0c929b5bffcfc13a5a88a8ed1c8c8686e068773a
|
Swift
|
tobybell/assassin
|
/Assassin/InputCell.swift
|
UTF-8
| 4,110
| 2.828125
| 3
|
[] |
no_license
|
//
// InputCell.swift
// Assassin
//
// Created by Tobin Bell on 11/7/15.
// Copyright © 2015 Tobin Bell. All rights reserved.
//
import UIKit
class InputCell: UITableViewCell {
var keyButton = UIButton()
var valueField = UITextField()
var key: String? {
get {
return keyButton.titleForState(.Normal)
}
set(newKey) {
keyButton.setTitle(newKey, forState: .Normal)
valueField.placeholder = newKey
}
}
var value: String? {
get {
return valueField.text
}
set(newValue) {
valueField.text = newValue
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .None
keyButton.translatesAutoresizingMaskIntoConstraints = false
keyButton.setTitleColor(kAssassinRedColor, forState: .Normal)
keyButton.titleLabel?.font = UIFont.systemFontOfSize(12)
keyButton.contentHorizontalAlignment = .Right
keyButton.addTarget(valueField, action: "becomeFirstResponder", forControlEvents: .TouchUpInside)
valueField.translatesAutoresizingMaskIntoConstraints = false
valueField.font = UIFont.systemFontOfSize(16)
valueField.borderStyle = .None
valueField.returnKeyType = .Done
valueField.addTarget(valueField, action: "resignFirstResponder", forControlEvents: .PrimaryActionTriggered)
contentView.addSubview(keyButton)
contentView.addSubview(valueField)
updateConstraintsIfNeeded()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func updateConstraints() {
super.updateConstraints()
// Key button
contentView.addConstraint(NSLayoutConstraint(
item: keyButton,
attribute: .Leading,
relatedBy: .Equal,
toItem: contentView,
attribute: .Leading,
multiplier: 1,
constant: 0))
contentView.addConstraint(NSLayoutConstraint(
item: keyButton,
attribute: .CenterY,
relatedBy: .Equal,
toItem: contentView,
attribute: .CenterY,
multiplier: 1,
constant: 0))
contentView.addConstraint(NSLayoutConstraint(
item: keyButton,
attribute: .Width,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: 60))
contentView.addConstraint(NSLayoutConstraint(
item: keyButton,
attribute: .Height,
relatedBy: .Equal,
toItem: contentView,
attribute: .Height,
multiplier: 1,
constant: 0))
// Value field
contentView.addConstraint(NSLayoutConstraint(
item: valueField,
attribute: .Leading,
relatedBy: .Equal,
toItem: contentView,
attribute: .Leading,
multiplier: 1,
constant: 68))
contentView.addConstraint(NSLayoutConstraint(
item: valueField,
attribute: .Trailing,
relatedBy: .Equal,
toItem: contentView,
attribute: .Trailing,
multiplier: 1,
constant: 0))
contentView.addConstraint(NSLayoutConstraint(
item: valueField,
attribute: .CenterY,
relatedBy: .Equal,
toItem: contentView,
attribute: .CenterY,
multiplier: 1,
constant: 0))
contentView.addConstraint(NSLayoutConstraint(
item: valueField,
attribute: .Height,
relatedBy: .Equal,
toItem: contentView,
attribute: .Height,
multiplier: 1,
constant: 0))
}
}
| true
|
c93d66e5a8cb474e691dd3152f5765ae86b18aec
|
Swift
|
nubioknupp/minhas-tarefas-app
|
/MinhasTarefas/MinhasTarefas/TarefaUserDefaults.swift
|
UTF-8
| 897
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
//
// TarefaUserDefaults.swift
// MinhasTarefas
//
// Created by Nubio Knupp on 14/02/17.
// Copyright © 2017 Nubio Knupp. All rights reserved.
//
import Foundation
class TarefaUserDefaults{
private let minhasTarefasChave = "MinhasTarefas";
func SalvarTarefa(tarefa : String) {
var tarefas = ListaTarefas();
tarefas.append(tarefa);
UserDefaults.standard.set(tarefas, forKey: minhasTarefasChave);
}
func ListaTarefas() -> [String] {
let tarefas = UserDefaults.standard.object(forKey: minhasTarefasChave);
if(tarefas != nil) {
return tarefas as! [String]
}
return [];
}
func DeletarTarefa(index : Int) {
var tarefas = ListaTarefas();
tarefas.remove(at: index);
UserDefaults.standard.set(tarefas, forKey: minhasTarefasChave);
}
}
| true
|
77f422436f61a9e3fea542a09a34d3b1c52266ce
|
Swift
|
nk8876/WebSevicesUsingURLSession
|
/WebSevicesUsingURLSession/Controller/ViewController.swift
|
UTF-8
| 3,250
| 2.765625
| 3
|
[] |
no_license
|
//
// ViewController.swift
// WebSevicesUsingURLSession
//
// Created by Dheeraj Arora on 05/07/19.
// Copyright © 2019 Dheeraj Arora. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var arrData = [JsonStruct]()
@IBOutlet weak var myTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.myTableView.rowHeight = 100
getData()
downloadTableViewJsonData()
self.setCustomeTitle()
self.setCustomeImage()
}
func getData()
{
let url = ConstantAPIURL.shareInstance.getURL
WebApiMethods.instance.resquestGetURL(strURL: url, parameters: ["" : ""]) { (data, error) in
if error == nil {
do{
let finalData = try JSONDecoder().decode(UserInfo2.self, from: data)
let address = finalData.address
print("Address Data:",address)
let geoData = address.geo
print("Geo Data:",geoData)
let comapnyData = finalData.company
print("Company Data:",comapnyData)
print(finalData)
}catch{
print("\(error)")
}
}
}
}
func downloadTableViewJsonData(){
let url = ConstantAPIURL.shareInstance.tableViewDataURL
WebApiMethods.instance.resquestGetURL(strURL: url, parameters: ["":""]) { (data, error) in
if error == nil{
do{
self.arrData = try JSONDecoder().decode([JsonStruct].self, from: data)
for mainArr in self.arrData{
//print(mainArr.name ,":",mainArr.capital)
DispatchQueue.main.async {
self.myTableView.reloadData()
}
}
}catch{
print("\(error)")
}
}
}
}
}
extension ViewController : UITableViewDataSource,UITableViewDelegate{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.arrData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
cell.lblName.text = "Name:\(arrData[indexPath.row].name)"
cell.lblCapital.text = "Capital:\(arrData[indexPath.row].capital)"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let detail:DetailViewController = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
detail.strRegion = arrData[indexPath.row].region
detail.strSubRegion = arrData[indexPath.row].subregion
detail.strAlpha2 = arrData[indexPath.row].name
detail.strAlpha3 = arrData[indexPath.row].capital
self.navigationController?.pushViewController(detail, animated: true)
}
}
| true
|
48d1f90b466f9dfe403b4fc494439f184b97a0c9
|
Swift
|
andreimarkoff/AndreiMarkovHomework2.2
|
/AndreiMarkovHomework2.2/ViewController.swift
|
UTF-8
| 1,571
| 2.71875
| 3
|
[] |
no_license
|
//
// ViewController.swift
// AndreiMarkovHomework2.2
//
// Created by Andrey Markov on 2020-08-24.
// Copyright © 2020 Andrey Markov. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var redValueLabel: UILabel!
@IBOutlet weak var greenValueLabel: UILabel!
@IBOutlet weak var blueValueLabel: UILabel!
@IBOutlet weak var redSlider: UISlider!
@IBOutlet weak var greenSlider: UISlider!
@IBOutlet weak var blueSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
redValueLabel.text = String(redSlider.value)
greenValueLabel.text = String(greenSlider.value)
blueValueLabel.text = String(blueSlider.value)
}
@IBAction func redSliderAction() {
redValueLabel.text = String(format: "%.2f", redSlider.value)
mainView.backgroundColor = UIColor(red:CGFloat(redSlider.value), green:CGFloat(greenSlider.value), blue: CGFloat(blueSlider.value),alpha: 1)
}
@IBAction func greenSliderAction() {
greenValueLabel.text = String(format: "%.2f",greenSlider.value)
mainView.backgroundColor = UIColor(red:CGFloat(redSlider.value), green:CGFloat(greenSlider.value), blue: CGFloat(blueSlider.value),alpha: 1)
}
@IBAction func blueSliderAction() {
blueValueLabel.text = String(format: "%.2f", blueSlider.value)
mainView.backgroundColor = UIColor(red:CGFloat(redSlider.value), green:CGFloat(greenSlider.value), blue: CGFloat(blueSlider.value),alpha: 1)
}
}
| true
|
0b2c3838dc20097774dc6c8c8a19e6999d354443
|
Swift
|
X-code-swift/ImageandText
|
/ImageAndText/SecondViewController.swift
|
UTF-8
| 4,928
| 2.546875
| 3
|
[] |
no_license
|
//
// SecondViewController.swift
// ImageAndText
//
// Created by Furkan on 19.06.2020.
// Copyright © 2020 x-swift. All rights reserved.
//
import UIKit
class SecondViewController: UIViewController {
var textData = ""
@IBOutlet weak var showImage: UIImageView!
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//Size of image
let imageView: UIImageView = UIImageView(image: myImage)
let imageViewHeight: CGFloat = imageView.frame.height
let imageViewWidth: CGFloat = imageView.frame.width
let height = imageViewHeight
let width = imageViewWidth
print("Height: \(height) \nWidth: \(width)")
showImage.image = myImage
label.isHidden = true
label.isUserInteractionEnabled = true
let dragGesture = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
label.addGestureRecognizer(dragGesture)
// Do any additional setup after loading the view.
}
@IBAction func saveButton(_ sender: Any) {
label.isHidden = true
let newImage = mergeTextAndImage(image: myImage, withLabel: label, outputSize: myImage.size)
showImage.image = newImage
UIImageWriteToSavedPhotosAlbum(newImage!, nil, nil, nil)
}
@IBAction func addButton(_ sender: Any) {
let randomAlert = UIAlertController(title: "Add Text", message: "", preferredStyle: .alert)
randomAlert.addTextField()
let addRandom = UIAlertAction(title: "Add", style: .default) { (action) in
var randomText = randomAlert.textFields![0]
if randomText.text == "" {
let alertEror = UIAlertController(title: "Warning", message: "Empty expression cannot be entered", preferredStyle: .alert)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertEror.addAction(cancel)
}else{
self.textData = randomText.text!
self.label.text = self.textData
self.label.isHidden = false
}
}
let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
randomAlert.addAction(addRandom)
randomAlert.addAction(cancelButton)
present(randomAlert, animated: true, completion: nil)
}
@objc func handlePan(_ recognizer: UIPanGestureRecognizer){
let translation = recognizer.translation(in: self.view)
recognizer.view!.center = CGPoint(x: recognizer.view!.center.x + translation.x, y: recognizer.view!.center.y + translation.y)
recognizer.setTranslation(CGPoint(x: 0, y: 0), in: self.view)
}
func mergeTextAndImage(image:UIImage, withLabel label: UILabel, outputSize:CGSize) -> UIImage? {
let inputSize:CGSize = image.size
let scale = max(outputSize.width / inputSize.width, outputSize.height / inputSize.height)
let scaledSize = CGSize(width: inputSize.width * scale, height: inputSize.height * scale)
let center = CGPoint(x: outputSize.width / 2, y: outputSize.height / 2)
let outputRect = CGRect(x: center.x - scaledSize.width/2, y: center.y - scaledSize.height/2, width: scaledSize.width, height: scaledSize.height)
UIGraphicsBeginImageContextWithOptions(outputSize, true, 0.0)
let context:CGContext = UIGraphicsGetCurrentContext()!
context.interpolationQuality = CGInterpolationQuality.high
image.draw(in: outputRect)
if let text = label.text {
if text.count > 0 {
var range:NSRange? = NSMakeRange(0, text.count)
let drawPoint = CGPoint(
x: label.frame.origin.x / label.superview!.frame.width * outputSize.width,
y: label.frame.origin.y / label.superview!.frame.height * outputSize.height)
let originalFont = label.font
print(drawPoint.y)
label.font = UIFont(name: label.font!.fontName, size: label.font!.pointSize / label.superview!.frame.width * outputSize.width)
let attributes = label.attributedText?.attributes(at: 0, effectiveRange: &range!)
let angle = atan2(label.transform.b, label.transform.a)
context.translateBy(x: drawPoint.x, y: drawPoint.y)
context.rotate(by: angle)
text.draw(in: outputRect, withAttributes: attributes)
label.font = originalFont
}
}
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
}
| true
|
bf0b653c137e00ae4b3b2f789b5267818bfcaf15
|
Swift
|
levantAJ/AroundKids
|
/AroundKids/Common/View/USDZNode.swift
|
UTF-8
| 3,222
| 2.546875
| 3
|
[] |
no_license
|
//
// USDZNode.swift
// AroundKids
//
// Created by Tai Le on 23/05/2021.
//
import UIKit
import SceneKit
import QuickLook
class USDZNode: SCNReferenceNode {
let arObjectType: USDZNodeARObjectType
init?(
arObjectType: USDZNodeARObjectType,
position: SCNVector3? = nil,
pivot: SCNMatrix4? = nil
) {
let name: String = arObjectType.name
guard let usdzURL: URL = Bundle.main.url(forResource: name, withExtension: "usdz") else { return nil }
self.arObjectType = arObjectType
super.init(url: usdzURL)
self.scale = arObjectType.scale
if let position: SCNVector3 = position {
self.position = position
}
if let pivot: SCNMatrix4 = pivot {
self.pivot = pivot
}
self.load()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - SCNMatrix4
extension SCNMatrix4 {
static func random() -> SCNMatrix4 {
return SCNMatrix4MakeRotation(Float.random(in: 0...2*Float.pi), 0, 1, 0)
}
}
// MARK: - USDZNodeARObjectType
enum USDZNodeARObjectType: Equatable, CaseIterable {
case chicken
case shark
case fish
case cat
var name: String {
switch self {
case .chicken:
return "chicken"
case .shark:
return "shark"
case .cat:
return "cat"
case .fish:
return "fish"
}
}
var scale: SCNVector3 {
switch self {
case .fish:
return SCNVector3(x: 0.3, y: 0.3, z: 0.3)
case .chicken:
return SCNVector3(x: 0.01, y: 0.01, z: 0.01)
case .cat:
return SCNVector3(x: 0.003, y: 0.003, z: 0.003)
case .shark:
return SCNVector3(x: 0.002, y: 0.002, z: 0.002)
}
}
var soundName: String? {
switch self {
case .chicken:
return "rooster-crowing"
case .shark, .cat, .fish:
return nil
}
}
}
// MARK: - USDZNodeARObjectTypeThumbnailGenerator
final class USDZNodeARObjectTypeThumbnailGenerator {
func gennerate(
arObjectType: USDZNodeARObjectType,
size: CGSize,
completion: ((Result<UIImage, Error>) -> Void)?
) {
let name: String = arObjectType.name
guard let usdzURL: URL = Bundle.main.url(forResource: name, withExtension: "usdz") else { return }
let scale: CGFloat = UIScreen.main.scale
let generator: QLThumbnailGenerator = QLThumbnailGenerator.shared
let request: QLThumbnailGenerator.Request = QLThumbnailGenerator.Request(
fileAt: usdzURL,
size: size,
scale: scale,
representationTypes: .all
)
generator.generateRepresentations(
for: request
) { (thumbnail, type, error) in
DispatchQueue.main.async {
if let image: UIImage = thumbnail?.uiImage {
completion?(.success(image))
} else if let error: Error = error {
completion?(.failure(error))
}
}
}
}
}
| true
|
591d2f638a12b9b6a975dc0791f2eb4a47647aca
|
Swift
|
swift-develop/algorithms_playgrounds_swift
|
/compareTriplets.playground/Contents.swift
|
UTF-8
| 390
| 3.578125
| 4
|
[] |
no_license
|
import UIKit
func compareTriplets(a: [Int], b: [Int]) -> [Int] {
var aPoints = 0
var bPoints = 0
let combined = zip(a,b)
for (a,b) in combined {
if a > b{
aPoints += 1
} else if a < b {
bPoints += 1
}
}
return [aPoints, bPoints]
}
print( compareTriplets(a: [1,2,3], b: [3,2,1] ) )
| true
|
10cd86f5c290efc7f2f90ad7d70bb6d7b4628e20
|
Swift
|
TaniaCB/Color-Quotes
|
/Color Quotes/Color Quotes/QuotesGenerator.swift
|
UTF-8
| 1,597
| 3.234375
| 3
|
[] |
no_license
|
//
// GeneradorCitas.swift
// Color Quotes
//
// Created by Tania on 21/2/18.
// Copyright © 2018 TaniaCB. All rights reserved.
//
import GameKit
struct QuotesGenerator{
let quotes = [
Quote(text: "Sé el cambio que quieres ver en el mundo", author: "M.Gandhi"),
Quote(text: "Stay hungry stay foolish", author: "Steve Jobs"),
Quote(text: "Aquel que no se equivoca es el que nunca hace nada", author:"Goethe"),
Quote(text: "Be yourself, everyone else is already taken", author: "Oscar Wilde"),
Quote(text: "Don't cry because it's over, smile because it happened", author: "Dr. Seuss"),
Quote(text: "So many books, so little time", author: "Frank Zappa"),
Quote(text: "In three words I can sum up everything I've learned about life: it goes on", author: "Robert Frost"),
Quote(text: "A friend is someone who knows all about you and still loves you", author: "Elbert Hubbard"),
Quote(text: "Todos somos aficionados. La vida es tan corta que no da para más", author: "Charles Chaplin"),
Quote(text: "La vida es una obra teatral que no importa cuánto haya durado, sino lo bien que haya sido representada", author: "Séneca"),
Quote(text: "Se necesitan dos años para aprender a hablar, y sesenta para aprender a callar", author: "Ernest Hemingway"),
Quote(text: "El éxito tiene muchos padres, el fracaso es huérfano", author: "John F. Kennedy")
]
func randomQuoteGenerate() -> Quote {
let numberRand = GKRandomSource.sharedRandom().nextInt(upperBound: quotes.count)
return quotes[numberRand]
}
}
| true
|
d0ed49d646b304b0f94badb58984a57d07bd6ff5
|
Swift
|
NoahKnudsen/Router
|
/Router.playground/Sources/Extensions/Collection.swift
|
UTF-8
| 354
| 2.953125
| 3
|
[] |
no_license
|
import Foundation
public extension Collection {
public subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
public extension Collection {
public func toDictionary<Key, Value>() -> [Key : Value] where Element == (Key, Value) {
return Dictionary(self) { _, last in last }
}
}
| true
|
32f3f0b3645ae441c29ed62669a4268974ee33f7
|
Swift
|
inquisitiveSoft/TipTapGestureRecognizer
|
/TipTapGestureRecognizer.swift
|
UTF-8
| 6,140
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// TipTapGestureRecognizer.swift
// TipTap
//
// Created by Harry Jordan on 14/11/2015.
// Copyright © 2015 Inquisitive Software. All rights reserved.
//
// If used in an app which contains you'll need to add
// '#import <UIKit/UIGestureRecognizerSubclass.h>' to your BridgingHeader
// so that the touches… can be overridden
//
// Released under the MIT License: http://www.opensource.org/licenses/MIT
//
import UIKit
@objc public enum TipTapType: Int {
case left, middle, right
}
@objc public protocol TipTapGestureRecognizerDelegate: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: TipTapGestureRecognizer, didRecognizeTipTap tipTapType: TipTapType)
}
let TipTapGestureMaximumTapDuration: TimeInterval = 0.25
let TipTapGestureMinimumDragDistance: CGFloat = 105.0
open class TipTapGestureRecognizer: UIGestureRecognizer {
@objc open var maximumTapDuration: TimeInterval = TipTapGestureMaximumTapDuration
@objc open var minimumDragDistance: CGFloat = TipTapGestureMinimumDragDistance
@objc open var requiredNumberOfSourceTaps: Int = 1
@objc open var requiredNumberOfTipTaps: Int = 1
@objc open var requiredNumberOfCombinedTaps: Int = 2
@objc open var maximumNumberOfSourceTaps: Int = Int.max
@objc open var maximumNumberOfTipTaps: Int = Int.max
@objc open var maximumNumberOfCombinedTaps: Int = Int.max
@objc open var tapCount: Int = 0
internal var currentTouches: [UITouch: (startTimestamp: TimeInterval, startPosition: CGPoint)] = [:]
override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
reset()
}
open override func reset() {
currentTouches.removeAll()
tapCount = 0
state = .possible
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
guard let view = view else {
return
}
for touch in touches {
currentTouches[touch] = (event.timestamp, touch.location(in: view))
}
if(state == .possible) {
state = .began
} else {
state = .changed
}
}
open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
guard let view = view else {
return
}
let currentTime = event.timestamp
for touch in touches {
if let touchDetails = currentTouches[touch] , (currentTime - touchDetails.startTimestamp) > maximumTapDuration {
let touchPosition = touch.location(in: view)
if CGPoint.distanceBetweenPoints(touchDetails.startPosition, touchPosition) > minimumDragDistance {
state = .failed
return
}
}
}
state = .changed
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
var sourceTouches = Set(currentTouches.keys)
let currentTime = event.timestamp
var tapTouches: [UITouch] = []
for touch in touches {
if let touchDetails = currentTouches[touch] , (currentTime - touchDetails.startTimestamp) < maximumTapDuration {
tapTouches.append(touch)
sourceTouches.remove(touch)
}
currentTouches[touch] = nil
}
let numberOfTapTouches = tapTouches.count
let numberOfSourceTouches = sourceTouches.count
let combinedNumberOfTouches = numberOfTapTouches + numberOfSourceTouches
if let view = view , !tapTouches.isEmpty &&
(numberOfTapTouches >= requiredNumberOfTipTaps) && (numberOfTapTouches <= maximumNumberOfTipTaps)
&& (numberOfSourceTouches >= requiredNumberOfSourceTaps) && (numberOfSourceTouches <= maximumNumberOfSourceTaps)
&& (combinedNumberOfTouches >= requiredNumberOfCombinedTaps) && (combinedNumberOfTouches <= maximumNumberOfCombinedTaps) {
let tapPoints = tapTouches.map { (touch) -> (CGPoint) in
return touch.location(in: view)
}
let sourcePoints = sourceTouches.map { (touch) -> (CGPoint) in
return touch.location(in: view)
}
let tapPoint = CGPoint.averageOfPoints(tapPoints)
let sourceRect = CGRect(containingPoints: sourcePoints)
let type: TipTapType
if tapPoint.x <= sourceRect.minX {
type = .left
} else if tapPoint.x >= sourceRect.maxX {
type = .right
} else {
type = .middle
}
state = .changed
tapCount += 1
if let delegate = delegate as? TipTapGestureRecognizerDelegate {
delegate.gestureRecognizer(self, didRecognizeTipTap: type)
}
} else {
if currentTouches.isEmpty {
if tapCount > 0 {
state = .ended
} else {
state = .failed
}
} else {
state = .changed
}
}
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {
touchesEnded(touches, with: event)
}
}
extension CGRect {
init(containingPoints: [CGPoint]) {
guard let firstPoint = containingPoints.first else {
self = CGRect.null
return
}
var topLeftPoint: CGPoint = firstPoint
var bottomRightPoint: CGPoint = firstPoint
for point in containingPoints {
topLeftPoint.x = min(point.x, topLeftPoint.x)
topLeftPoint.y = min(point.y, topLeftPoint.y)
bottomRightPoint.x = max(point.x, bottomRightPoint.x)
bottomRightPoint.y = max(point.y, bottomRightPoint.y)
}
self = CGRect(origin: topLeftPoint, size: CGSize(width: bottomRightPoint.x - topLeftPoint.x, height: bottomRightPoint.y - topLeftPoint.y))
}
}
extension CGPoint {
static func averageOfPoints(_ points: [CGPoint]) -> CGPoint {
let combinedPoints = points.reduce(CGPoint.zero) {
return CGPoint(x: ($0.x + $1.x), y: ($0.y + $1.y))
}
let numberOfSourceTouches = points.count
let averagedPoint = CGPoint(x: combinedPoints.x / CGFloat(numberOfSourceTouches), y: combinedPoints.y / CGFloat(numberOfSourceTouches))
return averagedPoint
}
static func distanceBetweenPoints(_ firstPoint: CGPoint, _ secondPoint: CGPoint) -> CGFloat {
let distance = CGSize(width: abs(secondPoint.x - firstPoint.x), height: fabs(secondPoint.y - firstPoint.y))
let epsilon: CGFloat = 0.0001
if(distance.width < epsilon) {
return distance.height;
} else if (distance.height < epsilon) {
return distance.width;
}
return CGFloat(sqrt(Double(distance.width * distance.width) + Double(distance.height * distance.height)))
}
}
| true
|
89e92a7da2bea031e2f6cecc65bd5c296deedfab
|
Swift
|
romikabi/cggen
|
/Sources/Base/SVG.swift
|
UTF-8
| 46,190
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
import CoreGraphics
import Foundation
// https://www.w3.org/TR/SVG11/
public enum SVG: Equatable {
public typealias NotImplemented = Never
public typealias NotNeeded = Never
// MARK: Attributes
public typealias Float = Swift.Double
public typealias Color = RGBColor<UInt8>
public struct Length: Equatable {
public enum Unit: String, CaseIterable {
case px, pt
case percent = "%"
}
public var number: Float
public var unit: Unit?
}
public typealias Coordinate = SVG.Length
// Should be tuple, when Equatable synthesys improves
// https://bugs.swift.org/browse/SR-1222
public struct CoordinatePair: Equatable {
public var _1: Float
public var _2: Float
public init(_ pair: (Float, Float)) {
_1 = pair.0
_2 = pair.1
}
}
// Should be tuple, when Equatable synthesys improves
// https://bugs.swift.org/browse/SR-1222
public struct NumberOptionalNumber: Equatable {
public var _1: Float
public var _2: Float?
}
public struct Angle: Equatable {
public var degrees: Float
}
public typealias CoordinatePairs = [CoordinatePair]
public struct ViewBox: Equatable {
public var minx: Float
public var miny: Float
public var width: Float
public var height: Float
public init(
_ x: SVG.Float,
_ y: SVG.Float,
_ width: SVG.Float,
_ height: SVG.Float
) {
minx = x
miny = y
self.width = width
self.height = height
}
}
public enum Paint: Equatable {
case none
case currentColor(NotNeeded) // Used for animations
case rgb(Color)
case funciri(id: String)
}
public enum FillRule: String, CaseIterable {
case nonzero
case evenodd
}
public enum Transform: Equatable {
public struct Anchor: Equatable {
public var cx: Float
public var cy: Float
}
case matrix(a: Float, b: Float, c: Float, d: Float, e: Float, f: Float)
case translate(tx: Float, ty: Float?)
case scale(sx: Float, sy: Float?)
case rotate(angle: Angle, anchor: Anchor?)
case skewX(Angle)
case skewY(Angle)
}
public enum Units: String, CaseIterable {
case userSpaceOnUse, objectBoundingBox
}
public enum FilterPrimitiveIn: Equatable {
public enum Predefined: String, CaseIterable {
case sourcegraphic = "SourceGraphic"
case sourcealpha = "SourceAlpha"
case backgroundimage = "BackgroundImage"
case backgroundalpha = "BackgroundAlpha"
case fillpaint = "FillPaint"
case strokepaint = "StrokePaint"
}
case predefined(Predefined)
case previous(String)
}
public enum BlendMode: String, CaseIterable {
case normal, multiply, screen, darken, lighten
}
public enum ColorInterpolation: String, CaseIterable {
case sRGB, linearRGB
}
// MARK: Attribute group
public struct CoreAttributes: Equatable {
public var id: String?
public init(id: String?) {
self.id = id
}
}
public enum LineCap: String, CaseIterable {
case butt, round, square
}
public enum LineJoin: String, CaseIterable {
case miter, round, bevel
}
public struct PresentationAttributes: Equatable {
public var clipPath: String?
public var clipRule: FillRule?
public var mask: String?
public var filter: String?
public var fill: Paint?
public var fillRule: FillRule?
public var fillOpacity: Float?
public var stroke: Paint?
public var strokeWidth: Length?
public var strokeLineCap: LineCap?
public var strokeLineJoin: LineJoin?
public var strokeDashArray: [Length]?
public var strokeDashOffset: Length?
public var strokeOpacity: Float?
public var opacity: SVG.Float?
public var stopColor: SVG.Color?
public var stopOpacity: SVG.Float?
public var colorInterpolationFilters: ColorInterpolation?
public init(
clipPath: String?,
clipRule: FillRule?,
mask: String?,
filter: String?,
fill: Paint?,
fillRule: FillRule?,
fillOpacity: Float?,
stroke: Paint?,
strokeWidth: Length?,
strokeLineCap: LineCap?,
strokeLineJoin: LineJoin?,
strokeDashArray: [Length]?,
strokeDashOffset: Length?,
strokeOpacity: Float?,
opacity: Float?,
stopColor: SVG.Color?,
stopOpacity: SVG.Float?,
colorInterpolationFilters: ColorInterpolation?
) {
self.clipPath = clipPath
self.clipRule = clipRule
self.mask = mask
self.filter = filter
self.fill = fill
self.fillRule = fillRule
self.fillOpacity = fillOpacity
self.stroke = stroke
self.strokeWidth = strokeWidth
self.strokeLineCap = strokeLineCap
self.strokeLineJoin = strokeLineJoin
self.strokeDashArray = strokeDashArray
self.strokeDashOffset = strokeDashOffset
self.strokeOpacity = strokeOpacity
self.opacity = opacity
self.stopColor = stopColor
self.stopOpacity = stopOpacity
self.colorInterpolationFilters = colorInterpolationFilters
}
}
public struct FilterPrimitiveCommonAttributes: Equatable {
var result: String?
var height: Length?
var width: Length?
var x: Coordinate?
var y: Coordinate?
}
// MARK: Content group
public enum FilterPrimitiveContent: Equatable {
case feBlend(FeBlend)
case feColorMatrix(FeColorMatrix)
case feComponentTransfer(NotImplemented)
case feComposite(NotImplemented)
case feConvolveMatrix(NotImplemented)
case feDiffuseLighting(NotImplemented)
case feDisplacementMap(NotImplemented)
case feFlood(FeFlood)
case feGaussianBlur(FeGaussianBlur)
case feImage(NotImplemented)
case feMerge(NotImplemented)
case feMorphology(NotImplemented)
case feOffset(FeOffset)
case feSpecularLighting(NotImplemented)
case feTile(NotImplemented)
case feTurbulence(NotImplemented)
}
// MARK: Elements
public struct Document: Equatable {
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var width: Length?
public var height: Length?
public var viewBox: ViewBox?
public var children: [SVG]
public init(
core: CoreAttributes,
presentation: PresentationAttributes,
width: Length?,
height: Length?,
viewBox: ViewBox?,
children: [SVG]
) {
self.core = core
self.presentation = presentation
self.width = width
self.height = height
self.viewBox = viewBox
self.children = children
}
}
public struct ShapeElement<T: Equatable>: Equatable {
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var transform: [Transform]?
public var data: T
@inlinable
public init(
core: CoreAttributes,
presentation: PresentationAttributes,
transform: [Transform]?,
data: T
) {
self.core = core
self.presentation = presentation
self.transform = transform
self.data = data
}
}
public struct RectData: Equatable {
public var x: Coordinate?
public var y: Coordinate?
public var rx: Length?
public var ry: Length?
public var width: Coordinate?
public var height: Coordinate?
public init(
x: SVG.Coordinate?,
y: SVG.Coordinate?,
rx: Length?,
ry: Length?,
width: SVG.Coordinate?,
height: SVG.Coordinate?
) {
self.x = x
self.y = y
self.rx = rx
self.ry = ry
self.width = width
self.height = height
}
}
public struct CircleData: Equatable {
public var cx: Coordinate?
public var cy: Coordinate?
public var r: Length?
}
public struct EllipseData: Equatable {
public var cx: Coordinate?
public var cy: Coordinate?
public var rx: Length?
public var ry: Length?
}
public struct PathData: Equatable {
public enum Positioning {
case relative
case absolute
}
public struct CurveArgument: Equatable {
public var cp1: CoordinatePair
public var cp2: CoordinatePair
public var to: CoordinatePair
}
public struct SmoothCurveArgument: Equatable {
public var cp2: CoordinatePair
public var to: CoordinatePair
}
public struct QuadraticCurveArgument: Equatable {
public var cp1: CoordinatePair
public var to: CoordinatePair
}
/*
8.3.8 The elliptical arc curve commands
*/
public struct EllipticalArcArgument: Equatable {
public var rx: Float
public var ry: Float
public var xAxisRotation: Float
public var largeArcFlag: Bool
public var sweepFlag: Bool
public var end: CoordinatePair
public typealias Destructed = (
rx: Float, ry: Float, xAxisRotation: Float,
largeArcFlag: Bool, sweepFlag: Bool,
end: CoordinatePair
)
@inlinable
public func destruct() -> Destructed {
(rx, ry, xAxisRotation, largeArcFlag, sweepFlag, end)
}
}
public enum CommandKind: Equatable {
case closepath
case moveto([CoordinatePair])
case lineto([CoordinatePair])
case horizontalLineto([Float])
case verticalLineto([Float])
case curveto([CurveArgument])
case smoothCurveto([SmoothCurveArgument])
case quadraticBezierCurveto([QuadraticCurveArgument])
case smoothQuadraticBezierCurveto(to: [CoordinatePair])
case ellipticalArc([EllipticalArcArgument])
}
public struct Command: Equatable {
public var positioning: Positioning
public var kind: CommandKind
}
public var d: [Command]?
public var pathLength: Float?
}
public struct PolygonData: Equatable {
public var points: [CoordinatePair]?
}
public typealias Path = ShapeElement<PathData>
public typealias Rect = ShapeElement<RectData>
public typealias Circle = ShapeElement<CircleData>
public typealias Ellipse = ShapeElement<EllipseData>
public typealias Line = ShapeElement<NotImplemented>
public typealias Polyline = ShapeElement<NotImplemented>
public typealias Polygon = ShapeElement<PolygonData>
public struct Group: Equatable {
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var transform: [Transform]?
public var children: [SVG]
public init(
core: CoreAttributes,
presentation: PresentationAttributes,
transform: [Transform]?,
children: [SVG]
) {
self.core = core
self.presentation = presentation
self.transform = transform
self.children = children
}
}
public struct Use: Equatable {
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var transform: [Transform]?
public var x: Coordinate?
public var y: Coordinate?
public var width: Length?
public var height: Length?
public var xlinkHref: String?
}
public struct Defs: Equatable {
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var transform: [Transform]?
public var children: [SVG]
}
public struct Mask: Equatable {
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var transform: [Transform]?
public var x: Coordinate?
public var y: Coordinate?
public var width: Length?
public var height: Length?
public var maskUnits: Units?
public var maskContentUnits: Units?
public var children: [SVG]
}
public struct ClipPath: Equatable {
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var transform: [Transform]?
public var clipPathUnits: Units?
public var children: [SVG]
}
public struct Stop: Equatable {
public enum Offset: Equatable {
case number(SVG.Float)
case percentage(SVG.Float)
}
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var offset: Offset?
}
public struct LinearGradient: Equatable {
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var unit: Units?
public var x1: Coordinate?
public var y1: Coordinate?
public var x2: Coordinate?
public var y2: Coordinate?
public var stops: [Stop]
}
public struct RadialGradient: Equatable {
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var unit: Units?
public var cx: Coordinate?
public var cy: Coordinate?
public var r: Length?
public var fx: Coordinate?
public var fy: Coordinate?
public var gradientTransform: [Transform]?
public var stops: [Stop]
}
@dynamicMemberLookup
public struct FilterPrimitiveElement<T: Equatable>: Equatable {
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var common: FilterPrimitiveCommonAttributes
public var data: T
@inlinable
public init(
core: CoreAttributes,
presentation: PresentationAttributes,
common: FilterPrimitiveCommonAttributes,
data: T
) {
self.core = core
self.presentation = presentation
self.common = common
self.data = data
}
@inlinable
public subscript<U>(dynamicMember kp: KeyPath<T, U>) -> U {
data[keyPath: kp]
}
}
public struct FilterPrimitiveFeBlend: Equatable {
var `in`: FilterPrimitiveIn?
var in2: FilterPrimitiveIn?
var mode: BlendMode?
}
public typealias FeBlend = FilterPrimitiveElement<FilterPrimitiveFeBlend>
public struct FilterPrimitiveFeColorMatrix: Equatable {
public enum Kind: String, CaseIterable {
case matrix
case saturate
case hueRotate
case luminanceToAlpha
}
var `in`: FilterPrimitiveIn?
var type: Kind?
var values: [Float]?
}
public typealias FeColorMatrix =
FilterPrimitiveElement<FilterPrimitiveFeColorMatrix>
public struct FilterPrimitiveFeFlood: Equatable {
var floodColor: Color?
var floodOpacity: Float?
}
public typealias FeFlood = FilterPrimitiveElement<FilterPrimitiveFeFlood>
public struct FilterPrimitiveFeGaussianBlur: Equatable {
public var `in`: FilterPrimitiveIn?
public var stdDeviation: NumberOptionalNumber?
}
public typealias FeGaussianBlur =
FilterPrimitiveElement<FilterPrimitiveFeGaussianBlur>
public struct FilterPrimitiveFeOffset: Equatable {
public var `in`: FilterPrimitiveIn?
public var dx: Float?
public var dy: Float?
}
public typealias FeOffset = FilterPrimitiveElement<FilterPrimitiveFeOffset>
@dynamicMemberLookup
public struct ElementWithChildren<
Attributes: Equatable,
Child: Equatable
>: Equatable {
public var attributes: Attributes
public var children: [Child]
@inlinable
public subscript<T>(dynamicMember kp: KeyPath<Attributes, T>) -> T {
attributes[keyPath: kp]
}
}
public struct FilterAttributes: Equatable {
public var core: CoreAttributes
public var presentation: PresentationAttributes
public var x: Coordinate?
public var y: Coordinate?
public var width: Length?
public var height: Length?
public var filterUnits: Units?
}
public typealias Filter = ElementWithChildren<
FilterAttributes,
FilterPrimitiveContent
>
case svg(Document)
case group(Group)
case use(Use)
case path(Path)
case rect(Rect)
case circle(Circle)
case ellipse(Ellipse)
case line(NotImplemented)
case polyline(NotImplemented)
case polygon(Polygon)
case mask(Mask)
case clipPath(ClipPath)
case defs(Defs)
case title(String)
case desc(String)
case linearGradient(LinearGradient)
case radialGradient(RadialGradient)
case filter(Filter)
}
// MARK: - Categories
extension SVG {
public enum Shape {
case path(Path)
case rect(Rect)
case circle(Circle)
case ellipse(Ellipse)
case line(NotImplemented)
case polyline(NotImplemented)
case polygon(Polygon)
}
public var shape: Shape? {
switch self {
case let .path(e):
return .path(e)
case let .rect(e):
return .rect(e)
case let .circle(e):
return .circle(e)
case let .ellipse(e):
return .ellipse(e)
case let .line(e):
return .line(e)
case let .polyline(e):
return .polyline(e)
case let .polygon(e):
return .polygon(e)
default:
return nil
}
}
}
// MARK: - Serialization
private enum Tag: String {
// shape
case circle, ellipse, polygon, rect, path
// structural
case defs, g, svg, use
// gradient
case linearGradient, radialGradient
// descriptive
case title, desc
case stop, mask, clipPath, filter
case feBlend
case feColorMatrix
case feComponentTransfer
case feComposite
case feConvolveMatrix
case feDiffuseLighting
case feDisplacementMap
case feFlood
case feGaussianBlur
case feImage
case feMerge
case feMorphology
case feOffset
case feSpecularLighting
case feTile
case feTurbulence
}
private enum Attribute: String {
// XML
case xmlns, xmlnsxlink = "xmlns:xlink"
// Core
case id
case x, y, width, height, rx, ry
// Filters
case result, `in`, in2, mode
// - Presentation
case clipRule = "clip-rule", clipPath = "clip-path", mask, opacity
case filter
case stopColor = "stop-color", stopOpacity = "stop-opacity"
case gradientTransform, gradientUnits
// Color and Painting
case colorInterpolation = "color-interpolation"
case colorInterpolationFilters = "color-interpolation-filters"
case colorProfile = "color-profile"
case colorRendering = "color-rendering"
case fill
case fillOpacity = "fill-opacity", fillRule = "fill-rule"
case imageRendering = "image-rendering"
case marker
case markerEnd = "marker-end", markerMid = "marker-mid"
case markerStart = "marker-start"
case shapeRendering = "shape-rendering"
case stroke
case strokeDasharray = "stroke-dasharray"
case strokeDashoffset = "stroke-dashoffset"
case strokeLinecap = "stroke-linecap", strokeLinejoin = "stroke-linejoin"
case strokeMiterlimit = "stroke-miterlimit", strokeOpacity = "stroke-opacity"
case strokeWidth = "stroke-width"
case textRendering = "text-rendering"
case viewBox, version
case points
case transform
case offset
case x1, y1, x2, y2
case d, pathLength
case cx, cy, r, fx, fy
case xlinkHref = "xlink:href"
case filterUnits
case type, values, floodColor = "flood-color", floodOpacity = "flood-opacity"
case stdDeviation
case dx, dy
case maskUnits, maskContentUnits, clipPathUnits
// Ignore
case maskType = "mask-type"
}
extension SVG.Length {
public init(_ number: SVG.Float, _ unit: Unit? = nil) {
self.number = number
self.unit = unit
}
}
extension SVG.Length: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self.init(.init(value))
}
}
// MARK: - Parser
public enum SVGParser {
private enum Error: Swift.Error {
case expectedSVGTag(got: String)
case unexpectedXMLText(String)
case unknown(attribute: String, tag: Tag)
case nonbelongig(attributes: Set<Attribute>, tag: Tag)
case invalidAttributeFormat(
tag: String,
attribute: String,
value: String,
type: String,
parseError: Swift.Error
)
case titleHasInvalidFormat(XML)
case uknownTag(String)
case invalidVersion(String)
case notImplemented
}
private typealias ParserForAttribute<T> = (Attribute) -> AttributeParser<T>
private typealias AttributeParser<T> = Base.Parser<[String: String], T?>
private typealias AttributeGroupParser<T> = Base.Parser<[String: String], T>
private static var len: ParserForAttribute<SVG.Length> {
attributeParser(SVGAttributeParsers.length)
}
private static var coord: ParserForAttribute<SVG.Coordinate> {
attributeParser(SVGAttributeParsers.length)
}
private static var color: ParserForAttribute<SVG.Color> {
attributeParser(SVGAttributeParsers.rgbcolor)
}
private static var paint: ParserForAttribute<SVG.Paint> {
attributeParser(SVGAttributeParsers.paint)
}
private static var viewBox: ParserForAttribute<SVG.ViewBox> {
attributeParser(SVGAttributeParsers.viewBox)
}
private static let num = attributeParser(SVGAttributeParsers.number)
private static let numList =
attributeParser(SVGAttributeParsers.listOfNumbers)
private static let numberOptionalNumber =
attributeParser(SVGAttributeParsers.numberOptionalNumber)
private static let identifier: ParserForAttribute<String> =
attributeParser(SVGAttributeParsers.identifier)
private static let transform: ParserForAttribute<[SVG.Transform]> =
attributeParser(SVGAttributeParsers.transformsList)
private static let listOfPoints: ParserForAttribute<SVG.CoordinatePairs> =
attributeParser(SVGAttributeParsers.listOfPoints)
private static let pathData = attributeParser(SVGAttributeParsers.pathData)
private static let stopOffset: ParserForAttribute<SVG.Stop.Offset> =
attributeParser(SVGAttributeParsers.stopOffset)
private static let fillRule: ParserForAttribute<SVG.FillRule> =
attributeParser(oneOf(SVG.FillRule.self))
private static var version: AttributeGroupParser<Void> {
identifier(.version).flatMapResult {
$0.map { $0 == "1.1" ? .success(()) : .failure(Error.invalidVersion($0))
} ?? .success(())
}
}
private static let lineCap = attributeParser(oneOf(SVG.LineCap.self))
private static let lineJoin = attributeParser(oneOf(SVG.LineJoin.self))
private static let funciri = attributeParser(SVGAttributeParsers.funciri)
private static let x = coord(.x)
private static let y = coord(.y)
private static let width = len(.width)
private static let height = len(.height)
private static let colorInterpolation =
attributeParser(oneOf(SVG.ColorInterpolation.self))
private static var xml: AttributeGroupParser<Void> {
zip(identifier(.xmlns), identifier(.xmlnsxlink)) { _, _ in () }
}
private static let ignoreAttribute =
attributeParser(consume(while: always(true)))
private static let ignore: AttributeGroupParser<Void> =
ignoreAttribute(.maskType).map(always(()))
private static let dashArray = attributeParser(SVGAttributeParsers.dashArray)
private static let presentation = zip(
funciri(.clipPath),
fillRule(.clipRule),
funciri(.mask),
funciri(.filter),
paint(.fill),
fillRule(.fillRule),
num(.fillOpacity),
paint(.stroke),
len(.strokeWidth),
lineCap(.strokeLinecap),
lineJoin(.strokeLinejoin),
dashArray(.strokeDasharray),
len(.strokeDashoffset),
num(.strokeOpacity),
num(.opacity),
color(.stopColor),
num(.stopOpacity),
colorInterpolation(.colorInterpolationFilters),
with: SVG.PresentationAttributes.init
)
private static let core = identifier(.id).map(SVG.CoreAttributes.init)
public static func root(from data: Data) throws -> SVG.Document {
try root(from: XML.parse(from: data).get())
}
public static func root(from xml: XML) throws -> SVG.Document {
switch xml {
case let .el(el):
try check(el.tag == Tag.svg.rawValue, Error.expectedSVGTag(got: el.tag))
return try document(from: el)
case let .text(t):
throw Error.unexpectedXMLText(t)
}
}
public static func document(
from el: XML.Element
) throws -> SVG.Document {
let attrs = try (zip(
core, presentation,
width, height, viewBox(.viewBox),
with: identity
) <<~ version <<~ xml <<~ endof()).run(el.attrs).get()
return .init(
core: attrs.0,
presentation: attrs.1,
width: attrs.2,
height: attrs.3,
viewBox: attrs.4,
children: try el.children.map(element(from:))
)
}
private static func shape<T>(
_ parser: AttributeGroupParser<T>
) -> AttributeGroupParser<SVG.ShapeElement<T>> {
zip(
core, presentation, transform(.transform), parser,
with: SVG.ShapeElement<T>.init
)
}
private static let rect = shape(zip(
x, y, len(.rx), len(.ry),
width, height,
with: SVG.RectData.init
))
private static let polygon = shape(
listOfPoints(.points).map(SVG.PolygonData.init)
)
private static let circle = shape(zip(
coord(.cx), coord(.cy), coord(.r),
with: SVG.CircleData.init
))
private static let ellipse = shape(zip(
coord(.cx), coord(.cy), len(.rx), len(.ry),
with: SVG.EllipseData.init
))
private static let path = shape(zip(
pathData(.d), num(.pathLength), with: SVG.PathData.init
))
public static func rect(from el: XML.Element) throws -> SVG.Rect {
try (rect <<~ endof()).run(el.attrs).get()
}
public static func group(from el: XML.Element) throws -> SVG.Group {
let attrs = try (zip(
core, presentation, transform(.transform), with: identity
) <<~ endof()).run(el.attrs).get()
return try .init(
core: attrs.0,
presentation: attrs.1,
transform: attrs.2,
children: el.children.map(element(from:))
)
}
public static func defs(from el: XML.Element) throws -> SVG.Defs {
let attrs =
try (
zip(core, presentation, transform(.transform), with: identity) <<~
endof()
)
.run(el.attrs).get()
return try .init(
core: attrs.0,
presentation: attrs.1,
transform: attrs.2,
children: el.children.map(element(from:))
)
}
public static func polygon(from el: XML.Element) throws -> SVG.Polygon {
try (polygon <<~ endof()).run(el.attrs).get()
}
public static func circle(from el: XML.Element) throws -> SVG.Circle {
try (circle <<~ endof()).run(el.attrs).get()
}
public static func ellipse(from el: XML.Element) throws -> SVG.Ellipse {
try (ellipse <<~ endof()).run(el.attrs).get()
}
private static var stop: AttributeGroupParser<SVG.Stop> {
zip(core, presentation, stopOffset(.offset), with: SVG.Stop.init)
}
public static func stops(from el: XML.Element) throws -> SVG.Stop {
try (stop <<~ endof()).run(el.attrs).get()
}
private static let units = attributeParser(oneOf(SVG.Units.self))
public static func linearGradient(
from el: XML.Element
) throws -> SVG.LinearGradient {
let attrs = try (zip(
core, presentation, units(.gradientUnits),
coord(.x1), coord(.y1), coord(.x2), coord(.y2),
with: identity
) <<~ endof()).run(el.attrs).get()
let subelements: [XML.Element] = try el.children.map {
switch $0 {
case let .el(el):
return el
case let .text(t):
throw Error.unexpectedXMLText(t)
}
}
return try .init(
core: attrs.0,
presentation: attrs.1,
unit: attrs.2,
x1: attrs.3,
y1: attrs.4,
x2: attrs.5,
y2: attrs.6,
stops: subelements.map(stops(from:))
)
}
public static func radialGradient(
from el: XML.Element
) throws -> SVG.RadialGradient {
let attrs = try (zip(
core, presentation, units(.gradientUnits),
coord(.cx), coord(.cy), len(.r),
coord(.fx), coord(.fy), transform(.gradientTransform),
with: identity
) <<~ endof()).run(el.attrs).get()
let subelements: [XML.Element] = try el.children.map {
switch $0 {
case let .el(el):
return el
case let .text(t):
throw Error.unexpectedXMLText(t)
}
}
return try .init(
core: attrs.0,
presentation: attrs.1,
unit: attrs.2,
cx: attrs.3,
cy: attrs.4,
r: attrs.5,
fx: attrs.6,
fy: attrs.7,
gradientTransform: attrs.8,
stops: subelements.map(stops(from:))
)
}
public static func path(from el: XML.Element) throws -> SVG.Path {
try (path <<~ endof()).run(el.attrs).get()
}
private static let iri: ParserForAttribute<String> =
attributeParser(SVGAttributeParsers.iri)
private static let use: AttributeGroupParser<SVG.Use> = zip(
core, presentation,
transform(.transform),
x, y, width, height,
iri(.xlinkHref),
with: SVG.Use.init
)
public static func use(from el: XML.Element) throws -> SVG.Use {
try (use <<~ endof()).run(el.attrs).get()
}
public static func mask(from el: XML.Element) throws -> SVG.Mask {
let attrs = try (zip(
core, presentation,
transform(.transform),
x, y, width, height,
units(.maskUnits), units(.maskContentUnits),
with: identity
) <<~ ignore <<~ endof()).run(el.attrs).get()
return try .init(
core: attrs.0,
presentation: attrs.1,
transform: attrs.2,
x: attrs.3,
y: attrs.4,
width: attrs.5,
height: attrs.6,
maskUnits: attrs.7,
maskContentUnits: attrs.8,
children: el.children.map(element(from:))
)
}
public static func clipPath(from el: XML.Element) throws -> SVG.ClipPath {
let attrs = try (zip(
core, presentation, transform(.transform), units(.clipPathUnits),
with: identity
) <<~ endof()).run(el.attrs).get()
return try .init(
core: attrs.0,
presentation: attrs.1,
transform: attrs.2,
clipPathUnits: attrs.3,
children: el.children.map(element(from:))
)
}
private static
let filterAttributes: AttributeGroupParser<SVG.FilterAttributes> = zip(
core, presentation,
x, y, width, height, units(.filterUnits),
with: SVG.FilterAttributes.init
)
private static func elementWithChildren<Attributes, Child>(
attributes: AttributeGroupParser<Attributes>,
child: Parser<XML, Child>
) -> Parser<XML, SVG.ElementWithChildren<Attributes, Child>> {
let childParser = Parser<ArraySlice<XML>, Child>.next { child.run($0) }
let childrenParser: Parser<[XML], [Child]> =
(childParser* <<~ endof())
.pullback(get: { $0[...] }, set: { $0 = Array($1) })
let attrs = (attributes <<~ endof())
return zip(
attrs.pullback(\XML.Element.attrs),
childrenParser.pullback(\XML.Element.children),
with: SVG.ElementWithChildren.init
).optional.pullback(\XML.el)
}
private static func element<Attributes>(
tag: Tag
) -> (AttributeGroupParser<Attributes>) -> Parser<XML, Attributes> {
let tag: Parser<XML.Element, Void> =
consume(tag.rawValue)
.pullback(get: { $0[...] }, set: { $0 = String($1) })
.pullback(\XML.Element.tag)
return { attributes in
(tag ~>> (attributes <<~ endof()).pullback(\.attrs))
.optional.pullback(\.el)
}
}
private static let filterPrimitiveAttributes = zip(
identifier(.result),
height, width, x, y,
with: SVG.FilterPrimitiveCommonAttributes.init
)
private static func filterPrimitive<T>(
_ data: AttributeGroupParser<T>
) -> AttributeGroupParser<SVG.FilterPrimitiveElement<T>> {
zip(
core, presentation, filterPrimitiveAttributes, data,
with: SVG.FilterPrimitiveElement.init
)
}
private static let filterPrimitiveIn =
attributeParser(SVGAttributeParsers.filterPrimitiveIn)
private static let blendMode = attributeParser(SVGAttributeParsers.blendMode)
private static let feColorMatrixType =
attributeParser(oneOf(SVG.FilterPrimitiveFeColorMatrix.Kind.self))
private static let feBlend = zip(
filterPrimitiveIn(.in),
filterPrimitiveIn(.in2),
blendMode(.mode),
with: SVG.FilterPrimitiveFeBlend.init
) |> filterPrimitive >>> element(tag: .feBlend)
private static let feColorMatrix = zip(
filterPrimitiveIn(.in),
feColorMatrixType(.type),
numList(.values),
with: SVG.FilterPrimitiveFeColorMatrix.init
) |> filterPrimitive >>> element(tag: .feColorMatrix)
private static let feFlood = zip(
color(.floodColor),
num(.floodOpacity),
with: SVG.FilterPrimitiveFeFlood.init
) |> filterPrimitive >>> element(tag: .feFlood)
private static let feGaussianBlur = zip(
filterPrimitiveIn(.in),
numberOptionalNumber(.stdDeviation),
with: SVG.FilterPrimitiveFeGaussianBlur.init
) |> filterPrimitive >>> element(tag: .feGaussianBlur)
private static let feOffset = zip(
filterPrimitiveIn(.in),
num(.dx),
num(.dy),
with: SVG.FilterPrimitiveFeOffset.init
) |> filterPrimitive >>> element(tag: .feOffset)
private static
let filterPrimitiveContent: Parser<XML, SVG.FilterPrimitiveContent> = oneOf([
feBlend.map(SVG.FilterPrimitiveContent.feBlend),
feColorMatrix.map(SVG.FilterPrimitiveContent.feColorMatrix),
feFlood.map(SVG.FilterPrimitiveContent.feFlood),
feGaussianBlur.map(SVG.FilterPrimitiveContent.feGaussianBlur),
feOffset.map(SVG.FilterPrimitiveContent.feOffset),
])
private static let filter: Parser<XML, SVG.Filter> = elementWithChildren(
attributes: filterAttributes, child: filterPrimitiveContent
)
public static func element(from xml: XML) throws -> SVG {
switch xml {
case let .el(el):
guard let tag = Tag(rawValue: el.tag) else {
throw Error.uknownTag(el.tag)
}
switch tag {
case .svg:
return try .svg(document(from: el))
case .rect:
return try .rect(rect(from: el))
case .title:
guard case let .text(title)? = el.children.firstAndOnly else {
throw Error.titleHasInvalidFormat(xml)
}
return .title(title)
case .desc:
guard case let .text(desc)? = el.children.firstAndOnly else {
throw Error.titleHasInvalidFormat(xml)
}
return .desc(desc)
case .g:
return try .group(group(from: el))
case .polygon:
return try .polygon(polygon(from: el))
case .defs:
return try .defs(defs(from: el))
case .linearGradient:
return try .linearGradient(linearGradient(from: el))
case .radialGradient:
return try .radialGradient(radialGradient(from: el))
case .stop:
fatalError()
case .path:
return try .path(path(from: el))
case .circle:
return try .circle(circle(from: el))
case .ellipse:
return try .ellipse(ellipse(from: el))
case .mask:
return try .mask(mask(from: el))
case .use:
return try .use(use(from: el))
case .clipPath:
return try .clipPath(clipPath(from: el))
case .filter:
return try .filter(filter.run(xml).get())
case .feColorMatrix,
.feComponentTransfer,
.feComposite,
.feConvolveMatrix,
.feDiffuseLighting,
.feDisplacementMap,
.feBlend,
.feFlood,
.feGaussianBlur,
.feImage,
.feMerge,
.feMorphology,
.feOffset,
.feSpecularLighting,
.feTile,
.feTurbulence:
fatalError()
}
case let .text(t):
throw Error.unexpectedXMLText(t)
}
}
}
private func attributeParser<T>(
_ parser: SVGAttributeParsers.Parser<T>
) -> (Attribute) -> Parser<[String: String], T?> {
{
key(key: $0.rawValue)~?.flatMapResult {
guard let value = $0 else { return .success(nil) }
return parser.map(Optional.some).whole(value)
}
}
}
public enum SVGAttributeParsers {
typealias Parser<T> = Base.Parser<Substring, T>
internal static let wsp: Parser<Void> = oneOf(
[0x20, 0x9, 0xD, 0xA]
.map(Unicode.Scalar.init).map(Character.init)
.map(consume)
)
internal static let comma: Parser<Void> = ","
// (wsp+ comma? wsp*) | (comma wsp*)
internal static let commaWsp: Parser<Void> =
(wsp+ ~>> comma~? ~>> wsp* | comma ~>> wsp*).map(always(()))
internal static let number: Parser<SVG.Float> = double()
internal static let listOfNumbers = zeroOrMore(number, separator: commaWsp)
internal static let numberOptionalNumber = zip(
number,
(commaWsp ~>> number)~?,
with: SVG.NumberOptionalNumber.init
)
internal static let coord: Parser<SVG.Float> = number
internal static let lengthUnit: Parser<SVG.Length.Unit> = oneOf()
internal static let length: Parser<SVG.Length> = (number ~ lengthUnit~?)
.map { SVG.Length(number: $0.0, unit: $0.1) }
internal static let flag: Parser<Bool> =
oneOf(consume("0").map(always(false)), consume("1").map(always(true)))
internal static let viewBox: Parser<SVG.ViewBox> =
zip(
number <<~ commaWsp, number <<~ commaWsp, number <<~ commaWsp, number,
with: SVG.ViewBox.init
)
// Has no equivalent in specification, for code deduplication only.
// "$name" wsp* "(" wsp* parser wsp* ")"
internal static func namedTransform(
_ name: String,
_ value: Parser<SVG.Transform>
) -> Parser<SVG.Transform> {
(consume(name) ~ wsp* ~ "(" ~ wsp*) ~>> value <<~ (wsp* ~ ")")
}
// "translate" wsp* "(" wsp* number ( comma-wsp number )? wsp* ")"
internal static let translate: Parser<SVG.Transform> = namedTransform(
"translate",
zip(number, (commaWsp ~>> number)~?, with: SVG.Transform.translate)
)
// "scale" wsp* "(" wsp* number ( comma-wsp number )? wsp* ")"
internal static let scale: Parser<SVG.Transform> = namedTransform(
"scale",
zip(number, (commaWsp ~>> number)~?, with: SVG.Transform.scale)
)
// comma-wsp number comma-wsp number
private static let anchor: Parser<SVG.Transform.Anchor> = zip(
commaWsp ~>> number, commaWsp ~>> number,
with: SVG.Transform.Anchor.init
)
private static let angle: Parser<SVG.Angle> = number.map(SVG.Angle.init)
// "rotate" wsp* "(" wsp* number ( comma-wsp number comma-wsp number )? wsp* ")"
internal static let rotate: Parser<SVG.Transform> = namedTransform(
"rotate",
zip(angle, anchor~?, with: SVG.Transform.rotate)
)
// "skewX" wsp* "(" wsp* number wsp* ")"
internal static let skewX: Parser<SVG.Transform> = namedTransform(
"skewX", angle.map(SVG.Transform.skewX)
)
// "skewX" wsp* "(" wsp* number wsp* ")"
internal static let skewY: Parser<SVG.Transform> = namedTransform(
"skewY", angle.map(SVG.Transform.skewY)
)
/*
"matrix" wsp* "(" wsp*
number comma-wsp
number comma-wsp
number comma-wsp
number comma-wsp
number comma-wsp
number wsp* ")"
*/
internal static let matrix: Parser<SVG.Transform> = namedTransform(
"matrix", zip(
number <<~ commaWsp,
number <<~ commaWsp,
number <<~ commaWsp,
number <<~ commaWsp,
number <<~ commaWsp,
number,
with: SVG.Transform.matrix
)
)
internal static let transformsList: Parser<[SVG.Transform]> =
wsp* ~>> oneOrMore(transform, separator: commaWsp+) <<~ wsp*
internal static let transform: Parser<SVG.Transform> = oneOf([
translate,
scale,
rotate,
skewX,
skewY,
matrix,
])
internal static let hexByteFromSingle: Parser<UInt8> = readOne().flatMap {
guard let value = hexFromChar($0) else { return .never() }
return .always(value << 4 | value)
}
internal static let hexByte: Parser<UInt8> = (readOne() ~ readOne()).flatMap {
guard let v1 = hexFromChar($0.0),
let v2 = hexFromChar($0.1) else { return .never() }
return .always(v1 << 4 | v2)
}
private static let shortRGB: Parser<SVG.Color> =
zip(
hexByteFromSingle,
hexByteFromSingle,
hexByteFromSingle,
with: SVG.Color.init
)
private static let rgb: Parser<SVG.Color> = zip(
hexByte,
hexByte,
hexByte,
with: SVG.Color.init
)
public static let rgbcolor = oneOf([
"#" ~>> (rgb | shortRGB),
oneOf(SVGColorKeyword.self).map(\.color),
])
internal static let iri: Parser<String> =
"#" ~>> consume(while: always(true)).map(String.init)
internal static let funciri: Parser<String> =
"url(#" ~>> consume(while: { $0 != ")" }).map(String.init) <<~ ")"
internal static let paint: Parser<SVG.Paint> =
consume("none").map(always(.none)) |
rgbcolor.map(SVG.Paint.rgb) |
funciri.map(SVG.Paint.funciri(id:))
// coordinate comma-wsp coordinate
// | coordinate negative-coordinate
private static let coordinatePair: Parser<SVG.CoordinatePair> =
(number <<~ commaWsp~? ~ number).map(SVG.CoordinatePair.init)
// list-of-points:
// wsp* coordinate-pairs? wsp*
// coordinate-pairs:
// coordinate-pair
// | coordinate-pair comma-wsp coordinate-pairs
internal static let listOfPoints: Parser<SVG.CoordinatePairs> =
wsp* ~>> zeroOrMore(coordinatePair, separator: commaWsp) <<~ wsp*
// elliptical-arc-argument:
// nonnegative-number comma-wsp? nonnegative-number comma-wsp?
// number comma-wsp flag comma-wsp? flag comma-wsp? coordinate-pair
internal static
let ellipticalArcArg: Parser<SVG.PathData.EllipticalArcArgument> =
zip(
number <<~ commaWsp~?, number <<~ commaWsp~?,
number <<~ commaWsp, flag <<~ commaWsp~?, flag <<~ commaWsp~?,
coordinatePair,
with: SVG.PathData.EllipticalArcArgument.init
)
internal static let identifier: Parser<String> =
Parser<Substring>.identity().map(String.init)
internal static let stopOffset: Parser<SVG.Stop.Offset> = (number ~ "%"~?)
.map {
switch $0.1 {
case .some:
return .percentage($0.0)
case nil:
return .number($0.0)
}
}
// MARK: Path
private static let anyCommand: Parser<SVG.PathData.Command> = oneOf([
command("M", arg: coordinatePair) { .moveto($0) },
command("L", arg: coordinatePair) { .lineto($0) },
command("H", arg: coord) { .horizontalLineto($0) },
command("V", arg: coord) { .verticalLineto($0) },
command("C", arg: curveArgument) { .curveto($0) },
command("S", arg: smoothCurveArgument) { .smoothCurveto($0) },
command("Q", arg: quadraticCurveArgument) { .quadraticBezierCurveto($0) },
command("T", arg: coordinatePair) { .smoothQuadraticBezierCurveto(to: $0) },
command("A", arg: ellipticalArcArg) { .ellipticalArc($0) },
positioning(of: "Z").map { .init(positioning: $0, kind: .closepath) },
])
internal static let pathData =
wsp* ~>> oneOrMore(anyCommand, separator: wsp*) <<~ wsp*
private static let quadraticCurveArgument = zip(
coordinatePair <<~ commaWsp~?,
coordinatePair,
with: SVG.PathData.QuadraticCurveArgument.init
)
private static let smoothCurveArgument = zip(
coordinatePair <<~ commaWsp~?,
coordinatePair,
with: SVG.PathData.SmoothCurveArgument.init
)
private static let curveArgument = zip(
coordinatePair <<~ commaWsp~?,
coordinatePair <<~ commaWsp~?,
coordinatePair,
with: SVG.PathData.CurveArgument.init
)
private static func command<T>(
_ cmd: Character,
arg: Parser<T>,
builder: @escaping ([T]) -> SVG.PathData.CommandKind
) -> Parser<SVG.PathData.Command> {
zip(
positioning(of: cmd) <<~ wsp*,
argumentSequence(arg)
) { pos, args in
SVG.PathData.Command(positioning: pos, kind: builder(args))
}
}
private static func positioning(
of cmd: Character
) -> Parser<SVG.PathData.Positioning> {
consume(cmd.lowercased()).map(always(.relative))
| consume(cmd.uppercased()).map(always(.absolute))
}
private static func argumentSequence<T>(_ p: Parser<T>) -> Parser<[T]> {
oneOrMore(p, separator: commaWsp~?)
}
private static func hexFromChar(_ c: Character) -> UInt8? {
c.hexDigitValue.flatMap(UInt8.init(exactly:))
}
// Dash Array
internal static let dashArray = oneOrMore(length, separator: commaWsp)
private static let filterPrimitiveInPredefined:
Parser<SVG.FilterPrimitiveIn.Predefined> = oneOf()
internal static let filterPrimitiveIn: Parser<SVG.FilterPrimitiveIn> =
Parser<Substring>.identity()
.map {
let value = String($0)
return SVG.FilterPrimitiveIn.Predefined(rawValue: value)
.map(SVG.FilterPrimitiveIn.predefined) ?? .previous(value)
}
internal static let blendMode: Parser<SVG.BlendMode> = oneOf()
}
// MARK: - Render
public func renderXML(from document: SVG.Document) -> XML {
.el("svg", attrs: [
"width": document.width?.encode(),
"height": document.height?.encode(),
"viewBox": document.viewBox?.encode(),
].compactMapValues(identity), children: document.children.map(renderXML))
}
public func renderXML(from svg: SVG) -> XML {
switch svg {
case let .svg(doc):
return renderXML(from: doc)
case let .rect(r):
return .el("rect", attrs: [
"x": r.data.x?.encode(),
"y": r.data.y?.encode(),
"width": r.data.width?.encode(),
"height": r.data.height?.encode(),
"fill": r.presentation.fill?.encode(),
"fill-opacity": r.presentation.fillOpacity?.description,
].compactMapValues(identity))
case .group, .polygon, .mask, .use, .defs, .title, .desc, .linearGradient,
.circle, .path, .ellipse, .radialGradient, .clipPath, .filter:
fatalError()
}
}
extension SVG.Float {
public func encode() -> String {
description
}
}
extension SVG.Length {
public func encode() -> String {
"\(number)\(unit?.rawValue ?? "")"
}
}
extension SVG.Paint {
public func encode() -> String {
switch self {
case let .rgb(color):
return color.hexString
case .none:
return "none"
case .currentColor:
return "currentColor"
case let .funciri(id):
return "url(#\(id)"
}
}
}
extension SVG.Color {
var hexString: String {
hex((red, green, blue))
}
}
extension SVG.ViewBox {
public func encode() -> String {
""
}
}
// Helpers
extension SVG.PresentationAttributes {
public static let empty = SVG.PresentationAttributes(
clipPath: nil,
clipRule: nil,
mask: nil,
filter: nil,
fill: nil,
fillRule: nil,
fillOpacity: nil,
stroke: nil,
strokeWidth: nil,
strokeLineCap: nil,
strokeLineJoin: nil,
strokeDashArray: nil,
strokeDashOffset: nil,
strokeOpacity: nil,
opacity: nil,
stopColor: nil,
stopOpacity: nil,
colorInterpolationFilters: nil
)
public static func construct(
_ constructor: (inout SVG.PresentationAttributes) -> Void
) -> SVG.PresentationAttributes {
var temp = empty
constructor(&temp)
return temp
}
}
| true
|
b5ec0fb9bdd3284cb378b2e77ee1a034db59578f
|
Swift
|
MissZou/food-ordering-by-zwy-liyan
|
/ios/FoodOrderingSystem/Account.swift
|
UTF-8
| 2,583
| 2.78125
| 3
|
[] |
no_license
|
//
// Account.swift
// FoodPersistantLayer
//
// Created by MoonSlides on 16/2/5.
// Copyright © 2016年 李龑. All rights reserved.
//
import Alamofire
protocol AccountDelegate {
func finishCreateAccount(status:String)
func finishLogin(status:String)
}
class Account: NSObject {
let baseUrl = "http://localhost:8080/api/";
var delegate:AccountDelegate?
var email:String
var name:String
var phone:String
var password:String
var photoUrl:String?
var deliveryAddress:String?
//static var sharedManager: Account
override init() {
email = ""
password = ""
name = ""
phone = ""
}
class var sharedManager:Account {
struct Static {
static var onceToken: dispatch_once_t = 0
static var sharedManager: Account?
}
dispatch_once(&Static.onceToken){
Static.sharedManager = Account()
}
return Static.sharedManager!
}
func createAccount(email:String, password:String, name:String, phone:String){
let params:[String : AnyObject] = [
"email" : email,
"password" : password,
"phone" : phone,
"name" : name
]
Alamofire.request(.POST, "\(baseUrl) + register", parameters: params, encoding: .JSON).responseData { response in
let dataString = NSString(data: response.data!, encoding: NSUTF8StringEncoding)
print(dataString!)
print(NSString(data: response.request!.HTTPBody!, encoding: NSUTF8StringEncoding)!)
if (dataString! == "ok"){
self.delegate?.finishCreateAccount("ok")
}
else {
self.delegate?.finishCreateAccount(dataString! as String)
}
}
}
func login(email:String, password:String){
let params:[String : AnyObject] = [
"email" : email,
"password" : password
]
Alamofire.request(.POST, "\(baseUrl) + login", parameters: params, encoding: .JSON).responseData { response in
let dataString = NSString(data: response.data!, encoding: NSUTF8StringEncoding)
print(dataString!)
print(NSString(data: response.request!.HTTPBody!, encoding: NSUTF8StringEncoding)!)
if (dataString! == "true"){
self.delegate?.finishLogin("ok")
}
else {
self.delegate?.finishLogin(dataString! as String)
}
}
}
}
| true
|
f4441bfb20785d1ad46ae6c7a982ee6b0c8ea209
|
Swift
|
swipip/Quotip
|
/Quotip/Views/TagCell.swift
|
UTF-8
| 5,276
| 2.640625
| 3
|
[] |
no_license
|
//
// TagCell.swift
// Quotip
//
// Created by Gautier Billard on 17/05/2020.
// Copyright © 2020 Gautier Billard. All rights reserved.
//
import Foundation
import UIKit
class TagCell: UITableViewCell {
private lazy var tagLabel: UILabel = {
let label = UILabel()
label.text = "Chargement"
label.font = UIFont.init(name: "American Typewriter", size: 25)
label.numberOfLines = 3
label.textAlignment = .left
label.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
return label
}()
private lazy var countLabel: UILabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 45)
label.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
return label
}()
private var countLabelLeading: NSLayoutConstraint!
private lazy var plusButton: UIButton = {
let button = UIButton()
let config = UIImage.SymbolConfiguration(pointSize: 35, weight: .thin)
button.setImage(UIImage(systemName: "arrow.right.circle",withConfiguration: config), for: .normal)
button.alpha = 0.0
button.tintColor = .black
button.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
return button
}()
var leadingLabelAnchor: NSLayoutConstraint!
var quoteTag: Tag?
var buttonTapped: ((Tag)->Void)?
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = .clear
self.selectionStyle = .none
addButton()
addLabel()
addCountLabel()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func passData(tag: Tag) {
self.quoteTag = tag
self.tagLabel.text = tag.name.capitalized
self.countLabel.text = String(tag.count)
}
@objc private func buttonPressed(_ sender:UIButton!){
if let tag = quoteTag {
buttonTapped?(tag)
}
}
private func addCountLabel() {
self.addSubview(countLabel)
func addConstraints(fromView: UIView, toView: UIView) {
fromView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([fromView.bottomAnchor.constraint(equalTo: toView.topAnchor,constant: 0)])
}
addConstraints(fromView: countLabel, toView: self.tagLabel)
countLabelLeading = NSLayoutConstraint(item: countLabel, attribute: .leading, relatedBy: .equal, toItem: tagLabel, attribute: .leading, multiplier: 1, constant: 25)
self.addConstraint(countLabelLeading)
}
private func addButton() {
self.addSubview(plusButton)
func addConstraints(fromView: UIView, toView: UIView) {
fromView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([fromView.widthAnchor.constraint(equalToConstant: 50),
fromView.trailingAnchor.constraint(equalTo: toView.trailingAnchor ,constant: -20),
fromView.centerYAnchor.constraint(equalTo: toView.centerYAnchor, constant: 0),
fromView.heightAnchor.constraint(equalTo: toView.heightAnchor,constant: 50)])
}
addConstraints(fromView: plusButton, toView: self)
plusButton.transform = CGAffineTransform(scaleX: 0.7, y: 0.7)
}
private func addLabel() {
self.addSubview(tagLabel)
func addConstraints(fromView: UIView, toView: UIView) {
fromView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([fromView.widthAnchor.constraint(equalToConstant: 200),
fromView.centerYAnchor.constraint(equalTo: toView.centerYAnchor ,constant: 20)])
}
addConstraints(fromView: tagLabel, toView: self)
leadingLabelAnchor = NSLayoutConstraint(item: tagLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)
self.addConstraint(leadingLabelAnchor)
}
func magnify(on: Bool) {
let scale:CGFloat = on ? 1 : 0.6
UIView.animate(withDuration: 0.5) {
self.leadingLabelAnchor.constant = on ? 70 : 0
self.tagLabel.transform = CGAffineTransform(scaleX: scale, y: scale)
self.countLabel.transform = CGAffineTransform(scaleX: scale, y: scale)
self.countLabelLeading.constant = on ? 0 : 25
self.plusButton.transform = CGAffineTransform(scaleX: scale, y: scale)
self.plusButton.alpha = on ? 1.0 : 0.0
self.layoutIfNeeded()
}
}
override func prepareForReuse() {
super.prepareForReuse()
magnify(on: false)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
| true
|
f38dcf97f78c79d6d065d7e76dc1b5b1a480bb66
|
Swift
|
ppjia/WeatherApp
|
/WeatherAPP/WeatherListViewController.swift
|
UTF-8
| 2,428
| 2.65625
| 3
|
[] |
no_license
|
//
// MasterViewController.swift
// WeatherAPP
//
// Created by ruixue on 7/10/17.
// Copyright © 2017 rui. All rights reserved.
//
import UIKit
class WeatherListViewController: UITableViewController {
private let viewModel = WeatherListViewModel()
// MARK: - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = tableView.indexPathForSelectedRow {
guard let city = viewModel.city(at: indexPath.row),
let weatherDetails = viewModel.weatherDetails(forCity: city.1) else { return }
let controller = segue.destination as! DetailViewController
controller.weatherDetails = weatherDetails
controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfCities
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "WeatherCell", for: indexPath) as! WeatherCell
if let city = viewModel.city(at: indexPath.row) {
cell.cityLabel.text = city.0
cell.loadingIndicator.isHidden = false
cell.loadingIndicator.startAnimating()
viewModel.fetchWeather(for: city.1) { [weak self] error in
DispatchQueue.main.sync {
guard let sself = self else { return }
cell.loadingIndicator.stopAnimating()
cell.loadingIndicator.isHidden = true
if error == nil, let temperature = sself.viewModel.temperature(forCity: city.1) {
cell.temperatureLabel.text = "\(temperature)"
} else {
cell.temperatureLabel.text = "Loading error!"
}
}
}
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "showDetail", sender: self)
}
}
| true
|
c7449dbf68a47dc454095dca08f1ae80b0c10a2e
|
Swift
|
khawlittaa/TunisianDestinations
|
/TunisianDestinations/Models/APIResponse.swift
|
UTF-8
| 602
| 2.984375
| 3
|
[] |
no_license
|
//
// APIResponse.swift
// TunisianDestinations
//
// Created by khaoula hafsia on 6/14/20.
// Copyright © 2020 khaoula hafsia. All rights reserved.
//
enum APIResponseCodingKeys: String, CodingKey {
case code
case message
}
import Foundation
class APIResponse: Codable {
var code: String?
var message: String?
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: APIResponseCodingKeys.self)
code = try container.decode(String.self, forKey: .code)
message = try container.decode(String.self, forKey: .message)
}
}
| true
|
fa0bb5c294063eac240b431372ae4786641b88ca
|
Swift
|
vladislav14141/Figma-Colors
|
/Figma Colors/Views/MRCheckBox.swift
|
UTF-8
| 888
| 2.9375
| 3
|
[] |
no_license
|
//
// MRCheckBox.swift
// Figma Colors
//
// Created by Владислав Миронов on 26.04.2021.
//
import SwiftUI
struct MRCheckBox: View {
@Binding var isOn: Bool
var onToggle: ((Bool)->()) = { _ in}
var body: some View {
Button(action: {
isOn.toggle()
onToggle(isOn)
}, label: {
Group {
if isOn {
Image(systemName: "checkmark.circle.fill").renderingMode(.original).font(.system(size: 17, weight: .light))
} else {
Image(systemName: "checkmark.circle").font(.system(size: 17, weight: .light))
}
}.background(Color.clear).clipShape(Circle())
}).buttonStyle(MRButtonStyle(type: .plain))
}
}
struct MRCheckBox_Previews: PreviewProvider {
static var previews: some View {
MRCheckBox(isOn: .constant(true))
}
}
| true
|
69b4d8d10688fd33863be565a80115037f6a2359
|
Swift
|
SamBuydens/Major4DeBuuus
|
/DeBuuus/CLLocationManagerExtension.swift
|
UTF-8
| 1,181
| 2.71875
| 3
|
[] |
no_license
|
//
// CLLocationManagerExtension.swift
// DeBuuus
//
// Created by Sam Buydens on 16/06/15.
// Copyright (c) 2015 Devine. All rights reserved.
//
import UIKit
import GoogleMaps
extension CLLocationManager {
func deleteMarker(sid:String, arr:Array<BusMarker>)->Int{
var arr = arr
var doesContain = arr.filter( { (marker: BusMarker) -> Bool in
return marker.sid == sid
})
if(doesContain.count > 0){println("with a marker")
println(doesContain[0])
var index = find(arr, doesContain[0])
arr.removeAtIndex(index!)
return index!
}
return -1
}
func removeObject<T : Equatable>(object: T, inout fromArray array: [T]){
var index = find(array, object)
array.removeAtIndex(index!)
}
func checkDistance(helperLoc:CLLocationCoordinate2D, mapView:MapView)->Bool{
if((mapView.myLocation) != nil){
var needingLoc = mapView.myLocation.coordinate
return GMSGeometryDistance(helperLoc, needingLoc) < 10
}
return false
}
}
| true
|
b0417136b94d407e80f5b5b1997ec09984c533c1
|
Swift
|
vardhanpatel/SimpleGPA
|
/GPACalc/view2.swift
|
UTF-8
| 2,086
| 2.53125
| 3
|
[] |
no_license
|
//
// view2.swift
// MyGPA
//
// Created by Hanuman on 11/28/17.
// Copyright © 2017 Timodox. All rights reserved.
//
import UIKit
class view2: UIViewController {
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label45: UILabel!
@IBOutlet weak var overview: UILabel!
@IBOutlet weak var youregpais: UILabel!
override func viewDidLoad() {
label45.numberOfLines = 0;
[label45.sizeToFit];
overview.adjustsFontSizeToFitWidth = true
youregpais.adjustsFontSizeToFitWidth = true
if 4.0...5.0 ~= gpa {
self.view.backgroundColor = UIColor.green
label45.text = "Great , Keep up the work. This GPA will get you $cholorships"
}
if 3.0...4.0 ~= gpa {
self.view.backgroundColor = UIColor(hue: 0.475, saturation: 1, brightness: 0.94, alpha: 1.0)
label45.text = "OK , Let's work a little bit and add more effort. I know you can do it"
}
if 2.0...3.0 ~= gpa {
self.view.backgroundColor = UIColor(hue: 0.9694, saturation: 1, brightness: 0.97, alpha: 1.0)
label45.text = "OH, This GPA is a little low, I know you can raise it up, make sure you turn in your homework on time and spend time at home for homework."
}
if 1.0...2.0 ~= gpa {
self.view.backgroundColor = UIColor(hue: 0.9694, saturation: 1, brightness: 0.97, alpha: 1.0)
label45.text = "UMMM, This GPA is a little low, I know you can raise it up, make sure you turn in your homework on time and spend time at home for homework."
}
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
label2.text = String(gpa)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| true
|
650e813263bd53a60e8c47094b821bf86f5b6ccc
|
Swift
|
PaulSola/MacPaw
|
/MacPaw_Project/Cells/SportsTableViewCell.swift
|
UTF-8
| 2,968
| 2.640625
| 3
|
[] |
no_license
|
//
// SportsTableViewCell.swift
// MacPaw_Project
//
// Created by Paul Solyanikov on 4/30/19.
// Copyright © 2019 Paul Solyanikov. All rights reserved.
//
import UIKit
class SportsTableViewCell: UITableViewCell {
let sportImage: UIImageView = {
let image = UIImageView()
image.translatesAutoresizingMaskIntoConstraints = false
image.contentMode = UIView.ContentMode.scaleAspectFill
image.clipsToBounds = true
return image
}()
let sportDescr: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "SportDesct"
label.font = UIFont(name:"Helvetica-Light", size: 15)
label.numberOfLines = 0
return label
}()
let sportLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
label.text = "Sport"
label.font = UIFont(name:"Helvetica-Bold", size: 25)
return label
}()
func configureSportView(sportName: String, image: String?, descrText : String){
sportLabel.text = sportName
sportImage.image = UIImage(named: image ?? "default")
sportDescr.text = descrText
contentView.addSubview(sportLabel)
contentView.addSubview(sportImage)
contentView.addSubview(sportDescr)
sportLabel.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 10).isActive = true
sportLabel.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10).isActive = true
sportLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: 10).isActive = true
sportLabel.heightAnchor.constraint(equalToConstant: 25).isActive = true
sportImage.topAnchor.constraint(equalTo: sportLabel.bottomAnchor, constant: 5).isActive = true
sportImage.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 0).isActive = true
sportImage.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: 0).isActive = true
sportImage.heightAnchor.constraint(equalToConstant: Device.width ).isActive = true
sportDescr.topAnchor.constraint(equalTo: sportImage.bottomAnchor, constant: 10).isActive = true
sportDescr.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 10).isActive = true
sportDescr.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -10).isActive = true
sportDescr.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20).isActive = true
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| true
|
dbc01fad60985dc881f3e119723b904b3ae496f4
|
Swift
|
qiweipeng/Algorithms
|
/Algorithms/Sort/BubbleSort.swift
|
UTF-8
| 665
| 3.625
| 4
|
[
"MIT"
] |
permissive
|
//
// BubbleSort.swift
// Algorithms
//
// Created by Weipeng Qi on 2020/3/25.
// Copyright © 2020 Weipeng Qi. All rights reserved.
//
import Foundation
/// 冒泡排序。
/// - Parameters:
/// - elements: 需要排序的数组。
/// - comparison: 比较规则。
/// - Complexity: O(n^2)
/// - Returns: 排序后的数组。
public func bubbleSort<T> (_ elements: [T], _ comparison: (T, T) -> Bool) -> [T] {
var array = elements
for i in 0..<array.count {
for j in 1..<array.count - i {
if comparison(array[j], array[j - 1]) {
array.swapAt(j, j - 1)
}
}
}
return array
}
| true
|
33b8e28bf6fb20f510287083afc123f5cfca0533
|
Swift
|
Yuanjihua1/BuildingAnimation
|
/BuildingAnimation/BuildingAnimation/DoOtherAnimation.swift
|
UTF-8
| 497
| 2.515625
| 3
|
[] |
no_license
|
//
// DoOtherAnimation.swift
// EZAnimation
//
// Created by 李修冶 on 2017/3/24.
// Copyright © 2017年 李修冶. All rights reserved.
//
import UIKit
public func doOther(_ duration : TimeInterval , closure : (()->Void)?) -> AnimatState{
return { view in
view.animCount += 1
closure?()
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + duration, execute: {
view.animCount -= 1
})
return view
}
}
| true
|
c01ac32fd5d446d0473db31c695255c2b47376c9
|
Swift
|
wai84n/AqarMall_ios
|
/AqarMall/Controllers/Advertisements/SearchAds/AdvFilterViewController.swift
|
UTF-8
| 2,710
| 2.609375
| 3
|
[] |
no_license
|
//
// AdvFilterViewController.swift
// AqarMall
//
// Created by Macbookpro on 4/3/19.
// Copyright © 2019 Macbookpro. All rights reserved.
//
import UIKit
protocol AdvFilterDelegate : class {
func advFilter(with orderBy : Int16, orderType : String)
}
enum AdvFilterOptions {
case HigherPrice
case lowerPrices
case biggerSize
case smallestSize
case newAdv
case oldAdv
case mostViews
case lowerViews
}
class AdvFilterViewController: ViewController {
var delegate: AdvFilterDelegate? = nil
override func viewDidLoad() {
super.viewDidLoad()
// AppUtils.SendGAIScreenName(screenName: "ترتيب الإعلانات")
// Do any additional setup after loading the view.
}
@IBAction func HigherPrice(_ sender: Any) {
implementFilterAction(order: .HigherPrice)
}
@IBAction func lowerPrices(_ sender: Any) {
implementFilterAction(order: .lowerPrices)
}
@IBAction func biggerSize(_ sender: Any) {
implementFilterAction(order: .biggerSize)
}
@IBAction func smallestSize(_ sender: Any) {
implementFilterAction(order: .smallestSize)
}
@IBAction func newAdv(_ sender: Any) {
implementFilterAction(order: .newAdv)
}
@IBAction func oldAdv(_ sender: Any) {
implementFilterAction(order: .oldAdv)
}
@IBAction func mostViews(_ sender: Any) {
implementFilterAction(order: .mostViews)
}
@IBAction func lowerViews(_ sender: Any) {
implementFilterAction(order: .lowerViews)
}
func implementFilterAction(order : AdvFilterOptions){
if let _delegate = delegate{
switch order {
case .lowerPrices:
_delegate.advFilter(with: 1, orderType: "Asc")
case .HigherPrice:
_delegate.advFilter(with: 1, orderType: "DESC")
case .smallestSize:
_delegate.advFilter(with: 2, orderType: "Asc")
case .biggerSize:
_delegate.advFilter(with: 2, orderType: "DESC")
case .newAdv:
_delegate.advFilter(with: 3, orderType: "DESC")
case .oldAdv:
_delegate.advFilter(with: 3, orderType: "Asc")
case .mostViews:
_delegate.advFilter(with: 4, orderType: "DESC")
case .lowerViews:
_delegate.advFilter(with: 3, orderType: "Asc")
}
}
self.leftAction()
// 1 = Price 2 = Size 3 = Entry date 4 = Most viewed
//order_type: (Asc,Dec).
}
@IBAction func goBackAction() {
self.leftAction()
}
}
| true
|
55ca7c85455205a4637a3b872f4d894a1c251e87
|
Swift
|
sadeedch/FavouriteThings-CoreData
|
/FavouriteThings/View/LocationView.swift
|
UTF-8
| 7,765
| 3.125
| 3
|
[] |
no_license
|
//
// SwiftUIView.swift
// FavouriteThings
//
// Created by Sadeed Ahmed on 22/5/20.
// Copyright © 2020 Sadeed Ahmad. All rights reserved.
//
import Foundation
import SwiftUI
import CoreLocation
struct LocationView: View {
@ObservedObject var location: Things
@Environment(\.managedObjectContext) var context
@ObservedObject var keyboard = Keyboard()
@State var currentPosition = CLLocationCoordinate2D()
@State var locationName: String // locationName : a temporary variable to hold the location name
@State var latitudeString: String // latitudeString : a temporary variable to hold the latitude coordinates
@State var longitudeString: String // longitudeString : a temporary variable to hold the longitude coordinates
var body: some View {
ScrollView(.vertical){
VStack(alignment: .center){
// Displays the map
MapView(things: location, locModel: LocationModel(thing: location))
.padding(3.0)
.frame(width: 400, height: 300, alignment: .top)
HStack {
Text("Location Name") // Displays the location name
.fontWeight(.bold)
.font(Font.system(size: 20))
.multilineTextAlignment(.leading)
TextField("Enter location..", text: self.$locationName, onCommit: {
// updates the map location, longitude and latitude when location name is updated
let geoCoder = CLGeocoder()
let region = CLCircularRegion(center: self.currentPosition, radius: 2_000_000, identifier: "\(self.currentPosition)")
geoCoder.geocodeAddressString(self.locationName, in: region) { (placemarks, error ) in
guard let location = placemarks?.first?.location
else {
print("Error locating '\(self.locationName)': \(error.map {"\($0)"} ?? "<unknown error>")")
return
}
let position = location.coordinate
self.currentPosition.latitude = position.latitude
self.currentPosition.longitude = position.longitude
self.location.boundLatitude = "\(position.latitude)"
self.latitudeString = self.location.boundLatitude
self.location.boundLongitude = "\(position.longitude)"
self.longitudeString = self.location.boundLongitude
self.location.boundLoaction = self.locationName
}
try? self.context.save()
})
}
HStack {
Text("Latitude") // Displays the location latitude
.fontWeight(.bold)
.font(Font.system(size: 20))
.multilineTextAlignment(.leading)
TextField("Enter latitude..", text: self.$latitudeString, onEditingChanged: { _ in try? self.context.save() }, onCommit: {
// updates the location name and map when latitude is updated
guard let latitude = CLLocationDegrees(self.latitudeString),
let longitude = CLLocationDegrees(self.longitudeString)
else {
print("Invalid Coordinates")
return
}
self.currentPosition.latitude = latitude
self.currentPosition.longitude = longitude
let geoCoder = CLGeocoder()
let position = CLLocation(latitude: self.currentPosition.latitude, longitude: self.currentPosition.longitude)
geoCoder.reverseGeocodeLocation(position) { (placemarks, error ) in
guard let placemark = placemarks?.first
else {
print("Error locating \(self.currentPosition.latitude) / \(self.currentPosition.longitude) / : \(error.map {"\($0)"} ?? "<unknown error>")")
return
}
self.locationName = placemark.name ?? placemark.locality ?? placemark.subLocality ?? placemark.administrativeArea ?? placemark.country ?? "<unknown>"
self.location.boundLoaction = self.locationName
self.location.boundLatitude = self.latitudeString
self.location.boundLongitude = self.longitudeString
}
try? self.context.save()
})
}
HStack {
Text("Longitude") // Displays the location longitude
.fontWeight(.bold)
.font(Font.system(size: 20))
.multilineTextAlignment(.leading)
TextField("Enter longitude..", text: self.$longitudeString, onEditingChanged: { _ in try? self.context.save() }, onCommit: {
// updates the location name and map when longitude is updated
guard let latitude = CLLocationDegrees(self.latitudeString),
let longitude = CLLocationDegrees(self.longitudeString)
else {
print("Invalid Coordinates")
return
}
self.currentPosition.latitude = latitude
self.currentPosition.longitude = longitude
let geoCoder = CLGeocoder()
let position = CLLocation(latitude: self.currentPosition.latitude, longitude: self.currentPosition.longitude)
geoCoder.reverseGeocodeLocation(position) { (placemarks, error ) in
guard let placemark = placemarks?.first
else {
print("Error locating \(self.currentPosition.latitude) / \(self.currentPosition.longitude) / : \(error.map {"\($0)"} ?? "<unknown error>")")
return
}
self.locationName = placemark.name ?? placemark.locality ?? placemark.subLocality ?? placemark.administrativeArea ?? placemark.country ?? "<unknown>"
self.location.boundLoaction = self.locationName
self.location.boundLatitude = self.latitudeString
self.location.boundLongitude = self.longitudeString
}
try? self.context.save()
})
}
}
}.frame(width: 300)
.offset(x: 0, y: CGFloat(-(keyboard.h + 50)))
}
}
| true
|
33c8dae62a7c311714b6e1bf8043b781ea2158c6
|
Swift
|
donka-s27/GeoConfess
|
/Sources/NotificationCell.swift
|
UTF-8
| 4,578
| 2.796875
| 3
|
[] |
no_license
|
//
// NotificationCell.swift
// GeoConfess
//
// Created by Dan on April 19, 2016.
// Reviewed by Dan Dobrev on June 2, 2016.
// Copyright © 2016 KOT. All rights reserved.
//
import UIKit
/// A row in the notifications table.
/// See `NotificationsViewController` for more information.
final class NotificationCell: UITableViewCell {
@IBOutlet weak private var titleLabel: UILabel!
@IBOutlet weak private var statusLabel: UILabel!
@IBOutlet weak private var iconImage: UIImageView!
@IBOutlet weak private var distanceLabel: UILabel!
@IBOutlet weak private var goToImage: UIImageView!
@IBOutlet weak private var goToLabel: UILabel!
private var notification: Notification!
override func prepareForReuse() {
super.prepareForReuse()
setSelected(false, animated: false)
distanceLabel.hidden = false
goToLabel.hidden = false
goToImage.hidden = false
}
/// Configure the view for the selected state.
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
self.titleLabel.textColor = UIColor.whiteColor()
self.statusLabel.textColor = UIColor.whiteColor()
self.distanceLabel.textColor = UIColor.whiteColor()
self.goToLabel.textColor = UIColor.whiteColor()
self.iconImage.image = UIImage(named: "logo-blanc-liste");
self.backgroundColor = UIColor.redColor()
} else {
setUnread(notification?.unread ?? true)
self.iconImage.image = UIImage(named: "logo-couleur-liste");
}
}
func setNotification(notification: Notification) {
self.notification = notification
let user = User.current!
selectionStyle = .None
setUnread(notification.unread)
setDistanceLabel(notification)
func title(name: String) -> String { return name.uppercaseString }
func status(name: String) -> String { return name.uppercaseString }
switch notification.model {
case .MeetRequestNotification(let meetRequest):
switch user.roleAt(meetRequest) {
case .Penitent, .Admin:
titleLabel.text = title(meetRequest.priest.name)
switch meetRequest.status {
case .Pending:
statusLabel.text = status("Demande envoyée")
goToLabel.text = "Voir la fiche"
case .Accepted:
statusLabel.text = status("Demande acceptée")
goToLabel.text = "Voir conversation"
case .Refused:
statusLabel.text = status("Demande refusée")
goToLabel.text = "Voir la fiche"
}
case .Priest:
titleLabel.text = title(meetRequest.penitent.name)
switch meetRequest.status {
case .Pending:
statusLabel.text = status("Demande reçue")
goToLabel.text = "Répondre"
case .Accepted:
statusLabel.text = status("Demande acceptée")
goToLabel.text = "Voir conversation"
case .Refused:
statusLabel.text = status("Demande refusée")
goToLabel.hidden = true
goToImage.hidden = true
}
}
case .MessageNotification(let message):
titleLabel.text = title(message.sender.name)
switch user.role {
case .Penitent, .Priest, .Admin:
statusLabel.text = status("Message")
goToLabel.text = "Voir conversation"
}
}
}
/// Unread notifications will be shown in black.
private func setUnread(unread: Bool) {
if unread {
titleLabel.textColor = UIColor.blackColor()
statusLabel.textColor = UIColor.blackColor()
distanceLabel.textColor = UIColor.blackColor()
} else {
titleLabel.textColor = UIColor.lightGrayColor()
statusLabel.textColor = UIColor.lightGrayColor()
distanceLabel.textColor = UIColor.lightGrayColor()
}
goToLabel.textColor = App.tintColor
backgroundColor = UIColor.whiteColor()
}
private func setDistanceLabel(notification: Notification) {
let user = User.current!
let otherUserLocationOrNil: CLLocationCoordinate2D?
switch notification.model {
case .MeetRequestNotification(let meetRequest):
switch user.roleAt(meetRequest) {
case .Penitent, .Admin:
otherUserLocationOrNil = meetRequest.priest.location
case .Priest:
otherUserLocationOrNil = meetRequest.penitent.location
}
case .MessageNotification:
otherUserLocationOrNil = nil
}
guard let otherUserLocation = otherUserLocationOrNil,
let userLocation = User.current.location else {
distanceLabel.hidden = true
return
}
let dist = userLocation.distanceFromLocation(CLLocation(at: otherUserLocation))
distanceLabel.text = String(format: "à %.0f mètres", dist)
}
}
| true
|
ea3522660e025d70062cd9bdf794364ec788edb4
|
Swift
|
dequin-cl/SuggestionSearchBar
|
/Example/Example-iOS/SuggestionDemo/SuggestionDemo/ViewController.swift
|
UTF-8
| 4,385
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
//
// ViewController.swift
// SuggestionDemo
//
// Created by Iván on 14-10-20.
//
import UIKit
import SuggestionSearchBar
class ViewController: UIViewController {
@IBOutlet var searchBar: SuggestionSearchBar!
// Keep information about Keyboard height
fileprivate var keyboardHeight: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
searchBar.rootViewController = UIApplication.getWindow().rootViewController
searchBar.delegateSuggestionSearchBar = self
searchBar.barTintColor = UIColor.white
searchBar.backgroundColor = UIColor.clear
searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
configureKeyboard()
// prepareSuggestionWithStrings()
prepareSuggestionWithSuggestionSearchBarModel()
}
func prepareSuggestionWithStrings() {
let list: [String] = ["Chocolate", "Sugar", "Flour", "Butter", "Vanilla", "Eggs", "Salt", "Yeast"]
searchBar.setDatas(datas: list)
}
func prepareSuggestionWithSuggestionSearchBarModel() {
var list: [SuggestionSearchBarModel] = []
list.append(SuggestionSearchBarModel(title: "Alpha", url: "https://github.com/dequin-cl/SuggestionSearchBar/raw/main/Screenshots/Alpha.png"))
list.append(SuggestionSearchBarModel(title: "Bravo",
url: "https://github.com/dequin-cl/SuggestionSearchBar/raw/main/Screenshots/Bravo.png"))
list.append(SuggestionSearchBarModel(title: "Charlie",
url: "https://github.com/dequin-cl/SuggestionSearchBar/raw/main/Screenshots/Charlie.png"))
list.append(SuggestionSearchBarModel(title: "Delta",
url: "https://github.com/dequin-cl/SuggestionSearchBar/raw/main/Screenshots/Delta.png"))
list.append(SuggestionSearchBarModel(title: "Echo",
url: "https://github.com/dequin-cl/SuggestionSearchBar/raw/main/Screenshots/Echo.png"))
list.append(SuggestionSearchBarModel(title: "Foxtrot",
url: "https://github.com/dequin-cl/SuggestionSearchBar/raw/main/Screenshots/Foxtrot.png"))
searchBar.setDatasWithUrl(datas: list)
}
}
extension ViewController: SuggestionSearchBarDelegate {
func getKeyboardHeight() -> CGFloat {
return keyboardHeight
}
func onClickItemSuggestionsView(suggestionSearchBar: SuggestionSearchBar, item: String) {
print("Using suggestionSearchBar: \(suggestionSearchBar)")
print("User touched this item: "+item)
}
func onClickItemWithUrlSuggestionsView(suggestionSearchBar: SuggestionSearchBar, item: SuggestionSearchBarModel) {
print("Using suggestionSearchBar: \(suggestionSearchBar)")
print("User touched this item: " + item.title + " with this url: " + item.url.absoluteString)
}
}
extension ViewController {
fileprivate func configureKeyboard() {
// register for notifications when the keyboard appears:
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow(note:)),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil
)
// register for notifications when the keyboard disappears:
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardHideShow(note:)),
name: UIResponder.keyboardWillHideNotification,
object: nil
)
}
// Handle keyboard frame changes here.
// Use the CGRect stored in the notification to determine what part of the screen the keyboard will cover.
// Adjust our table view's contentInset and scrollIndicatorInsets properties so that the table view content avoids the part of the screen covered by the keyboard
@objc func keyboardWillShow(note: NSNotification) {
// read the CGRect from the notification (if any)
if let newFrame = (note.userInfo?[ UIResponder.keyboardFrameEndUserInfoKey ] as? NSValue)?.cgRectValue {
keyboardHeight = newFrame.height
}
}
@objc func keyboardHideShow(note: NSNotification) {
keyboardHeight = 0
}
}
| true
|
bd1cd2cd14fcdfa5db0382d5b3b36a9be0bf3039
|
Swift
|
alexoverseer/IMDB-Popular
|
/IMDB Popular/Utilities/ConvenienceFunctions.swift
|
UTF-8
| 297
| 2.765625
| 3
|
[] |
no_license
|
import UIKit
let isPad: Bool = {
return UIDevice.current.userInterfaceIdiom == .pad
}()
let isPhone: Bool = {
return UIDevice.current.userInterfaceIdiom == .phone
}()
func interval<T: Comparable>(_ minimum: T, _ num: T, _ maximum: T) -> T {
return min(maximum, max(minimum, num))
}
| true
|
2312fd77746047ec552e7dfe3eded4914d1cec34
|
Swift
|
Kaitachi/HackerRank
|
/HackerRank - Euler.playground/Pages/Project 001.xcplaygroundpage/Contents.swift
|
UTF-8
| 1,524
| 3.421875
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
import XCTest
func addMultiples(below: Int, multiples: [Int]) -> Int {
var result = 0
func find_k(below: Int, d: Int) -> Int {
// a(n) > a(1) + d*(n-1)
// below > 0 + d*(n-1)
// below > d*n - d
// below + d > d*n
// (below + d)/d > n
let adjust = (below % d == 0) ? 1 : 0
return (below + d)/d - adjust
}
func arithmeticSequencePosition(n: Int, d: Int) -> Int {
// a(n) = a(1) + d*(n-1)
// a(n) = 0 + d*(n-1)
return d*(n-1)
}
// Find the arithmetic sum from each multiple...
for m in multiples {
let k = find_k(below: below, d: m)
result += k * (arithmeticSequencePosition(n: k, d: m)) / 2
}
// Then subtract the arithmetic sum from each product that the multiples form.
for x in [multiples.reduce(1, *)] {
let k = find_k(below: below, d: x)
result -= k * (arithmeticSequencePosition(n: k, d: x)) / 2
}
return result
}
class EulerTest: XCTestCase {
func testCase_1() {
// Assemble
let test = 10
// Activate
let result = addMultiples(below: test, multiples: [3, 5])
// Assert
XCTAssertEqual(result, 23)
}
func testCase_2() {
// Assemble
let test = 100
// Activate
let result = addMultiples(below: test, multiples: [3, 5])
// Assert
XCTAssertEqual(result, 2318)
}
}
EulerTest.defaultTestSuite.run()
//let lines = 2
//let test = [1000000000]
//
//for i in test {
// print(addMultiples(below: i, multiples: [3, 5]))
//}
//_ = readLine()
//while let i = readLine() {
// print(addMultiples(below: Int(i)!, multiples: [3, 5]))
//}
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.