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
767ba415c394910ba28fb6256cb09eba671005d9
Swift
erawanmoekti/GroupStar
/5/b.swift
UTF-8
168
3.125
3
[]
no_license
import Foundation let input = [1, 2, 3, 7, 8, 9, 11, 12, 13] var output = 0 for number in input { if number < 11 { output += number } } print(output)
true
4cfe8d3f7dac7c87a10f7be786041b83294d6028
Swift
AmankulYerkebulan/News
/News/Helper/Extension/Extension.swift
UTF-8
2,499
2.78125
3
[]
no_license
import Foundation import UIKit extension UIViewController { func showAlert(title: String, message: String, complition: @escaping () -> Void) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in complition() })) self.present(alert, animated: true, completion: nil) } func setUpBackItem() { self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "Back")?.original, style: UIBarButtonItem.Style.plain, target: self, action: #selector(backPressed)) } @objc func backPressed() { self.navigationController?.popViewController(animated: true) } } extension Int { var width: CGFloat { get { return ScreenSize.SCREEN_WIDTH / (375 / CGFloat(self)) } } var height: CGFloat { get { return ScreenSize.SCREEN_HEIGHT / (812 / CGFloat(self)) } } } extension UIImage { func imageWithColor(color1: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) color1.setFill() let context = UIGraphicsGetCurrentContext() context?.translateBy(x: 0, y: self.size.height) context?.scaleBy(x: 1.0, y: -1.0) context?.setBlendMode(CGBlendMode.normal) let rect = CGRect(origin: .zero, size: CGSize(width: self.size.width, height: self.size.height)) context?.clip(to: rect, mask: self.cgImage!) context?.fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } var original: UIImage { get { return self.withRenderingMode(UIImage.RenderingMode.alwaysOriginal) } } } extension UIView { func addSubviews(_ subviews: [UIView]) { subviews.forEach({ self.addSubview($0) }) } } extension String { func stringToDate() -> String { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" let yourDate = formatter.date(from: self) formatter.dateFormat = "dd.MM.yyyy" if let _yourDate = yourDate { let myStringafd = formatter.string(from: _yourDate) return myStringafd } return "" } }
true
6a2939143575aa248447ea2c5c157a80b35adcc4
Swift
chenyueuk/AWSRekognitionDemo
/AWSRekognitionDemo/UI/PhotoTable/PhotoTableViewModel.swift
UTF-8
2,138
2.65625
3
[ "MIT" ]
permissive
// // PhotoTableViewModel.swift // AWSRekognitionDemo // // Created by YUE CHEN on 24/11/2019. // Copyright © 2019 YUE CHEN. All rights reserved. // import Foundation import RealmSwift import RxRealm import RxSwift import RxCocoa class PhotoTableViewModel { var photoData: Results<RekognitionCellData> var sourcePhoto: BehaviorRelay<SourcePhotoData> = BehaviorRelay(value: Realm.sourcePhotoData()) var awsRekognitionProcessCount = 0 /** * Init view model, set photoData to Realm query collection */ init() { photoData = Realm.defaultRealmInstance() .objects(RekognitionCellData.self) .sorted(byKeyPath: "creationDate", ascending: false) } /** * Compare face using AWS service. Find source face in all target photoes */ func compareFaces() { for data in photoData { awsRekognitionProcessCount += 1 guard let sourceImage = Realm.sourcePhotoData().retrieveImage(), let targetImage = data.baseImage?.retrieveImage() else { return } let awsUtil = AWSRekognitionUtils(sourceImage: sourceImage, targetImage: targetImage) awsUtil.compareFaces(onCompletion: { (matchingRects, unmatchingRects) in self.awsRekognitionProcessCount -= 1 DispatchQueue.main.async { /// For matched faces, draw yellow rect, for unmatched faces, draw red rect var resultImage = targetImage resultImage = resultImage.drawRects(rects: matchingRects, color: .yellow) resultImage = resultImage.drawRects(rects: unmatchingRects, color: .red) /// Update realm object with result image try? Realm.defaultRealmInstance().write { let newImage = RekognitionImage() newImage.setImage(image: resultImage) data.resultImage = newImage } } }) } } }
true
62bf247418c8ef798a53a124a0e5060b95568d08
Swift
Agiaq87/RPM
/RPM/View/Settings/ListElement.swift
UTF-8
1,247
3.21875
3
[]
no_license
// // ListElement.swift // RPM // // Created by Alessandro Giaquinto on 23/02/2020. // Copyright © 2020 Alessandro Giaquinto. All rights reserved. // import SwiftUI struct ListElement: View { let icon: String let title: String let subTitle: String var body: some View { HStack { Image(systemName: icon) .font(.largeTitle) .foregroundColor(Color(#colorLiteral(red: 0.08664352447, green: 0.4768136144, blue: 0.2081719935, alpha: 1))) .padding() .accessibility(hidden: true) VStack(alignment: .leading) { Text(title) .font(.headline) .foregroundColor(Color(#colorLiteral(red: 0.08664352447, green: 0.4768136144, blue: 0.2081719935, alpha: 1))) .accessibility(addTraits: .isHeader) Text(subTitle) .font(.body) .foregroundColor(Color.gray) .fixedSize(horizontal: false, vertical: true) } } } } struct ListElement_Previews: PreviewProvider { static var previews: some View { ListElement(icon: "clockwise", title: "Clock", subTitle: "a clock") } }
true
79d4d2b0b3e8617cee4be453330449e2f8c1de80
Swift
GuiyeC/WWDC-2019
/Neural Networks.playgroundbook/Contents/Chapters/Chapter1.playgroundchapter/Pages/3_Training.playgroundpage/Contents.swift
UTF-8
5,127
4.0625
4
[ "MIT" ]
permissive
//#-hidden-code // // Contents.swift // // Created by Guillermo Cique on 23/03/2019. // //#-end-hidden-code /*: This is all cool but, **how do they learn?** Well, that might be the trickiest part of all. Training a neural network can be more art than science. After getting some results from a neural network we might not be able to measure how wrong they are or even if they are wrong at all. We would need some way of letting it know its doing a good job or if it's not, give it data to improve towards better results. There is a lot of math involved in training a neural network, so taking that into account, let's try to at least understand what's going on without digging too deep into the mathematics of it. A way of updating the weights and biases of a neural network in order to improve it is called **backpropagation**. Basically we will take the actual outputs of a neural network, compare them to a set of goal outputs and calculate how wrong our predictions were. Then we iterate backwards calculating the amount of error each neuron on each layer is responsible for. Finally we calibrate all the weights and biases to end up with an improved neural network. We need to repeat this process calibrating little by little until we have a neural network that is able to output correct values. */ class NeuralNetwork { let layers: [NeuralLayer] /* We can set the rate at which weights and biases are updated This is useful to avoid overcorrecting which could cause the network to forget what it already has learnt */ var learningRate: Double = 0.2 var biasLearningRate: Double = 0.2 // We can save the ouputs to save us computations when backpropagating var lastOutputs: [Double]? //#-hidden-code init(layers: [NeuralLayer]) { self.layers = layers } //#-end-hidden-code func update(goals: [Double]) { var lastOutputs = self.lastOutputs! // First, we calculate how wrong we were var lastDeltas = zip(lastOutputs, goals).map { (derivative(sigmoid: $0) * ($0 - $1)) } var layerDeltas = [lastDeltas] // We iterate the layers backwards calculating the errors of each one of them for layer in layers.reversed() { let inputs = layer.lastInputs! var newDeltas: [Double] = [] for (index, input) in inputs.enumerated() { var weights = [Double]() for neuron in layer.neurons { weights.append(neuron.weights[index]) } let dot = zip(lastDeltas, weights).reduce(0) { $0 + ($1.0*$1.1) } let r = derivative(sigmoid: input) * dot newDeltas.append(r) } layerDeltas.append(newDeltas) lastDeltas = newDeltas } /* Finally we update the weights and biases The more they contribute to the error the more they need to change */ for (deltas, layer) in zip(layerDeltas, layers.reversed()) { var inputs = layer.lastInputs! for (delta, neuron) in zip(deltas, layer.neurons) { /* The bias is also updated when backpropagating it's updated as if it had an input of 1 */ neuron.bias -= delta * biasLearningRate for (index, input) in inputs.enumerated() { let change = delta * input * learningRate neuron.weights[index] -= change } } } } } /* When backpropagating we can take advantage that we already have sigmoid(z) and use that to simplify obtaining its derivative */ func derivative(sigmoid z: Double) -> Double { return z * (1 - z) } //#-hidden-code func sigmoid(_ z: Double) -> Double { return 1.0 / (1.0 + exp(-z)) } class NeuralLayer { let neurons: [Neuron] = [] var lastInputs: [Double]? } class Neuron { var weights: [Double] = [] var bias: Double = 0 } import UIKit //#-end-hidden-code /*: Here you can play with training your own neural network, try entering different colors and changing the amoung of iterations to see how it affects the outputs of the neural network. */ let trainingIterations: UInt = /*#-editable-code*/1000/*#-end-editable-code*/ let input1Color: UIColor = /*#-editable-code*/.cyan/*#-end-editable-code*/ let input2Color: UIColor = /*#-editable-code*/.yellow/*#-end-editable-code*/ let input3Color: UIColor = /*#-editable-code*/UIColor(red: 253/255, green: 26/255, blue: 146/255, alpha: 1)/*#-end-editable-code*/ /*: These colors will be transformed to an array of values (red, green, blue), then you will be able to select the input by pressing a button and the neural network will try to predict what the expected color is. */ //#-hidden-code import PlaygroundSupport let viewController = TrainingViewController(iterations: trainingIterations, goalColors: [input1Color, input2Color, input3Color]) PlaygroundPage.current.liveView = viewController //#-end-hidden-code
true
c7e893e7cad9e305bb3d069cd362dc17ad8b9855
Swift
emckee4/SwiftSparseArray
/SwiftSparseArray/SparseArrayProtocol+Extension.swift
UTF-8
6,129
3.25
3
[ "MIT" ]
permissive
// // SparseArrayProtocol+Extension.swift // SwiftSparseArray // // Created by Evan Mckee on 10/10/15. // Copyright © 2015 McKeeMaKer. All rights reserved. // import Foundation ///The protocol and its extension define and provide default implementation of nearly all the functionality needed for the sparse arrays. Due to some swift issues it's not currently possible to unite the SparseArrayNilDefault with the non optional SparseArray, but this protocol and extension ensure they function quite similarly. public protocol SparseArrayProtocol: CollectionType, MutableCollectionType, CustomStringConvertible, RangeReplaceableCollectionType { typealias Element ///Essentially we want to ensure the Index is an integer with all the power and convenience that comes with that typealias Index:RandomAccessIndexType,Hashable,IntegerLiteralConvertible var data:[Index:Element] {get set} var defaultValue:Element {get} var startIndex:Index {get} var endIndex:Index {set get} var array:[Element] {get} var nonDefaultCount:Int {get} var nonDefaultIndices:[Index] {get} func elementIsdefaultValue(element: Element) -> Bool } public extension SparseArrayProtocol { public var startIndex:Index { return 0 } ///Number of non-nil values represented by the array public var nonDefaultCount:Int { return data.count } public var nonDefaultIndices:[Index]{ return data.keys.sort() } public var array:[Element] { return self.map({$0 as! Self.Element}) } public var description:String { return "\(self.array)" } ///Collection/MutableCollection conformance public subscript(position:Index)->Element{ get{return data[position] ?? defaultValue} set{ if elementIsdefaultValue(newValue) { if let dictIndex = data.indexForKey(position) { data.removeAtIndex(dictIndex) } } else { data[position] = newValue } } } ////////////// RangeReplaceableCollectionType conformance////////////// mutating public func append(newElement: Element){ self[endIndex++] = newElement } mutating public func appendContentsOf<S : SequenceType where S.Generator.Element == Generator.Element>(newElements: S) { for val in newElements { self.append(val as! Element) } } mutating public func insert(newElement: Self.Generator.Element, atIndex i: Self.Index) { //We need to modify the indices of equal or higher index elements from the top down let higherIndices = data.keys.filter({$0 >= i}).sort().reverse() endIndex++ for j in higherIndices { self[j.successor()] = self[j] self[j] = defaultValue } self[i] = newElement } mutating public func insertContentsOf<S : CollectionType where S.Generator.Element == Generator.Element>(newElements: S, at i: Self.Index) { guard i <= endIndex else {fatalError("Array index out of range")} //The below cast should always work since both types are ultimately typedefed as Ints somewhere if let newElementCount = newElements.count as? Self.Index.Distance { guard newElementCount > 0 else {return} endIndex = endIndex.advancedBy(newElementCount) let higherIndices = data.keys.filter({$0 >= i}).sort().reverse() for j in higherIndices { self[j.advancedBy(newElementCount)] = self[j] self[j] = defaultValue } for (k,newItem) in newElements.enumerate() { self[i.advancedBy(k as! Self.Index.Distance)] = newItem } } else { print("failed to cast: newElementCount = newElements.count as? Self.Index.Distance") var insertIndex = i for item in newElements { self.insert(item, atIndex: insertIndex++) } } } mutating public func removeAll(keepCapacity keepCapacity: Bool) { endIndex = 0 data.removeAll(keepCapacity: keepCapacity) } mutating public func removeAtIndex(index: Self.Index) -> Self.Generator.Element{ let higherIndices = data.keys.filter({$0 > index}).sort() print(higherIndices) let returnValue = self[index] self[index] = defaultValue for j in higherIndices { self[j.predecessor()] = self[j] self[j] = defaultValue } endIndex-- return returnValue } mutating public func removeFirst() -> Self.Generator.Element { return removeAtIndex(startIndex) } mutating public func removeFirst(n: Int) { let stopIndex:Self.Index = n as! Self.Index self.removeRange(startIndex..<stopIndex) } mutating public func removeRange(subRange: Range<Self.Index>) { guard subRange.count > 0 else {return} //first remove all elements in the range let inRangeIndices:[Self.Index] = data.keys.filter({($0 >= subRange.startIndex) && ($0 < subRange.endIndex)}).sort() //the higherIndices are all the values above but outside of the range which will need reindexing let higherIndices:[Self.Index] = data.keys.filter({$0 >= subRange.endIndex}).sort() for k in inRangeIndices { self[k] = defaultValue } for j in higherIndices { self[j.advancedBy(-subRange.count)] = self[j] self[j] = defaultValue } endIndex = endIndex.advancedBy(-subRange.count) } mutating public func replaceRange<C : CollectionType where C.Generator.Element == Generator.Element>(subRange: Range<Self.Index>, with newElements: C) { //simple implementation. This could be optimised as some of the other bulk operations have been. removeRange(subRange) insertContentsOf(newElements, at: subRange.startIndex) } }
true
ff5975840ce95b59bf7f10353935aa878ffade29
Swift
LIFX/AudioKit
/AudioKit/Common/Nodes/Effects/Modulation/Chorus/AKChorusAudioUnit.swift
UTF-8
3,093
2.59375
3
[ "MIT" ]
permissive
// // AKChorusAudioUnit.swift // AudioKit // // Created by Shane Dunne, revision history on Github. // Copyright © 2018 AudioKit. All rights reserved. // import AVFoundation public class AKChorusAudioUnit: AKAudioUnitBase { func setParameter(_ address: AKModulatedDelayParameter, value: Double) { setParameterWithAddress(address.rawValue, value: Float(value)) } func setParameterImmediately(_ address: AKModulatedDelayParameter, value: Double) { setParameterImmediatelyWithAddress(address.rawValue, value: Float(value)) } var frequency: Double = AKChorus.defaultFrequency { didSet { setParameter(.frequency, value: frequency) } } var depth: Double = AKChorus.defaultDepth { didSet { setParameter(.depth, value: depth) } } var feedback: Double = AKChorus.defaultFeedback { didSet { setParameter(.feedback, value: feedback) } } var dryWetMix: Double = AKChorus.defaultDryWetMix { didSet { setParameter(.dryWetMix, value: dryWetMix) } } var rampDuration: Double = 0.0 { didSet { setParameter(.rampDuration, value: rampDuration) } } public override func initDSP(withSampleRate sampleRate: Double, channelCount count: AVAudioChannelCount) -> AKDSPRef { return createChorusDSP(Int32(count), sampleRate) } public override init(componentDescription: AudioComponentDescription, options: AudioComponentInstantiationOptions = []) throws { try super.init(componentDescription: componentDescription, options: options) let frequency = AUParameter( identifier: "frequency", name: "Frequency (Hz)", address: AKModulatedDelayParameter.frequency.rawValue, range: AKChorus.frequencyRange, unit: .hertz, flags: .default) let depth = AUParameter( identifier: "depth", name: "Depth 0-1", address: AKModulatedDelayParameter.depth.rawValue, range: AKChorus.depthRange, unit: .generic, flags: .default) let feedback = AUParameter( identifier: "feedback", name: "Feedback 0-1", address: AKModulatedDelayParameter.feedback.rawValue, range: AKChorus.feedbackRange, unit: .generic, flags: .default) let dryWetMix = AUParameter( identifier: "dryWetMix", name: "Dry Wet Mix 0-1", address: AKModulatedDelayParameter.dryWetMix.rawValue, range: AKChorus.dryWetMixRange, unit: .generic, flags: .default) setParameterTree(AUParameterTree(children: [frequency, depth, feedback, dryWetMix])) frequency.value = Float(AKChorus.defaultFrequency) depth.value = Float(AKChorus.defaultDepth) feedback.value = Float(AKChorus.defaultFeedback) dryWetMix.value = Float(AKChorus.defaultDryWetMix) } public override var canProcessInPlace: Bool { return true } }
true
b2e3a22d5ddaf07300afcc82ec8500bf32f63f08
Swift
keshavgn/iOSProject
/iOSProject/Views/UIViews/CustomAlertView.swift
UTF-8
6,768
2.578125
3
[]
no_license
// // CustomAlertView.swift // iOSProject // // Created by Keshav on 21/02/18. // Copyright © 2018 Keshav. All rights reserved. // import UIKit protocol CustomAlertViewDelegate { func didTapDoneButton() func didTapCancelButton() } final class CustomAlertView: UIView { var delegate: CustomAlertViewDelegate? var shouldShowCancel = false private var contentView: AlertView = { let subView = AlertView() return subView }() public override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) isUserInteractionEnabled = false commonInit() } private func commonInit() { backgroundColor = UIColor(white: 0.4, alpha: 0.4) contentView.doneButton.addTarget(self, action: #selector(doneButtonAction), for: UIControl.Event.touchDragInside) contentView.cancelButton.addTarget(self, action: #selector(cancelButtonAction), for: UIControl.Event.touchDragInside) contentView.shouldShowCancel = shouldShowCancel } override func layoutSubviews() { let maxWidth: CGFloat = 300 let width = frame.size.width - 40 let subViewWidth = width > maxWidth ? maxWidth : width let subViewHeight: CGFloat = 180 iOS_centerSubview(contentView, width: subViewWidth, height: subViewHeight) } } extension CustomAlertView { public func udpateTitle(title: String) { contentView.titleLabel.text = title } public func udpateDescription(description: String) { contentView.descriptionLabel.text = description } @objc private func doneButtonAction() { isHidden = true delegate?.didTapDoneButton() } @objc private func cancelButtonAction() { isHidden = true delegate?.didTapCancelButton() } } final class AlertView: UIView, Cardable { var maskedCarner: CACornerMask = [.layerMinXMinYCorner,.layerMaxXMinYCorner, .layerMinXMaxYCorner, .layerMaxXMaxYCorner] var titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textAlignment = .center label.textColor = UIColor.black return label }() var descriptionLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 label.textAlignment = .center label.textColor = UIColor.black label.font = UIFont.systemFont(ofSize: 12) return label }() private var lineView: UIView = { let subView = UIView() subView.backgroundColor = UIColor.gray subView.translatesAutoresizingMaskIntoConstraints = false return subView }() var doneButton: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("OK", for: UIControl.State.normal) button.setTitleColor(UIColor.black, for: UIControl.State.normal) return button }() private var dividerView: UIView = { let subView = UIView() subView.backgroundColor = UIColor.gray subView.translatesAutoresizingMaskIntoConstraints = false return subView }() var cancelButton: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("CANCEL", for: UIControl.State.normal) button.setTitleColor(UIColor.black, for: UIControl.State.normal) return button }() var shouldShowCancel = false public override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { backgroundColor = UIColor.white } override func layoutSubviews() { layoutCard() setupUI() } } extension AlertView { private func setupUI() { addSubview(titleLabel) titleLabel.leftAnchor.constraint(equalTo: leftAnchor).isActive = true titleLabel.topAnchor.constraint(equalTo: topAnchor, constant: 20).isActive = true titleLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true titleLabel.heightAnchor.constraint(equalToConstant: 35).isActive = true addSubview(descriptionLabel) descriptionLabel.leftAnchor.constraint(equalTo: leftAnchor).isActive = true descriptionLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 1).isActive = true descriptionLabel.rightAnchor.constraint(equalTo: rightAnchor).isActive = true descriptionLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true addSubview(lineView) lineView.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true lineView.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor, constant: 10).isActive = true lineView.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true lineView.heightAnchor.constraint(equalToConstant: 1).isActive = true addSubview(doneButton) doneButton.leftAnchor.constraint(equalTo: leftAnchor).isActive = true doneButton.topAnchor.constraint(equalTo: lineView.bottomAnchor, constant: 10).isActive = true doneButton.heightAnchor.constraint(equalToConstant: 35).isActive = true if shouldShowCancel { doneButton.widthAnchor.constraint(equalToConstant: frame.size.width/2).isActive = true addSubview(dividerView) dividerView.leftAnchor.constraint(equalTo: doneButton.rightAnchor, constant: 1).isActive = true dividerView.topAnchor.constraint(equalTo: doneButton.topAnchor).isActive = true dividerView.widthAnchor.constraint(equalToConstant: 1).isActive = true dividerView.bottomAnchor.constraint(equalTo: doneButton.bottomAnchor).isActive = true addSubview(cancelButton) cancelButton.leftAnchor.constraint(equalTo: doneButton.rightAnchor).isActive = true cancelButton.topAnchor.constraint(equalTo: doneButton.topAnchor).isActive = true cancelButton.heightAnchor.constraint(equalToConstant: 35).isActive = true cancelButton.widthAnchor.constraint(equalTo: doneButton.widthAnchor).isActive = true } else { doneButton.rightAnchor.constraint(equalTo: rightAnchor).isActive = true } } }
true
64416dd9de75fd76304d446040826e60e6a85e0f
Swift
gymshark/ios-shark-utils
/Tests/SharkUtilsTests/ObservableTests.swift
UTF-8
11,648
2.8125
3
[]
no_license
import XCTest import SharkUtils private struct Root: Equatable { var valA = 0 var child = Child() } private struct Child: Equatable { var valB = 0 var grandChild = GrandChild() } private struct GrandChild: Equatable { var valC = 0 } public func ignoreNeverUsed(_ x: Any) {} class ObservableTests: XCTestCase { func testOnSet_valueSet_called() { let observable = Observable.onSet(Root()) var valC = observable.value.child.grandChild.valC var calls = 0 let binding = observable.observeFromNextValue { calls.increment() valC = $0.child.grandChild.valC } ignoreNeverUsed(binding) observable.value.valA = 0 XCTAssertEqual(calls, 1) observable.value.child.grandChild.valC = 3 XCTAssertEqual(calls, 2) XCTAssertEqual(valC, 3) observable.value.valA = 4 XCTAssertEqual(calls, 3) XCTAssertEqual(valC, 3) } func testOnChange_valueSetButNotChanged_notCalled() { let observable = Observable.onChange(Root()) var calls = 0 let binding = observable.observeFromNextValue { _ in calls.increment() } ignoreNeverUsed(binding) observable.value.child.grandChild.valC = 0 XCTAssertEqual(calls, 0) observable.value.valA = 0 XCTAssertEqual(calls, 0) } func testOnChange_valueSetChanged_called() { let observable = Observable.onChange(Root()) var calls = 0 let binding = observable.observeFromNextValue { _ in calls.increment() } ignoreNeverUsed(binding) observable.value.child.grandChild.valC = 3 XCTAssertEqual(calls, 1) observable.value.valA = 5 XCTAssertEqual(calls, 2) } func testOnChange_valueSet_noSetChildrenNotCalled() { let rootObservable = Observable.onChange(Root()) let childObservable = rootObservable.synced(\.child) let grandChildObservable = childObservable.synced(\.grandChild) var rootCalls = 0 var childCalls = 0 var grandChildCalls = 0 let bindings = [ rootObservable.observeFromNextValue { _ in rootCalls.increment() }, childObservable.observeFromNextValue { _ in childCalls.increment() }, grandChildObservable.observeFromNextValue { _ in grandChildCalls.increment() } ] ignoreNeverUsed(bindings) func assertNoCalls(line: UInt = #line) { XCTAssertEqual(rootCalls, 0, line: line) XCTAssertEqual(childCalls, 0, line: line) XCTAssertEqual(grandChildCalls, 0, line: line) } rootObservable.value.valA = 0 assertNoCalls() rootObservable.value.child.grandChild.valC = 0 assertNoCalls() grandChildObservable.value.valC = 0 assertNoCalls() rootObservable.value.child.grandChild.valC = 0 assertNoCalls() grandChildObservable.value.valC = 0 assertNoCalls() } func testOnChange_parentRefNotRetained_called() { var rootObservable: Observable? = Observable.onChange(Root()) let childObservable = rootObservable?.synced(\.child) var rootCalls = 0 var childCalls = 0 let bindings = [ rootObservable?.observeFromNextValue { _ in rootCalls.increment() }, childObservable?.observeFromNextValue { _ in childCalls.increment() } ] ignoreNeverUsed(bindings) rootObservable = nil childObservable?.value.valB = 5 XCTAssertEqual(rootCalls, 0) XCTAssertEqual(childCalls, 1) } func testOnChange_setSameValueOnRoot_noCalls() { let rootObservable = Observable.onChange(Root()) let childObservable = rootObservable.synced(\.child) let grandChildObservable = childObservable.synced(\.grandChild) var rootCalls = 0 var childCalls = 0 var grandChildCalls = 0 let bindings = [ rootObservable.observeFromNextValue { _ in rootCalls.increment() }, childObservable.observeFromNextValue { _ in childCalls.increment() }, grandChildObservable.observeFromNextValue { _ in grandChildCalls.increment() } ] ignoreNeverUsed(bindings) func assertNoCalls(line: UInt = #line) { XCTAssertEqual(rootCalls, 0, line: line) XCTAssertEqual(childCalls, 0, line: line) XCTAssertEqual(grandChildCalls, 0, line: line) } rootObservable.value.valA = 0 assertNoCalls() rootObservable.value.child.grandChild.valC = 0 assertNoCalls() } func testOnChang_setSameValueOnGrandChild_noCalls() { let rootObservable = Observable.onChange(Root()) let childObservable = rootObservable.synced(\.child) let grandChildObservable = childObservable.synced(\.grandChild) var rootCalls = 0 var childCalls = 0 var grandChildCalls = 0 let bindings = [ rootObservable.observeFromNextValue { _ in rootCalls.increment() }, childObservable.observeFromNextValue { _ in childCalls.increment() }, grandChildObservable.observeFromNextValue { _ in grandChildCalls.increment() } ] ignoreNeverUsed(bindings) func assertNoCalls(line: UInt = #line) { XCTAssertEqual(rootCalls, 0, line: line) XCTAssertEqual(childCalls, 0, line: line) XCTAssertEqual(grandChildCalls, 0, line: line) } grandChildObservable.value.valC = 0 assertNoCalls() rootObservable.value.child.grandChild.valC = 0 assertNoCalls() } func testOnChangeWritable_changeRootValue_onlyRootCalled() { let rootObservable = Observable.onChange(Root()) let childObservable = rootObservable.synced(\.child) let grandChildObservable = childObservable.synced(\.grandChild) var valA = 0 var valB = 0 var valC = 0 var rootCalls = 0 var childCalls = 0 var grandChildCalls = 0 let bindings = [ rootObservable.observeFromNextValue { valA = $0.valA rootCalls.increment() }, childObservable.observeFromNextValue { valB = $0.valB childCalls.increment() }, grandChildObservable.observeFromNextValue { valC = $0.valC grandChildCalls.increment() } ] ignoreNeverUsed(bindings) func assertCalls(expectedRootCalls: Int, expectedChildCalls: Int, expectedGrandChildCalls: Int, line: UInt = #line) { XCTAssertEqual(rootCalls, expectedRootCalls, line: line) XCTAssertEqual(childCalls, expectedChildCalls, line: line) XCTAssertEqual(grandChildCalls, expectedGrandChildCalls, line: line) } func assertValues(expectedValA: Int, expectedValB: Int, expectedValC: Int, line: UInt = #line) { XCTAssertEqual(valA, expectedValA, line: line) XCTAssertEqual(valB, expectedValB, line: line) XCTAssertEqual(valC, expectedValC, line: line) } rootObservable.value.valA = 10 assertCalls(expectedRootCalls: 1, expectedChildCalls: 0, expectedGrandChildCalls: 0) assertValues(expectedValA: 10, expectedValB: 0, expectedValC: 0) } func testOnChangeWritable_changeGrandChildValue_allCalled() { let rootObservable = Observable.onChange(Root()) let childObservable = rootObservable.synced(\.child) let grandChildObservable = childObservable.synced(\.grandChild) var valA = 0 var valB = 0 var valC = 0 var rootCalls = 0 var childCalls = 0 var grandChildCalls = 0 let bindings = [ rootObservable.observeFromNextValue { valA = $0.valA rootCalls.increment() }, childObservable.observeFromNextValue { valB = $0.valB childCalls.increment() }, grandChildObservable.observeFromNextValue { valC = $0.valC grandChildCalls.increment() } ] ignoreNeverUsed(bindings) func assertCalls(expectedRootCalls: Int, expectedChildCalls: Int, expectedGrandChildCalls: Int, line: UInt = #line) { XCTAssertEqual(rootCalls, expectedRootCalls, line: line) XCTAssertEqual(childCalls, expectedChildCalls, line: line) XCTAssertEqual(grandChildCalls, expectedGrandChildCalls, line: line) } func assertValues(expectedValA: Int, expectedValB: Int, expectedValC: Int, line: UInt = #line) { XCTAssertEqual(valA, expectedValA, line: line) XCTAssertEqual(valB, expectedValB, line: line) XCTAssertEqual(valC, expectedValC, line: line) } rootObservable.value.child.grandChild.valC = 10 assertCalls(expectedRootCalls: 1, expectedChildCalls: 1, expectedGrandChildCalls: 1) assertValues(expectedValA: 0, expectedValB: 0, expectedValC: 10) rootObservable.value.child.grandChild.valC = 20 assertCalls(expectedRootCalls: 2, expectedChildCalls: 2, expectedGrandChildCalls: 2) assertValues(expectedValA: 0, expectedValB: 0, expectedValC: 20) } func testObserveFromNextValue_bindTokenNotRetained_notCalled() { let observable = Observable.onSet(Root()) var calls = 0 _ = observable.observeFromNextValue { _ in calls.increment() } observable.value.child.grandChild.valC = 3 XCTAssertEqual(calls, 0) } func testObserve_all_called() { let observable = Observable.onSet(Root()) var calls = 0 let binding = observable.observe { _ in calls.increment() } ignoreNeverUsed(binding) XCTAssertEqual(calls, 1) observable.value.child.grandChild.valC = 3 XCTAssertEqual(calls, 2) } static var allTests = [ ("testObserve_all_called", testObserve_all_called), ("testObserveFromNextValue_bindTokenNotRetained_notCalled", testObserveFromNextValue_bindTokenNotRetained_notCalled), ("testOnChangeWritable_changeGrandChildValue_allCalled", testOnChangeWritable_changeGrandChildValue_allCalled), ("testOnChangeWritable_changeRootValue_onlyRootCalled", testOnChangeWritable_changeRootValue_onlyRootCalled), ("testOnChange_setSameValueOnRoot_noCalls", testOnChange_setSameValueOnRoot_noCalls), ("testOnChang_setSameValueOnGrandChild_noCalls", testOnChang_setSameValueOnGrandChild_noCalls), ("testOnChange_parentRefNotRetained_called", testOnChange_parentRefNotRetained_called), ("testOnChange_valueSet_noSetChildrenNotCalled", testOnChange_valueSet_noSetChildrenNotCalled), ("testOnChange_valueSetChanged_called", testOnChange_valueSetChanged_called), ("testOnChange_valueSetButNotChanged_notCalled", testOnChange_valueSetButNotChanged_notCalled), ("testOnSet_valueSet_called", testOnSet_valueSet_called), ] }
true
5f105c5da5bd0fd65866d662d7e854393b0fe65f
Swift
otv-app/frontend
/OTVDraft/View/Youtube/YoutubeTabBar.swift
UTF-8
4,880
3.015625
3
[]
no_license
// // YoutubeTabBar.swift // OTVDraft // // Created by Cheng Xi Tsou on 4/7/2020. // Copyright © 2020 Cheng Xi Tsou. All rights reserved. // import SwiftUI /// This struct implements a `View` protocol and is the youtube tab bar on the youtube view page. struct YoutubeTabBar: View { /// This `Binding<YoutubeTab>` keeps track of the current tab that the tab bar is on using the `YoutubeTab` enum. @Binding var tab: YoutubeTab @Binding var showFullTab: Bool /// This variable is passed in from the parent youtube view as a reference to the parent container size. var geometry: GeometryProxy /** Creates the body for this `View`. Contains a title and the tab bar with a red background. */ var body: some View { ZStack { Color.red // .frame(width: geometry.size.width, height: geometry.size.height/4) VStack (spacing: 0) { //the size used for scaling is the view's height since we aren't supporting landscape view so it makes more sense to //scale according to the portrait dimension //the padding and frame are called outside the dimension as those are not really part of the text, but the frame Spacer() Spacer() Spacer() Text("Youtube").toYoutubeLogo(fontScaleFactor: youtubeTitleScaleFactor, size: geometry.size.height, color: .white) .padding() .frame(width: geometry.size.width, height: geometry.size.height/10, alignment: .leading) Spacer() HStack (spacing: 0) { YoutubeIcon(iconImageString: "home", tab: YoutubeTab.home) YoutubeIcon(iconImageString: "twitter", tab: YoutubeTab.byStreamer) // YoutubeIcon(iconImageString: "youtube", tab: YoutubeTab.showAll) } } } .frame(width: geometry.size.width, height: geometry.size.height/4) .shadow(radius: shadowRadius) // .background(Color.red) // VStack (spacing: 0) { // //the size used for scaling is the view's height since we aren't supporting landscape view so it makes more sense to // //scale according to the portrait dimension // //the padding and frame are called outside the dimension as those are not really part of the text, but the frame // ZStack { // Color.red // .frame(width: geometry.size.width, height: geometry.size.height/10) // Text("Youtube").toYoutubeLogo(fontScaleFactor: youtubeTitleScaleFactor, size: geometry.size.height, color: .white) // .padding() // .frame(width: geometry.size.width, height: geometry.size.height/10, alignment: .leading) // } // ZStack { // Color.red // .frame(width: geometry.size.width, height: geometry.size.height/10) // HStack (spacing: 0) { // YoutubeIcon(iconImageString: "home", tab: YoutubeTab.home) // YoutubeIcon(iconImageString: "twitter", tab: YoutubeTab.byStreamer) // YoutubeIcon(iconImageString: "youtube", tab: YoutubeTab.showAll) // } // } // } } /** A helper function to help create a youtube icon on the youtube tab bar. Creates a button, adds an action, and an image. - Parameters: - iconImageString: the string reference to the icon image - tab: the `YoutubeTab` that this icon is associated wtih - Returns: some `View` that represents an icon on the youtube tab bar */ private func YoutubeIcon(iconImageString: String, tab: YoutubeTab) -> some View { VStack (spacing: 0) { Button(action: { self.tab = tab }) { Image(iconImageString) .renderingMode(.template) .resizable().toIcon(width: geometry.size.width/numberOfIcons, height: geometry.size.height/10) .foregroundColor(self.tab == tab ? .white : .black) } Rectangle().size(width: geometry.size.width/numberOfIcons, height: youtubeIconBarHeight) .foregroundColor(self.tab == tab ? .white : .red) } .frame(width: geometry.size.width/numberOfIcons, height: geometry.size.height/10 + youtubeIconBarHeight) } // MARK: - Drawing Constants let numberOfIcons: CGFloat = 2 let youtubeIconBarHeight: CGFloat = 3 let youtubeTitleScaleFactor: CGFloat = 0.08 let shadowRadius: CGFloat = 2 } /// this is an enum for a tab on the youtube tab bar public enum YoutubeTab { case home case byStreamer case showAll }
true
0c93f037237e69356554e14b30768c09a98df1f3
Swift
zhulihong89/Extension
/Extension/Kit/CGPoint+Extension.swift
UTF-8
2,349
3.359375
3
[ "MIT" ]
permissive
// // CGPoint+Extension.swift // Extension // // Created by lihong on 2020/12/19. // Copyright © 2020 lihong. All rights reserved. // import UIKit public func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } public func += (left:inout CGPoint, right: CGPoint) { left.x = left.x + right.x left.y = left.y + right.y } public func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } public func -= (left:inout CGPoint, right: CGPoint) { left.x = left.x - right.x left.y = left.y - right.y } public func * (left: CGPoint, right: CGFloat) -> CGPoint { return CGPoint(x: left.x * right, y: left.y * right) } public func *= (left:inout CGPoint, right: CGFloat) { left.x = left.x * right left.y = left.y * right } public func * (left: CGFloat, right: CGPoint) -> CGPoint { return CGPoint(x: left * right.x, y: left * right.y) } public func / (left: CGPoint, right: CGFloat) -> CGPoint { return CGPoint(x: left.x / right, y: left.y / right) } extension CGPoint { public func getVector(cross line: CGPoint) -> CGPoint { let x1 = line.x let y1 = line.y let x2 = x let y2 = y return CGPoint(x: y1*(y1*x2 - y2*x1) / (y1*y1 + x1*x1), y: -x1*(y1*x2 - y2*x1) / (y1*y1 + x1*x1)) } public func getVector(at direction: CGPoint) -> CGPoint { let x1 = x let y1 = y let x2 = direction.x let y2 = direction.y return CGPoint(x: x2*(x1*x2+y1*y2)/(y2*y2+x2*x2), y: y2*(x1*x2+y1*y2)/(y2*y2+x2*x2)) } public func oneVector() -> CGPoint { let vectorLen = sqrt(x * x + y * y) return CGPoint(x: x / vectorLen, y: y / vectorLen) } public func distance(to point: CGPoint) -> CGFloat { return hypot((self.x - point.x), (self.y - point.y)) } } public extension CGRect { var center: CGPoint { CGPoint(x: midX, y: midY) } } public func + (left: UIEdgeInsets, right: UIEdgeInsets) -> UIEdgeInsets { return UIEdgeInsets(top: left.top + right.top, left: left.left + right.left, bottom: left.bottom + right.bottom, right: left.right + right.right) }
true
5664e32f0512933768eed2f8046fabf029e62806
Swift
crowdpro3/UMEFanApp
/UMEFanAppiOS/Screens/SignUp/SignInViewController.swift
UTF-8
2,070
2.59375
3
[]
no_license
// // File.swift // UMEFanAppiOS // // Created by Jaroslav Veselovsky on 14/06/2016. // Copyright © 2016 Connect on UME (Australia) Pty Ltd. All rights reserved. // import UIKit class SignInViewController: UIViewController { @IBOutlet weak var passwordTF: TextField! @IBOutlet weak var emailTF: TextField! @IBOutlet weak var scrollView : UIScrollView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) scrollView.delegate = self emailTF.text = "[email protected]" passwordTF.text = "password" } @IBAction func signInButtonPressed(_ sender: AnyObject) { if emailTF.text?.characters.count == 0 && passwordTF.text?.characters.count == 0 { self.presentAlert("Enter the missing details") } else if let email = emailTF.text , Validator.isValidEmail(email), let password = passwordTF.text , (password.characters.count > 5) { Server.loginUME(email, password: password, success: { (dictionary) in let account = UserAccount.init(dictionary: dictionary as! [String : String]) AccountManager.accountManager.register(account) self.dismiss(animated: true, completion: nil) }, failure: { (error) in if let message = error?.localizedDescription { self.presentAlert(message) } }) } else { self.presentAlert("Email is Invalid") } } @IBAction func signUpButtonPressed(_ sender: AnyObject) { let createAccountViewController = CreateAccountViewController() navigationController?.pushViewController(createAccountViewController, animated: true) } } extension SignInViewController : UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollView.contentOffset.x > 0 { scrollView.contentOffset.x = 0 } } }
true
45d248fa5da5dbc7bbd2aaeca8db68c20b18d20b
Swift
mohmmadAK/MyCityWeather
/MyCityWeather/LocationDetail.swift
UTF-8
1,751
3.015625
3
[]
no_license
// // LocationDetail.swift // MyCityWeather // import CoreLocation class LocationDetail: CLLocationManager, CLLocationManagerDelegate { // Store current latitude and longitude values public static var current: LocationDetail! public var currentLatitude: Double public var currentLongitude: Double public var authorizationStatus: CLAuthorizationStatus // Initializers private init(withLocation latitude: Double, longitude: Double) { currentLatitude = latitude currentLongitude = longitude authorizationStatus = CLLocationManager.authorizationStatus() super.init() } // Public methods to initialize the service public static func initializeService() { // initialize with example data current = LocationDetail(withLocation: 37.3318598, longitude: -122.0302485) LocationDetail.current.delegate = LocationDetail.current LocationDetail.current.desiredAccuracy = kCLLocationAccuracyNearestTenMeters LocationDetail.current.startUpdatingLocation() } // MARK: - Delegate Methods func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { authorizationStatus = status NotificationCenter.default.post(name: Notification.Name(rawValue: KeyValues.locationAuthorizationUpdated.rawValue), object: self) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let currentLocation: CLLocationCoordinate2D = manager.location!.coordinate currentLatitude = currentLocation.latitude currentLongitude = currentLocation.longitude } }
true
7ac34a3f2c7c511e8591225484abcb236bdd6827
Swift
gbuela/kanjiryokucha
/KanjiRyokucha/UIViewControllerContainment.swift
UTF-8
771
2.53125
3
[ "MIT" ]
permissive
// // UIViewControllerContainment.swift // KanjiRyokucha // // Created by German Buela on 5/7/17. // Copyright © 2017 German Buela. All rights reserved. // import UIKit extension UIViewController { func add(childViewController viewController: UIViewController, insideView view: UIView) { addChild(viewController) view.addSubview(viewController.view) viewController.view.frame = view.bounds viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] viewController.didMove(toParent: self) } func remove(childViewController viewController: UIViewController) { viewController.willMove(toParent: nil) viewController.view.removeFromSuperview() viewController.removeFromParent() } }
true
3492a3acd64b05171bc03b9b00f0e266d60d5b81
Swift
demonukg/RxMVVM-C
/RxMVVM-C/Model/Services/Network/Api/ApiService.swift
UTF-8
435
3.078125
3
[]
no_license
typealias ApiRequestFactory = (ApiTarget) -> ApiRequestable protocol ApiService { func makeRequest(to target: ApiTarget) -> ApiRequestable } struct ApiServiceImpl: ApiService { private let requestFactory: ApiRequestFactory init(requestFactory: @escaping ApiRequestFactory) { self.requestFactory = requestFactory } func makeRequest(to target: ApiTarget) -> ApiRequestable { return requestFactory(target) } }
true
2a4944f901d56a8f3efd2d36771f017bcdd99d7b
Swift
Hackthings/govhack2015
/client/QuestionTime/Network.swift
UTF-8
6,648
2.6875
3
[ "BSD-2-Clause" ]
permissive
// // Network.swift // QuestionTime // // Created by Jon Manning on 3/07/2015. // Copyright (c) 2015 Secret Lab. All rights reserved. // import Foundation import UIKit enum Answer : Int { case DisagreeStrong = 1 // 0 - 20 case Disagree = 2 // 20 - 40 case Neutral = 3 // 40 - 60 case Agree = 4 // 60 - 80 case AgreeStrong = 5 // 80 - 100 case Abstain = -1 static func fromFloat(float:Float) -> Answer { switch float { case 0.0...0.2: return Answer.DisagreeStrong case 0.2...0.4: return Answer.Disagree case 0.4...0.6: return Answer.Neutral case 0.6...0.8: return Answer.Agree case 0.8...1.0: return Answer.AgreeStrong default: return Answer.Abstain } } } // Messages from server struct HelloMessage { // contains nothing } struct GameStartMessage { var opponentHero : Int var portfolioName : String var questions : [Int] } struct ProgressMessage { var yourScore : Int var opponentScore : Int } struct KeepAliveMessage { // contains nothing } struct GameOverMessage { var youWon : Bool var portfolios : [Int] } protocol NetworkDelegate { func networkConnected() func networkDisconnected(error: NSError?) func networkDidStartGame(message: GameStartMessage) func networkDidEndGame(message: GameOverMessage) func networkDidUpdateGameProgress(message: ProgressMessage) } class Network: NSObject, GCDAsyncSocketDelegate { static var sharedNetwork = { return Network() }() let port : UInt16 = 8888 var socket = GCDAsyncSocket() var delegate : NetworkDelegate? var timer : NSTimer? override init() { super.init() timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "sendKeepalive:", userInfo: nil, repeats: true) } deinit { timer?.invalidate() } func sendKeepalive(timer: NSTimer) { if socket.isConnected { let data = [ "Type":"Keepalive", "Data":["foo":"bar"] ] sendMessage(JSON(data).rawString(encoding: NSUTF8StringEncoding, options: NSJSONWritingOptions.allZeros)!) } } func connect() { let host = NSUserDefaults.standardUserDefaults().stringForKey("server") ?? "localhost" connect(host) } func connect(host:String) { socket = GCDAsyncSocket() socket.delegate = self socket.delegateQueue = dispatch_get_main_queue() var error : NSError? socket.connectToHost(host, onPort: self.port, error: &error) } func sendMessage(message:String) { assert(socket.isConnected) println("Sending: \(message)") let data = (message+"\n").dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) socket.writeData(data, withTimeout: 2.0, tag: 0) } func listenForNewData() { socket.readDataToData(GCDAsyncSocket.LFData(), withTimeout: -1, tag:0) } func socket(sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16) { println("Connected!") updateName() delegate?.networkConnected() listenForNewData() } func socket(sock: GCDAsyncSocket!, didReadData data: NSData!, withTag tag: Int) { if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { println("Read: \(string)") // Parse the response into json let loadedData = JSON(data: data) switch loadedData["Type"].stringValue { case "GameStart": receivedGameStart(loadedData["Data"]) case "Progress": receivedProgress(loadedData["Data"]) case "GameOver": receivedGameOver(loadedData["Data"]) default: () } } listenForNewData() } func socketDidDisconnect(sock: GCDAsyncSocket!, withError err: NSError!) { delegate?.networkDisconnected(err) } func selectPlayerData(politician: Int, questionCategory: Int) { // Send 'here's my MP and category' var data = [ "Type":"Player", "Data":[ "HeroPick":politician, "PortfolioPick":questionCategory ] ] var json = JSON(data) sendMessage(json.rawString(encoding: NSUTF8StringEncoding, options: NSJSONWritingOptions.allZeros)!) } func submitAnswer(questionID: Int, answer: Answer) { // Send "I answered a question correctly/incorrectly" var data = [ "Type":"Answer", "Data":[ "Question":questionID, "Answer": answer.rawValue ] ] var json = JSON(data) sendMessage(json.rawString(encoding: NSUTF8StringEncoding, options: NSJSONWritingOptions.allZeros)!) } private func updateName() { var data = [ "Type":"Nickname", "Data":[ "Name":UIDevice.currentDevice().name ] ] var json = JSON(data) sendMessage(json.rawString(encoding: NSUTF8StringEncoding, options: NSJSONWritingOptions.allZeros)!) } private func receivedGameStart(data:JSON) { let message = GameStartMessage(opponentHero: data["OpponentHero"].intValue, portfolioName: data["PortfolioName"].stringValue, questions: (data["Questions"].arrayObject as! [Int])) delegate?.networkDidStartGame(message) } private func receivedGameOver(data:JSON) { let message = GameOverMessage(youWon: data["YouWon"].boolValue, portfolios: (data["Portfolios"].arrayObject as! [Int]) ) delegate?.networkDidEndGame(message) } private func receivedProgress(data:JSON) { let message = ProgressMessage(yourScore: data["YourScore"].intValue, opponentScore: data["OpponentScore"].intValue) delegate?.networkDidUpdateGameProgress(message) } }
true
76ed402adf8d1756826886117a7de33c92b5c3bf
Swift
valic/OpenWeather
/Yalantis/Services/OpenWeatherMap.swift
UTF-8
1,928
3.046875
3
[]
no_license
// // OpenWeatherMap.swift // Yalantis // // Created by Valentyn Mialin on 10/12/18. // Copyright © 2018 Valentyn Mialin. All rights reserved. // import Foundation import Alamofire struct OpenWeatherMap { enum Response<T: Codable> { case failure(error: Error) case success(T) } static private let scheme = "https" static private let host = "api.openweathermap.org" static private let apiVersion = "2.5" static private let apiID = "5dc62ac0baf9fbd81c64676523e5b679" /** - parameter cityID: city ID - parameter cnt: number of days returned (from 1 to 16) - parameter response: Forecast */ public static func getDailyForecast(cityID id: String, cnt: Int, response: ((_ r: Response<Forecast>) -> Void)?) { var urlComponents = URLComponents() urlComponents.scheme = scheme urlComponents.host = host urlComponents.path = "/data/\(apiVersion)/forecast/daily" let queryApiID = URLQueryItem(name: "APPID", value: apiID) let queryCityID = URLQueryItem(name: "id", value: id) let queryLanguageCode = URLQueryItem(name: "lang", value: Locale.current.languageCode ?? "en") let units = Locale.current.usesMetricSystem ? "metric" : "imperial" let queryUnitsFormat = URLQueryItem(name: "units", value: units) let queryNumberOfDay = URLQueryItem(name: "cnt", value: String(cnt)) urlComponents.queryItems = [queryApiID, queryCityID, queryLanguageCode, queryUnitsFormat, queryNumberOfDay] guard let url = urlComponents.url else { return } Alamofire.request(url).responseForecast { r in switch r.result { case .success(let forecast): response?(Response.success(forecast)) case .failure(let error): response?(Response.failure(error: error)) } } } }
true
7c92ac1828f308ceb9ceb6eab88dba53f808fab6
Swift
grisme/skyeng-words
/SkyengWords/Modules/Search/View/SearchViewProtocols.swift
UTF-8
842
2.75
3
[]
no_license
// // SearchViewProtocols.swift // SkyengWords // // Created by Eugene Garifullin on 11.07.2020. // Copyright © 2020 Grisme Team. All rights reserved. // import Foundation protocol SearchViewInput: class { func setSearchBarEnabled(enabled: Bool) func completeEditing(clearSearchBar: Bool) func setLoadingEnabled(enabled: Bool) func setFetchingLoader(enabled: Bool) func setNoResultsState() func setInitialState() func setErrorState(text: String) func reloadResults(models: [WordViewModel]) func insertResults(models: [WordViewModel]) } protocol SearchViewOutput: class { func viewDidLoad() func searchBarShouldChange(text: String) -> Bool func searchBarSearch(text: String) func searchBarCancel() func shouldFetchMore() func didSelectMeaning(meaningViewModel: MeaningViewModel) }
true
71c71d2c692403f7c8dcec0a3ea7c95450a4eba5
Swift
FrancisLF/swiftExtern
/swiftExtern/UIFontExtensions_lf.swift
UTF-8
3,163
2.90625
3
[ "MIT" ]
permissive
// // UIFontExtensions_lf.swift // MarketSmithCH // // Created by 刘方 on 2018/7/17. // Copyright © 2018年 刘方. All rights reserved. // import UIKit class UIFontExtensions_lf: NSObject { } //加粗程度:浅 正常 中等 黑体 public enum LFBoldFontType{ case light case regular case medium case bold } //字体类型:中文、字母、数字 public enum LFFontType{ case number case chinese case english } extension UIFont{ //分配不同字体类型的正常字体 func regularFont(type:LFFontType,size:CGFloat) -> UIFont{ switch type { case .number: return UIFont(name: "HelveticaNeue", size: size)! case .chinese: if #available(iOS 9.0, *){ return UIFont(name: "PingFangSC-Regular", size: size)! }else{ return UIFont(name: "STHeiti", size: size)! } case .english: return UIFont(name: "Helvetica", size: size)! } } //分配不同字体类型、不同加粗程度的字体 func font(boldType:LFBoldFontType,fontType:LFFontType,size:CGFloat) -> UIFont { switch fontType { case .number: switch boldType{ case .light: return UIFont(name: "HelveticaNeue-Light", size: size)! case .regular: return UIFont(name: "HelveticaNeue", size: size)! case .medium: return UIFont(name: "HelveticaNeue-Medium", size: size)! case .bold: return UIFont(name: "HelveticaNeue-Bold", size: size)! } case .english: switch boldType{ case .light: return UIFont(name: "Helvetica-Light", size: size)! case .regular: return UIFont(name: "Helvetica", size: size)! case .medium: return UIFont(name: "Helvetica-Medium", size: size)! case .bold: return UIFont(name: "Helvetica-Bold", size: size)! } case .chinese: switch boldType{ case .light: if #available(iOS 9.0, *){ return UIFont(name: "PingFangSC-Light", size: size)! }else{ return UIFont(name: "STHeiti-Light", size: size)! } case .regular: if #available(iOS 9.0, *){ return UIFont(name: "PingFangSC-Regular", size: size)! }else{ return UIFont(name: "STHeiti", size: size)! } case .medium: if #available(iOS 9.0, *){ return UIFont(name: "PingFangSC-Medium", size: size)! }else{ return UIFont(name: "STHeiti-Medium", size: size)! } case .bold: if #available(iOS 9.0, *){ return UIFont(name: "PingFangSC-Semibold", size: size)! }else{ return UIFont(name: "STHeiti-Bold", size: size)! } } } } }
true
8d2438067a11a39db82a58f99d46fcbfe3fcd345
Swift
sebastianwr/VIPER-Persons
/Persons/PersonListViewController.swift
UTF-8
2,197
2.65625
3
[]
no_license
// // PersonListViewController.swift // MdB // // Created by Sebastian Wramba on 01.10.14. // Copyright (c) 2014 Sebastian Wramba. All rights reserved. // import Foundation import UIKit let CellIdentifier = "PersonListCellIdentifier" class PersonListViewController : UITableViewController { var displayData : PersonListDisplayData? var presenter : PersonListPresenter? override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) presenter?.updateView() } func reloadEntries() { self.tableView.reloadData() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { var numberOfSections = displayData?.sections.count if displayData?.sections.count == nil { numberOfSections = 0 } return numberOfSections! } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let upcomingSection = displayData?.sections[section] return upcomingSection!.items.count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String { let upcomingSection = displayData?.sections[section] return upcomingSection!.name } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let upcomingSection = displayData?.sections[indexPath.section] let personItem : PersonListViewModel = upcomingSection!.items[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as UITableViewCell cell.imageView!.image = personItem.image cell.textLabel!.text = personItem.name cell.detailTextLabel!.text = personItem.detailInformation return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) -> Void { let section = displayData?.sections[indexPath.section] let person = section!.items[indexPath.row] self.presenter?.handleCellSelection(person) } }
true
eb1a245f813bcedcc766adf13e51cb18ef6aad56
Swift
Kharchevskyi/photo-albums
/MediaMonks Photos/Scenes/Photos Scene/PhotosPresenter.swift
UTF-8
1,644
2.765625
3
[]
no_license
// // PhotosPresenter.swift // MediaMonks Photos // // Created by Anton Kharchevskyi on 4/24/19. // Copyright © 2019 Anton Kharchevskyi. All rights reserved. // import Foundation // MARK: - Protocols protocol PhotosPresenterInput: class { func update(with state: State<MediaMonksPhoto>) } protocol PhotosPresenterOutput: class { func handle(state: ViewState<MediaMonksPhotoViewModel>) } // MARK: - Implementation final class PhotosPresenter { private weak var output: PhotosPresenterOutput? private let router: PhotosRouting init(output: PhotosPresenterOutput, router: PhotosRouting) { self.output = output self.router = router } } extension PhotosPresenter: PhotosPresenterInput { func update(with state: State<MediaMonksPhoto>) { ViewState(state).map { output?.handle(state: $0) } } } fileprivate extension ViewState where T == MediaMonksPhotoViewModel { init?(_ state: State<MediaMonksPhoto>) { switch state { case .idle: self = .idle case .failed(let error): switch error { case .dataMapping: self = .failed(.message(error.userDescription)) case .malformedBaseURL: self = .failed(.message(error.userDescription)) case .request: self = .failed(.retryable(error.userDescription)) } case .loading(.initial): self = .loading(.initial) case .loading(.new): self = .loading(.new) case .loaded(let model): let viewModels = model.items.map(MediaMonksPhotoViewModel.init) self = .loaded(viewModels) } } }
true
0f88573377c34d27166374a4f04b1ed9c24127fb
Swift
luyendao29/MVCStructPerson
/MVCStructPerson/controller/TableViewController.swift
UTF-8
3,531
2.625
3
[]
no_license
// // TableViewController.swift // MVCStructPerson // // Created by Boss on 4/24/19. // Copyright © 2019 Boss. All rights reserved. // import UIKit class TableViewController: UITableViewController { var person: [Person] = [] 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 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) person = DataService.conpho.person tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return person.count } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let vc = segue.destination as? ViewController if let index = tableView.indexPathForSelectedRow{ vc?.perSon = person[index.row] vc?.indexPath = index } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? TableViewCell let student = person[indexPath.row] cell?.photo.image = student.image cell?.nameLabel.text = student.name cell?.phoneLabel.text = student.phone cell?.sexLabel.text = student.sex // Configure the cell... 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 { DataService.conpho.remove(indexPath: indexPath) } person = DataService.conpho.person tableView.reloadData() } /* // 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
65fa8c07d02c34efb83410559d9db605d45b42e8
Swift
CooperCodeComposer/GPS-MapKit-Swift-IB
/GPS-MapKit-Swift-IB/JsonBuilder.swift
UTF-8
2,658
2.84375
3
[]
no_license
// // JsonBuilder.swift // GPS-MapKit-Swift-IB // // Created by Alistair Cooper on 6/1/16. // Copyright © 2016 Alistair Cooper. All rights reserved. // import Foundation struct JsonBuilder { static func makeRestaurantArray() -> [[String : String]] { var restaurantArray: [[String : String]] = [] let restaurant1: [String: String] = ["name": "Lidos", "category": "Pizza", "yLoc": "34.186438", "xLoc": "-118.465329", "price": "$"] restaurantArray.append(restaurant1) let restaurant2: [String: String] = ["name": "Kinnara", "category": "Thai", "yLoc": "34.201536", "xLoc": "-118.468155", "price": "$$"] restaurantArray.append(restaurant2) let restaurant3: [String: String] = ["name": "Humble Bee Bakery", "category": "Cafe", "yLoc": "34.208744", "xLoc": "-118.510641", "price": "$$"] restaurantArray.append(restaurant3) let restaurant4: [String: String] = ["name": "Pizza Rev", "category": "Pizza", "yLoc": "34.1752513", "xLoc": "-118.448375", "price": "$"] restaurantArray.append(restaurant4) let restaurant5: [String: String] = ["name": "Napoli's Pizza Kitchen", "category": "Pizza", "yLoc": "34.172339", "xLoc": "-118.456431", "price": "$"] restaurantArray.append(restaurant5) let restaurant6: [String: String] = ["name": "Creme Caramel", "category": "Cafe", "yLoc": "34.172316", "xLoc": "-118.456960", "price": "$$$"] restaurantArray.append(restaurant6) let restaurant7: [String: String] = ["name": "Midici Neapolitan Pizza", "category": "Pizza", "yLoc": "34.151150", "xLoc": "-118.451412", "price": "$$$"] restaurantArray.append(restaurant7) return restaurantArray } static func JSONStringify(jsonObject: AnyObject, prettyPrinted:Bool = false) -> String? { let options = prettyPrinted ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions(rawValue: 0) if JSONSerialization.isValidJSONObject(jsonObject) { do{ let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) { return string as String } } catch { print("error") //Access error here } } return nil } }
true
0318659cdade5b3026e9400fe941ec3f2f82ae81
Swift
prashanthspatil/SwiftPlayground
/SwiftAbstractClass.playground/Contents.swift
UTF-8
6,374
4.09375
4
[]
no_license
//: Playground - noun: a place where people can play import UIKit // A simple protocol, actually a delegate protocol FoodPriceProtocol{ func price(pricePerUnit:Double) -> Double } //The abstract pizza base class class AbstractPizza { //our Abstract pizza Class let pizzaPi = 3.14 var size:Double! = nil // Nil helps indicate empty var crust:AnyObject! = nil var topping:[String]! = nil init(){ //use an empty method to initialize values pizzaDidLoad() } class func personalPizza() -> AnyObject!{ //AnyObject helps subclass let pizza = AbstractPizza() pizza.size = 10.0 pizza.topping = ["Pizza Sauce","Cheese"] pizza.crust = "White" as AnyObject! return pizza } func area() -> Double! { //Abstract functions often return nil return nil // to indicate empty } func pizzaDidLoad(){ //empty method for initialization } } // FlatPizza -- demonstrating the basic subclassing of a abstract class //Also demonstrates protocol adoption class FlatPizza:AbstractPizza,FoodPriceProtocol{ //flat round pizza //define area override func area() -> Double! { let radius = size / 2.0 return radius * radius * pizzaPi } //set default values for properties override func pizzaDidLoad() { size = 10.0 crust = "White" as AnyObject! topping = ["Pizza Sauce","Cheese"] } //protocol func price(pricePerUnit: Double) -> Double { return area() * pricePerUnit } } //PanPizza -- demonstrate adding a property and methods with optional chaining class PanPizza:AbstractPizza{ var depth = 0.0 override func area() -> Double! { if let currentSize = size{ let radius = currentSize / 2.0 return radius * radius * pizzaPi }else{ return nil } } func volume() -> Double!{ if let area = area() { return area * depth }else{ return nil } } } // Demonstring overriding properties, or not... class RectPizza:AbstractPizza{ struct PizzaDimension{ //a struct for the height and width of a rectangle var height:Double = 0.0 var width:Double = 0.0 } //this does not work -- we cant overrride type of a property //var size:PizzaDimension = PizzaDimension() //added property sizeRect var sizeRect = PizzaDimension() override func area() -> Double! { return sizeRect.height * sizeRect.width } override func pizzaDidLoad() { sizeRect.height = 10.0 sizeRect.width = 12.0 crust = "Wheat" as AnyObject! topping = ["Pizza Sauce","Cheese","Mushroom"] } } //Subclassing a subclass that used an abstract class class FlatBreadPizza:RectPizza{ override func area() -> Double!{ let rect = (sizeRect.height - sizeRect.width) * sizeRect.width //area with round parts removed to make a rectangle let radius = sizeRect.width / 2.0 let circle = radius * radius * pizzaPi return rect + circle } } //Demonstrating class methods and AnyObject! //Also Demonstrates protocol adoption class BowlPizza:AbstractPizza,FoodPriceProtocol{ //protocol adoption override class func personalPizza() -> AnyObject! { let pizza = super.personalPizza() as! AbstractPizza let bowlPizza = BowlPizza() bowlPizza.size = pizza.size bowlPizza.topping = pizza.topping bowlPizza.crust = pizza.crust return bowlPizza } func volume() -> Double!{ if let bowlSize = size { let radius = bowlSize / 2.0 return radius * radius * radius * pizzaPi * (2.0/3.0) //volume of half a sphere } else { return nil } } //Protocols (delegates and Data sources) func price(pricePerUnit: Double) -> Double { if pricePerUnit == 1.0 { return 23.50 } else if pricePerUnit == 0.5 { return 11.75 } else { return 0 } } } //An example of a data source protocol ChocolateChipCookieDataSource{ func numberOfChipsPerCookie() -> Int func bagOfCookiesCount() -> Double } //examples of delegates and data sources with a different class // no superclass here, so the protocols goes directly after the class declaration // If there is a superclass, like aboove, the superclass goes first in the list. class ChocolateChipCookie:FoodPriceProtocol,ChocolateChipCookieDataSource{ var chipCount = 0 func price(pricePerUnit: Double) -> Double { //return price pricePerUnit * Double(chipCount) return pricePerUnit * Double(numberOfChipsPerCookie()) } func numberOfChipsPerCookie() -> Int { //simple datasource which returns a value return 15 } func bagOfCookiesCount() -> Double { //datasource whihc calcualtes its value //return 10.0 //get more cookies differnt days of the week let now = NSDate.timeIntervalSinceReferenceDate //get the number of seconds from refrence date to now let dayInSeconds:Double = 60 * 60 * 24 //convert to days let day = Int(now / dayInSeconds) % 7 // convert to day of week as 0 - 6 return Double(day) + 5.0 //five plus however many cookies for the day } func bagOfCookiesPrice(cookieCount:Double) -> Double{ //using the protocol method return price(pricePerUnit: 0.05) * cookieCount } func bagOfCookiesPrice() -> Double{ //using the protocol method in two different classes let pricePerUnit = 0.05 let pizza = FlatPizza() let discount = (pizza.price(pricePerUnit: pricePerUnit) * 0.10) return discount * price(pricePerUnit: pricePerUnit) * bagOfCookiesCount() } } // test area let flatRoundPizza = FlatPizza() flatRoundPizza.area() flatRoundPizza.price(pricePerUnit: 0.05) let panPizza = PanPizza() panPizza.size = 10.0 panPizza.depth = 2.0 panPizza.volume() let rectanglePizza = RectPizza() rectanglePizza.area() let bowlPizza = BowlPizza.personalPizza() as! BowlPizza bowlPizza.size bowlPizza.volume() bowlPizza.price(pricePerUnit: 1.0) bowlPizza.price(pricePerUnit: 0.5) bowlPizza.price(pricePerUnit: 1.1) let cookie = ChocolateChipCookie() cookie.price(pricePerUnit: 0.05) cookie.bagOfCookiesPrice(cookieCount: 5)
true
29a96220e1666693ce9a077869a6caf80c74279f
Swift
gustavotravassos/desafio-ios
/desafio-ios/desafio-ios/Models/Statement.swift
UTF-8
1,190
3.078125
3
[]
no_license
// // Statement.swift // desafio-ios // // Created by Gustavo Igor Gonçalves Travassos on 12/01/21. // import Foundation // MARK: - Struct struct Statement: Decodable { let createdAt: String let id: String let amount: Double let description: String let tType: String let to: String? let from: String? var bankName: String? let authentication: String? var transferenceType: String { switch tType { case "PIXCASHIN": return "Tranferência Pix recebida" case "PIXCASHOUT": return "Transferência Pix realizada" case "TRANSFEROUT": return "Transferência realizada" case "TRANSFERIN": return "Transferência recebida" case "BANKSLIPCASHIN": return "Depósito via boleto" default: return "Outros" } } var amountToString: String { if tType.contains("IN") { return "\(String(amount).formatToCurrency)" } return "-\(String(amount).formatToCurrency)" } } struct StatementArray: Decodable { var items: [Statement] }
true
8c14bc3ecae6802dc2c5a2437ead1637da1e1cb0
Swift
MigueAJM/securitySwift
/securityApp/ViewControllerMap.swift
UTF-8
2,987
2.59375
3
[]
no_license
// // ViewControllerMap.swift // securityApp // // Created by Miguel Angel Jimenez Melendez on 23/05/20. // Copyright © 2020 Miguel Angel Jimenez Melendez. All rights reserved. // import UIKit import GoogleMaps import GooglePlaces class ViewControllerMap: UIViewController, CLLocationManagerDelegate{ var location: String = "" var latitude: String = "" var longitude: String = "" var Reportes = [Reporte]() let dataJsonUrlClass = JsonClass() let locationManager: CLLocationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() Reportes.removeAll() let data_to_send = ["id": ""] as NSMutableDictionary dataJsonUrlClass.arrayFromJson(url: "webservice/getreports.php", data_send: data_to_send) { (array_request) in DispatchQueue.main.async { let cuenta = array_request?.count for indice in stride(from: 0, to: cuenta!, by: 1){ let report = array_request?.object(at: indice) as! NSDictionary let location = report.object(forKey: "location") as! String? let latitude = report.object(forKey: "latitude") as! String? let longitude = report.object(forKey: "longitud") as! String? let description = report.object(forKey: "description") as! String? let score = report.object(forKey: "score") as! String? self.Reportes.append(Reporte(location: location, latitude: latitude, longitude: longitude, description: description, score: score)) } } } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { for currentLocation in locations{ location = "\(currentLocation.coordinate.latitude), \(currentLocation.coordinate.longitude)" latitude = "\(currentLocation.coordinate.longitude)" longitude = "\(currentLocation.coordinate.longitude)" } let camera = GMSCameraPosition.camera(withLatitude: Double(Double(latitude)!), longitude: Double(Double(longitude)!), zoom: 6.0) let mapView = GMSMapView.map(withFrame: self.view.frame, camera: camera) self.view.addSubview(mapView) for report in Reportes{ let marker = GMSMarker() var latitud = report.latitude! var longitud = report.longitude! var location = report.location! var score = report.score! marker.position = CLLocationCoordinate2D(latitude: Double(Double(latitud)!), longitude: Double(Double(longitud)!)) marker.title = location marker.snippet = score marker.map = mapView print(marker.position) } } }
true
4c3f62a4f0a2e89f55e0eddedd13e88de85695f2
Swift
onurcelikeng/Horoscoper
/Horoscoper/Horoscoper/Models/WidgetModel.swift
UTF-8
1,166
2.9375
3
[ "MIT" ]
permissive
// // WidgetModel.swift // Horoscoper // // Created by Onur Celik on 3.12.2017. // Copyright © 2017 Onur Celik. All rights reserved. // import Foundation class WidgetModel: NSObject, NSCoding { var name: String var image: String var horoscopeDescription: String var date: String init(name: String, image: String, horoscopeDescription: String, date: String) { self.name = name self.image = image self.horoscopeDescription = horoscopeDescription self.date = date } required init(coder decoder: NSCoder) { self.name = decoder.decodeObject(forKey: "name") as? String ?? "" self.image = decoder.decodeObject(forKey: "image") as? String ?? "" self.horoscopeDescription = decoder.decodeObject(forKey: "horoscopeDescription") as? String ?? "" self.date = decoder.decodeObject(forKey: "date") as? String ?? "" } func encode(with coder: NSCoder) { coder.encode(name, forKey: "name") coder.encode(image, forKey: "image") coder.encode(horoscopeDescription, forKey: "horoscopeDescription") coder.encode(date, forKey: "date") } }
true
6f63f69fb60a4a3eef244af267289a3cfc481541
Swift
Zekhniddin/Collection_Scroll_View
/Collection_Scroll_View/controllers/HomeViewController.swift
UTF-8
3,149
2.65625
3
[]
no_license
// // HomeViewController.swift // Collection_Scroll_View // // Created by Зехниддин on 12/7/20. // import UIKit class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet var collectionView: UICollectionView! let numberOfColumns: CGFloat = 2 var items: [Item] = Array() override func viewDidLoad() { super.viewDidLoad() initViews() } // MARK: - Method func initViews() { setNavigationBar() collectionView.delegate = self collectionView.dataSource = self self.collectionView.register(UINib(nibName: "ItemCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "myCell") if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { let screenSize: CGRect = UIScreen.main.bounds let cellWidth = screenSize.width / numberOfColumns - 15 flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth) } items.append(Item(image: "im_coding1", title: "Best Coding")) items.append(Item(image: "im_coding2", title: "Amazing Code")) items.append(Item(image: "im_coding1", title: "Best Coding")) items.append(Item(image: "im_coding2", title: "Amazing Code")) items.append(Item(image: "im_coding1", title: "Best Coding")) items.append(Item(image: "im_coding2", title: "Amazing Code")) items.append(Item(image: "im_coding1", title: "Best Coding")) items.append(Item(image: "im_coding2", title: "Amazing Code")) items.append(Item(image: "im_coding1", title: "Best Coding")) items.append(Item(image: "im_coding2", title: "Amazing Code")) items.append(Item(image: "im_coding1", title: "Best Coding")) items.append(Item(image: "im_coding2", title: "Amazing Code")) } func setNavigationBar() { title = "Collection View" let scroll = UIImage(named: "ic_scroll") navigationItem.rightBarButtonItem = UIBarButtonItem(image: scroll, style: .plain, target: self, action: #selector(rightTapped)) } func callScrollController() { let vc = ScrollViewController(nibName: "ScrollViewController", bundle: nil) self.navigationController?.pushViewController(vc, animated: true) } // MARK: - Action @objc func rightTapped() { callScrollController() } // MARK: - Collection View func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = items[indexPath.row] let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath) as! ItemCollectionViewCell cell.imageView.image = UIImage(named: item.image!) cell.titleLabel.text = item.title return cell } }
true
1803412554934f8629b639a082d873e8323339fb
Swift
simajune/iOS_School
/SourceCode/171016_DataModel/171016_DataModel/DataModel.swift
UTF-8
8,192
2.921875
3
[]
no_license
// // DataModel.swift // 171016_DataModel // // Created by SIMA on 2017. 10. 16.. // Copyright © 2017년 SIMA. All rights reserved. // import Foundation enum Gender: Int { case male = 1 case female = 2 } struct UserModel { var userID: String var userPW: String var userEmail: String var birthday: String? var gender: Gender? init?(dataDic: [String: Any]) { guard let userID = dataDic["userID"] as? String else { return nil } self.userID = userID guard let userPW = dataDic["userPW"] as? String else { return nil } self.userPW = userPW guard let userEmail = dataDic["userEmail"] as? String else { return nil } self.userEmail = userEmail self.birthday = dataDic["birthday"] as? String if let rawData = dataDic["gender"] as? Int, (rawData == 1 || rawData == 2) { self.gender = Gender(rawValue: rawData) } } } var exhibition:[String: Any] = [:] var imageURL: [String] = [] var exhibitName1: [String] = [] var place: [String] = [] var startDate: [String] = [] var endDate: [String] = [] struct Exhibition { var imageURL: String? var exhibitName: String var place: String? var startDate: Date var endDate: String init?(dataDic: [String: String]) { self.imageURL = dataDic["imageURL"] guard let exhibitName = dataDic["exhibitName"] else { return nil } self.exhibitName = exhibitName self.place = dataDic["place"] let formatter = DateFormatter() formatter.dateFormat = "yyyy.MM.dd" guard let startDateStr = dataDic["startDate"] else { return nil } self.startDate = formatter.date(from: startDateStr)! guard let endDate = dataDic["endDate"] else { return nil } self.endDate = endDate } } //////////////////////////////////////////////////////////////////////////////////////////// struct AlbumInfo { var albumTitle: String var artist: String var genre: String init?(albumInfo: [String: Any]) { guard let albumTitle = albumInfo["albumTitle"] as? String else { return nil } self.albumTitle = albumTitle guard let artist = albumInfo["artist"] as? String else { return nil } self.artist = artist guard let genre = albumInfo["genre"] as? String else { return nil } self.genre = genre } } struct SongData { var songTitle: String var trackNum: Int var artist: String var writer: String var playTime: Int var playURL: String var formatter: DateFormatter = DateFormatter() // var playTime: Int = 0{ // willSet{ // let now = Date(timeIntervalSince1970: TimeInterval(newValue)) // formatter.dateFormat = "mm:ss" // self.totalPlayTime = formatter.string(from: now) // } // // } var totalPlayTime: String = "00:00" init?(songData: [String: Any]) { guard let songTitle = songData["songTitle"] as? String else { return nil } self.songTitle = songTitle guard let trackNum = songData["trackNum"] as? Int else { return nil } self.trackNum = trackNum guard let artist = songData["artist"] as? String else { return nil } self.artist = artist guard let writer = songData["writer"] as? String else { return nil } self.writer = writer guard let playTime = songData["playTime"] as? Int else { return nil } self.playTime = playTime guard let playURL = songData["playURL"] as? String else { return nil } self.playURL = playURL } } struct AlbumModel { var albumInfo: AlbumInfo var songList: [SongData] = [] init?(albumModel: [String: Any]) { guard let albumInfo = albumModel["albumInfo"] as? [String:Any] else { return nil } self.albumInfo = AlbumInfo(albumInfo: albumInfo)! guard let list = albumModel["songList"] as? [[String: Any]] else { return nil } for index in list{ self.songList.append(SongData(songData: index)!) } } } //////////////////////////////////////////////// /*{ - playlists: array of playlist - id: 3 - upid: nil - title: “나의 노래” - main_img_url: “http://naver.com” - thumb_img_url: “http://naver.com” - song_cnt: 3 - is_premium: “N” - monthly_ym: 201705 - like_info: 좋아요 정보 - song: object key for song. - id: 321 - like_cnt - is_like: “N” - up: object key for user playlist. - id: nil - like_cnt : nil - is_like: “N” - artist: object key for artist. - id: 103 - like_cnt : 1022 - is_like: “Y” }*/ ///////////////////////////////////////////////// // //let playModel = // ["playList":["id": 3, "upid": nil, "title": "나의 노래", ""]] struct PlayList { var id: Int? var upid: String? var title: String var mainImgURL: String var thumbImgURL: String var songCnt: Int var isPremium: Bool var monthlyYM: Date let datefomatter: DateFormatter = DateFormatter() init? (dataDic: [String: Any]) { // guard let id = dataDic["id"] as? Int else { return nil } // self.id = id // // guard let upid = dataDic["upid"] as? String else { return nil } // self.upid = upid if let id = dataDic["id"] as? Int { self.id = id self.upid = dataDic["upid"] as? String }else { if let upid = dataDic["upid"] as? String { self.id = dataDic["id"] as? Int self.upid = upid }else { return nil } } guard let title = dataDic["title"] as? String else { return nil } self.title = title guard let mainImgURL = dataDic["mainImgURL"] as? String else { return nil } self.mainImgURL = mainImgURL guard let thumbImgURL = dataDic["thumbImgURL"] as? String else { return nil } self.thumbImgURL = thumbImgURL guard let songCnt = dataDic["songCnt"] as? Int else { return nil } self.songCnt = songCnt if let isPremium = dataDic["isPremium"] as? String, (isPremium == "Y" || isPremium == "N"){ self.isPremium = isPremium == "Y" ? true:false } else { return nil } guard let monthlyYM = dataDic["monthlyYM"] as? Date else { return nil } datefomatter.dateFormat = "yyyyMM" datefomatter.string(from: monthlyYM) self.monthlyYM = monthlyYM } } enum LikeType { case song case up case artist } struct LikeInfo { var type: LikeType? var likeCnt: Int? var isLike: Bool? init?(likeInfo: [String: Any]) { if let _ = likeInfo["song"] as? String { self.type = .song self.likeCnt = (likeInfo["likeInfo"] as? Int)! if let isLike = likeInfo["isLike"] as? String, (isLike == "Y" || isLike == "N") { self.isLike = isLike == "Y" ? true:false } }else { if let _ = likeInfo["up"] as? String { self.type = .up self.likeCnt = (likeInfo["likeInfo"] as? Int)! if let isLike = likeInfo["isLike"] as? String, (isLike == "Y" || isLike == "N") { self.isLike = isLike == "Y" ? true:false } }else { if let _ = likeInfo["artist"] as? String { self.type = .artist self.likeCnt = (likeInfo["likeInfo"] as? Int)! if let isLike = likeInfo["isLike"] as? String, (isLike == "Y" || isLike == "N") { self.isLike = isLike == "Y" ? true:false } }else { self.type = nil self.likeCnt = nil self.isLike = nil } } } } }
true
8fc73764a29c69c569609f0e8f9c78d059f85fa4
Swift
brettawaytoday/QuizApp
/QuizAppTests/QuestionTest.swift
UTF-8
1,388
2.859375
3
[]
no_license
// // QuestionTest.swift // QuizAppTests // // Created by Brett Christian on 8/03/21. // // //import Foundation //import XCTest //@testable import QuizApp // //class QuestionTest: XCTestCase { // // func test_hashValue_singleAnswer_returnsTypeHash() { // let type = "a string" // // let sut = Question.singleAnswer(type) // // XCTAssertEqual(sut.hashValue, type.hashValue) // } // // func test_hashValue_multipleAnswer_returnsTypeHash() { // let type = "a string" // // let sut = Question.multipleAnswer(type) // // XCTAssertEqual(sut.hashValue, type.hashValue) // } // // func test_equal_isEqual() { // XCTAssertEqual(Question.singleAnswer("a string"), Question.singleAnswer("a string")) // XCTAssertEqual(Question.multipleAnswer("a string"), Question.multipleAnswer("a string")) // } // // func test_notEqual_singleAnswer_isNotEqual() { // XCTAssertNotEqual(Question.singleAnswer("a string"), Question.singleAnswer("another string")) // XCTAssertNotEqual(Question.multipleAnswer("a string"), Question.multipleAnswer("another string")) // XCTAssertNotEqual(Question.singleAnswer("a string"), Question.multipleAnswer("another string")) // XCTAssertNotEqual(Question.singleAnswer("a string"), Question.multipleAnswer("a string")) // } //}
true
fc2de5ddc2a8013d743dc726d0755acff9cafa63
Swift
Ani-Adhikary/USAKCenter
/USAKneeCenters/SignUpViewController.swift
UTF-8
2,165
2.734375
3
[]
no_license
// // SignUpViewController.swift // USAKneeCenters // // Created by Ani Adhikary on 17/02/18. // import UIKit class SignUpViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var mobileTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var inviteCodeTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() } @IBAction func signUpTouchUpInside(_ sender: UIButton) { do { try signUp() } catch LoginError.incompleteForm { Alert.showBasicAlert(title: "Incomplete Form", message: "Please fill out both email and password fields", vc: self) } catch LoginError.invalidEmail { Alert.showBasicAlert(title: "Invalid Email Format", message: "Please make sure you format your email correctly", vc: self) } catch LoginError.incorrectPasswordLength { Alert.showBasicAlert(title: "Password Too Short", message: "Password should be at least 8 characters", vc: self) } catch { Alert.showBasicAlert(title: "Unable To Login", message: "There was an error when attempting to login", vc: self) } } func signUp() throws { let email = emailTextField.text! let mobile = mobileTextField.text! let password = passwordTextField.text! let inviteCode = inviteCodeTextField.text! if email.isEmpty || mobile.isEmpty || password.isEmpty || inviteCode.isEmpty { throw LoginError.incompleteForm } // if !email.isValidEmail { // throw LoginError.invalidEmail // } if password.count < 2 { throw LoginError.incorrectPasswordLength } let signUpVC = storyboard?.instantiateViewController(withIdentifier: "SignUpUser") self.present(signUpVC!, animated: true, completion: nil) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } }
true
c4da96fdf1c376a72fcac8bcf941ca72234ea380
Swift
afnankhanvectra/SeekAsia
/SeekAsia/SeekAsia/View Controller/SALoginViewController.swift
UTF-8
4,120
2.671875
3
[]
no_license
// // SALoginViewController.swift // SeekAsia // // Created by Afnan Khan on 3/22/19. // Copyright © 2019 Afnan Khan. All rights reserved. // import UIKit class SALoginViewController: UIViewController { //MARK: IBOutlets @IBOutlet weak var userNameField: UITextField! @IBOutlet weak var emailField: UITextField! @IBOutlet weak var passwordField: UITextField! @IBOutlet weak var signupButton: UIButton! @IBOutlet weak var nameErrorLabel: UILabel! @IBOutlet weak var emailErrorLabel: UILabel! @IBOutlet weak var passwordErrorLabel:UILabel! //MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() userNameField.becomeFirstResponder() setVisibilityOfErrorLabels(isHiddel: true) } @IBAction func signupButtonClicked(_ sender: UIButton) { if validateData() == true { DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self ] in self?.present((self?.JobListViewController())!, animated: true, completion: nil) } } } func validateData() -> Bool{ if userNameField.text == nil || (userNameField.text?.count )! < 5 { nameErrorLabel.isHidden = false nameErrorLabel.showWithShakeAnimation(withMessage: "User name must have minimum 5 letters") return false } if emailField.text == nil || emailField.text?.isValidEmail(emailString: emailField.text!) == false{ emailErrorLabel.isHidden = false emailErrorLabel.showWithShakeAnimation(withMessage: "email is invalid") return false } if passwordField.text == nil || isPasswordValid(passwordField.text!) == false { passwordErrorLabel.isHidden = false passwordErrorLabel.showWithShakeAnimation(withMessage: "password must have 6 letter with atleast 1 number and 1 ") return false } return true } func setVisibilityOfErrorLabels(isHiddel _isHidden : Bool){ nameErrorLabel.isHidden = _isHidden emailErrorLabel.isHidden = _isHidden passwordErrorLabel.isHidden = _isHidden } } extension SALoginViewController : UITextFieldDelegate {// TextField Delegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { // Try to find next responder if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField { nextField.becomeFirstResponder() } else { signupButtonClicked(signupButton) } // Do not add a line break return false } @objc func textFieldDidChange(textField:UITextField) { setVisibilityOfErrorLabels(isHiddel: false) } func isPasswordValid(_ password : String) -> Bool{ let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,}$") return passwordTest.evaluate(with: password) } } extension UILabel { func showWithShakeAnimation(withMessage message : String) { text = message isHidden = false let animation = CABasicAnimation(keyPath: "position") animation.duration = 0.07 animation.repeatCount = 3 animation.autoreverses = true animation.fromValue = NSValue(cgPoint: CGPoint(x: center.x - 10, y: center.y)) animation.toValue = NSValue(cgPoint: CGPoint(x: center.x + 10, y: center.y)) layer.add(animation, forKey: "position") DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { self.isHidden = true } } } extension String { // check email is valid func isValidEmail(emailString:String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: emailString) } }
true
8feccabe8e7ced22f54d1b4d08911376e416f6d6
Swift
surnan/Business_Search
/Business_Search/Business_Search/Views/TableView Cells/BusinessCell.swift
UTF-8
1,126
2.765625
3
[ "Apache-2.0" ]
permissive
// // DefaultCell.swift // Business_Search // // Created by admin on 4/17/19. // Copyright © 2019 admin. All rights reserved. // import UIKit class BusinessCell: UITableViewCell { var name: String? { didSet { myLabel.text = name } } let myLabel: UILabel = { let label = UILabel() label.text = "" label.numberOfLines = 2 label.textColor = UIColor.black label.translatesAutoresizingMaskIntoConstraints = false return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) [myLabel].forEach{addSubview($0)} myLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 20).isActive = true myLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -5).isActive = true myLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
a282d85ccb607675c3d8ece0d2b36b6267003b37
Swift
angelabadperez/WonkaCrew
/WonkaCrew/Managers/ServerFetcher.swift
UTF-8
1,474
2.875
3
[]
no_license
// // ServerFetcher.swift // WonkaCrew // // Created by Ángel Abad Pérez on 7/3/21. // import Foundation final class ServerFetcher: ServerFetcherType { // MARK: - Public API func getCrewList(page: Int, completion: @escaping CrewListResult) { // Create URL let url = APIConfiguration.init(page: page).url // Create datatask URLSession.shared.dataTask(with: url) { (data, response, error) in DispatchQueue.main.async { self.didFetchCrewList(data: data, response: response, error: error, completion: completion) } }.resume() } // MARK: - Helper methods private func didFetchCrewList(data: Data?, response: URLResponse?, error: Error?, completion: CrewListResult) { if error != nil { completion(.failure(.failedRequest)) } else if let data = data, let response = response as? HTTPURLResponse { if response.statusCode == 200 { do { let decoder = JSONDecoder() let crewList = try decoder.decode(CrewList.self, from: data) completion(.success(crewList)) } catch { completion(.failure(.invalidResponse)) } } else { completion(.failure(.failedRequest)) } } else { completion(.failure(.unknown)) } } }
true
d9061b6ec9040855849745c9a602f6a6a2144400
Swift
klampotang/tweeter
/tweeter/ComposeViewController.swift
UTF-8
2,197
2.625
3
[ "Apache-2.0" ]
permissive
// // ComposeViewController.swift // tweeter // // Created by Kelly Lampotang on 6/28/16. // Copyright © 2016 Kelly Lampotang. All rights reserved. // import UIKit class ComposeViewController: UIViewController, UITextViewDelegate { @IBOutlet weak var countdownLabel: UILabel! @IBOutlet weak var tweetEnterField: UITextView! @IBOutlet weak var textView: UITextView! @IBOutlet weak var tweetButton: UIButton! override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ComposeViewController.tap(_:))) view.addGestureRecognizer(tapGesture) textView.delegate = self textView.text = "tap to edit" textView.textColor = UIColor.lightGrayColor() tweetButton.layer.borderWidth = 1 tweetButton.layer.masksToBounds = false tweetButton.layer.borderColor = UIColor.whiteColor().CGColor tweetButton.layer.cornerRadius = tweetButton.frame.height/2 tweetButton.clipsToBounds = true } func textViewDidBeginEditing(textView: UITextView) { if textView.textColor == UIColor.lightGrayColor() { textView.text = nil textView.textColor = UIColor.blackColor() } } func tap(gesture: UITapGestureRecognizer) { tweetEnterField.resignFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tweetTapped(sender: AnyObject) { if tweetEnterField.text != nil { let tweetText = tweetEnterField.text APIClient.sharedInstance.postStatus(tweetText!) tweetEnterField.text = "" //Clear the thing } } func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { let newLength = (textView.text.utf16).count + (text.utf16).count - range.length if(newLength <= 140){ self.countdownLabel.text = "\(140 - newLength)" return true }else{ return false } } }
true
baad7d1f633e32d5c903a97b24a0992c8d33ca7d
Swift
jtwirtz/sportsApp
/SportsApp/FoundUserEventsViewController.swift
UTF-8
2,914
2.671875
3
[]
no_license
// // FoundUserEventsViewController.swift // SportsApp // // Created by Kawika Avilla on 4/23/16. // Copyright © 2016 jwirtz. All rights reserved. // import UIKit class FoundUserEventsViewController: UIViewController,UITableViewDelegate, UITableViewDataSource { //change for fucks var selectedSportsArray = [String]() var mySeguedArray: [String]!{ didSet{ selectedSportsArray = mySeguedArray //no need to call viewDidLoad } } @IBOutlet weak var foundEventTable: UITableView! var fakeSportArray = [Sport]() var showArray = [Sport]() override func viewDidLoad() { super.viewDidLoad() let basketballGame:Sport = Sport.init(name: "Lakeshore Basketball Game", location: "Lakeshore", time: "Today @ 2:30", gameType: "Basketball") let tennisGame:Sport = Sport.init(name: "Super Fun Tennis Game", location: "Serf", time: "Today @ 5:30", gameType: "Tennis") let tennisGame2:Sport = Sport.init(name: "Naked Tennis Game with Beetches", location: "Lakeshore Courtsf", time: "5:30 pm", gameType: "Tennis") fakeSportArray.append(basketballGame) fakeSportArray.append(tennisGame) fakeSportArray.append(tennisGame2) for index in 0 ..< fakeSportArray.count{ let fakeSportName = fakeSportArray[index].getGameType() if selectedSportsArray.contains(fakeSportName){ showArray.append(fakeSportArray[index]) } } foundEventTable.delegate = self foundEventTable.dataSource = self } @IBAction func backButtonTap(sender: AnyObject) { dismissViewControllerAnimated(true, completion: {}) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return showArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:FoundUserEventTableCell = tableView.dequeueReusableCellWithIdentifier("foundTableCell")! as! FoundUserEventTableCell let sportEvent = showArray[indexPath.row] cell.descriptionLabel.text = sportEvent.getName() cell.gameTypeLabel.text = sportEvent.getGameType() cell.locationLabel.text = sportEvent.getLocation() cell.timeLabel.text = sportEvent.getTime() return cell } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
4ceee827a4ed8363418acb855915ee0dfd2a200d
Swift
wy34/ChatApp
/pokeChat/Services/AuthManager.swift
UTF-8
2,738
2.84375
3
[]
no_license
// // Authorization.swift // pokeChat // // Created by William Yeung on 7/24/20. // Copyright © 2020 William Yeung. All rights reserved. // import Foundation import Firebase class AuthManager { static let shared = AuthManager() func signIn(withEmail email: String, andPassword password: String, completion: @escaping (Result<Bool, ErrorMessage>) -> Void) { Auth.auth().signIn(withEmail: email, password: password) { (result, error) in if let _ = error { completion(.failure(.SignInError)) return } completion(.success(true)) } } func register(withName name: String, email: String, password: String, andImage image: UIImage, completion: @escaping (Result<Bool, ErrorMessage>) -> Void) { let imageName = UUID().uuidString let storageRef = Storage.storage().reference().child("profileImages/\(imageName)") var selectedImage: UIImage? if image == UIImage(systemName: "plus.square") { selectedImage = UIImage(systemName: "person.circle.fill") } else { selectedImage = image } guard let data = selectedImage!.jpegData(compressionQuality: 0.2) else { return } storageRef.putData(data, metadata: nil) { (metadata, error) in if let _ = error { completion(.failure(.PutDataError)) return } storageRef.downloadURL { (url, error) in if let _ = error { completion(.failure(.DownloadUrlError)) return } guard let imageUrl = url?.absoluteString else { return } Auth.auth().createUser(withEmail: email, password: password) { (result, error) in if let _ = error { completion(.failure(.RegisteringUserError)) return } guard let user = result?.user else { return } let userInfo = ["name": name, "email": email, "imageUrl": imageUrl] let databaseRef = Database.database().reference().child("users").child(user.uid) databaseRef.updateChildValues(userInfo) { (error, ref) in if let _ = error { completion(.failure(.UpdatingDatabaseError)) return } completion(.success(true)) } } } } } }
true
c69ff0edb6cc57b880fa1034adccd111360d54dd
Swift
Yoshiko-Tsu/SleepWell
/Log.swift
UTF-8
4,068
2.703125
3
[]
no_license
// // Log.swift // minikura_ios // // Created by 鶴田義子 on 2015/02/02. // Copyright (c) 2015年 鶴田義子. All rights reserved. // import Foundation //#if DEBUG // func LOG(msg: Any) { // println("[\(__FILE__) : \(__FUNCTION__) : \(__LINE__)] \(msg)") // } //#else // func LOG(msg: Any) { // } //#endif final class Log { class func checkAndDeleteLog() { // 保存期間を1日に設定 let intervalTime = 1.0 // 保存ヂレクトリをLogに設定 let logDirName = "Log" // 日付フォーマッター作成 let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "ja_JP") formatter.timeStyle = .MediumStyle formatter.dateStyle = .MediumStyle // パスを取得 let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let documentsPath: AnyObject = paths[0] let logDirPath = documentsPath as! String + "/" + logDirName // ディレクトリ確認 let fileManager = NSFileManager.defaultManager() let bTrue = fileManager.fileExistsAtPath(logDirPath) if (!bTrue) { fileManager.createDirectoryAtPath(logDirPath, withIntermediateDirectories: false, attributes: nil, error: nil) } // 現在の年月日を取得 let date = NSDate() let interval: NSTimeInterval = 60.0 * 60.0 * 24.0 * intervalTime * -1.0 let deleteDate = date.dateByAddingTimeInterval(interval) let deleteDateStr = formatter.stringFromDate(deleteDate) NSLog("ログファイル保存期日 ーーー \(deleteDateStr)") let logFiles: [AnyObject]? = fileManager.contentsOfDirectoryAtPath(logDirPath, error: nil) for oneFile in logFiles! { let oneFileStr = oneFile as! NSString let oneFilePath = logDirPath.stringByAppendingPathComponent(oneFileStr as String) let fileAttr: NSDictionary = fileManager.attributesOfItemAtPath(oneFilePath, error: nil)! let fileDate = fileAttr.fileCreationDate() let fileDateStr = formatter.stringFromDate(fileDate!) NSLog("ログファイル名 == \(oneFile)\t 作成時間 == \(fileDateStr)") if (fileDateStr < deleteDateStr) { // 削除 NSLog("ーーー 削除") fileManager.removeItemAtPath(oneFilePath, error: nil) } else { NSLog("ーーー 保存") } } } class func setFile() { // 保存ヂレクトリをLogに設定 let logDirName = "Log" // 日付フォーマッター作成 let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "ja_JP") formatter.timeStyle = .MediumStyle formatter.dateStyle = .MediumStyle // パスを取得 let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) let documentsPath: AnyObject = paths[0] let logDirPath = documentsPath as! String + "/" + logDirName // 現在の年月日を取得 let date = NSDate() let dateStr0 = formatter.stringFromDate(date) // dateStrを分解 let dateStr1 = dateStr0.componentsSeparatedByString(" ") // 月日と時刻を分割 let dateStrYMD = dateStr1[0].componentsSeparatedByString("/") let dateStrHMS = dateStr1[1].componentsSeparatedByString(":") let dateStr = dateStrYMD[0] + dateStrYMD[1] + dateStrYMD[2] + dateStrHMS[0] + dateStrHMS[1] // Logファイル名 let logFilePath = logDirPath + "/" + "log_" + dateStr + ".txt" NSLog("新規作成ログファイル名 == \(logFilePath)") freopen(logFilePath, "a+", stderr) } }
true
627df0e31e25cf65e23256ab5b27e533c1177e7b
Swift
martin3zra/zttp
/Tests/ZttpTests/URLSessionMock.swift
UTF-8
1,372
2.921875
3
[]
no_license
// // URLSessionMock.swift // ZttpTests // // Created by Alfredo Martinez on 6/21/20. // import Foundation class URLSessionMock: URLSession { typealias CompletionHandler = (Data?, URLResponse?, Error?) -> Void // Properties that enable us to set exactly what data or error // we want our mocked URLSession to return for any request. var data: Data? var error: Error? var response: HTTPURLResponse? override func dataTask( with request: URLRequest, completionHandler: @escaping CompletionHandler ) -> URLSessionDataTask { var data = self.data let error = self.error let response = self.response var queries : [String: Any] = [:] let queriesString = request.url?.query?.components(separatedBy: "&") queriesString?.forEach({ (item) in let queryItem = item.components(separatedBy: "=") if queryItem.count == 2 { queries[queryItem[0]] = queryItem[1] } }) let components: Dictionary<String, Any> = [ "data": data?.toDictionary as Any, "headers": request.allHTTPHeaderFields as Any, "query": queries ] data = components.toJSON return URLSessionDataTaskMock { completionHandler(data, response, error) } } }
true
ae1461b929915dc4800f00d95bf5567ed74cebf8
Swift
nickrobison/iot-lis
/ios/LISManager/LISManager/Results/Protocols+Extensions.swift
UTF-8
1,530
2.59375
3
[]
no_license
// // Protocols+Extensions.swift // LISManager // // Created by Nicholas Robison on 10/20/20. // import Foundation import LISKit import FlatBuffers import CoreData struct OrderInformation { let orderID: String let testType: String } extension LIS_Protocols_Order { func toOrderInformation() -> OrderInformation { return OrderInformation(orderID: self.orderId ?? "(no id)", testType: self.testTypeName!) } func toEntity(_ ctx: NSManagedObjectContext) -> OrderEntity { let entity = OrderEntity(context: ctx) entity.orderID = self.orderId entity.sampleType = self.testTypeName return entity } } struct ResultInformation { let resultType: String let value: String let resultDate: Date } extension LIS_Protocols_Result { func toResultInformation() -> ResultInformation { let timestamp = self.timestamp return ResultInformation(resultType: self.testResultType ?? "unknown", value: self.testValue ?? "unknown", resultDate: Date.init(timeIntervalSince1970: TimeInterval(timestamp))) } func toEntity(_ ctx: NSManagedObjectContext) -> ResultEntity { let entity = ResultEntity(context: ctx) entity.resultDate = Date.init(timeIntervalSince1970: TimeInterval(self.timestamp)) entity.result = self.testValue entity.resultType = self.testResultType entity.units = self.testUnits return entity } }
true
e36403b5703f1bab6ba62f8465cd300676e5d919
Swift
submariner100/SimpleTable
/SimpleTable/ViewController.swift
UTF-8
1,620
2.5625
3
[]
no_license
// // ViewController.swift // SimpleTable // // Created by Macbook on 02/02/2017. // Copyright © 2017 Chappy-App. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { var restaurantNames = [ "Cafe Deadend", "Homei", "Teakha", "Cafe Loisl", "Petite Oyster", "For Kee Restaurant", "Po's Atelier", "Bourke Street Bakery", "Haigh's Chocolate", "Palomio Espresso", "Upstate", "Traif", "Graham Avenue Meats And Deli", "Waffle & Wolf", "Five Leaves", "Cafe Lore", "Confessional", "Barrafina", "Donostia", "Royal Oak", "CASK Pub and Kitchen", ] override func viewDidLoad() { super.viewDidLoad() //tableView.delegate = self //tableView.dataSource = self } override var prefersStatusBarHidden: Bool { return true } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return restaurantNames.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "Cell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) // configure the cell.. cell.textLabel?.text = restaurantNames[indexPath.row] cell.imageView?.image = UIImage(named: "restaurant") return cell } }
true
fbd099553732b480dd310eec160d8b587d2e29d8
Swift
MelonMania/IOS-Study
/Quizzler-iOS13_ex/Quizzler-iOS13/Model/Question.swift
UTF-8
405
2.78125
3
[]
no_license
// // Question.swift // Quizzler-iOS13 // // Created by RooZin on 2021/02/21. // Copyright © 2021 The App Brewery. All rights reserved. // import Foundation struct Question{ let text : String var answer = [String]() let cA : String init(q : String, a : [String], correctAnswer : String){ text = q answer.append(contentsOf: a) cA = correctAnswer } }
true
084659af3177c17331b74ae2bfa4659132721b4c
Swift
omerjanjua/OVO
/OVO/ItemsTableViewCell.swift
UTF-8
1,548
2.703125
3
[]
no_license
// // ItemsTableViewCell.swift // OVO // // Created by Omer Janjua on 25/07/2016. // Copyright © 2016 Janjua Ltd. All rights reserved. // import UIKit import AlamofireImage import NSDate_TimeAgo class ItemsTableViewCell: UITableViewCell { //IBOutlets @IBOutlet weak var mediaImage: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! func configureCellWithItems (items: Items) { self.titleLabel.text = items.title let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" let dateFromString = dateFormatter.dateFromString(items.date!) self.subtitleLabel.text = dateFromString!.timeAgo() if items.media != nil { self.mediaImage.image = UIImage(data: items.media!, scale: 1.0) } else { self.downloadImageForItems(items) } } func downloadImageForItems (items: Items){ let url: NSURL = NSURL(string: items.mediaURL!)! let placeholderImage: UIImage = UIImage(named: "contact-image")! self.mediaImage.af_setImageWithURL(url, placeholderImage: placeholderImage, completion: { (response) in if let value = response.result.value { items.media = UIImagePNGRepresentation(value) let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.saveContext() } }) } }
true
2edeee20e528ec78b04e46d5bdb4e952774d82b6
Swift
arunblan/Apicall-and-store-in-local
/userDetails/Controllers/LoginViewController.swift
UTF-8
3,022
2.53125
3
[]
no_license
// // LoginViewController.swift // userDetails // // Created by lilac infotech on 09/08/21. // import UIKit import CoreData class LoginViewController: UIViewController { @IBOutlet weak var userNameTxt: UITextField! @IBOutlet weak var passwordTxt: UITextField! let userName = "[email protected]" let password = "Opentrend1" private let userManger:UserManger = UserManger() var userResponce : [LocalUserResponce]? = [] private var httpUtillity : HttpUtility? override func viewDidLoad() { super.viewDidLoad() httpUtillity = HttpUtility() let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) debugPrint(path[0],"-------the Url") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) NetworkHandler.checkInternetConnected(viewController: self) } @IBAction func loginButton(_ sender: Any) { validateUser(un: userNameTxt.text ?? "", pw: passwordTxt.text ?? "") } @IBAction func registerButton(_ sender: Any) { registerUser(un: userNameTxt.text ?? "", pw: passwordTxt.text ?? "") } //Register func registerUser(un:String,pw:String){ if un.count != 0 && pw.count != 0{ httpUtillity?.registerUser(completionHandler: { (respoce) in //Responce print(respoce) DispatchQueue.main.async() { AlertHandler.showAlertDissmissAction("Alert", "Login sucess", target: self) { let push = self.storyboard?.instantiateViewController(identifier: "ListUsersViewController") as! ListUsersViewController self.navigationController?.pushViewController(push, animated: true) } } }) }else{ AlertHandler.showAlert(title: "Alert!", message: "Please fill all the fields", color: .black, target: self) } } //Login func validateUser(un:String,pw:String){ if un == userName && pw == password{ let push = self.storyboard?.instantiateViewController(identifier: "ListUsersViewController") as! ListUsersViewController self.navigationController?.pushViewController(push, animated: true) }else{ AlertHandler.showAlert(title: "Alert!", message: "Enter Credentials are wrong", color: .black, target: self) } } @IBAction func showOfflineData(_ sender: Any) { userResponce = userManger.fetchuser() if userResponce?.count == 0{ AlertHandler.showAlert(title: "Alert", message: "There is no data", color: .black, target: self) }else{ let push = self.storyboard?.instantiateViewController(identifier: "ListUsersViewController") as! ListUsersViewController push.showOfflineData = true self.navigationController?.pushViewController(push, animated: true) } } }
true
746a6bbcdab813332dd11afbb8c34f97a8554536
Swift
Mentifresh/iOS_memeMaker
/MemeMaker/ViewController.swift
UTF-8
7,475
2.578125
3
[]
no_license
// // ViewController.swift // MemeMaker // // Created by Daniel Kilders Díaz on 20.06.19. // Copyright © 2019 Daniel Kilders. All rights reserved. // import UIKit import Photos class ViewController: UIViewController { @IBOutlet weak var memeImageView: UIImageView! @IBOutlet weak var cameraButton: UIBarButtonItem! @IBOutlet weak var shareMemeButton: UIBarButtonItem! @IBOutlet weak var bottomToolbar: UIToolbar! @IBOutlet weak var topToolbar: UIToolbar! @IBOutlet weak var firstMemeLineTextField: UITextField! @IBOutlet weak var secondMemeLineTextField: UITextField! var meme: Meme? var imagePickerController: UIImagePickerController? override func viewDidLoad() { super.viewDidLoad() // Init vars meme = Meme() // Enable cameraButton if there is a camera present cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera) // Disable button until user adds a pic shareMemeButton.isEnabled = false applyTextFieldCustomization(to: firstMemeLineTextField) applyTextFieldCustomization(to: secondMemeLineTextField) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // Unsubscribe to observers NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } override func viewWillAppear(_ animated: Bool) { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @IBAction func shareMeme(_ sender: Any) { let finalImage = generateMeme() let vc = UIActivityViewController(activityItems: [finalImage], applicationActivities: []) vc.completionWithItemsHandler = {(activityType: UIActivity.ActivityType?, completed: Bool, returnedItems: [Any]?, error: Error?) in if completed { self.save(finalMeme: finalImage) self.dismiss(animated: true, completion: nil) } } present(vc, animated: true) } @IBAction func dismissView(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func pickAnImage(_ sender: Any) { checkPhotosPermissions({ openImageSource(from: .photoLibrary) }()) } @IBAction func OpenCamera(_ sender: Any) { openImageSource(from: .camera) } func openImageSource(from imageSource: UIImagePickerController.SourceType) { if imagePickerController == nil { imagePickerController = UIImagePickerController() imagePickerController!.delegate = self } imagePickerController!.sourceType = imageSource present(imagePickerController!, animated: true, completion: nil) } func generateMeme() -> UIImage { // Hide Toolbars topToolbar.isHidden = true bottomToolbar.isHidden = true // Generate meme UIGraphicsBeginImageContext(self.view.frame.size) self.view.drawHierarchy(in: self.view.frame, afterScreenUpdates: true) let memeImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() // Show toolbars topToolbar.isHidden = false bottomToolbar.isHidden = false return memeImage } func save(finalMeme: UIImage) { // Create the meme let meme = Meme( bottomString: secondMemeLineTextField.text!, topString: firstMemeLineTextField.text!, originalImage: memeImageView.image, finalImage: finalMeme ) // Add it to the memes array in the Application Delegate let object = UIApplication.shared.delegate let appDelegate = object as! AppDelegate appDelegate.memes.append(meme) } func applyTextFieldCustomization(to textField: UITextField) { let memeTextAttributes: [NSAttributedString.Key: Any] = [ NSAttributedString.Key.strokeColor: UIColor.black, //Outline Color NSAttributedString.Key.foregroundColor: UIColor.white, //Fill color .font: UIFont.boldSystemFont(ofSize: 40), .strokeWidth: -4.0 ] textField.autocapitalizationType = .allCharacters textField.borderStyle = .none textField.defaultTextAttributes = memeTextAttributes textField.textAlignment = .center textField.delegate = self } @objc func keyboardWillShow(_ notification: Notification) { print(secondMemeLineTextField.isEditing) if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue, secondMemeLineTextField.isFirstResponder { let keyboardRectangle = keyboardFrame.cgRectValue let keyboardHeight = keyboardRectangle.height view.frame.origin.y = keyboardHeight * (-1) } } @objc func keyboardDidHide(_ notification: Notification) { if secondMemeLineTextField.isFirstResponder { view.frame.origin.y = 0 } } } extension ViewController: UIImagePickerControllerDelegate { func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage { self.memeImageView.image = image self.meme?.originalImage = image // Enable sharing button self.shareMemeButton.isEnabled = true } dismiss(animated: true, completion: nil) } func checkPhotosPermissions(_ closure: () ) { let status = PHPhotoLibrary.authorizationStatus() switch status { case .authorized: print("Access granted by user") case .notDetermined: print("Not determined") PHPhotoLibrary.requestAuthorization { (status) in if status == PHAuthorizationStatus.authorized { closure } } case .denied, .restricted: print("Denied / restricted") } } } extension ViewController: UINavigationControllerDelegate { } extension ViewController: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { if textField.tag == 1 { meme?.topString = textField.text } else if textField.tag == 2 { meme?.bottomString = textField.text } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false } }
true
246f4878fe118da388f7d1e9c64cb361f919c8e7
Swift
wortman/stroll_safe_ios
/Stroll SafeTests/PasscodeSpec.swift
UTF-8
1,040
2.53125
3
[ "Apache-2.0" ]
permissive
// // PasscodeSpec.swift // Stroll Safe // // Created by Lynda Prince on 8/3/15. // Copyright © 2015 Stroll Safe. All rights reserved. // import Foundation import Foundation import Quick import Nimble @testable import Stroll_Safe import CoreData class PasscodeSpec: QuickSpec { override func spec() { describe("The Passcode Model") { var managedObjectContext: NSManagedObjectContext! beforeEach { managedObjectContext = TestUtils().setUpInMemoryManagedObjectContext() } it ("throws an error when there is no stored passcode") { expect{ try Passcode.get(managedObjectContext) }.to(throwError()) } it ("get returns the passcode used in set") { let passcode = "1234" Passcode.set(passcode, managedObjectContext: managedObjectContext) expect(try! Passcode.get(managedObjectContext)).to(equal(passcode)) } } } }
true
9e91f82a57d01c1d00c2e10e1e46d5ffd1665ebe
Swift
ryanmoran/Radar
/Concourse/Concourse/Domain/Pipeline.swift
UTF-8
1,621
2.65625
3
[ "MIT" ]
permissive
import Foundation import ConcourseAPI public struct Pipeline { let pipeline: ConcourseAPI.Pipeline public let target: Target public var jobs: [Job] public init(_ pipeline: ConcourseAPI.Pipeline, target: Target) { self.pipeline = pipeline self.target = target self.jobs = [] } public var id: Int { return pipeline.id } public var name: String { return pipeline.name } public var groups: [Group] { var groups: [Group] = [] if let apiGroups = pipeline.groups { for apiGroup in apiGroups { var group = Group(name: apiGroup.name, pipeline: self) for jobName in apiGroup.jobs { for job in jobs { if job.name == jobName { group.jobs.append(job) } } } groups.append(group) } } return groups } public var status: String { for status in ["paused", "started", "failed", "pending", "errored", "aborted", "succeeded"] { for job in jobs { if job.status == status { return status } } } return "unknown" } public var transientStatus: String { for status in ["started", "pending", "paused", "failed", "errored", "aborted", "succeeded"] { for job in jobs { if job.transientStatus == status { return status } } } return "unknown" } } extension Pipeline: Equatable { public static func ==(lhs: Pipeline, rhs: Pipeline) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name && lhs.groups == rhs.groups && lhs.jobs == rhs.jobs } }
true
8e67b749823d14bc5fe036f649d93e0fbb137723
Swift
BugPersonality/LeetCodeTasksForYandex
/LeetCodeTraining/LeetCodeTraining/squaresOfASortedArray.swift
UTF-8
689
3.390625
3
[]
no_license
import Foundation func sortedSquares(_ nums: [Int]) -> [Int] { // Runtime -> 540 ms, Memory -> 15.9 MB // var array = nums.map { $0 * $0 } // array = array.sorted() // return array // Runtime -> 336 ms, Memory -> 15.5 MB var array = nums var size = nums.count var begin = 0 var end = size - 1 var index = size - 1 while (index >= 0) { if (nums[begin] * nums[begin] > nums[end] * nums[end]) { array[index] = nums[begin] * nums[begin] begin += 1 } else { array[index] = nums[end] * nums[end] end -= 1 } index -= 1 } return array }
true
2753caa3503b0110ccfb8c6dd4528cd3cf027b16
Swift
koltenfluckiger/GoalieList
/GoalieList/Model/GoalsManager/GoalRetriever.swift
UTF-8
729
2.765625
3
[]
no_license
// // GoalsRetriever.swift // GoalieList // // Created by Kolten Fluckiger on 7/4/18. // Copyright © 2018 Kolten Fluckiger. All rights reserved. // import CoreData import Foundation class GoalRetriever { let managedContext: NSManagedObjectContext let fetchRequest: NSFetchRequest<Goal> init(managedContext: NSManagedObjectContext, fetchRequest: NSFetchRequest<Goal>) { self.managedContext = managedContext self.fetchRequest = fetchRequest } func executeFetch(completion: ([Goal]?) -> Void) { do { let goals = try managedContext.fetch(fetchRequest) completion(goals) } catch { print("Could not fetch") completion(nil) } } }
true
a7db701b0d46f288a10f5f39303588c7a6f7ece7
Swift
gruj1995/HouseKeeper
/HouseKeepers/View/Cell/Helper/SummaryTableViewCell.swift
UTF-8
1,588
2.609375
3
[]
no_license
// // SummaryTableViewCell.swift // HouseKeepers // // Created by developer on 2021/1/12. // import UIKit protocol SummaryTableViewCellDelegate { func buttonTapped(cell:SummaryTableViewCell) } class SummaryTableViewCell: UITableViewCell { var summaryTableViewCellDelegate : SummaryTableViewCellDelegate? var articleId = "" @IBOutlet weak var articleTitleLB: UILabel! @IBOutlet weak var textView: UITextView! @IBOutlet weak var dateLB: UILabel! @IBAction func readBtnOnclick(_ sender: UIButton) { summaryTableViewCellDelegate?.buttonTapped(cell: self) } override func awakeFromNib() { super.awakeFromNib() textView.textContainer.maximumNumberOfLines = 3 textView.textContainer.lineBreakMode = .byTruncatingTail textView.isEditable = false textView.isSelectable = false } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override open var frame: CGRect { get { return super.frame } set (newFrame) { var frame = newFrame frame.origin.x = 15//調整x起點 frame.size.height -= 1.7 * frame.origin.x//調整高度 frame.size.width -= 2 * frame.origin.x super.frame = frame } } override func layoutSubviews() { super.layoutSubviews() layer.cornerRadius = 20 layer.masksToBounds = false//超過框線的地方會被裁掉 } }
true
a05e84503b927cb1c0810fc1a16547c280bb1cfb
Swift
gaosa/Useful-iOS-Codes
/Zoom In Transition/ImageViewController.swift
UTF-8
1,462
2.953125
3
[]
no_license
import UIKit class BaseImageViewController: UIViewController { let imageView = UIImageView(image: UIImage(named: "some image")) override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white view.addSubview(imageView) imageView.contentMode = .scaleAspectFit imageView.isUserInteractionEnabled = true } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() imageView.frame = frameForImageView() } func frameForImageView() -> CGRect { return view.frame } } class SmallImageViewController: BaseImageViewController { override func frameForImageView() -> CGRect { return CGRect(x: 20, y: 30, width: view.frame.width/4, height: view.frame.width/4) } override func viewDidLoad() { super.viewDidLoad() imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap))) } @objc func tap() { let vc = BigImageViewController() // important vc.transitioningDelegate = self present(vc, animated: true) } } class BigImageViewController: BaseImageViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap))) } @objc func tap() { dismiss(animated: true) } }
true
32356d821d8afb52c25a0c24371ccb7799ae9c01
Swift
xmliteworkltd/WaniKani-iOS
/WaniKani/ViewControllers/Setup/NotificationsSetupVC.swift
UTF-8
2,949
2.671875
3
[]
no_license
// // NotificationsSetupVC.swift // WaniKani // // Created by Andriy K. on 11/17/15. // Copyright © 2015 Andriy K. All rights reserved. // import UIKit import PermissionScope class NotificationsSetupVC: SetupStepViewController { private let pscope: PermissionScope = { let p = PermissionScope() p.addPermission(NotificationsPermission(notificationCategories: nil), message: "We will only send you notification when Reviews are up. No spam.") p.headerLabel.text = "₍ᐢ•ﻌ•ᐢ₎*・゚。" p.bodyLabel.text = "This app works best with notifications." p.bodyLabel.superview?.backgroundColor = UIColor(patternImage: UIImage(named: "pattern")!) return p }() @IBOutlet weak var dogeHintView: DogeHintView! @IBOutlet weak var setupButton: UIButton! @IBAction func setupNotificationsPressed(sender: AnyObject) { pscope.show({ (finished, results) -> Void in self.nextButton?.enabled = true if results.first?.status == .Authorized { self.allowed() } else { self.denied() } }, cancelled: { (results) -> Void in self.nextButton?.enabled = true self.canceled() }) } var userDecided = false func allowed() { dogeHintView.message = "Wow, u so smart and much wise! " userDecided = true setupButton.enabled = false } func canceled() { if userDecided == false { dogeHintView.message = "You haven't allowed notifications yet. Go allow them or move on without." } } func denied() { dogeHintView.message = "Seems like you don't like notifications. Not a problem, you can allow them later if you want! " userDecided = true } override func viewDidLoad() { super.viewDidLoad() switch PermissionScope().statusNotifications() { case .Unauthorized, .Disabled, .Unknown: nextButton?.enabled = false setupButton.enabled = true dogeHintView.message = "I can keep you so notified when much Reviews or Lessons are avaliable." return case .Authorized: nextButton?.enabled = true setupButton.enabled = false dogeHintView.message = "Notifications are all set.\n Proceed to the next step! " return } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) delay(0.5) { () -> () in self.dogeHintView.show() } } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) dogeHintView.hide() } } extension NotificationsSetupVC { override func nextStep() { dogeHintView.hide { (success) -> Void in self.performSegueWithIdentifier("nextPage", sender: self) } } override func previousStep() { navigationController?.popViewControllerAnimated(true) } override func needsPreviousStep() -> Bool { return false } override func needsNextButton() -> Bool { return true } }
true
b392d359cbcce1c6392433aeb60ec381af4f855e
Swift
DesireForSmth/OxygenTest
/OxygenTest/MainViewController.swift
UTF-8
3,810
2.609375
3
[]
no_license
// // MainViewController.swift // OxygenTest // // Created by Александр Сетров on 05.04.2021. // import UIKit class MainViewController: UIViewController { private struct Constants { static let buttonOffset: CGFloat = 10 static let viewLayoutOffset: CGFloat = 16 static let cornerRadius: CGFloat = 10 static let fontSize: CGFloat = 30 } var viewModel: MainViewModelProtocol? override func viewDidLoad() { super.viewDidLoad() self.setupDataFetching() self.setupUI() } private func setupDataFetching() { self.viewModel?.modelName = { [ weak self ] model in self?.modelLabel.text = model self?.view.layoutIfNeeded() } self.viewModel?.systemVersion = { [ weak self ] version in self?.systemVersionLabel.text = version self?.view.layoutIfNeeded() } } lazy private var buttonBackground: UIView = { let view = UIView() view.backgroundColor = .gray view.translatesAutoresizingMaskIntoConstraints = false return view }() lazy private var modelLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy private var systemVersionLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy private var fetchButton: UIButton = { let button = UIButton(type: .system) button.setTitle("Запустить", for: .normal) button.tintColor = .black button.titleLabel?.font = UIFont.systemFont(ofSize: Constants.fontSize) button.addTarget(self, action: #selector(fetchDeviceInfoData), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false return button }() @objc func fetchDeviceInfoData() { self.viewModel?.fetchSystemInfo() } private func setupUI() { self.view.backgroundColor = UIColor.systemBackground self.view.addSubview(self.buttonBackground) self.buttonBackground.addSubview(self.fetchButton) self.view.addSubview(self.modelLabel) self.view.addSubview(self.systemVersionLabel) self.setupConstraints() self.buttonBackground.layer.cornerRadius = Constants.cornerRadius self.view.layoutIfNeeded() } private func setupConstraints() { NSLayoutConstraint.activate([ self.buttonBackground.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), self.buttonBackground.centerYAnchor.constraint(equalTo: self.view.centerYAnchor), self.fetchButton.topAnchor.constraint(equalTo: self.buttonBackground.topAnchor, constant: Constants.buttonOffset), self.fetchButton.leadingAnchor.constraint(equalTo: self.buttonBackground.leadingAnchor, constant: Constants.buttonOffset), self.fetchButton.trailingAnchor.constraint(equalTo: self.buttonBackground.trailingAnchor, constant: -Constants.buttonOffset), self.fetchButton.bottomAnchor.constraint(equalTo: self.buttonBackground.bottomAnchor, constant: -Constants.buttonOffset), self.modelLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), self.systemVersionLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), self.systemVersionLabel.topAnchor.constraint(equalTo: self.modelLabel.bottomAnchor, constant: Constants.viewLayoutOffset), self.systemVersionLabel.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor, constant: -Constants.viewLayoutOffset) ]) } }
true
2ed3015b351a0faf5294df4596a521d609553f78
Swift
rlt202/MeAppV2
/MeAppV2/ViewControllers/ViewController.swift
UTF-8
2,474
2.765625
3
[]
no_license
// // ViewController.swift // MeAppV2 // // Created by Даниил Никулин on 23.10.2020. // import UIKit class ViewController: UIViewController { @IBOutlet weak var userTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! private let userData = UserData.catchDataOfUser() override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == "user" else { return } let userView = segue.destination as! UITabBarController let userVC = userView.viewControllers?.first as! UserViewController userVC.name = userTextField.text ?? "" } @IBAction func passButtonTapped() { alertViewIsOpen(title: "Wrong password", message: "Your pass is \(userData.password)") } @IBAction func nameButtonTapped() { alertViewIsOpen(title: "Wrong name", message: "Your name is \(userData.name)") } @IBAction func letsGoButtonTapped() { guard userTextField.text == userData.name, passwordTextField.text == userData.password else { alertViewIsOpen(title: "Wrong Data", message: "Check your data", textField: passwordTextField) return } performSegue(withIdentifier: "user", sender: nil) } @IBAction func backSegue(segue: UIStoryboardSegue) { userTextField.text = nil passwordTextField.text = nil } } extension ViewController { private func alertViewIsOpen(title: String, message: String, textField: UITextField? = nil) { let alertView = UIAlertController(title: title, message: message, preferredStyle: .alert) let retryButton = UIAlertAction(title: "Retry", style: .default) { (UIAlertAction) in textField?.text = nil } present(alertView, animated: true) alertView.addAction(retryButton) } } extension ViewController { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super .touchesBegan(touches, with: event) view.endEditing(true) } } //extension ViewController: UITextFieldDelegate { // // func textFieldShouldReturn(_ textField: UITextField) -> Bool { // if userTextField.resignFirstResponder() { // passwordTextField.becomeFirstResponder() // } else { // letsGoButtonTapped() // } // return true // } //}
true
d1ddad1b2a8bd7f5f2d589ef9641124653ec4e26
Swift
TrendingTechnology/SyndiKit
/Sources/SyndiKit/Formats/Media/iTunes/iTunesDuration.swift
UTF-8
1,118
2.96875
3
[ "MIT" ]
permissive
import Foundation // swiftlint:disable:next type_name public struct iTunesDuration: Codable { static func timeInterval(_ timeString: String) -> TimeInterval? { let timeStrings = timeString.components(separatedBy: ":").prefix(3) let doubles = timeStrings.compactMap(Double.init) guard doubles.count == timeStrings.count else { return nil } return doubles.reduce(0) { partialResult, value in partialResult * 60.0 + value } } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let stringValue = try container.decode(String.self) guard let value = Self.timeInterval(stringValue) else { let context = DecodingError.Context( codingPath: decoder.codingPath, debugDescription: "Invalid time value", underlyingError: nil ) throw DecodingError.dataCorrupted(context) } self.value = value } public init?(_ description: String) { guard let value = Self.timeInterval(description) else { return nil } self.value = value } public let value: TimeInterval }
true
013750e4566c01023974a12f3519bde84c72ee68
Swift
Satish1729/Fitpass
/Fitpass/DASHBOARD/Models/Members.swift
UTF-8
2,952
2.546875
3
[]
no_license
// // Members.swift // Fitpass // // Created by SatishMac on 29/05/17. // Copyright © 2017 Satish. All rights reserved. // import UIKit class Members: NSObject { var address : String? = "" var agreed_amount : NSNumber? var contact_number : NSNumber? var created_at : String? = "" var created_by : String? = "" var dob : String? = "" var email : String? = "" var gender : String? var id : NSNumber? var is_active : NSNumber? var is_deleted : NSNumber? var joining_date : String? var name : String? = "" var payment_date : NSNumber? var preferred_time_slot_from : String? var preferred_time_slot_to : String? var remarks : String? = "" var status : String? var subscription_plan : String? = "" var updated_at : String? var updated_by : String? func updateMembers(responseDict : NSDictionary?) -> NSMutableArray { let resultDict: NSDictionary = responseDict!.object(forKey: "result") as! NSDictionary let dataArray : NSArray = resultDict.object(forKey: "data") as! NSArray let tempArray : NSMutableArray = NSMutableArray() for memberObj in (dataArray as? [[String:Any]])! { let memberBean : Members = Members() memberBean.address = memberObj[ "member_address"] as? String memberBean.agreed_amount = memberObj["agreed_amount"] as? NSNumber memberBean.contact_number = memberObj[ "contact_number"] as? NSNumber memberBean.created_at = memberObj[ "created_at"] as? String memberBean.created_by = memberObj[ "created_by"] as? String memberBean.dob = memberObj[ "date_of_birth"] as? String memberBean.email = memberObj[ "email_address"] as? String memberBean.gender = memberObj[ "gender"] as? String memberBean.id = memberObj[ "id"] as? NSNumber memberBean.is_active = memberObj["is_active"] as? NSNumber memberBean.is_deleted = memberObj[ "is_deleted"] as? NSNumber memberBean.joining_date = memberObj["joining_date"] as? String memberBean.name = memberObj[ "member_name"] as? String memberBean.payment_date = memberObj[ "payment_date"] as? NSNumber memberBean.preferred_time_slot_from = memberObj[ "preferred_time_slot_from"] as? String memberBean.preferred_time_slot_to = memberObj[ "preferred_time_slot_to"] as? String memberBean.remarks = memberObj[ "remarks"] as? String memberBean.status = memberObj["member_status"] as? String memberBean.subscription_plan = memberObj[ "subscription_plan"] as? String memberBean.updated_at = memberObj["updated_at"] as? String memberBean.updated_by = memberObj["updated_by"] as? String tempArray.add(memberBean) } return tempArray } }
true
37fefd990ee7fecc1f696138c1df15d6a1c2d5a2
Swift
magic-IOS/leetcode-swift
/0132. Palindrome Partitioning II.swift
UTF-8
1,269
3.1875
3
[ "Apache-2.0" ]
permissive
class Solution { // Solution @ Sergey Leschev, Belarusian State University // 132. Palindrome Partitioning II // Given a string s, partition s such that every substring of the partition is a palindrome. // Return the minimum cuts needed for a palindrome partitioning of s. // Example 1: // Input: s = "aab" // Output: 1 // Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut. // Example 2: // Input: s = "a" // Output: 0 // Example 3: // Input: s = "ab" // Output: 1 // Constraints: // 1 <= s.length <= 2000 // s consists of lower-case English letters only. func minCut(_ s: String) -> Int { let chars = Array(s) var dp0: [[Bool]] = Array(repeating: Array(repeating: false, count: s.count), count: s.count) for i in (0..<s.count).reversed() { for j in (i..<s.count).reversed() { if i == j { dp0[i][j] = true } else if chars[i] == chars[j] { dp0[i][j] = i + 1 == j || dp0[i+1][j-1] } } } var dp1: [Int] = Array(repeating: Int.max, count: s.count + 1) dp1[0] = -1 for i in 1...s.count { for j in 0..<i { if dp0[j][i-1] == true { dp1[i] = min(dp1[j] + 1, dp1[i]) } } } return dp1[s.count] } }
true
bfe1b6d89cdb69dd95792b4639af79e42cfffab3
Swift
RazCoH/Moneyger-IOS
/Project/models/coreData/CoreDatabase.swift
UTF-8
3,571
3.046875
3
[]
no_license
// // CoreDatabase.swift // Project // // Created by raz cohen on 03/05/2020. // Copyright © 2020 raz cohen. All rights reserved. // import Foundation import CoreData class CoreDatabase{ //singletone private init(){} static let shared = CoreDatabase() // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Project") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } //computed property for the context: var context: NSManagedObjectContext{ return persistentContainer.viewContext } func fetchUser()->[User]{ let request = NSFetchRequest<User>(entityName: "User") do{ let users = try context.fetch(request) return users }catch let error{ print("Error!",error) return[] } } func fetchAction()->[Action]{ let request = NSFetchRequest<Action>(entityName: "Action") do{ let action = try context.fetch(request) return action }catch let error{ print("Error!",error) return[] } } }
true
76a818ef5affdbd06665604b23a7fecf5e9cced4
Swift
vapor/sql-kit
/Sources/SQLKit/Query/SQLConflictAction.swift
UTF-8
1,789
2.84375
3
[ "MIT" ]
permissive
/// An action to take when an `INSERT` query encounters a unique constraint violation. /// /// - Note: This is one of the only types at this layer which is _not_ an `SQLExpression`. /// This is down to the unfortunate fact that while PostgreSQL and SQLite both support the /// standard's straightforward `ON CONFLICT DO NOTHING` syntax which goes in the same place /// in the query as an update action would, MySQL can only express the `noAction` case /// with `INSERT IGNORE`. This requires considering the conflict action twice in the same /// query when serializing, and to decide what to emit in either location based on both /// the specific action _and_ the dialect's supported sybtax. As a result, the logic for /// this has to live in ``SQLInsert``, and it is not possible to serialize a conflict action /// to SQL in isolation (but again, _only_ because MySQL couldn't be bothered), and this /// enum can not conform to ``SQLExpression``. public enum SQLConflictAction { /// Specifies that conflicts this action is applied to should be ignored, allowing the query to complete /// successfully without inserting any new rows or changing any existing rows. case noAction /// Specifies that conflicts this action is applied to shall cause the INSERT to be converted to an UPDATE /// on the same schema which performs the column updates specified by the associated column assignments and, /// where supported by the database, constrained by the associated predicate. The column assignments may /// include ``SQLExcludedColumn`` expressions to refer to values which would have been inserted into the row /// if the conflict had not taken place. case update(assignments: [any SQLExpression], predicate: (any SQLExpression)?) }
true
38a602983a6f2875e787f4f802e7787238511299
Swift
HuangJinyong/WeiboDemo-Swfit
/AYWeibo/AYWeibo/classes/Home/UserModel.swift
UTF-8
1,072
2.859375
3
[ "Apache-2.0" ]
permissive
// // UserModel.swift // AYWeibo // // Created by Ayong on 16/6/23. // Copyright © 2016年 Ayong. All rights reserved. // import UIKit class UserModel: NSObject { /// 字符串型的用户UID var idstr: String? /// 用户昵称 var screen_name: String? /// 用户头像地址(中图),50×50像素 var profile_image_url: String? /// 用户认证类型 /// -1:没有认真, 0:认证用户, 2,3,5:企业认证, 220:达人 var verified_type: Int = -1 /// 会员等级 /// 1~6:分别表示对应等级的会员 var mbrank: Int = -1 init(dict: [String: AnyObject]) { super.init() self.setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } override var description: String { let keys = ["idstr", "screen_name", "profile_image_url", "verified_type"] let dict = self.dictionaryWithValuesForKeys(keys) return "\(dict)" } }
true
42d8cd6d3a1cb578bbf808ae96efa95efeea25e4
Swift
pillboxer/PurchaseCalculator
/PurchaseCalculator/Views/Evaluation/Brands/BrandSelectionView.swift
UTF-8
2,254
2.78125
3
[]
no_license
// // BrandSelectionView.swift // PurchaseCalculator // // Created by Henry Cooper on 16/01/2021. // import SwiftUI struct BrandSelectionView: View { @State private var selectedBrand: PurchaseBrand? @Binding var isActive: Bool @State var isPushed = false var item: PurchaseItem? var isAddingYourOwn: Bool = false var brands: [PurchaseBrand] { let brandsToSort = isAddingYourOwn ? DecodedObjectProvider.purchaseBrands ?? [] : item?.brands ?? DecodedObjectProvider.allSpecificPurchaseUnits?.compactMap { $0.brand } ?? [] let unsorted = Set(brandsToSort) return unsorted.sorted { $0.handle < $1.handle } } var units: [SpecificPurchaseUnit] { let allUnits = selectedBrand?.units?.sorted { $0.modelName < $1.modelName } ?? [] if let item = item { return allUnits.filter { $0.item == item } } return allUnits } private var header: String { let base = "brands_header" return isAddingYourOwn ? base.appending("_add_your_own") : base } @ViewBuilder private var destination: some View { if isAddingYourOwn, let item = item { CustomUnitCreationView(item: item, initialBrandName: selectedBrand?.handle ?? "", isActive: $isActive) } else { EvaluationUnitSelectionView(units: units, isActive: $isActive) } } var body: some View { HiddenNavigationLink(destination: destination, isActive: $isPushed) EmptorColorSchemeAdaptingView { VStack { if isAddingYourOwn { CTAButton(text: "custom_brand_cta", width: 150) { isPushed = true } .padding() } BasicGridSelectionView(header: header) { ForEach(brands) { brand in CTAButton(text: brand.handle, imageWrapper: ImageWrapper(name: brand.imageName), animationPeriod: nil) { selectedBrand = brand isPushed = true } } } } } } }
true
6e2c4d1715352d71fb410f2315772d5909b772b7
Swift
hamsternik/robotdreams-ios-course
/lecture-8/lecture08-project-starter/lecture08-project/Sources/MealsTableViewController.swift
UTF-8
2,320
3.03125
3
[ "MIT" ]
permissive
// // MealsTableViewController.swift // lecture08-project // // Created by hamsternik on 15.03.2021. // import UIKit class MealsTableViewController: UITableViewController { var meals = [Meal]() override func viewDidLoad() { super.viewDidLoad() /// Load the sample data. loadSampleMeals() } // MARK: Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return meals.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell( withIdentifier: MealTableViewCell.reusableIdentifier, for: indexPath ) as? MealTableViewCell else { fatalError("The dequeued cell is not an instance of MealTableViewCell.") } let meal = meals[indexPath.row] cell.update( with: .init( name: meal.name, photo: meal.photo, rating: meal.rating ) ) 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. } // MARK: Private private func loadSampleMeals() { let photo1 = UIImage(named: "meal1") let photo2 = UIImage(named: "meal2") let photo3 = UIImage(named: "meal3") guard let firstMeal = Meal(name: "Caprese Salad", photo: photo1, rating: 4) else { fatalError("Unable to instantiate meal1") } guard let secondMeal = Meal(name: "Chicken and Potatoes", photo: photo2, rating: 5) else { fatalError("Unable to instantiate meal2") } guard let lastMeal = Meal(name: "Pasta with Meatballs", photo: photo3, rating: 3) else { fatalError("Unable to instantiate meal3") } meals.append(contentsOf: [firstMeal, secondMeal, lastMeal]) } }
true
faae8e94553d245823b86fbfd8132480ccdd4826
Swift
avdyushin/Injected
/Sources/Injected/Injected.swift
UTF-8
3,052
3.203125
3
[]
no_license
// // Injected.swift // Injected // // Created by Grigory Avdyushin on 14/05/2020. // Copyright © 2020 Grigory Avdyushin. All rights reserved. // import Foundation public struct Dependency { public typealias ResolveBlock<T> = () -> T fileprivate(set) var value: Any! fileprivate let block: ResolveBlock<Any> fileprivate let name: String public init<T>(_ block: @escaping ResolveBlock<T>) { self.block = block self.name = String(describing: T.self) } mutating func resolve() { value = block() } } @dynamicMemberLookup open class Dependencies: Sequence { static private(set) public var shared = Dependencies() fileprivate var dependencies = [Dependency]() @_functionBuilder public struct DependencyBuilder { public static func buildBlock(_ dependency: Dependency) -> Dependency { dependency } public static func buildBlock(_ dependencies: Dependency...) -> [Dependency] { dependencies } } public init(@DependencyBuilder _ dependencies: () -> [Dependency]) { dependencies().forEach { register($0) } } public init(@DependencyBuilder _ dependency: () -> Dependency) { register(dependency()) } /// Builds (resolves) all dependencies graph open func build() { // We assuming that at this point all needed dependencies are registered for index in dependencies.startIndex..<dependencies.endIndex { dependencies[index].resolve() } Self.shared = self } /// Returns iterator for all registered dependencies public func makeIterator() -> AnyIterator<Any> { var iter = dependencies.makeIterator() return AnyIterator { iter.next()?.value } } /// Returns dependency by given camelCase name of the object type /// For example: if dependency registered as `MyService` name should be `myService` public subscript<T>(dynamicMember name: String) -> T? { dependencies.first { $0.name == name.prefix(1).capitalized + name.dropFirst() }?.value as? T } /// Returns resolved dependency public func resolve<T>() -> T { guard let dependency = dependencies.first(where: { $0.value is T })?.value as? T else { fatalError("Can't resolve \(T.self)") } return dependency } // MARK: - Private fileprivate init() { } fileprivate func register(_ dependency: Dependency) { // Avoid duplicates guard dependencies.firstIndex(where: { $0.name == dependency.name }) == nil else { debugPrint("\(String(describing: dependency.name)) already registered, ignoring") return } dependencies.append(dependency) } } @propertyWrapper public class Injected<Dependency> { private var dependency: Dependency! public var wrappedValue: Dependency { if dependency == nil { let copy: Dependency = Dependencies.shared.resolve() self.dependency = copy } return dependency } public init() { } }
true
0f0962aa990d352db6e77f95d855ecaf5b8aeaaa
Swift
adachmielewska/MyFlickrGallery
/MyFlickrGallery/Modules/Gallery/Details/DetailsGalleryViewController.swift
UTF-8
3,974
2.71875
3
[]
no_license
// // DetailsGalleryViewController.swift // MyFlickrGallery // // Created by Ada Chmielewska on 24.09.2017. // Copyright © 2017 Ada Chmielewska. All rights reserved. // import UIKit import SDWebImage enum DetailsGallerySections: Int { case title = 0, author, tags, dates func sectionTitle() -> String { switch self { case .title: return "TITLE" case .author: return "AUTHOR" case .tags: return "TAGS" case .dates: return "DATES" } } func data(galleryCellModel: GalleryCellViewModel) -> [String] { switch self { case .title: return [galleryCellModel.title] case .author: return [galleryCellModel.author] case .tags: return [galleryCellModel.tags] case .dates: return [galleryCellModel.takenAt, galleryCellModel.publishedAt] } } func numberOfRows() -> Int { switch self { case .dates: return 2 default: return 1 } } } class DetailsGalleryViewController: UIViewController { private let textCellIdentifier = "DetailsGalleryTextCell" private let sectionCellIdentifier = "DetailsGallerySectionCell" @IBOutlet private weak var tableView: UITableView! { didSet { tableView.register(UINib(nibName: textCellIdentifier, bundle: nil), forCellReuseIdentifier: textCellIdentifier) tableView.register(UINib(nibName: sectionCellIdentifier, bundle: nil), forCellReuseIdentifier: sectionCellIdentifier) tableView.allowsSelection = false tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none } } @IBOutlet private weak var photoView: UIImageView! let viewModel: GalleryCellViewModel init(viewModel: GalleryCellViewModel) { self.viewModel = viewModel super.init(nibName: "DetailsGalleryViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { photoView.sd_setShowActivityIndicatorView(true) photoView.sd_setIndicatorStyle(.gray) photoView.sd_setImage(with: viewModel.imageURL, placeholderImage: nil) } } extension DetailsGalleryViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return DetailsGallerySections.dates.rawValue + 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let rows = DetailsGallerySections.init(rawValue: section)?.numberOfRows() else { return 1 } return rows } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: textCellIdentifier, for: indexPath) as? DetailsGalleryTextCell else { return UITableViewCell() } guard let title = DetailsGallerySections.init(rawValue: indexPath.section)?.data(galleryCellModel: viewModel)[indexPath.row] else { return UITableViewCell() } cell.configure(title: title) return cell } } extension DetailsGalleryViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let cell = tableView.dequeueReusableCell(withIdentifier: sectionCellIdentifier) as? DetailsGallerySectionCell else { return nil } guard let title = DetailsGallerySections.init(rawValue: section)?.sectionTitle() else { return nil } cell.configure(title: title) return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 20 } }
true
5f8d0f30d553494b5a1be8c61fb121dbbcdef586
Swift
your-friend-jimmy/instagramClone
/DogGram/DogGram/Views/Subviews/PostView.swift
UTF-8
3,089
3.0625
3
[]
no_license
// // PostView.swift // DogGram // // Created by James Phillips on 9/25/21. // import SwiftUI struct PostView: View { @State var post: PostModel var showHeaderAndFooter: Bool var body: some View { VStack(alignment: .center, spacing: 0, content: { //MARK: - Header if showHeaderAndFooter { HStack { NavigationLink(destination: ProfileView(isMyProfile: false, profileDisplayName: post.username, profileUserID: post.userID)) { Image("dog1") .resizable() .scaledToFill() .frame(width: 30, height: 30, alignment: .center) .cornerRadius(15) Text(post.username) .font(.callout) .fontWeight(.medium) .foregroundColor(.primary) } Spacer() Image(systemName: "ellipsis") .font(.headline) } .padding(.all,6) } //MARK: - Image Image("dog1") .resizable() .scaledToFit() //MARK: - Footer if showHeaderAndFooter{ HStack(alignment: .center, spacing: 20) { Image(systemName: "heart") //MARK: - Comment Icon NavigationLink(destination: CommentsView()) { Image(systemName: "bubble.middle.bottom") .font(.title3) .foregroundColor(.primary) } Image(systemName: "paperplane") Spacer() } .font(.title3) .padding(.all, 6) if let caption = post.caption { HStack { Text(caption) Spacer(minLength: 0) } .padding(.all, 6) } } }) } } struct PostView_Previews: PreviewProvider { static var post: PostModel = PostModel(postID: "", userID: "", username: "Joe Green", caption: "This is a test caption", dateCreate: Date(), likeCount: 0, likedByUser: false) static var previews: some View { PostView(post: post, showHeaderAndFooter: true) .previewLayout(.sizeThatFits) } }
true
5b8ee5fc0539de6bb6eeaa283879b2d80da37ecf
Swift
afernandez-atsistemas/Formacion-iOS-at-sistemas
/Proyecto 4/Final-UITextField/CursoiOSProyecto4/Modules/MenuTabBar/MenuTabBarBuilder.swift
UTF-8
990
2.53125
3
[]
no_license
// // MenuTabBarBuilder.swift // CursoiOSProyecto4 // // Created by Abrahán Fernández on 1/3/21. // Copyright © 2021 ___ORGANIZATIONNAME___. All rights reserved. // // import UIKit class MenuTabBarBuilder { static func build() -> MenuTabBarView { let view = MenuTabBarView.init(nibName: String(describing: MenuTabBarView.self), bundle: nil) return view } static func setupPresenter(view: MenuTabBarViewContract) { let presenter = MenuTabBarPresenter() let entity = MenuTabBarEntity() let wireframe = MenuTabBarWireframe() let interactor = MenuTabBarInteractor() view.presenter = presenter view.presenter?.view = view view.presenter?.entity = entity view.presenter?.interactor = interactor view.presenter?.interactor.output = presenter view.presenter?.wireframe = wireframe view.presenter?.wireframe.output = presenter view.presenter?.wireframe.view = view } }
true
a02a5603a55bd966872f3d50a7a20ba13cf2813a
Swift
g0tcha/bookmarks
/SayCheese/SignUpViewController.swift
UTF-8
2,983
2.65625
3
[]
no_license
// // SignUpViewController.swift // SayCheese // // Created by vincent on 02/12/2016. // Copyright © 2016 kodappy. All rights reserved. // import UIKit class SignUpViewController: UIViewController { // MARK: - IBOutlets @IBOutlet weak var fullNameField: MainTextField! @IBOutlet weak var userNameField: MainTextField! @IBOutlet weak var emailField: MainTextField! @IBOutlet weak var passwordField: MainTextField! override func viewDidLoad() { super.viewDidLoad() fullNameField.delegate = self userNameField.delegate = self emailField.delegate = self passwordField.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - Helpers Methods private extension SignUpViewController { func signUp() { if let fullName = fullNameField.text, let userName = userNameField.text, let email = emailField.text, let password = passwordField.text { if !(fullName.isEmpty && userName.isEmpty && email.isEmpty && password.isEmpty) { // TODO - Try to create account let ws = WebService() ws.createUser(fullName: fullName, userName: userName, email: email, password: password, completionHandler: { (success, error) in if let error = error { DispatchQueue.main.sync { self.displaySimpleAlert(withTitle: NSLocalizedString("error_title", comment: "Error Title Alert"), andMessage: error.message(), withCompletionHandler: { self.fullNameField.becomeFirstResponder() }) } return } if success { DispatchQueue.main.sync { self.resetFields() self.performSegue(withIdentifier: Segue.loggedIn, sender: self) } } }) } } } func resetFields() { fullNameField.text = "" userNameField.text = "" emailField.text = "" passwordField.text = "" } } // MARK: - IBActions extension SignUpViewController { @IBAction func signUp(sender: LoginButton) { signUp() } } // MARK: - UITextFieldDelegate extension SignUpViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == fullNameField { userNameField.becomeFirstResponder() } else if textField == userNameField { emailField.becomeFirstResponder() } else if textField == emailField { passwordField.becomeFirstResponder() } else if textField == passwordField { signUp() } return true } }
true
8cb452082977b5fd9aa6cf9e26f93246e0849ac8
Swift
SanoHiroshi/InstagramApp
/Instagram/ViewController.swift
UTF-8
1,621
2.71875
3
[]
no_license
// // ViewController.swift // Instagram // // Created by hiro on 2016/10/11. // Copyright © 2016年 hiro. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var post = Post.allPosts override func viewDidLoad() { super.viewDidLoad() tableView.estimatedRowHeight = 300 tableView.rowHeight = UITableViewAutomaticDimension navigationController?.navigationBar.tintColor = .white navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] navigationController?.navigationBar.barTintColor = .blue title = "Instagram" let nib = UINib(nibName: "PostTableViewCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "postCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return post.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell cell.post = post[indexPath.row] return cell } }
true
aa37140c62447904ef2e60e5d5e9673ca682a8af
Swift
pablodelarosam/bondzuv3
/bondzuios/Camera.swift
UTF-8
1,476
2.859375
3
[]
no_license
// // Camera.swift // bondzuios // // Created by Luis Mariano Arobes on 12/08/15. // Copyright (c) 2015 Bondzu. All rights reserved. // Archivo Localizado import Foundation import Parse class Camera { var objectId: String!; var descripcion: String!; var animalId: String!; var animalName: String!; var funcionando: Bool!; var url: NSURL?; @available(*, deprecated=9.0, message="Please use the new object constructor!") init(_obj_id: String!, _description: String!, _animalId: String!, _type: Int!, _animalName: String!, _funcionando: Bool!, _url: String?) { self.objectId = _obj_id; self.descripcion = _description; self.animalId = _animalId; self.animalName = _animalName; self.funcionando = _funcionando; if let url = _url as String! { self.url = NSURL(string: url); }else{ self.url = nil } } init(object : PFObject){ self.objectId = object.objectId! self.descripcion = object[TableCameraColumnNames.Description.rawValue] as! String self.animalId = (object[TableCameraColumnNames.Animal.rawValue] as! PFObject).objectId! self.animalName = object[TableCameraColumnNames.AnimalName.rawValue] as! String self.funcionando = object[TableCameraColumnNames.Working.rawValue] as! Bool self.url = NSURL(string: object[TableCameraColumnNames.PlayBackURL.rawValue] as! String) } }
true
a50e5b891eed83e54db6a775c235ea806095cab4
Swift
shwetashahj/iOS
/EventOrganiser/EventOrganiser/Model/EventModel.swift
UTF-8
2,882
3.265625
3
[]
no_license
// // eventModel.swift // EventOrganiser // // Created by shweta shah on 10/10/18. // Copyright © 2018 shweta shah. All rights reserved. // import Foundation enum ScheduledType { case notAttending case attending case invited case none } enum EventType { case scheduled case imported case holiday case none } struct EventModel { var title : String = "" var eventType : EventType = .none var status : ScheduledType = .none var location : String = "" var clientName : String = "" var groupName : String = "" var epochDate : Int = 0 var eventDate : Date? var sectionDate : Date? init() {} init( params : [String : Any]) { if let title = params["title"] as? String { self.title = title } if let location = params["location"] as? String { self.location = location } if let groupName = params["groupName"] as? String { self.groupName = groupName } if let clientName = params["clientName"] as? String { self.clientName = clientName } if let status = params["status"] as? Int { self.status = getStatusType(status: status) } if let type = params["type"] as? String { self.eventType = getEventType(type: type) } if let epochDate = params["datetime"] as? Int { self.epochDate = epochDate self.eventDate = Date(timeIntervalSince1970: Double(epochDate)/1000) if let eventDate = self.eventDate { self.sectionDate = self.getSectionDate(eventDate: eventDate) } } } } extension EventModel { func getStatusType(status : Int) -> ScheduledType { switch status { case 0: return .notAttending case 1: return .attending case 2: return .invited default: return .none } } func getEventType(type : String) -> EventType { switch type.lowercased() { case "scheduled": return .scheduled case "holiday": return .holiday case "imported": return .imported default: return .none } } /// Returns the date object by removing the time func getSectionDate(eventDate : Date) -> Date? { var calendars = Calendar(identifier: .gregorian) calendars.timeZone = TimeZone(identifier: "UTC")! let components = calendars.dateComponents([.day, .month, .year], from: eventDate) return calendars.date(from: components) // //let pdate = calendars.date(byAdding: Calendar.Component.day, value: 1, to: newdate) // } }
true
662be7da5f39dbcfc36ac5cb106df9ee716f0b66
Swift
YerlanTemirbolat/Push_Present
/Push_Present/PushViewController.swift
UTF-8
1,320
2.890625
3
[]
no_license
// // PushViewController.swift // Push_Present // // Created by Admin on 3/17/21. // import UIKit class PushViewController: UIViewController { private var button = UIButton() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title = "Push" // navigationController?.popViewController(animated: true) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("Press the button", for: .normal) button.setTitleColor(.white, for: .normal) button.backgroundColor = .gray button.layer.cornerRadius = 5 button.addTarget(self, action: #selector(pressedButton), for: .touchUpInside) view.addSubview(button) constraints() } @objc func pressedButton() { let vc = ThirdViewController() navigationController?.pushViewController(vc, animated: true) } func constraints() { NSLayoutConstraint.activate([ button.centerXAnchor.constraint(equalTo: view.centerXAnchor), button.centerYAnchor.constraint(equalTo: view.centerYAnchor), button.widthAnchor.constraint(equalToConstant: 200), button.heightAnchor.constraint(equalToConstant: 50) ]) } }
true
8f85acdaffbe3482fd2b5059229c3db59c08bc3a
Swift
abymathew0485/classic-problem-solving-algorithms-and-data-structures-in-swift
/DataStructure/LinkedList/SinglyLinkedList/LinkQueue.swift
UTF-8
402
3.03125
3
[ "Apache-2.0" ]
permissive
//Link Queue //by Sayed Mahmudul Alam //TO DO: import DoubleEndedLinkedList.swift public class LinkQueue { private var list: DoubleEndedLinkedList? init() { list = DoubleEndedLinkedList() } func enqueue(data: Int) { list!.inserLast(data: data) } func dequeue() { list!.deleteFirst() } func isEmpty() -> Bool{ return (list!.isEmpty()) } func displayQueue() { list!.displayList() } }
true
e7d7b79aae3c317905905fec344d2c0c0423655a
Swift
ihValery/CombineFirebase
/CombineFirebase/View/ContentView.swift
UTF-8
3,780
3.1875
3
[]
no_license
// // ContentView.swift // CombineFirebase // // Created by Валерий Игнатьев on 29.05.21. // import SwiftUI struct ContentView: View { @ObservedObject private var signViewModel = SignViewModel.shared @State private var signInSelected = false @State private var presentAlert = false var body: some View { ZStack { LinearGradient(gradient: Gradient(colors: [.orangeGradientStart, .orangeGradientEnd]), startPoint: .topLeading, endPoint: .bottomTrailing) .ignoresSafeArea() BackgroundAnimation() .drawingGroup() .ignoresSafeArea() VStack { HStack(spacing: 1) { SignSelectButton(text: "Вход") .opacity(!signInSelected ? 1 : 0.4) .onTapGesture { signInSelected = false } SignSelectButton(text: "Регистрация") .opacity(signInSelected ? 1 : 0.4) .onTapGesture { signInSelected = true } } GeometryReader { gr in VStack { BackgroundCard(height: 320) .overlay(AnketaSignUp().padding()) .offset(y: gr.size.height / 4.5) .offset(x: signInSelected ? 0 : gr.size.width + 50) Button(self.signViewModel.isValidSignUp ? "Зарегистрироваться" : "Заполните все поля") { signUp() print("--------Зарегистрироваться--------") } .buttonStyle(SignStyleButton(colorBG: .white, colorText: signViewModel.isValidSignUp ? .orangeGradientEnd : .gray)) .offset(y: signInSelected ? 230 : gr.size.height + 50) .disabled(!signViewModel.isValidSignUp) } VStack { BackgroundCard(height: 190) .overlay(AnketaSignIn().padding().padding(.bottom, -20)) .offset(y: gr.size.height / 3.5) .offset(x: !signInSelected ? 0 : -gr.size.width - 50) Button(signViewModel.isValidSignIn ? "Войти" : "Заполните все поля") { signUp() print("--------Войти--------") } .buttonStyle(SignStyleButton(colorBG: .white, colorText: signViewModel.isValidSignIn ? .orangeGradientEnd : .gray)) .offset(y: !signInSelected ? 340 : gr.size.height + 150) .disabled(!signViewModel.isValidSignIn) } } .animation(.easeInOut) } } .sheet(isPresented: $presentAlert, content: { WelcomView() }) } func signUp() { presentAlert = true } } struct WelcomView: View { var body: some View { ZStack { Color.green.ignoresSafeArea() Text("Welcom! Greate to have you on board!") .font(.largeTitle) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
true
71253257b456515192dd30f3e854b78fd4af9881
Swift
analitk9/Note_yandex_course
/Note_yandex/Operation/BackendOpertations/SaveNotesBackendOperation.swift
UTF-8
1,107
2.828125
3
[]
no_license
import Foundation enum NetworkError { case unreachable } enum SaveNotesBackendResult { case success(FileNotebook) case failure(NetworkError) } class SaveNotesBackendOperation: BaseBackendOperation { var result: SaveNotesBackendResult? var gistService = GistService() let notebook: FileNotebook init(notebook: FileNotebook) { self.notebook = notebook super.init() } override func main() { // todo сделать окончание операции только после завершения записи на сервер let postGist = gistService.createGist(notebook: notebook) // print("создали гист для записи в бэк \(postGist)") let url = KeychainWrapper.standard.string(forKey: "url") let res = gistService.post(gist: postGist!, by: url) // print("сделали запись на сервер статус \(res)") if res { result = .success(notebook) }else { result = .failure(.unreachable) } finish() } }
true
31b354231947fcae2ad507c38cd9705ce0ffd185
Swift
JsouLiang/Swift3.0-WeiBo
/Swift3.0-WeiBo/Class/Model(模型)/WB_Status.swift
UTF-8
786
2.546875
3
[]
no_license
// // WB_Status.swift // Swift3.0-WeiBo // // Created by X-Liang on 2016/11/6. // Copyright © 2016年 X-Liang. All rights reserved. // import UIKit import YYModel /// 微博数据模型 class WB_Status: NSObject { /// Int 类型,在 64 位的机器是 64 位,在 32 位机器就是 32 位 /// 如果不写 Int64 在 iPad 2/iPhone 5/5c/4s/4 都无法正常运行 var id: Int64 = 0 /// 微博信息内容 var text: String? /// 微博的用户 var user: WB_User? /// 转发数 var reposts_count: Int = 0 /// 评论数 var comments_count: Int = 0 /// 点赞数 var attitudes_count: Int = 0 /// 重写description的计算型属性 override var description: String { return yy_modelDescription() } }
true
f56c1aef3cc13846c662c2db9c3d28a7a3fb4c17
Swift
seldon1000/Pic-A-Word
/Test1 iOS/SelectWord.swift
UTF-8
1,759
2.90625
3
[ "Apache-2.0" ]
permissive
// // SelectWord.swift // Test1 iOS // // Created by Nicolas Mariniello on 16/07/2020. // import SpriteKit import MultipeerConnectivity class SelectWord: SKScene, MPCManagerDelegate { private var mpcManager = MPCManager.sharedInstance var words = [String]() private var word1 = SKLabelNode() private var word2 = SKLabelNode() private var word3 = SKLabelNode() func connectedDevicesChanged(manager: MPCManager, connectedDevices: [MCPeerID]) { } func receivedData(data: String, fromPeer: MCPeerID) { } func selectWord(word: String) { mpcManager.sendData(text: word, peer: [mpcManager.getConnectedPeers().first!]) let whiteboard = Whiteboard(fileNamed: "Whiteboard") whiteboard?.scaleMode = .aspectFit self.view?.presentScene(whiteboard!) } override func didMove(to view: SKView) { backgroundColor = .white mpcManager.delegate = self word1 = childNode(withName: "word1") as! SKLabelNode word2 = childNode(withName: "word2") as! SKLabelNode word3 = childNode(withName: "word3") as! SKLabelNode word1.text = words[0] word2.text = words[1] word3.text = words[2] } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) let location = touches.first?.location(in: self) if word1.contains(location!){ selectWord(word: word1.text!) } else if word2.contains(location!) { selectWord(word: word2.text!) } else if word3.contains(location!) { selectWord(word: word3.text!) } } }
true
8a95515c1462e0bdd74f9f9737ef76a9ead6a38d
Swift
cameronklein/Class-Roster-2.0
/Class Roster/AddPersonViewController.swift
UTF-8
2,798
2.75
3
[]
no_license
// // AddPersonViewController.swift // Person Array iOS // // Created by Cameron Klein on 8/14/14. // Copyright (c) 2014 Cameron Klein. All rights reserved. // import UIKit class AddPersonViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate { var firstName : String? var lastName : String? var position : String = "Student" @IBOutlet weak var firstNameField: UITextField! @IBOutlet weak var lastNameField: UITextField! @IBOutlet weak var positionPicker: UIPickerView! //MARK: - Override Functions override func viewDidLoad() { super.viewDidLoad() self.positionPicker.dataSource = self self.positionPicker.delegate = self self.firstNameField.delegate = self self.lastNameField.delegate = self } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { firstName = firstNameField.text lastName = lastNameField.text } //MARK: UIPickerViewDataSource/Delegate func numberOfComponentsInPickerView(pickerView: UIPickerView!) -> Int { return 1 } func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int { return 2 } func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! { switch row{ case 0: return "Student" case 1: return "Teacher" default: return "" } } func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { switch row{ case 0: position = "Student" case 1: position = "Teacher" default: position = "Student" } } //MARK: UITextFieldDelegate func textFieldShouldReturn(textField: UITextField!) -> Bool { println("should return") if textField == firstNameField{ lastNameField.becomeFirstResponder() } else{ textField.resignFirstResponder() } return true } //MARK: Other override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { if firstNameField.isFirstResponder(){ firstNameField.resignFirstResponder() } else if lastNameField.isFirstResponder(){ lastNameField.resignFirstResponder() } } }
true
f319ce1ec27ff1d217f65c76bfe213d546c1a320
Swift
ajunlonglive/Milestones
/MilestonesCore/State/Milestone.swift
UTF-8
1,033
3.3125
3
[ "MIT" ]
permissive
import ComposableArchitecture import Foundation // MARK: - State struct Milestone: Codable, Hashable, Identifiable, Comparable { let id: UUID let calendar: Calendar var title: String var today: Date var date: Date var isEditing: Bool static func < (lhs: Milestone, rhs: Milestone) -> Bool { (lhs.date, lhs.title) < (rhs.date, rhs.title) } } // MARK: - Action enum MilestoneAction: Equatable { case delete case setIsEditing(Bool) case setTitle(String) case setDate(Date) } // MARK: - Environment struct MilestoneEnvironment {} // MARK: - Reducer let milestoneReducer = Reducer<Milestone, MilestoneAction, MilestoneEnvironment> { state, action, _ in switch action { case .delete: return .none case .setIsEditing(let isEditing): state.isEditing = isEditing return .none case .setTitle(let title): state.title = title return .none case .setDate(let date): state.date = date return .none } }
true
1093a59f6519003772429a81319f16c0ac13c3ab
Swift
magic-IOS/leetcode-swift
/0220. Contains Duplicate III.swift
UTF-8
2,104
3.640625
4
[ "Apache-2.0" ]
permissive
class Solution { // 220. Contains Duplicate III // Given an integer array nums and two integers k and t, return true if there are two distinct indices i and j in the array such that abs(nums[i] - nums[j]) <= t and abs(i - j) <= k. // Finds out whether there are two distinct indices i and j in the array such that the // absolute difference between nums[i] and nums[j] is at most t and the absolute // difference between i and j is at most k. // - Parameters: // - nums: An array of integers. // - k: The absolute difference between the two indices. // - t: The absolute difference between the two numbers. // - Returns: True if there are two different eligible indexes, otherwise it returns false. // Example 1: // Input: nums = [1,2,3,1], k = 3, t = 0 // Output: true // Example 2: // Input: nums = [1,0,1,1], k = 1, t = 2 // Output: true // Example 3: // Input: nums = [1,5,9,1,5,9], k = 2, t = 3 // Output: false // Constraints: // 0 <= nums.length <= 2 * 10^4 // -2^31 <= nums[i] <= 2^31 - 1 // 0 <= k <= 10^4 // 0 <= t <= 2^31 - 1 // - Complexity: // - time: O(n), where n is the length of the nums. // - space: O(min(n, k)), where n is the length of the nums, and k is the absolute difference between the two indices. func containsNearbyAlmostDuplicate(_ nums: [Int], _ k: Int, _ t: Int) -> Bool { guard k > 0, t >= 0 else { return false } var dict = [Int: Int]() let w = t + 1 for i in 0..<nums.count { let m = getID(nums[i], w) guard dict[m] == nil else { return true } if let num = dict[m - 1], abs(nums[i] - num) < w { return true } if let num = dict[m + 1], abs(nums[i] - num) < w { return true } dict[m] = nums[i] guard i >= k else { continue } dict.removeValue(forKey: getID(nums[i - k], w)) } return false } private func getID(_ x: Int, _ w: Int) -> Int { return x < 0 ? ((x + 1) / w) - 1 : x / w } }
true
48e81d7d183ccc349a734cfab2ed98c655575860
Swift
RaviDesai/CodeMash2016
/CodeMash2016Tests/TestModelEmailAddress.swift
UTF-8
2,878
2.796875
3
[]
no_license
// // TestModelEmailAddress.swift // CodeMash2016 // // Created by Ravi Desai on 12/19/15. // Copyright © 2015 RSD. All rights reserved. // import UIKit import XCTest import RSDSerialization @testable import CodeMash2016 class TestEmailAddress: XCTestCase { func testSerializeAndDeserialize() { let addr = EmailAddress(user: "ravi", host: "desai.com") let json = addr.convertToJSON() XCTAssert(json.count == 2) let newAddr = EmailAddress.createFromJSON(json) XCTAssertTrue(newAddr != nil) XCTAssertTrue(addr == newAddr!) } func testConvertToEmailAddressSuccess() { let string = "[email protected]" let addr = EmailAddress(string: string) XCTAssertTrue(addr != nil) XCTAssertTrue(addr! == EmailAddress(user: "ravi", host: "desai.com")) } func testConvertToEmailAddressFailure() { let string = "@desai.com" let addr = EmailAddress(string: string) XCTAssertTrue(addr == nil) } func testCollapsedEmailAddressString() { let result1 = EmailAddress.getCollapsedDisplayText([EmailAddress(user: "ravi", host: "desai.com")]) XCTAssertTrue(result1 == "[email protected]") let result2 = EmailAddress.getCollapsedDisplayText([EmailAddress(user: "ravi", host: "desai.com"), EmailAddress(user: "bonnie", host: "desai.com")]) XCTAssertTrue(result2 == "[email protected] and one other") let result3 = EmailAddress.getCollapsedDisplayText([EmailAddress(user: "ravi", host: "desai.com"), EmailAddress(user: "bonnie", host: "desai.com"), EmailAddress(user: "children", host: "desai.com")]) XCTAssertTrue(result3 == "[email protected] and 2 others") } func testSortingByHostThenUser() { let addresses = [ EmailAddress(user: "martin", host: "clunes.com"), EmailAddress(user: "walker", host: "desai.com"), EmailAddress(user: "eric", host: "idle.com"), EmailAddress(user: "alexander", host: "desai.com"), EmailAddress(user: "emerson", host: "desai.com"), EmailAddress(user: "john", host: "cleese.com") ] let sortedAddresses = [ EmailAddress(user: "john", host: "cleese.com"), EmailAddress(user: "martin", host: "clunes.com"), EmailAddress(user: "alexander", host: "desai.com"), EmailAddress(user: "emerson", host: "desai.com"), EmailAddress(user: "walker", host: "desai.com"), EmailAddress(user: "eric", host: "idle.com") ] XCTAssertTrue(addresses.sort(<) == sortedAddresses) } func testDescription() { let address = EmailAddress(user: "my.name", host: "my.cool.host.com") XCTAssertTrue(address.description == "[email protected]") XCTAssertTrue("\(address)" == "[email protected]") } }
true
24baba4b28a4b8ca3d2c1e762a89da8385dbca17
Swift
t3ndai/Zoo
/Sources/App/main.swift
UTF-8
2,053
2.5625
3
[ "MIT" ]
permissive
import Vapor import VaporSQLite let drop = Droplet() try drop.addProvider(VaporSQLite.Provider.self) let zookeepers = ZooController() let animals = AnimalController() let foods = FoodController() drop.preparations.append(Animal.self) drop.preparations.append(Zookeeper.self) drop.preparations.append(Food.self) drop.preparations.append(Exhibit.self) drop.get { req in return try drop.view.make("welcome", [ "message": drop.localization[req.lang, "welcome", "title"] ]) } drop.get("db") { request in //let result = try drop.database?.driver.raw("SELECT sqlite_version()") let result = try drop.database?.driver.raw("select sqlite_version()") return try JSON(node: result) } drop.get("animals", Animal.self) { request, animal in return animal.name } drop.get("animals", "search", ":animalName") { request in guard let animalName = request.parameters["animalName"]?.string else { throw Abort.custom(status: .preconditionFailed, message: "include animal name") } let animalQuery = try Animal.query().filter("name", animalName) return try JSON(node: Animal.query().filter("name", animalName).all().makeNode()) } drop.get("zookeepers", "search", ":lastName") { request in guard let lastName = request.parameters["lastName"]?.string else { throw Abort.badRequest } return try JSON(node: Zookeeper.query().filter("lastName", lastName).all().makeNode()) } drop.get("foods", "search", ":name") { request in guard let name = request.parameters["name"]?.string else { throw Abort.badRequest } return try JSON(node: Food.query().filter("foodName", name).all().makeNode()) } drop.get("foods", "type", ":type") { request in guard let type = request.parameters["type"]?.string else { throw Abort.badRequest } return try JSON(node: Food.query().filter("foodType", type).all().makeNode()) } drop.resource("animals", animals) drop.resource("zookeepers", zookeepers) drop.resource("foods", foods) drop.run()
true
54c2b3b09270b8a1b9e79fd84821a9eabeb82e70
Swift
BrianSadler/TaskManager-iOS
/TaskManageriOS/Storyboard/View Controllers/LoginViewController.swift
UTF-8
2,032
2.703125
3
[]
no_license
// // ViewController.swift // TaskManageriOS // // Created by Brian Sadler on 11/1/18. // Copyright © 2018 Brian Sadler. All rights reserved. // import UIKit class ViewController: UIViewController { //Outlets @IBOutlet weak var userNameTextBox: UITextField! @IBOutlet weak var passwordTextBox: UITextField! //Alerts func showIncorrectUserAlerts() { let userError = UIAlertController(title: "Incorrect Username", message: "Username is not recognized. Please try again or create an account", preferredStyle: .alert) let okAction = UIAlertAction(title: "Okay", style: .default, handler: nil) userError.addAction(okAction) self.present(userError, animated: true, completion: nil) } func showIncorrectPassAlert() { let passError = UIAlertController(title: "Incorrect Password", message: "Password is not recognized. Please try again or create a new account", preferredStyle: .alert) let okAction = UIAlertAction(title: "Okay", style: .default, handler: nil) passError.addAction(okAction) self.present(passError, animated: true, completion: nil) } @IBAction func signInButtonTapped(_ sender: Any) { let userName = userNameTextBox.text let password = passwordTextBox.text let userNameStored = UserDefaults.standard.string(forKey: "userName") let passwordStored = UserDefaults.standard.string(forKey: "password") if userName == userNameStored { if password == passwordStored { self.performSegue(withIdentifier: "TasksListSegue", sender: self) } else{ print("bad password") showIncorrectPassAlert() } } else { print("bad username") showIncorrectUserAlerts() } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } }
true
ec3018bd251d7ebb937fbaa50dd1b2d742de57d2
Swift
the-new-developers/tnd-schedule-poster
/tnd-schedule-poster-fall-2019.playground/Contents.swift
UTF-8
2,367
3.515625
4
[ "MIT" ]
permissive
import UIKit public class Event { let title: String let date: String? let location: String? let eventType: EventType enum EventType: String { case social = "Social Event" case community = "Community Event" case workshop = "Workshop" case panel = "Panel" case presentation = "Presentation" } init(title: String, date: String? = "TBA", location: String? = "TBA", eventType: EventType) { self.title = title self.date = date self.location = location self.eventType = eventType } } public class Schedule { let semester: String let schedule: [Event] let isInterested: Bool = true init() { semester = "Winter 2020" schedule = [ Event(title: "CSAIT IRL: A Social Event.", date: "Wednesday February 5, 6pm - 10pm", location: "Fennell Campus, The Cellar (back of The Arnie)", eventType: .social), Event(title: "The New Developers s02e01: Freelancing", date: "February TBA", // location: "Fennell Campus, TBA", eventType: .presentation), Event(title: "The New Developers s02e02: The Code Review", date: "March TBA", // location: "Fennell Campus, TBA", eventType: .workshop) ] for event in schedule { // if event details are unknown or you're interested to learn more... if event.date == "TBA" || event.location == "TBA" || self.isInterested { self.goToWebsite() // TODO: Visit us at // https://thenewdevelopers.com // Sign up for curated content straight to your inbox, // register for upcoming events, // meet cool people, build cool stuff. } } } func goToWebsite() { if let url = URL(string: "https://www.thenewdevelopers.com") { UIApplication.shared.open(url) } } } var schedule = Schedule() for event in schedule.schedule { print(event.title) print(event.date?.description) print(event.location?.description) print(event.eventType.rawValue) }
true
66a8ebecf1004381d864594e2a3cafe3e36578ee
Swift
Jimsane/swift-proposal-analyzer
/swift-proposal-analyzer.playground/Pages/SE-0171.xcplaygroundpage/Contents.swift
UTF-8
4,535
3.65625
4
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/*: # Reduce with `inout` * Proposal: [SE-0171](0171-reduce-with-inout.md) * Author: [Chris Eidhof](https://github.com/chriseidhof) * Review Manager: [Ben Cohen](https://github.com/airspeedswift) * Status: **Implemented (Swift 4)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170424/036126.html) ## Introduction A new variant of `reduce` should be added to the standard library. Instead of taking a `combine` function that is of type `(A, Iterator.Element) -> A`, the full type and implementation of the added `reduce` will be: ```swift extension Sequence { func reduce<A>(into initial: A, _ combine: (inout A, Iterator.Element) -> ()) -> A { var result = initial for element in self { combine(&result, element) } return result } } ``` Swift-evolution thread: [Reduce with inout](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170116/030300.html) ## Motivation The current version of `reduce` needs to make copies of the result type for each element in the sequence. The proposed version can eliminate the need to make copies (when the `inout` is optimized away). ## Proposed solution The first benefit of the proposed solution is efficiency. The new version of `reduce` can be used to write efficient implementations of methods that work on `Sequence`. For example, consider an implementation of `uniq`, which filters adjacent equal entries: ```swift extension Sequence where Iterator.Element: Equatable { func uniq() -> [Iterator.Element] { return reduce(into: []) { (result: inout [Iterator.Element], element) in if result.last != element { result.append(element) } } } } ``` In the code above, the optimizer will usually optimize the `inout` array into an `UnsafeMutablePointer`, or when inlined, into a simple mutable variable. With that optimization, the complexity of the algorithm is `O(n)`. The same algorithm, but implemented using the existing variant of reduce, will be `O(n²)`, because instead of `append`, it copies the existing array in the expression `result + [element]`: ```swift extension Sequence where Iterator.Element: Equatable { func uniq() -> [Iterator.Element] { return reduce([]) { (result: [Iterator.Element], element) in guard result.last != element else { return result } return result + [element] } } } ``` The second benefit is that the new version of `reduce` is more natural when dealing with `mutating` methods. For example, consider a function that computes frequencies in a `Sequence`: ```swift extension Sequence where Iterator.Element: Hashable { func frequencies() -> [Iterator.Element: Int] { return reduce(into: [:]) { (result: inout [Iterator.Element:Int], element) in if let value = result[element] { result[element] = value + 1 } else { result[element] = 1 } } } } ``` Without the `inout` parameter, we'd first have to make a `var` copy of the existing result, and have to remember to return that copy instead of the `result`. (The method above is probably clearer when written with a `for`-loop, but that's not the point). ## Source compatibility This is purely additive, we don't propose removing the existing `reduce`. Additionaly, because the first argument will have a label `into`, it doesn't add any extra burden to the type checker. ## Effect on ABI stability N/A ## Effect on API resilience N/A ## Alternatives considered We considered removing the existing `reduce`, but the problem with that is two-fold. First, removing it breaks existing code. Second, it's useful for algorithms that don't use mutating methods within `combine`. We considered overloading `reduce`, but that would stress the type checker too much. There has been a really active discussion about the naming of the first parameter. Naming it `mutating:` could deceive people into thinking that the value would get mutated in place. Naming it `mutatingCopyOf:` is also tricky: even though a copy of the struct gets mutated, copying is always implicit when using structs, and it wouldn't copy an instance of a class. `into:` seems the best name so far. Under active discussion: the naming of this method. See the [swift-evolution thread](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170116/030300). ---------- [Previous](@previous) | [Next](@next) */
true
c0d4b2a547fcd429961b60d963f94247671b85f0
Swift
nicholas11858/ContactBook
/ContactBook/Model/Person.swift
UTF-8
797
3.171875
3
[]
no_license
// // Person.swift // ContactBook // // Created by NIKOLAY OSIPOV on 08.06.2021. // struct Person { let firstName: String let surname: String let email: String let phone: String var fullName: String { "\(firstName) \(surname)" } static func getPerson() -> [Person] { [ Person(firstName: "Anjela", surname: "Sikens", email: "[email protected]", phone: "+1389893899"), Person(firstName: "John", surname: "Milov", email: "[email protected]", phone: "+79243932932"), Person(firstName: "Dora", surname: "Mora", email: "[email protected]", phone: "+73092039092") ] } }
true
6db7800ddb6a9d93e2fe7c3e0f56518c05c6cf62
Swift
wsl100624/RobotCardinality
/RobotCardinality/main.swift
UTF-8
1,537
2.828125
3
[]
no_license
// // main.swift // RobotCardinality // // Created by Wang Shilong on 2/14/18. // Copyright © 2018 Wang Shilong. All rights reserved. // import Foundation let world = World() let r1 = Robot(iD: "R1", startLocation: world.nestLocation) let r2 = Robot(iD: "R2", startLocation: (x: 3, y: 4)) let r3 = Robot(iD: "R2", startLocation: (x: 1, y: 2)) let r4 = Robot(iD: "R2", startLocation: (x: 4, y: 9)) // //let r5 = Robot(iD: "R5", startLocation: (x: 27, y: 32)) //let r6 = Robot(iD: "R6", startLocation: (x: 24, y: 40)) // //CardinalityChannel.saveCurrentLocation(robot: r5) //CardinalityChannel.saveCurrentLocation(robot: r6) // //r5.cardinality = (nest: 0, food: 1) //r6.cardinality = (nest: 0, food: 1) // //CardinalityChannel.saveCardinality(robot: r5) //CardinalityChannel.saveCardinality(robot: r6) // let queue1 = DispatchQueue(label: "R1") let queue2 = DispatchQueue(label: "R2") let queue3 = DispatchQueue(label: "R3") let queue4 = DispatchQueue(label: "R4") // queue1.async { r1.becomeBeacon() } queue2.async { r2.becomeBeacon() } queue3.async { r3.becomeBeacon() } queue4.async { r4.becomeBeacon() } r1.printStatus() r2.printStatus() r3.printStatus() r4.printStatus() // // DispatchQueue.global().async { // print("|||||||| All Robot's location |||||||||") // print(CardinalityChannel.locations) // } // DispatchQueue.global().async { // print("|||||||| All Robot's cardinalities |||||||||") // print(CardinalityChannel.cardinalities) // } //} // // //print("")
true
bee47b9853b31669160c8aaf6fd3b99fe616d9f7
Swift
TokMatok/BoringAPP
/CustomLabelStyle.swift
UTF-8
760
3.0625
3
[]
no_license
import Foundation import UIKit enum CustomLabelStyle : CaseIterable { case styleRed case styleBlue case styleYellow case styleGray case styleGreen var color : UIColor { switch self { case .styleRed: return .init(red: 235/255, green: 87/255, blue: 87/255, alpha: 1) case .styleBlue: return .init(red: 47/255, green: 128/255, blue: 237/255, alpha: 1) case .styleYellow: return .init(red: 242/255, green: 201/255, blue: 76/255, alpha: 1) case .styleGray: return .init(red: 130/255, green: 130/255, blue: 130/255, alpha: 1) case .styleGreen: return .init(red: 33/255, green: 150/255, blue: 83/255, alpha: 1) } } }
true
d3d09a00b398d77c77305d8bc1e6b111aa4c0c9b
Swift
jesustf97/MarvelList
/MarvelList/Networking/ApiService/Models/Comic.swift
UTF-8
238
2.546875
3
[]
no_license
// // Comic.swift // MarvelList // // Created by Jesús Calleja Rodríguez on 05/05/2020. // Copyright © 2020 Jesús Calleja Rodríguez. All rights reserved. // struct Comic: Decodable { let name: String enum CodingKeys: String, CodingKey { case name } }
true
d0732fe463f2eb3c7967556099bb87a2e82c225e
Swift
hammedopejin/AtCinemas-iOS-version
/AtCinemas-iOS/Model/Movie.swift
UTF-8
2,145
2.828125
3
[]
no_license
// // Movie.swift // AtCinemas-iOS // // Created by Hammed opejin on 6/9/19. // Copyright © 2019 Hammed opejin. All rights reserved. // import UIKit import CoreData import FirebaseDatabase struct MovieResults: Decodable { let results: [Movie] } class Movie: Decodable { let id: Int64 let title: String let overview: String let imageUrl: String let rating: Double let releaseDate: String private enum CodingKeys: String, CodingKey { case id case title case overview case imageUrl = "poster_path" case rating = "vote_average" case releaseDate = "release_date" } init?(entity: NSManagedObject) { guard let id = entity.value(forKey: Constants.Movie.id.rawValue) as? Int64, let title = entity.value(forKey: Constants.Movie.title.rawValue) as? String, let overview = entity.value(forKey: Constants.Movie.overview.rawValue) as? String, let imageUrl = entity.value(forKey: Constants.Movie.imageUrl.rawValue) as? String, let rating = entity.value(forKey: Constants.Movie.rating.rawValue) as? Double, let releaseDate = entity.value(forKey: Constants.Movie.releaseDate.rawValue) as? String else { return nil } self.id = id self.title = title self.overview = overview self.imageUrl = imageUrl self.rating = rating self.releaseDate = releaseDate } init?(snapshot: DataSnapshot) { guard let value = snapshot.value as? [String : Any] else { return nil } let stringId = value[Constants.Movie.id.rawValue] as! String self.id = Int64(stringId)! self.title = value[Constants.Movie.title.rawValue] as! String self.overview = value[Constants.Movie.overview.rawValue] as! String self.imageUrl = value[Constants.Movie.imageUrl.rawValue] as! String let stringRating = value[Constants.Movie.rating.rawValue] as! String self.rating = Double(stringRating)! self.releaseDate = value[Constants.Movie.releaseDate.rawValue] as! String } }
true
a3a106ac9e376286851ef81ee6ec3e575137c90a
Swift
ahmadmlk16/News
/News/News/NewsDetails.swift
UTF-8
3,484
3.0625
3
[]
no_license
// // NewsDetails.swift // News // // Created by cs3714 on 2/27/20. // Copyright © 2020 AhmadMalik. All rights reserved. // import SwiftUI //default view for any non favorite news Item struct NewsDetails: View { // Input Parameter let news: NewsObject @EnvironmentObject var userData: UserData @State private var showAddedMessage = false var body: some View { Form{ Section(header: Text("Source Name")){ Text(news.sourceName) } Section(header: Text("News Item Image")){ getImageFromUrl(url: news.urlToImage) .resizable() .aspectRatio(contentMode: .fill) } Section(header: Text("News Item Title")){ Text(news.title) } //clicking this button adds the current newsitem to the user objects favorites list Section(header: Text("Add this news item to my favorites list")) { Button(action: { // Append the country found to userData.countriesList self.userData.newsList.append(self.news) // Set the global variable point to the changed list newsStructList = self.userData.newsList self.showAddedMessage = true }) { Image(systemName: "plus") .imageScale(.medium) .font(Font.title.weight(.regular)) } } //navigation list to the newsItem Website Section(header: Text("News Item Publisher Website")){ NavigationLink(destination: WebView(url: news.url) .navigationBarTitle(Text("News Website"), displayMode: .inline)){ HStack{ Image(systemName: "globe") Text("Publisher Website") } .aspectRatio(contentMode: .fill) } } Section(header: Text("News Item Author")){ Text(news.author) } Section(header: Text("News Item Description")){ Text(news.description) } Section(header: Text("News Item Publication and Time")){ Text(DateConverter.getDate(stringDate: news.publishedAt)) } Section(header: Text("News Item Content")){ Text(news.content) } }//End of Form .alert(isPresented: $showAddedMessage, content: { self.alert }) } //Alert Messege when appending to the list is successful var alert: Alert { Alert(title: Text("News Item Added!"), message: Text("This News Item is added to your favorites list"), dismissButton: .default(Text("OK")) ) } } struct NewsDetails_Previews: PreviewProvider { static var previews: some View { MyFavoriteDetails(news: newsStructList[0]) } }
true
fa9fd4a228e8acb8e7c52735cf2a740f5090511a
Swift
RajathShetty-above/Above_Reusable
/ReusableSample/ReusableSample/Model/RequestManager.swift
UTF-8
2,378
2.90625
3
[]
no_license
// // RequestManager.swift // UnitTest // // Created by Rajath Shetty on 25/02/16. // Copyright © 2016 Above Solution. All rights reserved. // import UIKit //This class will manage all request class RequestManager: NSObject { let searchBaseURL = "https://ajax.googleapis.com/ajax/services/feed/find?v=1.0&q=" static let sharedInstance = RequestManager() private override init() {} //This prevents others from using the default '()' initializer for this class. func validateSearchString(text: String) -> Bool { if text.characters.count == 0 { return false } return true } func urlToGetNewsWithQueryText(queryText: String?) -> NSURL? { if let queryText = queryText where queryText.characters.count > 0{ var requestUrlString: String? = searchBaseURL + "\(queryText)" requestUrlString = requestUrlString?.percentEncoding() if let requestUrlString = requestUrlString, requestUrl = NSURL(string: requestUrlString) { return requestUrl } } return nil } func requestUrl(url: NSURL, completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) { let session = NSURLSession.sharedSession() session.dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in completionHandler(data, response, error) }) }).resume() } func getNewsRelatedToQueryText(queryText: String?, completionHandler: ((response: SearchResponse?, error: NSError?) -> Void)) { if let requestUrl = urlToGetNewsWithQueryText(queryText) { self.requestUrl(requestUrl, completionHandler: { (data, response, error) -> Void in if let data = data where error == nil { let json = JSON(data: data) let finalResponse = SearchResponse(json: json) completionHandler(response: finalResponse, error: nil) } else { completionHandler(response: nil, error: error) } }) } else { completionHandler(response: nil, error: NSError(domain: "Invalid Url", code: 0, userInfo: nil)) } } }
true
2ec0009e64fc25e96b685a7abd40e26e3a4590b3
Swift
samnovotny/swifttest
/Sources/swifttest/I2CIo.swift
UTF-8
4,657
2.609375
3
[]
no_license
// // I2CIo.swift // // // Created by Sam Novotny on 24/02/2020. // import Foundation internal let I2C_SLAVE: UInt = 0x703 internal let I2C_SLAVE_FORCE: UInt = 0x706 internal let I2C_SMBUS: UInt = 0x720 internal let SAMPLES_PER_SECOND_MAP: Dictionary<Int, UInt16> = [128: 0x0000, 250: 0x0020, 490: 0x0040, 920: 0x0060, 1600: 0x0080, 2400: 0x00A0, 3300: 0x00C0] internal let CHANNEL_MAP: Dictionary<Int, UInt16> = [0: 0x4000, 1: 0x5000, 2: 0x6000] internal let PROGRAMMABLE_GAIN_MAP: Dictionary<Int, UInt16> = [6144: 0x0000, 4096: 0x0200, 2048: 0x0400, 1024: 0x0600, 512: 0x0800, 256: 0x0A00] internal let samplesPerSecond = 1600 internal let programmableGain = 4096 internal let I2C_SMBUS_READ: UInt8 = 1 internal let I2C_SMBUS_WRITE: UInt8 = 0 internal let I2C_SMBUS_QUICK: UInt32 = 0 internal let I2C_SMBUS_BYTE: UInt32 = 1 internal let I2C_SMBUS_BYTE_DATA: UInt32 = 2 internal let I2C_SMBUS_WORD_DATA: UInt32 = 3 internal let REG_CONVERT:UInt8 = 0x00 internal let REG_CONFIG:UInt8 = 0x01 internal let I2C_SMBUS_BLOCK_MAX = 32 enum I2CError : Error { case ioctlError case readError case writeError } class I2CIo { let fd: Int32 let address: Int init?(address: Int, device: String) { self.address = address self.fd = open(device, O_RDWR) guard self.fd > 0 else { return nil } } deinit { print ("\(#function)") close(self.fd) } private func selectDevice() throws { let io = ioctl(self.fd, I2C_SLAVE, CInt(self.address)) guard io != -1 else {throw I2CError.ioctlError} } private func getConfig(channel: Int) -> UInt16 { var config: UInt16 = 0x8000 | 0x0003 | 0x0100 config |= SAMPLES_PER_SECOND_MAP[samplesPerSecond]! config |= PROGRAMMABLE_GAIN_MAP[programmableGain]! config |= CHANNEL_MAP[channel]! print("config = \(Int(config).hex16()),\(Int(config).binaryWord())") return config } private func setRegister(register: UInt8) throws { try selectDevice() try writeByte(byte: register) } func writeByte(byte: UInt8) throws { var ioctlData = i2c_smbus_ioctl_data(read_write: I2C_SMBUS_WRITE, command: 0, size: I2C_SMBUS_BYTE_DATA, byte: byte) let io = ioctl(self.fd, I2C_SMBUS, &ioctlData.data) guard io != -1 else {throw I2CError.writeError} } func writeWord(register: UInt8, word: UInt16) throws { try setRegister(register: register) var ioctlData = i2c_smbus_ioctl_data(read_write: I2C_SMBUS_WRITE, command: 0, size: I2C_SMBUS_WORD_DATA, word: word) let io = ioctl(self.fd, I2C_SMBUS, &ioctlData.data) guard io != -1 else {throw I2CError.writeError} } func readWord(register: UInt8) throws -> UInt16 { try setRegister(register: register) var ioctlData = i2c_smbus_ioctl_data(read_write: I2C_SMBUS_READ, command: 0, size: I2C_SMBUS_WORD_DATA, word: 0) // var ioctlData = i2c_smbus_ioctl_data(read_write: 255, // command: 255, // size: 0xffffffff, // word: 0) ioctlData.dump() let io = ioctl(self.fd, I2C_SMBUS, &ioctlData.data) guard io != -1 else {throw I2CError.readError} ioctlData.dump() return(ioctlData.word) } func getConfigRegister() throws { do { let config = try readWord(register: REG_CONFIG) print("Config = \(Int(config).hex16())") } } func readADC(channel: Int) throws -> Float { print ("\(#function) - \(channel)") let delay = (1.0 / Double(samplesPerSecond)) + 0.0001 let config = getConfig(channel: channel) try writeWord(register: REG_CONFIG, word: config) Thread.sleep(forTimeInterval: delay) let value = try readWord(register: REG_CONVERT) let intValue = Int(value >> 4) print( "intValue(\(intValue)) = \(intValue.binaryWord())") let result = Float(intValue) / 2047.0 * Float(programmableGain) / 3300.0 return (result) } }
true
1c1abc8aa14ba239f4b0b53d6e695e657b86a891
Swift
MoonshineSG/vpn.tv
/tvos/TopShelf/ServiceProvider.swift
UTF-8
1,750
2.671875
3
[]
no_license
import Foundation import TVServices import UIKit class ServiceProvider: NSObject, TVTopShelfProvider { let server_ip = "192.168.0.60:8080" var cache = "" let topShelfStyle: TVTopShelfContentStyle = .inset var topShelfItems: [TVContentItem] { let vpnItem = getFlag() return [vpnItem] } func getFlag()->TVContentItem { var flagpath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("flag_\(cache).png") let vpnIdentifier = TVContentIdentifier(identifier: "vpn_flag", container: nil)! let vpnItem = TVContentItem(contentIdentifier: vpnIdentifier)! vpnItem.imageShape = .extraWide vpnItem.setImageURL(flagpath, forTraits:.userInterfaceStyleLight) vpnItem.setImageURL(flagpath, forTraits:.userInterfaceStyleDark) if let country = try? String(contentsOf: URL(string: "http://\(server_ip)/country/")!) { cache = country flagpath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("flag_\(country).png") if !FileManager.default.fileExists(atPath: flagpath.path) { guard let data = try? Data(contentsOf: URL(string: "http://\(self.server_ip)/flag/")!) else { print("error getting data"); return vpnItem } guard let _ = try? data.write(to: flagpath) else { print("write error");return vpnItem } } vpnItem.setImageURL(flagpath, forTraits:.userInterfaceStyleLight) vpnItem.setImageURL(flagpath, forTraits:.userInterfaceStyleDark) } NotificationCenter.default.post(name: NSNotification.Name.TVTopShelfItemsDidChange, object: nil) return vpnItem } }
true
d9889dbfbb0c2951414bc44b55e26c342baf0212
Swift
Manlinup/vote
/Vote/Helpers/VHelper.swift
UTF-8
739
2.5625
3
[]
no_license
// // VHelper.swift // Vote // // Created by Grant Yuan on 2018/2/4. // Copyright © 2018年 林以达. All rights reserved. // import Foundation typealias CancelableTask = (_ cancel: Bool) -> Void func delay(_ delay: Double, closure: @escaping () -> ()) { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { closure() } } func cancel(_ cancelableTask: CancelableTask?) { cancelableTask?(true) } func mainAsync(closure: @escaping ()->()) { DispatchQueue.main.async { closure() } } func synced(lock: AnyObject, closure: () -> ()) { objc_sync_enter(lock) closure() objc_sync_exit(lock) } func currentMilliseconds()->Int64 { return Int64(Date().timeIntervalSince1970 * 1000) }
true
370b4f055244d3fe305d36080d4d57c9629d2e62
Swift
Amit-007/EasySDK
/EasySDK/Extensions/UIKitExtensions/UIApplication/UIApplication+EasyExtension.swift
UTF-8
1,981
2.5625
3
[ "MIT" ]
permissive
// // UIApplication+EasyExtension.swift // EasySDK // // Created by Amit Majumdar on 31/07/19. // Copyright © 2019 EasySDK. All rights reserved. // #if canImport(UIKit) import UIKit #if os(iOS) || os(tvOS) public extension UIApplication { /// EasySDK: Application running environment. /// /// - debug: Application is running in debug mode. /// - testFlight: Application is installed from Test Flight. /// - appStore: Application is installed from the App Store. enum Environment { case debug case testFlight case appStore } /// EasySDK: Current inferred app environment. var inferredEnvironment: Environment { #if DEBUG return .debug #elseif targetEnvironment(simulator) return .debug #else if Bundle.main.path(forResource: "embedded", ofType: "mobileprovision") != nil { return .testFlight } guard let appStoreReceiptUrl = Bundle.main.appStoreReceiptURL else { return .debug } if appStoreReceiptUrl.lastPathComponent.lowercased() == "sandboxreceipt" { return .testFlight } if appStoreReceiptUrl.path.lowercased().contains("simulator") { return .debug } return .appStore #endif } /// EasySDK: Application name (if applicable). var displayName: String? { return Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String } /// EasySDK: App current build number (if applicable). var buildNumber: String? { return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String } /// EasySDK: App's current version number (if applicable). var version: String? { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String } } #endif #endif
true
0ce9d0acda44265bab8342e9cf3874fd88a60214
Swift
brunobartol/MarvelApp
/MarvelApp/Services/ComicService.swift
UTF-8
1,539
2.734375
3
[]
no_license
import Combine import SwiftUI protocol ComicServiceType { func fetchComics(name: String) -> Future<[Comic], ApiError> } final class ComicService { public static let shared = ComicService() private let decoder = JSONDecoder() private var cancellables = Set<AnyCancellable>() private init() {} } extension ComicService: ComicServiceType { func fetchComics(name: String) -> Future<[Comic], ApiError> { return Future<[Comic], ApiError> { [unowned self] promise in do { try MarvelAPI .comicsByName(name: name) .request() .responseJSON { response in guard let data = response.data else { promise(.failure(.genericError)) print(response) return } do { let comicResponse = try self.decoder.decode(ComicDataWrapper.self, from: data) guard let comics = comicResponse.data?.results else { promise(.failure(.genericError)) return } promise(.success(comics)) } catch { print(error) } } } catch { print(error) } } } }
true
15b89f44f07c67e339709d3fc23c58c999d60479
Swift
Lumyk/apollo-mapper
/Sources/apollo-mapper/Mappable.swift
UTF-8
711
2.625
3
[ "MIT" ]
permissive
// // Mappable.swift // apollo-mapper // // Created by Evgeny Kalashnikov on 10.03.2018. // import Foundation public protocol Mappable { init(snapshot: [String : Any?]) throws init(mapper: Mapper) throws } public extension Mappable { init(snapshot: [String : Any?]) throws { do { try self.init(mapper: Mapper(snapshot: snapshot)) } catch let error { throw error } } @discardableResult static func map(_ snapshots: [[String : Any?]?], storage: MapperStorage? = nil, element: ((_ object: Self) -> Void)? = nil) throws -> [Self] { return try Mapper.map(Self.self, snapshots: snapshots, storage: storage, element: element) } }
true
0be3b795bd1b16346b1569e93664139fb081b5b2
Swift
emilia98/Mandala
/Mandala/Mandala/Mandala/MoodsConfigurable.swift
UTF-8
87
2.546875
3
[ "MIT" ]
permissive
import Foundation protocol MoodsConfigurable { func add(_ moodEntry: MoodEntry) }
true
846e48744e529b98d8e8b2a4da2b9921d42e8b2d
Swift
BhaskarReddyModasta/ProfileChecker
/ProfileChecker/CheckerInfo.swift
UTF-8
387
2.53125
3
[ "MIT" ]
permissive
// // CheckerInfo.swift // ProfileChecker // // Created by Bhaskar Reddy on 08/08/20. // Copyright © 2020 Bhaskar Reddy. All rights reserved. // import Foundation open class CheckerInfo { public let name: String public init(name: String){ self.name = name } open func testString() -> String { return "Check to hiding \(self.name)" } }
true
f9dc81e544fba4314a0b406bb63c67511c2e1b54
Swift
Digimoplus-Repo/AppInfrastructure
/Sources/AppInfrastructure/Extension/UIFont+Extension.swift
UTF-8
749
3.28125
3
[]
no_license
import UIKit public protocol FontStyle { var size: CGFloat { get } var weight: UIFont.Weight { get } var name: String? { get } } extension UIFont { private static func systemFontWithStyle(_ style: FontStyle) -> UIFont { .systemFont( ofSize: style.size, weight: style.weight ) } static public func withStyle(_ style: FontStyle) -> UIFont { if let name = style.name, let font = UIFont(name: name, size: style.size) { return font } return systemFontWithStyle(style) } static public func withSize(_ size: CGFloat, weight: UIFont.Weight) -> UIFont { .systemFont( ofSize: size, weight: weight ) } }
true