text
stringlengths
8
1.32M
// // Page1ViewController.swift // GoneTooSoon // // Created by Cagri Sahan on 4/16/18. // Copyright © 2018 Cagri Sahan. All rights reserved. // import UIKit import AVFoundation class Page1ViewController: DataViewController { // MARK: IBActions @IBAction func listenButtonPressed(_ sender: Any) { if !synthesizer.isSpeaking { startReading() } } @IBAction func homeButtonPressed(_ sender: Any) { returnToHome() } // MARK: IBOutlets @IBOutlet weak var darkLayer: UIView! @IBOutlet weak var storyText: UILabel! // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() synthesizer.delegate = self if let customFont = UIFont(name: "ThatPaper", size: 40) { attributedString = NSMutableAttributedString(string: storyText.text!, attributes: [ NSAttributedStringKey.font: customFont]) storyText.attributedText = attributedString } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIViewPropertyAnimator(duration: 3, curve: .easeInOut) { [unowned self] in self.darkLayer.alpha = 1.0 self.darkLayer.alpha = 0.5 }.startAnimation() } } // MARK: Extensions extension Page1ViewController: AVSpeechSynthesizerDelegate { func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) { if let previousRange = previousRange { attributedString.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.clear, range: previousRange) } attributedString.addAttribute(NSAttributedStringKey.backgroundColor, value: #colorLiteral(red: 0.968627451, green: 0.8039215686, blue: 0.8431372549, alpha: 1), range: characterRange) storyText.attributedText = attributedString previousRange = characterRange } func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) { if let previousRange = previousRange { attributedString.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.clear, range: previousRange) storyText.attributedText = attributedString } } }
// Copyright 2020 TensorFlow Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import x10_xla_tensor_wrapper extension XLAScalar { init(_ v: Double) { self.init() self.tag = XLAScalarTypeTag_d self.value.d = v } init(_ v: Int64) { self.init() self.tag = XLAScalarTypeTag_i self.value.i = v } } /// A supported datatype in x10. public protocol XLAScalarType { var xlaScalar: XLAScalar { get } static var xlaTensorScalarType: XLATensorScalarType { get } } extension Float: XLAScalarType { public var xlaScalar: XLAScalar { XLAScalar(Double(self)) } static public var xlaTensorScalarType: XLATensorScalarType { return XLATensorScalarType_Float } } extension Double: XLAScalarType { public var xlaScalar: XLAScalar { XLAScalar(self) } static public var xlaTensorScalarType: XLATensorScalarType { return XLATensorScalarType_Double } } extension Int64: XLAScalarType { public var xlaScalar: XLAScalar { XLAScalar(self) } static public var xlaTensorScalarType: XLATensorScalarType { return XLATensorScalarType_Int64 } } extension Int32: XLAScalarType { public var xlaScalar: XLAScalar { XLAScalar(Int64(self)) } static public var xlaTensorScalarType: XLATensorScalarType { return XLATensorScalarType_Int32 } } extension Int16: XLAScalarType { public var xlaScalar: XLAScalar { XLAScalar(Int64(self)) } static public var xlaTensorScalarType: XLATensorScalarType { return XLATensorScalarType_Int16 } } extension Int8: XLAScalarType { public var xlaScalar: XLAScalar { XLAScalar(Int64(self)) } static public var xlaTensorScalarType: XLATensorScalarType { return XLATensorScalarType_Int8 } } extension UInt8: XLAScalarType { public var xlaScalar: XLAScalar { XLAScalar(Int64(self)) } static public var xlaTensorScalarType: XLATensorScalarType { return XLATensorScalarType_UInt8 } } extension Bool: XLAScalarType { public var xlaScalar: XLAScalar { XLAScalar(Int64(self ? 1 : 0)) } static public var xlaTensorScalarType: XLATensorScalarType { return XLATensorScalarType_Bool } } /// Error implementations extension BFloat16: XLAScalarType { public var xlaScalar: XLAScalar { fatalError("BFloat16 not suported") } static public var xlaTensorScalarType: XLATensorScalarType { fatalError("BFloat16 not suported") } } extension UInt64: XLAScalarType { public var xlaScalar: XLAScalar { fatalError("UInt64 not suported") } static public var xlaTensorScalarType: XLATensorScalarType { fatalError("UInt64 not suported") } } extension UInt32: XLAScalarType { public var xlaScalar: XLAScalar { fatalError("UInt32 not suported") } static public var xlaTensorScalarType: XLATensorScalarType { fatalError("UInt32 not suported") } } extension UInt16: XLAScalarType { public var xlaScalar: XLAScalar { fatalError("UInt16 not suported") } static public var xlaTensorScalarType: XLATensorScalarType { fatalError("UInt16 not suported") } }
// // QRcodeScanner.swift // InventoryProject // // Created by Cody Mudrack on 10/13/19. // Copyright © 2019 Cody Mudrack. All rights reserved. // // This website helped me with this portion of the code: https://developer.apple.com/documentation/avfoundation/cameras_and_media_capture/avcam_building_a_camera_app import UIKit import AVFoundation class QRcodeScanner: UIViewController, AVCaptureMetadataOutputObjectsDelegate { var qrValue: String? var captureSession = AVCaptureSession() var videoPreviewLayer: AVCaptureVideoPreviewLayer? var camera: AVCaptureDevice? var cameraCaptureOutput: AVCaptureMetadataOutput? var qrCodeFrameView: UIView? override func viewDidLoad() { super.viewDidLoad() //check for authorization switch AVCaptureDevice.authorizationStatus(for: .video) { case .authorized: // The user has previously granted access to the camera. self.setupCaptureSession() case .notDetermined: // The user has not yet been asked for camera access. AVCaptureDevice.requestAccess(for: .video) { granted in if granted { self.setupCaptureSession() } } case .denied: // The user has previously denied access. return case .restricted: // The user can't grant access due to restrictions. return default: return } } func setupCaptureSession() { captureSession.sessionPreset = AVCaptureSession.Preset.high camera = AVCaptureDevice.default(for: .video) do{ let cameraCaptureInput = try AVCaptureDeviceInput(device: camera!) cameraCaptureOutput = AVCaptureMetadataOutput() captureSession.addInput(cameraCaptureInput) captureSession.addOutput(cameraCaptureOutput!) cameraCaptureOutput?.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) cameraCaptureOutput?.metadataObjectTypes = [AVMetadataObject.ObjectType.qr] } catch { print(error.localizedDescription) } // Initialize QR Code Frame to highlight the QR code DispatchQueue.main.async { self.qrCodeFrameView = UIView() } if let qrCodeFrameView = qrCodeFrameView { qrCodeFrameView.layer.borderColor = UIColor.green.cgColor qrCodeFrameView.layer.borderWidth = 2 view.addSubview(qrCodeFrameView) view.bringSubviewToFront(qrCodeFrameView) } DispatchQueue.main.async { self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession) self.videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill self.videoPreviewLayer?.frame = self.view.bounds self.videoPreviewLayer?.connection?.videoOrientation = AVCaptureVideoOrientation.portrait self.view.layer.insertSublayer(self.videoPreviewLayer!, at: 0) self.captureSession.startRunning() } } // Got function from https://www.appcoda.com/intermediate-swift-tips/qrcode-reader.html func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { // Check if the metadataObjects array is not nil and it contains at least one object. if metadataObjects.count == 0 { qrCodeFrameView?.frame = CGRect.zero return } // Get the metadata object. let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject if metadataObj.type == AVMetadataObject.ObjectType.qr { // If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj) qrCodeFrameView?.frame = barCodeObject!.bounds qrValue = metadataObj.stringValue! performSegue(withIdentifier: "QRCodeSegue", sender: nil) captureSession.stopRunning() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier else { return } guard identifier == "QRCodeSegue" else { return } let QRCodeDetails = segue.destination as! QRCodeDetails QRCodeDetails.chemicalName = qrValue } }
// // circleView.swift // autolayout_code_tutorial_01 // // Created by 백승엽 on 2020/11/23. // import Foundation import UIKit class CircleView: UIView { override func layoutSubviews() { super.layoutSubviews() print("CircleView - layoutSubview() called") self.layer.cornerRadius = self.frame.height / 2 } }
// // ToOptional.swift // Clok // // Created by Secret Asian Man Dev on 23/8/20. // Copyright © 2020 Secret Asian Man 3. All rights reserved. // import Foundation /// Returns input as an Optional. /// Used with `Combine` to change publisher type to optional public func toOptional<T>(input: T) -> T? { input }
// // PagedViewController.swift // keyboardTest // // Created by Sean McGee on 4/6/15. // Copyright (c) 2015 3 Callistos Services. All rights reserved. // import UIKit class PagingViewController1: PagingViewController0, UITextFieldDelegate { override func viewDidLoad() { var arrayFirstRow = ["B", "I", "V"] var arraySecondRow = ["H", "D", "A"] var arrayThirdRow = ["N", "P", "B"] var arrayOfTagsFirst = [66, 73, 86] var arrayOfTagsSecond = [72, 68, 65] var arrayOfTagsThird = [78, 80, 66] var buttonXFirst: CGFloat = 0 var buttonXSecond: CGFloat = 0 var buttonXThird: CGFloat = 0 var buttonTagFirst: Int = 0 var buttonTagSecond: Int = 0 var buttonTagThird: Int = 0 for key in arrayFirstRow { let keyButton1 = UIButton(frame: CGRect(x: buttonXFirst, y: 10, width: 52, height: 52)) buttonXFirst = buttonXFirst + 62 keyButton1.layer.cornerRadius = 0 keyButton1.layer.borderWidth = 1 keyButton1.setTitleColor(UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ), forState: UIControlState.Normal) keyButton1.layer.borderColor = UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ).CGColor; keyButton1.backgroundColor = UIColor(white: 248/255, alpha: 0.5) keyButton1.setTitle("\(key)", forState: UIControlState.Normal) keyButton1.setTitleColor(UIColor(white: 248/255, alpha: 0.5), forState: UIControlState.Highlighted) keyButton1.titleLabel!.text = "\(key)" keyButton1.tag = arrayOfTagsFirst[buttonTagFirst] buttonTagFirst = buttonTagFirst++ keyButton1.addTarget(self, action: "buttonHighlight:", forControlEvents: UIControlEvents.TouchDown); keyButton1.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchUpInside); keyButton1.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpOutside); self.view.addSubview(keyButton1) } for key in arraySecondRow { let keyButton2 = UIButton(frame: CGRect(x: buttonXSecond, y: 72, width: 52, height: 52)) buttonXSecond = buttonXSecond + 62 keyButton2.layer.cornerRadius = 0 keyButton2.layer.borderWidth = 1 keyButton2.setTitleColor(UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ), forState: UIControlState.Normal) keyButton2.layer.borderColor = UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ).CGColor; keyButton2.backgroundColor = UIColor(white: 248/255, alpha: 0.5) keyButton2.setTitle("\(key)", forState: UIControlState.Normal) keyButton2.titleLabel!.text = "\(key)" keyButton2.tag = arrayOfTagsSecond[buttonTagSecond] buttonTagSecond = buttonTagSecond++ keyButton2.addTarget(self, action: "buttonHighlight:", forControlEvents: UIControlEvents.TouchDown); keyButton2.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchUpInside); keyButton2.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpOutside); self.view.addSubview(keyButton2) } for key in arrayThirdRow { let keyButton3 = UIButton(frame: CGRect(x: buttonXThird, y: 134, width: 52, height: 52)) buttonXThird = buttonXThird + 62 keyButton3.layer.cornerRadius = 0 keyButton3.layer.borderWidth = 1 keyButton3.setTitleColor(UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ), forState: UIControlState.Normal) keyButton3.layer.borderColor = UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ).CGColor; keyButton3.backgroundColor = UIColor(white: 248/255, alpha: 0.5) keyButton3.setTitle("\(key)", forState: UIControlState.Normal) keyButton3.titleLabel!.text = "\(key)" keyButton3.tag = arrayOfTagsThird[buttonTagThird] buttonTagThird = buttonTagThird++ keyButton3.addTarget(self, action: "buttonHighlight:", forControlEvents: UIControlEvents.TouchDown); keyButton3.addTarget(self, action: "keyPressed:", forControlEvents: UIControlEvents.TouchUpInside); keyButton3.addTarget(self, action: "buttonNormal:", forControlEvents: UIControlEvents.TouchUpOutside); self.view.addSubview(keyButton3) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func buttonHighlight(sender: UIButton!) { var btnsendtag:UIButton = sender sender.backgroundColor = UIColor(red: 0.004, green: 0.078, blue: 0.216, alpha: 1.000 ) } override func buttonNormal(sender: UIButton!) { var btnsendtag:UIButton = sender sender.backgroundColor = UIColor(white: 248/255, alpha: 0.5) } }
// // Tags.swift // CBC // // Created by Steve Leeke on 2/11/18. // Copyright © 2018 Steve Leeke. All rights reserved. // import Foundation // Tried to use a struct and bad things happend. Copy on write problems? Simultaneous access problems? Are those two related? Could be. Don't know. // Problems went away when I switched to class class Tags { weak var globals:Globals! var showing:String? { get { return selected == nil ? Constants.ALL : Constants.TAGGED } } var selected:String? { get { return globals.mediaCategory.tag } set { if let newValue = newValue { if (globals.media.tagged[newValue] == nil) { if globals.media.all == nil { //This is filtering, i.e. searching all mediaItems => s/b in background globals.media.tagged[newValue] = MediaListGroupSort(mediaItems: mediaItemsWithTag(globals.mediaRepository.list, tag: newValue)) } else { if let key = stringWithoutPrefixes(newValue), let mediaItems = globals.media.all?.tagMediaItems?[key] { globals.media.tagged[newValue] = MediaListGroupSort(mediaItems: mediaItems) } } } } else { } globals.mediaCategory.tag = newValue } } }
// // QuadTree.swift // WordCloud-Swift // // Created by Saleh AlDhobaie on 10/31/16. // Copyright © 2016 Saleh AlDhobaie. All rights reserved. // import Foundation import UIKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } open class QuadTree : NSObject { fileprivate static let kLALBoundingRectThreshold : Int = 8; // MARK: private Vars // ===== /** The frame (region) corresponding to this node */ fileprivate var frame : CGRect! /** A strong reference to the bounding rects that fit within this node's frame @note These are rects that don't fit completely within a sub quad @note Will be nil if this node is empty, or if all its rects fit within sub quads */ fileprivate var boundingRects : [CGRect]? /** A strong reference to the top left quadrant of this node @note Will be nil if this node has no sub quads */ fileprivate var topLeftQuad : QuadTree? /** A strong reference to the top right quadrant of this node @note Will be nil if this node has no sub quads */ fileprivate var topRightQuad : QuadTree? /** A strong reference to the bottom left quadrant of this node @note Will be nil if this node has no sub quads */ fileprivate var bottomLeftQuad : QuadTree! /** A strong reference to the bottom right quadrant of this node @note Will be nil if this node has no sub quads */ fileprivate var bottomRightQuad : QuadTree? // ===== /** Returns a quadtree object @param frame The region in the delegate's cloud view that this node covers @return An initialized quadtree object, or nil if the object could not be created for some reason */ override convenience init() { self.init(frame: CGRect.zero) } init(frame: CGRect) { self.frame = frame super.init() } /** @warning Cannot initialize node without a region size (and origin). Use initWithFrame: */ // - (instancetype)init __attribute__((unavailable("Must use initWithFrame:"))); /** @warning Cannot initialize node without a region size (and origin). Use initWithFrame: */ // + (instancetype)new __attribute__((unavailable("Must use initWithFrame:"))); /** Add a bounding rect to this quadtree @param boundingRect The bounding rect to be inserted into the quadtree @return YES if the insert succeeds (i.e., the bounding rect fits completely within the node's frame), otherwise NO. */ open func insertBoundingRect(_ boundingRect: CGRect) -> Bool { if (self.frame.contains(boundingRect) == false) { // The rect doesn't fit in this node. Give up return false } // Pre-insert, check if no sub quads, and rect threshold reached if topLeftQuad == nil && boundingRects?.count > QuadTree.kLALBoundingRectThreshold { setupChildQuads() migrateBoundingRects() } if topLeftQuad != nil && migrateBoundingRect(boundingRect) { // The bounding rect was inserted into a sub quad return true } // The bounding rect did not fit into a sub quad. Add it to this node's array if boundingRects == nil { boundingRects = [] } boundingRects!.append(boundingRect) //[self.boundingRects addObject:[NSValue valueWithCGRect:boundingRect]]; return true } /** Checks to see if the word's desired location intersects with any glyph's bounding rect @param wordRect The location to be compared against the quadtree @return YES if a glyph intersects the word's location, otherwise NO */ open func hasGlyphThatIntersectsWithWordRect(_ wordRect : CGRect) -> Bool { // First test the node's bounding rects /*if boundingRects == nil { boundingRects = [] }*/ // Added By Saleh if let boundRects = boundingRects { // First test the node's bounding rects for glyphBoundingRect in boundRects { if glyphBoundingRect.intersects(wordRect) { return true } } } /*for glyphBoundingRect in boundingRects! { if CGRectIntersectsRect(glyphBoundingRect, wordRect) { return true } }*/ // If no sub quads, we're done looking for intersections if (topLeftQuad == nil) { return false } /* // Added By Saleh guard let topLQ = self.topLeftQuad else { return false }*/ // Added By Saleh if let check = checkIntersect(topLeftQuad!, wordRect: wordRect) { return check } /* // Check a sub quad if its frame intersects with the word if CGRectIntersectsRect(topLQ.frame, wordRect) { if topLQ.hasGlyphThatIntersectsWithWordRect(wordRect) { // One of its glyphs intersects with our word return true } if CGRectContainsRect(topLQuad.frame, wordRect) { // Our word fits completely within topLeft. No need to check other sub quads return false } }*/ // Added By Saleh if let topRQ = topRightQuad { if let check = checkIntersect(topRQ, wordRect: wordRect) { return check } } /* if CGRectIntersectsRect(self.topRightQuad.frame, wordRect) { if topRightQuad.hasGlyphThatIntersectsWithWordRect(wordRect) { // One of its glyphs intersects with our word return true } if CGRectContainsRect(topRightQuad.frame, wordRect) { // Our word fits completely within topRight. No need to check other sub quads return false } }*/ // Added By Saleh if let topLQ = bottomLeftQuad { if let check = checkIntersect(topLQ, wordRect: wordRect) { return check } } /*if CGRectIntersectsRect(bottomLeftQuad.frame, wordRect) { if bottomLeftQuad.hasGlyphThatIntersectsWithWordRect(wordRect) { // One of its glyphs intersects with our word return true } if (CGRectContainsRect(self.bottomLeftQuad.frame, wordRect)) { // Our word fits completely within bottomLeft. No need to check other sub quads return false } }*/ // Added By Saleh guard let bottomRQ = bottomRightQuad else { return false } if (bottomRQ.frame.intersects(wordRect)) { if bottomRQ.hasGlyphThatIntersectsWithWordRect(wordRect) { // One of its glyphs intersects with our word return true } } // No more sub quads to check. If we've got this far, there are no intersections return false } func checkIntersect(_ quadTree: QuadTree, wordRect: CGRect) -> Bool? { if quadTree.frame.intersects(wordRect) { if quadTree.hasGlyphThatIntersectsWithWordRect(wordRect) { // One of its glyphs intersects with our word return true } if quadTree.frame.contains(wordRect) { // Our word fits completely within topRight. No need to check other sub quads return false } } return nil } //MARK: Private Method /** Create sub quads, provided that they do not already exist */ func setupChildQuads() { if topLeftQuad != nil { // Sub quads already exist return } // Create sub quads let currentX : CGFloat = frame.minX; var currentY : CGFloat = frame.minY; let childWidth : CGFloat = frame.width / 2.0; let childHeight : CGFloat = frame.width / 2.0; let topLeftRect = CGRect(x: currentX, y: currentY, width: childWidth, height: childHeight) topLeftQuad = QuadTree(frame: topLeftRect) let topRightRect = CGRect(x: currentX + childWidth, y: currentY, width: childWidth, height: childHeight) topRightQuad = QuadTree(frame: topRightRect) currentY += childHeight; let bottomLeftRect = CGRect(x: currentX, y: currentY, width: childWidth, height: childHeight) bottomLeftQuad = QuadTree(frame: bottomLeftRect) let bottomRightRect = CGRect(x: currentX + childWidth, y: currentY, width: childWidth, height: childHeight) bottomRightQuad = QuadTree(frame: bottomRightRect) } /** Migrate any existing bounding rects to any sub quads that can enclose them */ func migrateBoundingRects() { // Setup an array to hold any migrated rects that will need to be deleted from this node's array of rects //NSMutableArray *migratedBoundingRects = [[NSMutableArray alloc] init]; var migratedBoundingRects : [CGRect] = [] for value in boundingRects! { if migrateBoundingRect(value) { // Can't delete during fast enumeration. Save to be deleted migratedBoundingRects.append(value) } } if migratedBoundingRects.count > 0 { for value in migratedBoundingRects { if let index = boundingRects?.index(of: value) { boundingRects?.remove(at: index) } } } if (boundingRects?.count == 0) { // All nodes were moved. Free up empty array self.boundingRects = nil; } } /** Migrate an existing bounding rect to any sub quad that can enclose it @param boundingRect The bounding rect to insert into a sub quad @return YES if the bounding rect fit within a sub quad and was migrated, else NO */ func migrateBoundingRect(_ boundingRect : CGRect) -> Bool { /*if let topLQ = topLeftQuad , topRQ = topRightQuad, bottomLQ = bottomLeftQuad, bottomRQ = bottomRightQuad { }*/ if ((topLeftQuad != nil) && topLeftQuad!.insertBoundingRect(boundingRect)) || ((topRightQuad != nil) && topRightQuad!.insertBoundingRect(boundingRect)) || ((bottomLeftQuad != nil) && bottomLeftQuad.insertBoundingRect(boundingRect)) || ((bottomRightQuad != nil) && bottomRightQuad!.insertBoundingRect(boundingRect)) { // Bounding rect migrated to a sub quad return true } return false } open override var debugDescription: String { return "<\(self.self): \(self)> frame = \(frame); boundingRects = \(boundingRects); topLeftQuad = \(topLeftQuad.debugDescription); topRightQuad = \(topRightQuad.debugDescription); bottomLeftQuad = \(bottomLeftQuad.debugDescription); bottomRightQuad = \(bottomRightQuad.debugDescription)" } }
// // SynonymCommandTests.swift // // // Created by Vladislav Fitc on 11/05/2020. // import Foundation import XCTest @testable import AlgoliaSearchClient class SynonymCommandTests: XCTestCase, AlgoliaCommandTest { func testSave() { let synonym = test.synonym let command = Command.Synonym.Save(indexName: test.indexName, synonym: synonym, forwardToReplicas: false, requestOptions: test.requestOptions) check(command: command, callType: .write, method: .put, urlPath: "/1/indexes/testIndex/synonyms/testObjectID", queryItems: [ .init(name: "testParameter", value: "testParameterValue"), .init(name: "forwardToReplicas", value: "false") ], body: synonym.httpBody, requestOptions: test.requestOptions) } func testGet() { let command = Command.Synonym.Get(indexName: test.indexName, objectID: test.objectID, requestOptions: test.requestOptions) check(command: command, callType: .read, method: .get, urlPath: "/1/indexes/testIndex/synonyms/testObjectID", queryItems: [.init(name: "testParameter", value: "testParameterValue")], body: nil, requestOptions: test.requestOptions) } func testDelete() { let command = Command.Synonym.Delete(indexName: test.indexName, objectID: test.objectID, forwardToReplicas: false, requestOptions: test.requestOptions) check(command: command, callType: .write, method: .delete, urlPath: "/1/indexes/testIndex/synonyms/testObjectID", queryItems: [ .init(name: "testParameter", value: "testParameterValue"), .init(name: "forwardToReplicas", value: "false") ], body: nil, requestOptions: test.requestOptions) } func testSearch() { let query: SynonymQuery = "testQuery" let command = Command.Synonym.Search(indexName: test.indexName, query: query, requestOptions: test.requestOptions) check(command: command, callType: .read, method: .post, urlPath: "/1/indexes/testIndex/synonyms/search", queryItems: [ .init(name: "testParameter", value: "testParameterValue"), ], body: query.httpBody, requestOptions: test.requestOptions) } func testClear() { let command = Command.Synonym.Clear(indexName: test.indexName, forwardToReplicas: false, requestOptions: test.requestOptions) check(command: command, callType: .write, method: .post, urlPath: "/1/indexes/testIndex/synonyms/clear", queryItems: [ .init(name: "testParameter", value: "testParameterValue"), .init(name: "forwardToReplicas", value: "false") ], body: nil, requestOptions: test.requestOptions) } func testSaveList() { let synonyms = [test.synonym] let command = Command.Synonym.SaveList(indexName: test.indexName, synonyms: synonyms, forwardToReplicas: true, clearExistingSynonyms: true, requestOptions: test.requestOptions) check(command: command, callType: .write, method: .post, urlPath: "/1/indexes/testIndex/synonyms/batch", queryItems: [ .init(name: "testParameter", value: "testParameterValue"), .init(name: "forwardToReplicas", value: "true"), .init(name: "replaceExistingSynonyms", value: "true") ], body: synonyms.httpBody, requestOptions: test.requestOptions) } }
// // TopBarV.swift // TimeTable // // Created by Ryuhei Kaminishi on 2017/06/19. // Copyright © 2017 kaminisea. All rights reserved. // import UIKit import Material final class TopBarView: View { var colorLayer: CALayer! var isAnimating = false } extension TopBarView { func playExpandingAnimation(with color: UIColor) { let duration = 0.35 guard !isAnimating else { return } isAnimating = true clipsToBounds = true // Prevent flickering when changing the color of the background immediately after termination. DispatchQueue.main.asyncAfter(deadline: .now() + (duration - 0.1)) { self.backgroundColor = color } colorLayer = CALayer() colorLayer.frame = CGRect(x: 0, y: 0, width: 0.05, height: 0.05) colorLayer.cornerRadius = 0.3 colorLayer.backgroundColor = color.cgColor colorLayer.position = CGPoint(x: self.bounds.width / 2, y: self.bounds.height / 2) layer.insertSublayer(colorLayer, at: 0) let materialExpandingAnimation = CABasicAnimation(keyPath: "transform") materialExpandingAnimation.delegate = self materialExpandingAnimation.keyPath = "transform.scale" materialExpandingAnimation.fromValue = 1 materialExpandingAnimation.toValue = 10000 materialExpandingAnimation.beginTime = 0 materialExpandingAnimation.duration = duration let curveMove = CAMediaTimingFunction(controlPoints: 0.645, 0.045, 0.355, 1.0) materialExpandingAnimation.timingFunction = curveMove materialExpandingAnimation.repeatCount = 1 materialExpandingAnimation.fillMode = kCAFillModeForwards materialExpandingAnimation.autoreverses = false materialExpandingAnimation.isRemovedOnCompletion = true colorLayer.add(materialExpandingAnimation, forKey: nil) } } extension TopBarView: CAAnimationDelegate { func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { isAnimating = false clipsToBounds = false } }
// // NKSimpleTable.swift // Median // // Created by Vojtech Rinik on 28/09/2016. // Copyright © 2016 Vojtech Rinik. All rights reserved. // import Foundation class NKSimpleTable<ItemType, ViewType: NSView>: NSScrollView, NSTableViewDataSource, NSTableViewDelegate { var build: ((Void) -> (ViewType))! var update: ((ViewType, ItemType, Int) -> ())! var tableView: NSTableView! var items = [ItemType]() { didSet { tableView.reloadData() } } convenience init() { self.init(frame: NSZeroRect) tableView = NSTableView(frame: NSZeroRect) self.documentView = tableView tableView.dataSource = self tableView.delegate = self tableView.headerView = nil tableView.selectionHighlightStyle = .none let column = NSTableColumn(identifier: "column") column.resizingMask = .autoresizingMask tableView.addTableColumn(column) } func numberOfRows(in tableView: NSTableView) -> Int { return items.count } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { var view: ViewType? = tableView.make(withIdentifier: "view", owner: self) as! ViewType? if view == nil { view = self.build() view?.identifier = "view" } self.update(view!, items[row], row) return view } func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat { return 20 } }
// // Widgets.swift // WavesWallet-iOS // // Created by rprokofev on 26.06.2019. // Copyright © 2019 Waves Platform. All rights reserved. // import Foundation public extension AnalyticManagerEvent { enum Widgets: AnalyticManagerEventInfo { public enum Style { case dark case classic } public enum Interval { case m1 case m5 case m10 case manually public var title: String { switch self { case .m1: return "1m" case .m5: return "5m" case .m10: return "10m" case .manually: return "manually" } } } public typealias AssetsIds = [String] case marketPulseActive case marketPulseAdded case marketPulseRemoved case marketPulseChanged(Style, Interval, AssetsIds) public var name: String { switch self { case .marketPulseActive: return "Market Pulse Active" case .marketPulseAdded: return "Market Pulse Added" case .marketPulseRemoved: return "Market Pulse Removed" case .marketPulseChanged: return "Market Pulse Settings Changed" } } public var params: [String : String] { switch self { case .marketPulseChanged(let style, let interval, let assetsIds): return ["Style": style == .classic ? "Classic" : "Dark", "Interval": interval.title, "Assets": assetsIds.joined(separator: ",")] default: return [:] } } } }
// // ViewExtensions.swift // BooksManager // // Created by Sebastian Staszczyk on 12/03/2021. // import SwiftUI // MARK: -- Embed in Navigation View extension View { func embedInNavigationView(_ style: NavigationBarItem.TitleDisplayMode = .automatic) -> some View { NavigationView { self.navigationBarTitleDisplayMode(style) } .navigationViewStyle(StackNavigationViewStyle()) } } // MARK: -- Change Size extension View { func changeSize(maxWidth: CGFloat? = nil, maxHeight: CGFloat? = nil, contentMode: ContentMode = .fit) -> some View { self .aspectRatio(contentMode: contentMode) .frame(maxWidth: maxWidth, maxHeight: maxHeight) } } // MARK: -- Dismiss Keyboard #if canImport(UIKit) extension View { func hideKeyboard() { UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) } } #endif
// // MenuViewController.swift // View2ViewTransitionExample // // Created by naru on 2016/09/06. // Copyright © 2016年 naru. All rights reserved. // import UIKit public class MenuViewController: UIViewController { override public func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.view.addSubview(self.tableView) } override public func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard !self.isViewControllerInitialized else { return } self.isViewControllerInitialized = true self.present(PresentingViewController(), animated: true, completion: nil) } // MARK: Constants private struct Constants { static let Font: UIFont = UIFont.systemFont(ofSize: 15.0) static let ButtonSize: CGSize = CGSize(width: 200.0, height: 44.0) } // MARK: Elements private var isViewControllerInitialized: Bool = false lazy var tableView: UITableView = { let tableView: UITableView = UITableView(frame: self.view.bounds, style: .grouped) tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") tableView.register(TableViewSectionHeader.self, forHeaderFooterViewReuseIdentifier: "header") tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.delegate = self tableView.dataSource = self return tableView }() } extension MenuViewController: UITableViewDataSource { public func numberOfSections(in tableView: UITableView) -> Int { return 1 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath) self.configulerCell(cell, at: indexPath as NSIndexPath) return cell } func configulerCell(_ cell: UITableViewCell, at indexPath: NSIndexPath) { cell.accessoryType = .disclosureIndicator cell.textLabel?.font = UIFont.systemFont(ofSize: 14.0) switch indexPath.row { case 0: cell.textLabel?.text = "Present and Dismiss" case 1: cell.textLabel?.text = "Push and Pop" default: break } } } extension MenuViewController: UITableViewDelegate { public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return TableViewSectionHeader.Constants.Height } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 44.0 } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: self.present(PresentingViewController(), animated: true, completion: nil) case 1: self.present(UINavigationController(rootViewController: PresentingViewController()), animated: true, completion: nil) default: break } tableView.deselectRow(at: indexPath as IndexPath, animated: true) } } private class TableViewSectionHeader: UITableViewHeaderFooterView { struct Constants { static let Height: CGFloat = 60.0 static let Width: CGFloat = UIScreen.main.bounds.width static let Font: UIFont = UIFont.boldSystemFont(ofSize: 14.0) } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) self.contentView.addSubview(self.titleLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var titleLabel: UILabel = { let frame: CGRect = CGRect(x: 12.0, y: Constants.Height - ceil(Constants.Font.lineHeight) - 8.0, width: Constants.Width - 24.0, height: ceil(Constants.Font.lineHeight)) let label: UILabel = UILabel(frame: frame) label.font = Constants.Font label.text = "Examples of View2View Transition" label.textColor = UIColor(white: 0.3, alpha: 1.0) return label }() }
import UIKit typealias AccountBlock = (_ success : Bool, _ request: Account, _ errorMessage: String) -> (Void) class Account: NSObject ,NSCoding { var accountBlock: AccountBlock = {_,_,_ in } var name : String = "" var last_name : String = "" var first_name : String = "" var email : String = "" var mobile_no : String = "" var avtar : String = "" var facebookId : String = "" var userId : String = "" var facebook_accessToken : String = "" var apple_accessToken : String = "" var accessToken : String = "" var radius : Int = 0 var device_type : String = "" var device_token : String = "" let ENCODING_VERSION:Int = 1; override init() {} func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "name"); aCoder.encode(last_name, forKey: "last_name"); aCoder.encode(first_name, forKey: "first_name"); aCoder.encode(mobile_no, forKey: "mobile_no"); aCoder.encode(email, forKey: "email"); aCoder.encode(avtar, forKey: "avtar"); aCoder.encode(facebookId, forKey: "facebook"); aCoder.encode(userId, forKey: "userId"); aCoder.encode(facebook_accessToken, forKey: "facebook_accessToken"); aCoder.encode(apple_accessToken, forKey: "apple_accessToken"); aCoder.encode(accessToken, forKey: "token"); aCoder.encode(ENCODING_VERSION, forKey: "version"); aCoder.encode(radius, forKey: "radius"); aCoder.encode(device_type, forKey: "device_type"); aCoder.encode(device_token, forKey: "device_token"); } required init?(coder aDecoder: NSCoder) { if(aDecoder.decodeInteger(forKey: "version") == ENCODING_VERSION) { name = aDecoder.decodeObject(forKey: "name") as? String ?? "" last_name = aDecoder.decodeObject(forKey: "last_name") as? String ?? "" first_name = aDecoder.decodeObject(forKey: "first_name") as? String ?? "" mobile_no = aDecoder.decodeObject(forKey: "mobile_no") as? String ?? "" email = aDecoder.decodeObject(forKey: "email") as? String ?? "" avtar = aDecoder.decodeObject(forKey: "avtar") as? String ?? "" facebookId = aDecoder.decodeObject(forKey: "facebookId") as? String ?? "" userId = aDecoder.decodeObject(forKey: "userId") as? String ?? "" facebook_accessToken = aDecoder.decodeObject(forKey: "facebook_accessToken") as? String ?? "" apple_accessToken = aDecoder.decodeObject(forKey: "apple_accessToken") as? String ?? "" accessToken = aDecoder.decodeObject(forKey: "accessToken") as? String ?? "" radius = aDecoder.decodeObject(forKey: "radius") as? Int ?? 0 device_type = aDecoder.decodeObject(forKey: "device_type") as? String ?? "" device_token = aDecoder.decodeObject(forKey: "device_token") as? String ?? "" } } func parseDict(inDict:[String : Any]) { if let aStr = inDict["id"] as? String{ self.facebookId = aStr self.avtar = "https://graph.facebook.com/v2.6/\(self.facebookId)/picture?type=large" } if let aStr = inDict["name"] as? String{ self.name = aStr } if let aStr = inDict["last_name"] as? String{ self.last_name = aStr } if let aStr = inDict["first_name"] as? String{ self.first_name = aStr } if let aStr = inDict["email"] as? String{ self.email = aStr } if let aStr = inDict["mobile_no"] as? String{ self.mobile_no = aStr } if let aStr = inDict["radius"] as? Int{ self.radius = aStr } if let aStr = inDict["device_type"] as? Int{ self.radius = aStr } if let aStr = inDict["device_token"] as? Int{ self.radius = aStr } } func updateDeviceToken(block : @escaping AccountBlock){ let request = Request.init(url: "\(kBaseUrl)\(kDeviceToken)\(self.userId)", method: .post) { (success:Bool, request:Request, message:NSString) -> (Void) in print(request) guard request.isSuccess else{ block(false,self,message as String) return } block(true,self,message as String) } let device = ["device_type":"iOS","device_token": ""] as [String : Any] request.setParameter(device, forKey: "device") request.startRequest() } }
// // ViewControllerViewModel.swift // CMoney_02_displayImageDemo // // Created by 張彩虹 on 2020/8/6. // Copyright © 2020年 張彩虹. All rights reserved. // import UIKit class ViewControllerViewModel { }
// // DequeIterator.swift // LiteTable // // Created by Yaxin Cheng on 2018-10-10. // Copyright © 2018 Yaxin Cheng. All rights reserved. // import Foundation struct DequeIterator<T>: IteratorProtocol { typealias Element = T private var current: Deque<T>.Node<T>? private let firstNode: Deque<T>.Node<T>? private var beforeFirstNode: Bool init(beginNode: Deque<T>.Node<T>?) { current = beginNode beforeFirstNode = true firstNode = beginNode } mutating func next() -> T? { if beforeFirstNode { beforeFirstNode = false return current?.content } else { guard current?.next != nil else { return nil } current = current?.next return current?.content } } mutating func previous() -> T? { if beforeFirstNode { return nil } guard current !== firstNode else { beforeFirstNode = true return nil } if current?.prev == nil { return nil } current = current?.prev return current?.content } var content: T? { return current?.content } }
// // USEWalletTxRecordCell.swift // USEChainWallet // // Created by Jacob on 2019/3/1. // Copyright © 2019 Jacob. All rights reserved. // import UIKit class USEWalletTxRecordCell: UITableViewCell { override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.backgroundColor = UIColor.white setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: -LazyloadKit fileprivate lazy var address: UILabel = UILabel(title: "0xasdfeasd.....SADWAew123", fontSize: 15, color: UIColor.black, redundance: 0) fileprivate lazy var date: UILabel = UILabel(title: "02-23-2019 22:10:29", fontSize: 12, color: UIColor.gray, redundance: 0) fileprivate lazy var count: UILabel = UILabel(title: "+3,500.123123", fontSize: 18, color: UIColor.black, redundance: 0) } extension USEWalletTxRecordCell { fileprivate func setupUI() { // addSubviews self.contentView.addSubview(address) self.contentView.addSubview(date) self.contentView.addSubview(count) for v in self.contentView.subviews { v.translatesAutoresizingMaskIntoConstraints = false } // layout address.snp.makeConstraints { (make) in make.top.equalTo(self.contentView).offset(10) make.left.equalTo(self.contentView).offset(10) } date.snp.makeConstraints { (make) in make.left.equalTo(self.contentView).offset(10) make.bottom.equalTo(self.contentView).offset(-10) } count.snp.makeConstraints { (make) in make.centerY.equalTo(self.contentView) make.right.equalTo(self.contentView).offset(-10) } } }
// // ZXDrugstoreListModel.swift // YDHYK // // Created by 120v on 2017/11/7. // Copyright © 2017年 screson. All rights reserved. // import UIKit @objcMembers class ZXDrugstoreListModel: LKDBModel { var storeId: Int = -1 var groupId: Int = -1 var groupName: String = "" var name: String = "" var tel: String = "" var address: String = "" var longitude: String = "" var latitude: String = "" var provinceId: Int = -1 var provinceName: String = "" var cityId: Int = -1 var cityName: String = "" var districtId: Int = -1 var districtName: String = "" var profile: String = "" var headPortrait: String = "" var headPortraitStr: String = "" var qrCode: String = "" var status: Int = -1 var remark: String = "" var distance: String = "" var isChineseMedicine: Int = -1 var isMember: Int = -1 /** 添加一个float字段,方便SQL筛选条件*/ var distanceF: Float = 0.0 override static func mj_replacedKeyFromPropertyName() -> [AnyHashable : Any]! { return ["storeId":"id"] } override class func describeColumnDict() -> [AnyHashable : Any] { var dic: Dictionary<String,Any> = Dictionary() let account: LKDBColumnDes = LKDBColumnDes() account.isPrimaryKey = true account.columnName = "storeId" let name:LKDBColumnDes = LKDBColumnDes.init(generalFieldWithAuto: false, unique: false, isNotNull: true, check: nil, defaultVa: nil) let noField:LKDBColumnDes = LKDBColumnDes() noField.isUseless = true dic["storeId"] = account dic["name"] = name dic["noField"] = noField return dic } }
// // NewsFeedPresenter.swift // VKNews // // Created by Eugene Kiselev on 20.02.2021. // Copyright (c) 2021 ___ORGANIZATIONNAME___. All rights reserved. // import UIKit protocol NewsFeedPresentationLogic { func presentData(response: NewsFeed.Model.Response.ResponseType) } class NewsFeedPresenter: NewsFeedPresentationLogic { weak var viewController: NewsFeedDisplayLogic? func presentData(response: NewsFeed.Model.Response.ResponseType) { switch response { case .presentNewsFeed(feed: let feed): let cells = feed.items.map { (feedItem) in cellViewModel(from: feedItem) } let feedViewModel = FeedViewModel.init(cells: cells) viewController?.displayData(viewModel: .displayNewsFeed(feedViewModel: feedViewModel)) } } private func cellViewModel(from feedItem: FeedItem) -> FeedViewModel.Cell { return FeedViewModel.Cell.init(iconURL: "URL IMAGE", name: "names", date: "00:00", text: feedItem.text, likes: String(feedItem.likes?.count ?? 0), comments: String(feedItem.comments?.count ?? 0), shares: String(feedItem.reposts?.count ?? 0), views: String(feedItem.views?.count ?? 0)) } }
// // SendToFriendsViewController.swift // PansChat2 // // Created by Jakub Iwaszek on 01/10/2020. // import UIKit class SendToFriendsViewController: UIViewController, Storyboarded { @IBOutlet weak var tableView: UITableView! var friendsList: [User] = [] var currentUser: User! weak var coordinator: MainCoordinator? var imageData: Data! var selectedUsers: [Int : User] = [:] override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.tableFooterView = UIView() fetchFriendsData() } func fetchFriendsData() { guard let currentUser = currentUser else { return } FirebaseDatabase.shared.getUserFriends(user: currentUser) { (friends) in guard let friends = friends else { return } self.friendsList = friends self.tableView.reloadData() } } @IBAction func sendToUsersButtonAction(_ sender: UIButton) { print(selectedUsers.count) if !selectedUsers.isEmpty { Loader.start(view: self.view ) FirebaseDatabase.shared.sendPhotoToUsers(fromUser: currentUser, toUsers: selectedUsers, photoData: imageData) { (checker) in Loader.stop() if checker { self.navigationController?.popToRootViewController(animated: true) } } } } } extension SendToFriendsViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return friendsList.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "FriendsTableViewCell", for: indexPath) as! FriendsTableViewCell cell.isFriendList = true //dac inne zdjecie cell cell.model = friendsList[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! FriendsTableViewCell cell.contentView.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1) selectedUsers.updateValue(cell.model, forKey: indexPath.row) //cos z indexem? print(selectedUsers) } func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! FriendsTableViewCell cell.contentView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) selectedUsers.removeValue(forKey: indexPath.row) print(selectedUsers) } }
//: [Previous](@previous) import Foundation /* func factorial(n: Int) -> Int { return n * factorial(n: n - 1) } */ func factorial(n: Int) -> Int { return n == 0 || n == 1 ? 1 : n * factorial(n: n - 1) } print(factorial(n: 3)) // recursive example func powerOfTwo(n: Int) -> Int { return n == 0 ? 1 : 2 * powerOfTwo(n: n - 1) } let fnResult = powerOfTwo(n: 3) // Non-recursive version func power2(n: Int) -> Int { var y = 1 for _ in 0...n - 1 { y *= 2 } return y } let result = power2(n: 4) // Recursive example func repateString(str: String, n: Int) -> String { return n == 0 ? "" : str + repateString(str: str , n: n - 1) } print(repateString(str: "Hello", n: 4)) // Non-recursive version func repeatString(str: String, n: Int) -> String { var ourString = "" for _ in 1...n { ourString += str } return ourString } print(repeatString(str: "Hello", n: 4)) //: [Next](@next)
// // SettingsController.swift // TWGSampleApp // // Created by Arsh Aulakh BHouse on 16/07/16. // Copyright © 2016 BHouse. All rights reserved. // import UIKit //MARK:- Interface class SettingsController: UITableViewController { //MARK: Properties //Outlets @IBOutlet weak var defaultThemeButton: UIButton! @IBOutlet weak var themeColorOneLabel: UILabel! @IBOutlet weak var themeColorOneSegmentColor: UISegmentedControl! @IBOutlet weak var themeColorTwoLabel: UILabel! @IBOutlet weak var themeColorTwoSegmentControl: UISegmentedControl! @IBOutlet weak var checkOnboardingButton: UIButton! //Constants let showCurrentSelectionForSegmentControl = { (color: UIColor, sender: UISegmentedControl) in switch color { case Color.Red.values.color: sender.selectedSegmentIndex = Color.Red.values.index case Color.Blue.values.color: sender.selectedSegmentIndex = Color.Blue.values.index case Color.Gray.values.color: sender.selectedSegmentIndex = Color.Gray.values.index case Color.Green.values.color: sender.selectedSegmentIndex = Color.Green.values.index case Color.White.values.color: sender.selectedSegmentIndex = Color.White.values.index case Color.Yellow.values.color: sender.selectedSegmentIndex = Color.Yellow.values.index default: return } } //MARK: Deinitilization deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } } //MRK:- Implementation extension SettingsController { //MARK: System override func viewDidLoad() { super.viewDidLoad() applyConfigurations() NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applyConfigurations), name: ConfigurationUpdatedKey, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) showCurrentSelections() updateAvailableOptionsByCurrentConfiguration() } //MARK: Apply Configurations func applyConfigurations() { tableView.backgroundColor = configuration.settingsConfiguration.backgroundColor navigationController?.navigationBar.barTintColor = configuration.settingsConfiguration.navigationBarTintColor navigationController?.navigationBar.tintColor = configuration.settingsConfiguration.navigationBarTextColor navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont.boldSystemFontOfSize(15), NSForegroundColorAttributeName: configuration.settingsConfiguration.navigationBarTextColor] //Set Labels Color themeColorOneLabel.textColor = configuration.settingsConfiguration.themeOneLabelColor themeColorTwoLabel.textColor = configuration.settingsConfiguration.themeTwoLabelColor //Set Segment Control Color themeColorOneSegmentColor.tintColor = configuration.settingsConfiguration.themeOneSegmentTintColor themeColorTwoSegmentControl.tintColor = configuration.settingsConfiguration.themeTwoSegmentTintColor //Set Buttons Colors defaultThemeButton.backgroundColor = configuration.secondaryThemeColor defaultThemeButton.setTitleColor(configuration.mainThemeColor, forState: .Normal) checkOnboardingButton.backgroundColor = configuration.secondaryThemeColor checkOnboardingButton.setTitleColor(configuration.mainThemeColor, forState: .Normal) } } extension SettingsController { //MARK: Handle Button Actions //Handle Resetting to default theme @IBAction func resetToDefaultThemeClicked(sender: UIButton) { configuration = Configuration() showCurrentSelections() updateAvailableOptionsByCurrentConfiguration() } //Handle Theme Override @IBAction func colorSelected(sender: UISegmentedControl) { guard let color = Color(rawValue: sender.selectedSegmentIndex) where sender.selectedSegmentIndex >= 0 && sender.selectedSegmentIndex <= 5 else { return } //Update Configuration var oldConfiguration = configuration if sender.tag == 1 { oldConfiguration.mainThemeColor = color.values.color } else { let color = color.values.color oldConfiguration.secondaryThemeColor = color } //Check For same colors in the theme configuration = Configuration(mainThemeColor: oldConfiguration.mainThemeColor, secondaryThemeColor: oldConfiguration.secondaryThemeColor) updateAvailableOptionsByCurrentConfiguration() } //Check Onboarding Flow @IBAction func checkOnboardingFlowClicked(sender: AnyObject) { if let welcomeObject = storyboard?.instantiateViewControllerWithIdentifier("WelcomeController") as? WelcomeController { welcomeObject.isDismissable = true presentViewController(welcomeObject, animated: true, completion: nil) } } } extension SettingsController { //MARK: Additionals func showCurrentSelections() { showCurrentSelectionForSegmentControl(configuration.mainThemeColor, themeColorOneSegmentColor) showCurrentSelectionForSegmentControl(configuration.secondaryThemeColor, themeColorTwoSegmentControl) } func updateAvailableOptionsByCurrentConfiguration() { //Show Selections If user leaves the segment unselected if !themeColorOneSegmentColor.selected { showCurrentSelectionForSegmentControl(configuration.mainThemeColor, themeColorOneSegmentColor) } if !themeColorTwoSegmentControl.selected { showCurrentSelectionForSegmentControl(configuration.secondaryThemeColor, themeColorTwoSegmentControl) } //Update Options let updateOptions = { (color: UIColor, sender: UISegmentedControl) in //Enable All Options for index in 0..<sender.numberOfSegments { sender.setEnabled(true, forSegmentAtIndex: index) } //Disable Unavailable Option switch color { case Color.Red.values.color: sender.setEnabled(false, forSegmentAtIndex: Color.Red.values.index) case Color.Blue.values.color: sender.setEnabled(false, forSegmentAtIndex: Color.Blue.values.index) case Color.Gray.values.color: sender.setEnabled(false, forSegmentAtIndex: Color.Gray.values.index) case Color.Green.values.color: sender.setEnabled(false, forSegmentAtIndex: Color.Green.values.index) case Color.White.values.color: sender.setEnabled(false, forSegmentAtIndex: Color.White.values.index) case Color.Yellow.values.color: sender.setEnabled(false, forSegmentAtIndex: Color.Yellow.values.index) default: sender.setEnabled(false, forSegmentAtIndex: Color.Yellow.values.index) return } } //Perform options updations updateOptions(configuration.mainThemeColor, themeColorTwoSegmentControl) updateOptions(configuration.secondaryThemeColor, themeColorOneSegmentColor) } }
// // ViewController.swift // SimpleTranslate // // Created by Artur Antonov on 04/12/2019. // Copyright © 2019 Artur. All rights reserved. // import UIKit import Foundation import Combine class ViewController: UIViewController { private var textInputView: UITextView! private var textOutputView: UITextView! @Published var requestString: String? var subscriber: AnyCancellable? override func viewDidLoad() { super.viewDidLoad() subscriber = AnyCancellable($requestString .removeDuplicates() .debounce(for: 0.5, scheduler: DispatchQueue.main) .sink(){[unowned self] sendString in self.sendRequest(requestString: sendString) }) view.backgroundColor = UIColor(red: 1, green: 0.88, blue: 0.45, alpha: 1) let font = UIFont.systemFont(ofSize: 20) textInputView = UITextView(frame: CGRect(x: 8, y: 44, width: view.bounds.width - 16, height: 100) ) textInputView.font = font textInputView.delegate = self view.addSubview(textInputView) let separator = UIView(frame: CGRect(x: 6, y: 148, width: view.bounds.width - 12, height: 2) ) separator.backgroundColor = .gray view.addSubview(separator) textOutputView = UITextView(frame: CGRect(x: 8, y: 154, width: view.bounds.width - 16, height: 100) ) textOutputView.font = font textOutputView.isEditable = false view.addSubview(textOutputView) } func sendRequest(requestString: String?){ if let text = requestString{ let apiKey = "" let url = URL( string: "https://translate.yandex.net/api/v1.5/tr.json/translate?key=\(apiKey)&text=\(text)&lang=en-ru" )! URLSession.shared.dataTask(with: url) { (data, response, error) in guard let data = data else { return } let dictionary = try! JSONSerialization.jsonObject( with: data, options: [] ) as! [String: Any] let translation = dictionary["text"] as! [String] DispatchQueue.main.async { self.textOutputView.text = translation.first! } }.resume() } } } extension ViewController: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { guard !textView.text.isEmpty else { textOutputView.text = "" return } let text = textView.text.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)! self.requestString = text } }
// main.swift // EchoClient sample programm // Simplenet // Copyright (c) 2018 Vladimir Raisov. All rights reserved. // Licensed under MIT License import Dispatch import Sockets import Interfaces import Transceiver let stopsem = DispatchSemaphore(value: 0) func stop(_: Int32) { print("\r", terminator: "") stopsem.signal() } struct ReplyAcceptor: DatagramHandler { func dataDidRead(_ datagram: Datagram) { let data = datagram.data print(" Reply received", terminator: "") datagram.sender.map{print(" from \($0)", terminator: "")} print(" with \(data.count) bytes of data:") String(data: datagram.data, encoding: .utf8).map{print(" \($0)")} } func errorDidOccur(_ error: Error) { print(error) stopsem.signal() } } let args = CommandLine.arguments let arg1 = args.dropFirst().first let arg2 = args.dropFirst().dropFirst().first let arg3 = args.dropFirst().dropFirst().dropFirst().first let rest = args.dropFirst().dropFirst().dropFirst().dropFirst().first func interface(_ name: String) -> Interface? { guard let interface = (Interfaces().first{$0.name == name}) else { print("Invalid value \"\(name)\" for <interface-name> parameter") print("Use `ifconfig` to view interfaces names") exit(2) } return interface } do { var transmitter: Transmitter switch (arg1, arg1.flatMap(UInt16.init), arg2.flatMap(UInt16.init), arg2, arg3, rest) { case (.some(let host), .none, .some(let port), _, let iname, .none): transmitter = try Transmitter(host: host, port: port, interface: iname.flatMap(interface)) case (_, .some(let port), .none, let iname, .none, _): transmitter = try Transmitter(port: port, interface: iname.flatMap(interface)) default: let cmd = String(args.first!.reversed().prefix{$0 != "/"}.reversed()) print("usage: \(cmd) [<host-name>] <port> [<interface-name>]") exit(1) } transmitter.delegate = ReplyAcceptor() print("Transmitter has been created.") print("Enter data to send: ", terminator: "") guard let data = readLine()?.data(using: .utf8) else {exit(0)} try transmitter.send(data: data) print(" \(data.count) bytes sent.") guard !data.isEmpty else {exit(0)} print("Waiting for reply. Press Ctrl-C to cancel.") signal(SIGINT, stop) // Ctrl-C signal(SIGQUIT, stop) // Ctrl-\ signal(SIGTSTP, stop) // Ctrl-Z _ = stopsem.wait(timeout: DispatchTime.now() + .seconds(2)) print("Waiting is over.") } catch { print(error) print("Transmitter can't be created.") }
import XCTest class PCParserTests: XCTestCase { func test_can_resolve_variables_in_value() { let variableList = PCList<PCVariable>( items: [ PCVariable(name: "var1", value: "yummy"), PCVariable(name: "var2", value: "yucky") ] ) let parser = PCParser(name: "parser", value: "{{var1}} is not {{var2}}") let value = parser.parsedValue(variables: variableList) XCTAssertEqual(value, "yummy is not yucky") } }
// // Moods.swift // Music-Player-App // // Created by Zari McFadden on 7/15/21. // import Foundation enum Moods: Identifiable { var id: Self { self } static var allCases: [Moods] = [.chillOut, .study, .soulful, .pop] case chillOut case study case soulful case pop var title: String { switch self { case .chillOut: return "Chill Out" case .study: return "Study" case .soulful: return "Soulful" case .pop: return "Pop" } } }
// // CategoryTableViewCell.swift // Free Ebook // // Created by MinhNT-Mac on 1/11/19. // Copyright © 2019 MinhNT-Mac. All rights reserved. // import UIKit protocol ConfigCellCategory { func setData(item:StoryEntity) } class CategoryTableViewCell: UITableViewCell, ConfigCellCategory { @IBOutlet weak var imgAvatar: UIImageView! @IBOutlet weak var lblName: UILabel! @IBOutlet weak var viewContent: UIView! override func awakeFromNib() { super.awakeFromNib() viewContent.setuplayoutCollectionView() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setData(item: StoryEntity) { lblName.text = item.name imgAvatar.image = UIImage(named: "\((item.name)!)") } @IBAction func selectCategory(_ sender: Any) { self.selectCategory?() } var selectCategory:(()->())? }
// // HippoSupportList.swift // SDKDemo1 // // Created by Vishal on 22/08/18. // Copyright © 2018 CL-macmini-88. All rights reserved. // import Foundation class HippoSupportList: NSObject { static var currentPathArray = [ListIdentifiers]() static var FAQName = "FAQ" static var list = [HippoSupportList]() static var currentFAQVersion: Int { get { return UserDefaults.standard.value(forKey: UserDefaultkeys.currentFAQVersion) as? Int ?? 0 } set { UserDefaults.standard.set(newValue, forKey: UserDefaultkeys.currentFAQVersion) } } static var FAQData: [String: Any] { get { return UserDefaults.standard.value(forKey: UserDefaultkeys.TicketsKey) as? [String: Any] ?? [:] } set { UserDefaults.standard.set(newValue, forKey: UserDefaultkeys.TicketsKey) } } var id = -1 var title = "" var parent_id = -1 var isActive = false var createdAt = "" var updatedAt = "" var action = ActionType.LIST var viewType = ViewType.list var content = HippoDescriptionContent() var items = [HippoSupportList]() override init() { } init(json: [String: Any]) { id = json["support_id"] as? Int ?? -1 title = json["title"] as? String ?? "" parent_id = json["parent_id"] as? Int ?? -1 createdAt = json["created_at"] as? String ?? "" updatedAt = json["updated_at"] as? String ?? "" if let action_type = json["action_type"] as? Int, let type = ActionType(rawValue: action_type) { action = type } if let view_type = json["view_type"] as? Int, let view = ViewType(rawValue: view_type) { viewType = view } if let is_active = json["is_active"] as? String { isActive = is_active == "1" ? true : false } if let content = json["content"] as? [String: Any] { self.content = HippoDescriptionContent(json: content) } guard let items = json["items"] as? [[String: Any]] else { return } for each in items { self.items.append(HippoSupportList(json: each)) } } class func getObjectFrom(_ array: [[String: Any]]) -> [HippoSupportList] { var tempArr = [HippoSupportList]() for each in array { let obj = HippoSupportList(json: each) if obj.id > 0 { tempArr.append(obj) } } return tempArr } class func getDataFromJson(dict: [String: Any]) -> [HippoSupportList] { var tempArray = [HippoSupportList]() guard let is_faq_enabled = userDetailData["is_faq_enabled"] as? Bool, is_faq_enabled else { return tempArray } var defaultKey = "Default" guard let support_data = dict["data"] as? [String: Any] else { return tempArray } if let key = dict["defaultFaqName"] as? String { defaultKey = key } HippoSupportList.FAQData = dict var data = [String: Any]() var list = [[String:Any]]() if !HippoConfig.shared.ticketDetails.FAQName.isEmpty, let temp = getListwhere(key: HippoConfig.shared.ticketDetails.FAQName, from: support_data), let lists = temp["list"] as? [[String: Any]] { list = lists data = temp } else if !defaultKey.isEmpty, let temp = getListwhere(key: defaultKey, from: support_data), let lists = temp["list"] as? [[String: Any]] { list = lists data = temp } if let category_name = data["faq_name"] as? String { HippoSupportList.FAQName = category_name } tempArray = HippoSupportList.getObjectFrom(list) return tempArray } class func getListwhere(key: String, from data: [String: Any]) -> [String: Any]? { var response: [String: Any]? for (_, value) in data { guard let dict = value as? [String: Any], let name = dict["faq_name"] as? String else { continue } if name.lowercased() == key.lowercased(){ response = dict return response } } return response } class func getListForBusiness(completion: ((_ success: Bool, _ objectArray: [HippoSupportList]?) -> Void)? = nil) { guard let userId = HippoUserDetail.fuguEnUserID else { return } let params: [String: Any] = ["app_secret_key" : HippoConfig.shared.appSecretKey, "en_user_id" : userId, "is_active": 1] print(params) HTTPClient.makeConcurrentConnectionWith(method: .POST, para: params, extendedUrl: "api/business/getBusinessSupportPanel") {(responseObject, error, tag, statusCode) in switch (statusCode ?? -1) { case StatusCodeValue.Authorized_Min.rawValue..<StatusCodeValue.Authorized_Max.rawValue: guard let response = responseObject as? [String: Any] else { return } let array = HippoSupportList.getDataFromJson(dict: response) completion?(true, array) case 406: completion?(false, nil) default: completion?(false, nil) } } } } struct ListIdentifiers { var id = 0 var title = "" var parentId = -1 init(id: Int, title: String, parentId: Int) { self.id = id self.title = title self.parentId = parentId } }
// // MyEventsProtocols.swift // app // // Created by Иван Лизогуб on 08.12.2020. // // import Foundation enum LoadingDataType { case nextPage case reload } protocol MyEventsModuleInput { var moduleOutput: MyEventsModuleOutput? { get } } protocol MyEventsModuleOutput: class { } protocol MyEventsViewInput: class { func updateCurrentView(with viewModels: [EventViewModel]) func updateForthcomingView(with viewModels: [EventViewModel]) func updateCompletedView(with viewModels: [EventViewModel]) } protocol MyEventsViewOutput: class { func viewDidLoad() func willDisplay(at index: Int, segmentIndex: Int) } protocol MyEventsInteractorInput: class { func reload() func loadCompleted() } protocol MyEventsInteractorOutput: class { func didLoadCurrent(with events: [Tournament], loadType: LoadingDataType) func didLoadForthcoming(with events: [Tournament], loadType: LoadingDataType) func didLoadCompleted(with events: [Tournament], eventsCountInDB: Int, loadType: LoadingDataType) } protocol MyEventsRouterInput: class { }
// // InformationModel.swift // KifuSF // // Created by Alexandru Turcanu on 04/01/2019. // Copyright © 2019 Alexandru Turcanu. All rights reserved. // import UIKit // MARK: - InformationModel struct InformationModel { // MARK: - Variables private let information: String var cellTitle: String var errorAlertController: UIAlertController // MARK: - Initializers init(cellTitle: String, information: String, errorMessage: String? = nil) { self.cellTitle = cellTitle self.information = information self.errorAlertController = UIAlertController(errorMessage: errorMessage) } } // MARK: - SettingsItemProtocol extension InformationModel: SettingsItem { var viewControllerToShow: UIViewController { let viewController = UIViewController() let textView = UITextView( font: UIFont.preferredFont(forTextStyle: .body), textColor: UIColor.Text.SubHeadline ) viewController.view.addSubview(textView) viewController.view.directionalLayoutMargins = NSDirectionalEdgeInsetsMake(16, 16, 16, 16) textView.translatesAutoresizingMaskIntoConstraints = false textView.autoPinEdgesToSuperviewMargins() textView.text = information textView.alwaysBounceVertical = true viewController.title = cellTitle viewController.view.backgroundColor = UIColor.Pallete.White return viewController } func didSelectItem(in viewController: UIViewController) { viewController.navigationController?.pushViewController(viewControllerToShow, animated: true) } }
/* Copyright 2011-present Samuel GRAU Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // // FluableView : FluableView.swift // import Foundation import UIKit public class FluableView: UITableView { public override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) self.registerToTheCellFactory() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.registerToTheCellFactory() } deinit { self.unregisterFromTheCellFactory() } // MARK: - Private private func registerToTheCellFactory() { let tvcf = TableCellFactory.sharedInstance tvcf.registerTableView(self) } private func unregisterFromTheCellFactory() { let tvcf = TableCellFactory.sharedInstance tvcf.unregisterTableView(self) } }
// // LoginViewController.swift // coachApp // // Created by ESPRIT on 24/03/2018. // Copyright © 2018 ESPRIT. All rights reserved. // import UIKit import Alamofire import Firebase class LoginViewController: UIViewController { let connectUser = "http://172.19.20.20/coachAppService/web/app_dev.php/users/" @IBOutlet weak var emailtext: DesignableTextField! @IBOutlet weak var passwordtext: DesignableTextField! var conncted = false override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginAction(_ sender: Any) { Auth.auth().signIn(withEmail: emailtext.text! , password: passwordtext.text!) { (user, error) in if error != nil { print (error!) return } } let parameters = [ "email": emailtext.text! , "password": passwordtext.text!, ] Alamofire.request(connectUser, method: .post, parameters: parameters).responseJSON { response in switch response.result { case .success: let res = response.result.value as! NSDictionary //example if there is an id let error = res.object(forKey: "error") as! Bool if error == false { let firstname = res.object(forKey: "firstName")! let lastName = res.object(forKey: "lastName")! let image = res.object(forKey: "image")! let email = res.object(forKey: "email")! let role = res.object(forKey: "role")! UserDefaults.standard.set(role, forKey: "role") UserDefaults.standard.set(firstname, forKey: "firstName") //setObject UserDefaults.standard.set(lastName, forKey: "lastName") //setObject UserDefaults.standard.set(image, forKey: "image") //setObject UserDefaults.standard.set(email, forKey: "email") //setObject self.performSegue(withIdentifier: "loginToHome", sender: nil) } else{ let alert = UIAlertController(title: "Login Failed", message: "Your password or mail is wrong", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } case .failure(let error): print(error) } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
// // WHCalendar.swift // WHCalendar // // Created by 王浩 on 2018/8/28. // Copyright © 2018年 haoge. All rights reserved. // import UIKit import SnapKit //回调 typealias ObjectCallback = (_ value: Any) -> Void let kScreenWidth: CGFloat = UIScreen.main.bounds.width let kScreenHeight: CGFloat = UIScreen.main.bounds.height let spaceMargin: CGFloat = 5.0 let KShowYearsCount: Int = 100 let KTipWidth: CGFloat = kScreenWidth/5 let KCol: Int = 7 let KBtnW: CGFloat = (kScreenWidth-KTipWidth-2*spaceMargin)/CGFloat(KCol) let KMaxCount: Int = 37 let KBtnTag: Int = 100 //适配iPhoneX var IS_IPHONE_X: Bool { return UIScreen.instancesRespond(to: #selector(getter: UIDynamicItem.bounds)) ? CGSize(width: 375, height: 812).equalTo(UIScreen.main.bounds.size) : false } let navHeight:CGFloat = IS_IPHONE_X ? 24 : 0 let tabHeight:CGFloat = IS_IPHONE_X ? 34 : 0 class WHCalendar: UIView { enum AnimationType { case top case bottom case center } var callback: ObjectCallback? //默认底部出现 var animationType = AnimationType.bottom var dafaultDate: Date = Date() var model = CalendarModel() fileprivate var weekArray: [String]? fileprivate var timeArray: [[String]]? fileprivate var yearArray: [String]? fileprivate var monthArray: [String]? fileprivate var calendarView: UIView! fileprivate var weekLabel: UILabel! fileprivate var yearLabel: UILabel! fileprivate var monthLabel: UILabel! fileprivate var dayLabel: UILabel! fileprivate var year: Int? fileprivate var month: Int? fileprivate var day: Int? fileprivate var currentYear: Int? fileprivate var currentMonth: Int? fileprivate var currentDay: Int? fileprivate var selectYear: Int? fileprivate var selectMonth: Int? fileprivate var yearBtn: WHOpthionButton! fileprivate var monthBtn: WHOpthionButton! fileprivate var yearBtnW: CGFloat = 70.0 fileprivate var monthbtnW: CGFloat = 70.0 fileprivate var todayBtnW: CGFloat = 70.0 fileprivate var control: UIControl? override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK:-初始化设置 fileprivate func setDefaultInfo(date: Date) { let components = Calendar.current year = components.component(.year, from: date) month = components.component(.month, from: date) day = components.component(.day, from: date) selectYear = year selectMonth = month self.getDatasouce() } //MARK:-获取当前时间 fileprivate func getCurrentDate() { let components = Calendar.current currentYear = components.component(.year, from: Date()) currentMonth = components.component(.month, from: Date()) currentDay = components.component(.day, from: Date()) self.setDefaultInfo(date: dafaultDate) } //MARK:-获取数据源 fileprivate func getDatasouce() { weekArray = ["日", "一", "二", "三", "四", "五", "六"] timeArray = [["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"], ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59"]] let firstYear = year! - KShowYearsCount/2 var yearArr = [String]() for i in 0..<KShowYearsCount { yearArr.append("\(firstYear+i)") } yearArray = yearArr monthArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"] } //MARK:-创建控件 fileprivate func creatControl() { //左侧视图 let letfView = UIView() letfView.backgroundColor = model.leftViewBackgroundColor self.addSubview(letfView) letfView.snp.makeConstraints { (make) in make.left.top.equalTo(self) make.width.equalTo(KTipWidth) make.height.equalTo(self.frame.height) } //星期标签 weekLabel = UILabel() weekLabel.backgroundColor = model.weekBackgroundColor weekLabel.textColor = model.weekLabelTextColor weekLabel.textAlignment = .center weekLabel.font = model.weekLabelFont letfView.addSubview(weekLabel) weekLabel.snp.makeConstraints { (make) in make.left.top.right.equalTo(letfView) make.height.equalTo(KBtnW) } //年份标签 yearLabel = UILabel() yearLabel.textColor = model.yearLabelTextColor yearLabel.textAlignment = .center yearLabel.font = model.yearLabelFont letfView.addSubview(yearLabel) yearLabel.snp.makeConstraints { (make) in make.top.equalTo(weekLabel.snp.bottom).offset(20) make.left.right.equalTo(letfView) } //月份标签 monthLabel = UILabel() monthLabel.textColor = model.monthLabelTextColor monthLabel.textAlignment = .center monthLabel.font = model.monthLabelFont letfView.addSubview(monthLabel) monthLabel.snp.makeConstraints { (make) in make.left.right.equalTo(letfView) make.top.equalTo(yearLabel.snp.bottom) } //日期标签 dayLabel = UILabel() dayLabel.textColor = model.dayLabelTextColor dayLabel.textAlignment = .center dayLabel.font = model.dayLabelFont letfView.addSubview(dayLabel) dayLabel.snp.makeConstraints { (make) in make.left.right.equalTo(letfView) make.centerY.equalTo(letfView.snp.centerY) } yearBtn = WHOpthionButton(frame: CGRect.zero, row: KShowYearsCount/2, array: yearArray, model: self.model) yearBtn.callBack = { [unowned self](value) in if let btn = value as? WHOpthionButton { if (btn.title?.count)! > 2 { self.year = Int(btn.title!) self.yearBtn.title = "\(self.year!)年" } else { self.month = Int(btn.title!) self.monthBtn.title = "\(self.month!)月" } } self.reloadData() } self.addSubview(yearBtn) yearBtn.snp.makeConstraints { (make) in make.left.equalTo(letfView.snp.right) make.top.equalTo(self.snp.top) make.height.equalTo(KBtnW) make.width.equalTo((self.frame.width-KTipWidth)*1.5/5) } let containerW = (self.frame.width-KTipWidth)*2/5 let container = UIView() self.addSubview(container) container.snp.makeConstraints { (make) in make.left.equalTo(yearBtn.snp.right) make.top.equalTo(yearBtn.snp.top) make.height.equalTo(KBtnW) make.width.equalTo(containerW) } let preMonthBtn = UIButton(type: .custom) preMonthBtn.setImage(UIImage(named:"left"), for: .normal) preMonthBtn.addTarget(self, action: #selector(preBtnOnClick(_:)), for: .touchUpInside) container.addSubview(preMonthBtn) preMonthBtn.snp.makeConstraints { (make) in make.top.left.bottom.equalTo(container) make.width.equalTo(containerW/4) } monthBtn = WHOpthionButton(frame: CGRect.zero, row: month!-1, array: monthArray, model: self.model) monthBtn.callBack = { [unowned self](value) in if let btn = value as? WHOpthionButton { if (btn.title?.count)! > 2 { self.year = Int(btn.title!) self.yearBtn.title = "\(self.year!)年" } else { self.month = Int(btn.title!) self.monthBtn.title = "\(self.month!)月" } } self.reloadData() } container.addSubview(monthBtn) monthBtn.snp.makeConstraints { (make) in make.centerX.equalTo(container.snp.centerX) make.top.equalTo(preMonthBtn.snp.top) make.height.equalTo(preMonthBtn.snp.height) make.width.equalTo(containerW/2) } let nextMonthBtn = UIButton(type: .custom) nextMonthBtn.setImage(UIImage(named:"right"), for: .normal) nextMonthBtn.addTarget(self, action: #selector(nextBtnOnClick(_:)), for: .touchUpInside) container.addSubview(nextMonthBtn) nextMonthBtn.snp.makeConstraints { (make) in make.right.equalTo(container.snp.right) make.top.equalTo(preMonthBtn.snp.top) make.height.width.equalTo(preMonthBtn) } //返回今天 let backTodayBtn = UIButton(type: .custom) backTodayBtn.titleLabel?.font = model.todayButtonFont backTodayBtn.setTitleColor(model.todayButtonTextColor, for: .normal) backTodayBtn.setTitle("今天", for: .normal) backTodayBtn.addTarget(self, action: #selector(backTodayBtnOnClick(_:)), for: .touchUpInside) self.addSubview(backTodayBtn) backTodayBtn.snp.makeConstraints { (make) in make.top.equalTo(container.snp.top) make.right.equalTo(self.snp.right) make.left.equalTo(container.snp.right) make.height.width.equalTo(yearBtn) } var tempWeekLabel: UILabel? //星期标签 for i in 0..<(weekArray?.count)! { let week = UILabel() week.font = model.rightWeekLabelFont week.textColor = model.rightWeekLabelTextColor week.textAlignment = .center week.text = (weekArray?[i])! self.addSubview(week) week.snp.makeConstraints { (make) in if i == (weekArray?.count)! { make.right.equalTo(self.snp.right) make.left.equalTo((tempWeekLabel?.snp.left)!) make.top.equalTo(backTodayBtn.snp.bottom) make.height.equalTo(KBtnW) make.width.equalTo(KBtnW) } else { if let tempWeekLabel = tempWeekLabel { make.left.equalTo(tempWeekLabel.snp.right) } else { make.left.equalTo(letfView.snp.right) } make.width.equalTo(KBtnW) make.top.equalTo(backTodayBtn.snp.bottom) make.height.equalTo(KBtnW) } } tempWeekLabel = week } //MARK:-日历核心视图 calendarView = UIView() self.addSubview(calendarView) calendarView.snp.makeConstraints { (make) in make.left.equalTo(letfView.snp.right) make.top.equalTo((tempWeekLabel?.snp.bottom)!) make.height.equalTo(KBtnW*6) make.right.equalTo(self.snp.right) } //每一个日期用一个按钮去创建,当一个月的第一天是星期六并且有31天时为最多个数,5行零2个,共37个 for i in 0...KMaxCount { // let margin: CGFloat = 2.0 let btnX = CGFloat(i%KCol) * KBtnW let btnY = CGFloat(i/KCol) * KBtnW let btn = UIButton(type: .custom) btn.frame = CGRect(x: btnX, y: btnY, width: KBtnW, height: KBtnW) btn.tag = i + KBtnTag btn.layer.cornerRadius = KBtnW/2 btn.layer.masksToBounds = true btn.titleLabel?.font = model.dayButtonDefaultFont btn.setTitle("\(i + 1)", for: .normal) btn.setTitleColor(model.dayButtonDefaultTextColor, for: .normal) btn.setTitleColor(model.dayButtonSelectorTextColor, for: .selected) btn.setBackgroundImage(self.imageWithColor(color: model.dayButtonSelectorBackgroundColor), for: .highlighted) btn.setBackgroundImage(self.imageWithColor(color: model.dayButtonSelectorBackgroundColor), for: .selected) btn.addTarget(self, action: #selector(dateBtnOnClick(_:)), for: .touchUpInside) calendarView.addSubview(btn) } //确认按钮 let sureBtn = UIButton(type: .custom) sureBtn.titleLabel?.font = model.sureButtonFont sureBtn.setTitle("确定", for: .normal) sureBtn.setTitleColor(model.sureButtonTextColor, for: .normal) sureBtn.addTarget(self, action: #selector(sureBtnOnClick(_:)), for: .touchUpInside) self.addSubview(sureBtn) sureBtn.snp.makeConstraints { (make) in make.right.equalTo(self.snp.right) make.height.equalTo(KBtnW) make.width.equalTo(2*KBtnW) make.top.equalTo(calendarView.snp.bottom) } //取消按钮 let cancelBtn = UIButton(type: .custom) cancelBtn.setTitle("取消", for: .normal) cancelBtn.titleLabel?.font = model.cancelButtonFont cancelBtn.setTitleColor(model.cancelButtonTextColor, for: .normal) cancelBtn.addTarget(self, action: #selector(cancelBtnOnClick(_:)), for: .touchUpInside) self.addSubview(cancelBtn) cancelBtn.snp.makeConstraints { (make) in make.right.equalTo(sureBtn.snp.left) make.height.equalTo(KBtnW) make.width.equalTo(2*KBtnW) make.top.equalTo(calendarView.snp.bottom) } } //MARK:日期选择 @objc fileprivate func dateBtnOnClick(_ sender: UIButton) { //记录选择了某年某月的一天 其他年月不显示选择的天 selectYear = self.year selectMonth = self.month day = sender.tag - KBtnTag - (self.firstDayOfWeekInMonth()-2) let week = weekArray?[(sender.tag - KBtnTag)%7] weekLabel.text = "星期\(week ?? "")" dayLabel.text = "\(day ?? 0)" if sender.isSelected { return } for i in 0...KMaxCount { if let btn = self.calendarView.viewWithTag(i + KBtnTag) as? UIButton { btn.isSelected = false } } sender.isSelected = true } //MARK:取消 @objc fileprivate func cancelBtnOnClick(_ sender: UIButton) { self.dismiss() } //MARK:确定按钮 @objc fileprivate func sureBtnOnClick(_ sender: UIButton) { self.dismiss() let date = "\(year!)-\(month!)-\(day!)" self.callback?(date) } //MARK:-弹入视图 func show() { //布局子控件 let vc = UIApplication.shared.keyWindow control = UIControl(frame: UIScreen.main.bounds) control?.backgroundColor = UIColor(white: 0, alpha: 0.5) control?.addTarget(self, action: #selector(dismiss), for: .touchUpInside) vc?.addSubview(control!) vc?.addSubview(self) switch self.animationType { case .bottom: self.frame = CGRect(x: spaceMargin, y: kScreenHeight+tabHeight, width: kScreenWidth-2*spaceMargin, height: KBtnW*9) case .center: self.frame = CGRect(x: spaceMargin, y: (kScreenHeight - KBtnW*9)/2, width: kScreenWidth-2*spaceMargin, height: KBtnW*9) case .top: self.frame = CGRect(x: 0, y: -kScreenHeight, width: kScreenWidth, height: KBtnW*9) } self.layer.setValue(0, forKeyPath: "transform.scale") UIView.animate(withDuration: 0.3) { switch self.animationType { case .bottom: self.frame = CGRect(x: spaceMargin, y: (kScreenHeight-KBtnW*9-tabHeight-2*spaceMargin), width: kScreenWidth-2*spaceMargin, height: KBtnW*9) case .center: self.layer.setValue(1.0, forKeyPath: "transform.scale") case .top: self.frame = CGRect(x: spaceMargin, y: navHeight+44, width: kScreenWidth-2*spaceMargin, height: KBtnW*9) } } self.backgroundColor = UIColor(hexString: "#efeff4") self.layer.cornerRadius = 8 self.layer.masksToBounds = true self.getCurrentDate() self.creatControl() self.reloadData() } //MARK:-弹出视图 @objc func dismiss() { UIView.animate(withDuration: 0.3, animations: { switch self.animationType { case .bottom: self.frame = CGRect(x: spaceMargin, y: kScreenHeight+tabHeight, width: kScreenWidth-2*spaceMargin, height: KBtnW*9) case .center: self.layer.setValue(0, forKeyPath: "transform.scale") case .top: self.frame = CGRect(x: spaceMargin, y: -kScreenHeight, width: kScreenWidth-2*spaceMargin, height: KBtnW*9) } self.control?.alpha = 0 }) { (finished) in self.control?.removeFromSuperview() self.removeFromSuperview() } } //MARK:返回今天 @objc fileprivate func backTodayBtnOnClick(_ sender: UIButton) { year = currentYear month = currentMonth selectYear = currentYear selectMonth = currentMonth day = currentDay self.reloadData() } //MARK:上一月点击 @objc fileprivate func preBtnOnClick(_ sender: UIButton) { if month == 1 { if yearBtn.row == 0 { return } year = year!-1 month = 12 yearBtn.row = yearBtn.row!-1 } else { month = month!-1 } monthBtn.row = month! - 1 self.reloadData() } //MARK:下一月按钮点击 @objc fileprivate func nextBtnOnClick(_ sender: UIButton) { if month == 12 { if yearBtn.row == (KShowYearsCount - 1) { return } year = year!+1 month = 1 yearBtn.row = yearBtn.row!+1 } else { month = month!+1 } monthBtn.row = month! + 1 self.reloadData() } //MARK:刷新界面 fileprivate func reloadData() { let totalDays = self.numberOfDaysInMonth() let firstDay = self.firstDayOfWeekInMonth() yearLabel.text = "\(year ?? 0)" monthLabel.text = "\(month ?? 0)月" yearBtn.title = "\(year ?? 0)年" monthBtn.title = "\(month ?? 0)月" for i in 0...KMaxCount { if let btn = self.calendarView.viewWithTag(i+KBtnTag) as? UIButton { btn.isSelected = false if i < (firstDay - 1) || (i > (totalDays + firstDay - 2)) { btn.isEnabled = false btn.setTitle("", for: .normal) } else { if year == selectYear && month == selectMonth { if day == (btn.tag - KBtnTag - (firstDay - 2)) { btn.isSelected = true let week = weekArray?[(btn.tag - KBtnTag)%7] weekLabel.text = "星期\(week ?? "")" dayLabel.text = "\(day ?? 0)" } } else { btn.isSelected = false dayLabel.text = nil } btn.isEnabled = true let d = i - (firstDay - 1) + 1 btn.setTitle("\(d)", for: .normal) } } } } //MARK:-计算字体大小 func calculateTextSize(text: String, font: UIFont) -> CGSize { let str = NSString(string: text) let size = str.size(withAttributes: [NSAttributedStringKey.font: font]) return size } //根据颜色返回图片 fileprivate func imageWithColor(color: UIColor) -> UIImage { let rect = CGRect(x: 0, y: 0, width: 1, height: 1) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context?.fill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image! } //根据选中日期,获取相应NSDate fileprivate func getSelectDate() -> Date { var dateComponents = DateComponents() dateComponents.year = year dateComponents.month = month let calendar = Calendar(identifier: .gregorian) return calendar.date(from: dateComponents)! } //获取目标月份的天数 fileprivate func numberOfDaysInMonth() -> Int { return Calendar.current.range(of: .day, in: .month, for: self.getSelectDate())?.count ?? 0 } //获取目标月份第一天星期几 fileprivate func firstDayOfWeekInMonth() -> Int { //获取选中日期月份第一天星期几,因为默认日历顺序为“日一二三四五六”,所以这里返回的1对应星期日,2对应星期一,依次类推 return Calendar.current.ordinality(of: .day, in: .weekOfYear, for: self.getSelectDate())! } }
// // RegisterResponse.swift // CartLife // // Created by Ravi Dubey on 9/21/18. // Copyright © 2018 Ravi Dubey. All rights reserved. // import Foundation struct RegisterResponse: Codable { let data: DataClass1? let errorCode: Int let message: String enum CodingKeys: String, CodingKey { case data case errorCode = "error_code" case message } } struct DataClass1: Codable { let name, email, password: String? let roleID, regType: Int? let deviceID, updatedAt, createdAt: String? let id: Int? enum CodingKeys: String, CodingKey { case name, email, password case roleID = "role_id" case regType = "reg_type" case deviceID = "device_id" case updatedAt = "updated_at" case createdAt = "created_at" case id } }
// // Notification+Name.swift // Sllti // // Created by ameer on 5/19/18. // Copyright © 2018 Novent App. All rights reserved. // import Foundation extension Notification.Name { static let testNotification = Notification.Name("testNotification") }
import Foundation import RxSwift import RxCocoa import RxRelay import HsToolKit protocol ISendXFeeValueService: AnyObject { var feeState: DataStatus<Decimal> { get } var feeStateObservable: Observable<DataStatus<Decimal>> { get } } protocol ISendXSendAmountBoundsService: AnyObject { var minimumSendAmount: Decimal { get } var minimumSendAmountObservable: Observable<Decimal> { get } var maximumSendAmount: Decimal? { get } var maximumSendAmountObservable: Observable<Decimal?> { get } } protocol ISendService { func sendSingle(logger: Logger) -> Single<Void> } class SendBitcoinAdapterService { private let disposeBag = DisposeBag() private let queue = DispatchQueue(label: "\(AppConfig.label).send.bitcoin_adapter_service", qos: .userInitiated) private let feeRateService: FeeRateService private let amountInputService: IAmountInputService private let addressService: AddressService private let timeLockService: TimeLockService? private let btcBlockchainManager: BtcBlockchainManager private let adapter: ISendBitcoinAdapter let inputOutputOrderService: InputOutputOrderService // Outputs let feeStateRelay = BehaviorRelay<DataStatus<Decimal>>(value: .loading) var feeState: DataStatus<Decimal> = .loading { didSet { if !feeState.equalTo(oldValue) { feeStateRelay.accept(feeState) } } } let availableBalanceRelay = BehaviorRelay<DataStatus<Decimal>>(value: .loading) var availableBalance: DataStatus<Decimal> = .loading { didSet { if !availableBalance.equalTo(oldValue) { availableBalanceRelay.accept(availableBalance) } } } let minimumSendAmountRelay = BehaviorRelay<Decimal>(value: 0) var minimumSendAmount: Decimal = 0 { didSet { if minimumSendAmount != oldValue { minimumSendAmountRelay.accept(minimumSendAmount) } } } let maximumSendAmountRelay = BehaviorRelay<Decimal?>(value: nil) var maximumSendAmount: Decimal? = nil { didSet { if maximumSendAmount != oldValue { maximumSendAmountRelay.accept(maximumSendAmount) } } } init(feeRateService: FeeRateService, amountInputService: IAmountInputService, addressService: AddressService, inputOutputOrderService: InputOutputOrderService, timeLockService: TimeLockService?, btcBlockchainManager: BtcBlockchainManager, adapter: ISendBitcoinAdapter) { self.feeRateService = feeRateService self.amountInputService = amountInputService self.addressService = addressService self.timeLockService = timeLockService self.inputOutputOrderService = inputOutputOrderService self.btcBlockchainManager = btcBlockchainManager self.adapter = adapter subscribe(disposeBag, amountInputService.amountObservable) { [weak self] _ in self?.sync(updatedFrom: .amount) } subscribe(disposeBag, addressService.stateObservable) { [weak self] _ in self?.sync(updatedFrom: .address) } if let timeLockService = timeLockService { subscribe(disposeBag, timeLockService.pluginDataObservable) { [weak self] _ in self?.sync(updatedFrom: .pluginData) } } subscribe(disposeBag, feeRateService.statusObservable) { [weak self] in self?.sync(feeRate: $0) } sync(feeRate: feeRateService.status) minimumSendAmount = adapter.minimumSendAmount(address: addressService.state.address?.raw) maximumSendAmount = adapter.maximumSendAmount(pluginData: pluginData) } private func sync(feeRate: DataStatus<Int>? = nil, updatedFrom: UpdatedField = .feeRate) { let feeRateStatus = feeRate ?? feeRateService.status let amount = amountInputService.amount var feeRate = 0 switch feeRateStatus { case .loading: guard !amount.isZero else { // force update fee for bitcoin, when clear amount to zero value feeState = .completed(0) return } feeState = .loading case .failed(let error): feeState = .failed(error) case .completed(let _feeRate): feeRate = _feeRate } update(feeRate: feeRate, amount: amount, address: addressService.state.address?.raw, pluginData: pluginData, updatedFrom: updatedFrom) } private func update(feeRate: Int, amount: Decimal, address: String?, pluginData: [UInt8: IBitcoinPluginData], updatedFrom: UpdatedField) { queue.async { [weak self] in if let fee = self?.adapter.fee(amount: amount, feeRate: feeRate, address: address, pluginData: pluginData) { self?.feeState = .completed(fee) } if updatedFrom != .amount, let availableBalance = self?.adapter.availableBalance(feeRate: feeRate, address: address, pluginData: pluginData) { self?.availableBalance = .completed(availableBalance) } if updatedFrom == .pluginData { self?.maximumSendAmount = self?.adapter.maximumSendAmount(pluginData: pluginData) } if updatedFrom == .address { self?.minimumSendAmount = self?.adapter.minimumSendAmount(address: address) ?? 0 } } } private var pluginData: [UInt8: IBitcoinPluginData] { timeLockService?.pluginData ?? [:] } } extension SendBitcoinAdapterService: ISendXFeeValueService, IAvailableBalanceService, ISendXSendAmountBoundsService { var feeStateObservable: Observable<DataStatus<Decimal>> { feeStateRelay.asObservable() } var availableBalanceObservable: Observable<DataStatus<Decimal>> { availableBalanceRelay.asObservable() } var minimumSendAmountObservable: Observable<Decimal> { minimumSendAmountRelay.asObservable() } var maximumSendAmountObservable: Observable<Decimal?> { maximumSendAmountRelay.asObservable() } func validate(address: String) throws { try adapter.validate(address: address, pluginData: pluginData) } } extension SendBitcoinAdapterService: ISendService { func sendSingle(logger: Logger) -> Single<Void> { let address: Address switch addressService.state { case .success(let sendAddress): address = sendAddress case .fetchError(let error): return Single.error(error) default: return Single.error(AppError.addressInvalid) } guard case let .completed(feeRate) = feeRateService.status else { return Single.error(SendTransactionError.noFee) } guard !amountInputService.amount.isZero else { return Single.error(SendTransactionError.wrongAmount) } let sortMode = btcBlockchainManager.transactionSortMode(blockchainType: adapter.blockchainType) return adapter.sendSingle( amount: amountInputService.amount, address: address.raw, feeRate: feeRate, pluginData: pluginData, sortMode: sortMode, logger: logger ) } } extension SendBitcoinAdapterService { private enum UpdatedField: String { case amount, address, pluginData, feeRate } }
import SpriteKit protocol SceneDelegate: class { func changeScene(to scene: GameScene.Type) func runSegue(name: String) }
// // EditItemVCExtension.swift // TestECommerceApp // // Created by Ivan Stebletsov on 04/02/2019. // Copyright © 2019 Ivan Stebletsov. All rights reserved. // import UIKit import CoreData extension EditItemViewController { // MARK: - UI configuration func makeAddEditFormTableView() { editFormTableView = UITableView(frame: CGRect(x: 0, y: 0, width: 0, height: 0), style: .grouped) editFormTableView.separatorStyle = .none editFormTableView.translatesAutoresizingMaskIntoConstraints = false editFormTableView.rowHeight = 44 editFormTableView.backgroundColor = .clear view.addSubview(editFormTableView) editFormTableView.delegate = self editFormTableView.dataSource = self let safeArea = view.safeAreaLayoutGuide let addEditFormTableViewConstraints = [ editFormTableView.topAnchor.constraint(equalTo: safeArea.topAnchor), editFormTableView.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor), editFormTableView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor), editFormTableView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor)] NSLayoutConstraint.activate(addEditFormTableViewConstraints) } func makeDoneButtonInNumPad(textField: UITextField) { let numpadToolbar = UIToolbar() let accessoryView = UIView() let toolBarDoneButton = UIBarButtonItem(title: "Готово", style: .done, target: self, action: #selector(dismissKeyboard)) let toolBarFlexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) numpadToolbar.setItems([toolBarFlexibleSpace, toolBarDoneButton], animated: true) numpadToolbar.translatesAutoresizingMaskIntoConstraints = false accessoryView.addSubview(numpadToolbar) numpadToolbar.centerYAnchor.constraint(equalTo: accessoryView.centerYAnchor).isActive = true numpadToolbar.leadingAnchor.constraint(equalTo: accessoryView.leadingAnchor).isActive = true numpadToolbar.trailingAnchor.constraint(equalTo: accessoryView.trailingAnchor).isActive = true textField.inputAccessoryView = numpadToolbar } func makeSaveBarButton() { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Готово", style: .done, target: self, action: #selector(saveData)) navigationItem.rightBarButtonItem?.isEnabled = false navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Отменить", style: .done, target: self, action: #selector(popViewController)) } // MARK: - Keyboard handling func setupKeyboardObserver() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } // Get the height of the keyboard, its Duration and Curve of the animation when it appears and animate the shift editFormTableView up with the resulting parameters to leave access to the text fields @objc func keyboardWillShow(notification: Notification) { guard let userInfo = notification.userInfo else { return } guard let keyboardSize = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } guard let keyboardAnimationDuration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else { return } guard let keyboardAnimationCurveRaw = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber else { return } let contentAnimationCurve = UIView.AnimationOptions(rawValue: UIView.AnimationOptions.RawValue(truncating: keyboardAnimationCurveRaw)) let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) UIView.animate(withDuration: keyboardAnimationDuration, delay: 0, options: contentAnimationCurve, animations: { self.editFormTableView.contentInset = contentInsets self.editFormTableView.scrollIndicatorInsets = contentInsets var contentRect = self.view.frame contentRect.size.height -= keyboardSize.height guard let activeField = self.activeField else { return } if contentRect.contains(activeField.frame.origin) { self.editFormTableView.scrollRectToVisible(activeField.frame, animated: true) } }, completion: nil) } // Get the Duration and animation Curve of the disappearance of the keyboard and animate removing the offset of the editFormTableView with received parameters @objc func keyboardWillHide(notification: Notification) { guard let userInfo = notification.userInfo else { return } guard let keyboardAnimationDuration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue else { return } guard let keyboardAnimationCurveRaw = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber else { return } let contentAnimationCurve = UIView.AnimationOptions(rawValue: UIView.AnimationOptions.RawValue(truncating: keyboardAnimationCurveRaw)) UIView.animate(withDuration: keyboardAnimationDuration, delay: 0, options: contentAnimationCurve, animations: { self.editFormTableView.contentInset = .zero self.editFormTableView.scrollIndicatorInsets = .zero self.view.resignFirstResponder() }, completion: nil) } func hideKeyboardByTapAnywhere() { editFormTableView.keyboardDismissMode = .interactive let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) tapRecognizer.cancelsTouchesInView = false editFormTableView.addGestureRecognizer(tapRecognizer) } @objc func dismissKeyboard() { view.endEditing(true) } // MARK: - TextFields handling func addTargetForTextFields() { itemNameTableViewCell.textField.delegate = self itemPriceTableViewCell.textField.delegate = self itemStockTableViewCell.textField.delegate = self itemNameTableViewCell.textField.addTarget(self, action: #selector(enableTheSaveButton), for: UIControl.Event.editingChanged) itemPriceTableViewCell.textField.addTarget(self, action: #selector(enableTheSaveButton), for: UIControl.Event.editingChanged) itemStockTableViewCell.textField.addTarget(self, action: #selector(enableTheSaveButton), for: UIControl.Event.editingChanged) } func addTargetForStepper() { itemStockTableViewCell.stockCountStepper.addTarget(self, action: #selector(enableTheSaveButton), for: .valueChanged) } @objc func enableTheSaveButton(target: Any) { navigationItem.title = itemNameTableViewCell.textField.text?.correctTheInputText() let itemName = itemNameTableViewCell.textField.text! var itemPrice = itemPriceTableViewCell.textField.text! var itemStock = itemStockTableViewCell.textField.text! if !itemPrice.isEmpty || !itemStock.isEmpty { itemPrice = itemPrice.correctTheInputNumber() itemPriceTableViewCell.textField.text? = itemPrice itemStock = itemStock.correctTheInputNumber() itemStockTableViewCell.textField.text = itemStock } // If indexPath is empty, we create new Item otherwise we edit and save existing item switch selectedItem { case nil: if itemName.isConformNameConditions() && itemPrice.isNumber() && itemStock.isNumber() { navigationItem.rightBarButtonItem?.isEnabled = true } else { navigationItem.rightBarButtonItem?.isEnabled = false } default: if (itemName.isConformNameConditions() && itemPrice.isNumber() && itemStock.isNumber()) && (itemName != selectedItem!.name! || itemPrice != selectedItem!.price! || itemStock != selectedItem!.stock!) { navigationItem.rightBarButtonItem?.isEnabled = true } else { navigationItem.rightBarButtonItem?.isEnabled = false } } } // Check the active text field for detect position for offset keyboard by call keyboardWillShow func textFieldDidBeginEditing(_ textField: UITextField) { activeField = textField } // Uncheck the active text field func textFieldDidEndEditing(_ textField: UITextField) { activeField = nil } func textFieldShouldReturn(_ textField: UITextField) -> Bool { guard let activeTextField = activeField else { return false } activeTextField.resignFirstResponder() return false } // MARK: - Save data @objc func saveData() { switch selectedItem { case nil: dataStorage?.saveNew(name: itemNameTableViewCell.textField.text!, price: itemPriceTableViewCell.textField.text!, stock: itemStockTableViewCell.textField.text!) popViewController() default: selectedItem?.name = itemNameTableViewCell.textField.text?.correctTheInputText() selectedItem?.price = itemPriceTableViewCell.textField.text?.correctTheInputNumber() selectedItem?.stock = itemStockTableViewCell.textField.text?.correctTheInputNumber() dataStorage?.save() popViewController() } } // MARK: - Navigation @objc func popViewController() { navigationController?.popViewController(animated: true) } }
import Foundation struct Investment: Codable { let investedAmount: Int let yearlyInterestRate: Float let maturityTotalDays: Int let maturityBusinessDays: Int let maturityDate: String let rate: Int let isTaxFree: Bool }
// // CachedImageView.swift // ObjectsWithStaticHosting // // Created by Tim Beals on 2018-09-18. // Copyright © 2018 Roobi Creative. All rights reserved. // import UIKit class CachedImageView: UIImageView { static let imageCache = NSCache<AnyObject, AnyObject>() var imageEndPoint: String? { didSet { if let endPoint = imageEndPoint { loadImage(from: endPoint) } } } private let activityIndicatorView: UIActivityIndicatorView = { let aiv = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) aiv.translatesAutoresizingMaskIntoConstraints = false return aiv }() override func layoutSubviews() { self.contentMode = .scaleAspectFill self.layer.masksToBounds = true activityIndicatorView.removeFromSuperview() addSubview(activityIndicatorView) NSLayoutConstraint.activate([ activityIndicatorView.centerXAnchor.constraint(equalTo: self.centerXAnchor), activityIndicatorView.centerYAnchor.constraint(equalTo: self.centerYAnchor), ]) activityIndicatorView.startAnimating() if let endPoint = imageEndPoint { loadImage(from: endPoint) } } private func loadImage(from endPoint: String) { if let imageFromCache = type(of: self).imageCache.object(forKey: endPoint as AnyObject) as? UIImage { self.image = imageFromCache activityIndicatorView.stopAnimating() return } APIService.fetchData(with: .image(endPoint: endPoint)) { (data, error) in guard error == nil else { print(error!.localizedDescription) return } DispatchQueue.main.async { let imageToCache = UIImage(data: data!) if self.imageEndPoint == endPoint { self.image = imageToCache self.activityIndicatorView.stopAnimating() } type(of: self).imageCache.setObject(imageToCache!, forKey: endPoint as AnyObject) } } } }
import UIKit class SortingViewController: UIViewController { // MARK:- Variant var category = String() private let allButton = UIButton() private let categoryButton = UIButton() private let placeButton = UIButton() // Class let imageModel = ImageModel() // UI Variant @IBOutlet weak var backgroundImage: UIImageView! // MARK:- Lifecycle override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = category // UI Setting self.createButton(button: allButton, caption: "All", x: view.frame.width/10, y: view.frame.height*6/40, selector: #selector(self.all(_ :)), imageID: 0) self.createButton(button: categoryButton, caption: "Category", x: view.frame.width/10, y: view.frame.height*17/40, selector: #selector(self.category(_ :)), imageID: 1) self.createButton(button: placeButton, caption: "Place", x: view.frame.width/10, y: view.frame.height*28/40, selector: #selector(self.place(_ :)), imageID: 2) backgroundImage.image = UIImage(named: imageModel.imageName.shuffled()[0]) } // MARK:- UI Generator // Button func createButton(button: UIButton, caption: String, x: CGFloat, y: CGFloat, selector: Selector, imageID: Int) { button.frame = CGRect(x: x, y: y, width: view.frame.width*8/10, height: view.frame.height*5/20) button.titleLabel?.font = UIFont(name: "AvenirNext-Heavy",size: CGFloat(50)) button.layer.cornerRadius = 15 button.clipsToBounds = true button.setBackgroundImage(UIImage(named: imageModel.imageName.shuffled()[imageID]), for: .normal) button.setTitle(caption, for: .normal) view.addSubview(button) button.addTarget(self,action: selector, for: .touchUpInside) } // MARK:- UI Action @objc func all(_ sender: UIButton) { let allVC = storyboard?.instantiateViewController(withIdentifier: "allVC") as! AllShopViewController allVC.category = category allVC.selectiveClass = (sender.titleLabel?.text)! self.navigationController?.pushViewController(allVC, animated: true) } @objc func category(_ sender: UIButton) { let categoryVC = storyboard?.instantiateViewController(withIdentifier: "categoryVC") as! CategoriesShopViewController categoryVC.category = category self.navigationController?.pushViewController(categoryVC, animated: true) } @objc func place(_ sender: UIButton) { let placeVC = storyboard?.instantiateViewController(withIdentifier: "placeVC") as! PlaceShopViewController placeVC.category = category self.navigationController?.pushViewController(placeVC, animated: true) } }
import Foundation import Firebase extension Event{ static func buildUserEvent(ownerID: String,ownerFirstName:String,ownerLastName:String,title:String,description:String,city: String,Accom: String,address:String,venueType:EVENT_LOCATION_TYPES,briefDescription:String,joinType:JOIN_TYPE,privlagedUsers: [String],date: Date,publicLocation: PUBLIC_LOCATIONS,joinedLocation: JOINED_LOCATIONS)-> Event{ let newEvent = Event() let aDocID = dbLocations.DB_EVENT_ROOT.document() let postid = aDocID.documentID let eventOwner = PostOwner() let querydate = Event.dateToQueryString(date: date) eventOwner.SetUserID(ID: ownerID) eventOwner.SetFirstName(name: ownerFirstName) eventOwner.SetLastName(name: ownerLastName) newEvent.SetPostID(id: postid) newEvent.SetPostOwner(owner: eventOwner) newEvent.SetTitle(title: title) newEvent.SetDescription(string: description) newEvent.SetPostType(type: POST_TYPE.event) newEvent.SetLocationType(type: venueType) newEvent.SetCity(city: city) newEvent.SetAddress(address: address) newEvent.SetPrivilagedUsers(users: privlagedUsers) newEvent.SetDateUploaded(date: Timestamp()) newEvent.SetQueryDate(date: querydate) newEvent.SetDate(date: date) newEvent.SetJoinType(type: joinType) if newEvent.GetLocationType() == EVENT_LOCATION_TYPES.accomodation{ newEvent.SetAccomodation(accom: Accom) newEvent.SetLocationDescription(localDes: "private") } else{ newEvent.SetAccomodation(accom: "private") newEvent.SetLocationDescription(localDes: briefDescription) } switch publicLocation { case PUBLIC_LOCATIONS.city: newEvent.SetPublicLocationPrivacy(type: PUBLIC_LOCATIONS.city) case PUBLIC_LOCATIONS.accom: newEvent.SetPublicLocationPrivacy(type: PUBLIC_LOCATIONS.accom) case PUBLIC_LOCATIONS.brief_description: newEvent.SetPublicLocationPrivacy(type: PUBLIC_LOCATIONS.brief_description) default: newEvent.SetPublicLocationPrivacy(type: PUBLIC_LOCATIONS.city) } switch joinedLocation { case JOINED_LOCATIONS.city: newEvent.SetOnJoinLocationPrivacy(type: JOINED_LOCATIONS.city) case JOINED_LOCATIONS.accom: newEvent.SetOnJoinLocationPrivacy(type: JOINED_LOCATIONS.accom) case JOINED_LOCATIONS.brief_description: newEvent.SetOnJoinLocationPrivacy(type: JOINED_LOCATIONS.brief_description) case JOINED_LOCATIONS.address: newEvent.SetOnJoinLocationPrivacy(type: JOINED_LOCATIONS.address) default: newEvent.SetOnJoinLocationPrivacy(type: JOINED_LOCATIONS.city) } return newEvent } } extension LoggedInUser{ static func buildNewLoggedInUser(uid:String,firstName:String,lastName:String,largeProfilePic:String,email:String)->LoggedInUser{ var newUser = LoggedInUser() newUser.SetUserID(ID: uid) newUser.SetFirstName(name: firstName) newUser.SetLastName(name: lastName) newUser.SetEmail(email: email) return newUser } }
import XCTest @testable import BowLaws import Bow class EitherTest: XCTestCase { func testEquatableLaws() { EquatableKLaws<EitherPartial<Int>, Int>.check() } func testHashableLaws() { HashableKLaws<EitherPartial<Int>, Int>.check() } func testFunctorLaws() { FunctorLaws<EitherPartial<Int>>.check() } func testApplicativeLaws() { ApplicativeLaws<EitherPartial<Int>>.check() } func testSelectiveLaws() { SelectiveLaws<EitherPartial<Int>>.check() } func testMonadLaws() { MonadLaws<EitherPartial<Int>>.check() } func testApplicativeErrorLaws() { ApplicativeErrorLaws<EitherPartial<CategoryError>>.check() } func testMonadErrorLaws() { MonadErrorLaws<EitherPartial<CategoryError>>.check() } func testSemigroupKLaws() { SemigroupKLaws<EitherPartial<Int>>.check() } func testCustomStringConvertibleLaws() { CustomStringConvertibleLaws<Either<Int, Int>>.check() } func testFoldableLaws() { FoldableLaws<EitherPartial<Int>>.check() } func testTraverseLaws() { TraverseLaws<EitherPartial<Int>>.check() } func testSemigroupLaws() { SemigroupLaws<Either<Int, Int>>.check() } func testMonoidLaws() { MonoidLaws<Either<Int, Int>>.check() } func testCheckers() { let left = Either<String, Int>.left("Hello") let right = Either<String, Int>.right(5) XCTAssertTrue(left.isLeft) XCTAssertFalse(left.isRight) XCTAssertFalse(right.isLeft) XCTAssertTrue(right.isRight) } func testSwap() { let left = Either<String, Int>.left("Hello") let right = Either<String, Int>.right(5) XCTAssertEqual(left.swap(), Either<Int, String>.right("Hello")) XCTAssertEqual(right.swap(), Either<Int, String>.left(5)) } func testExists() { let left = Either<String, Int>.left("Hello") let right = Either<String, Int>.right(5) let isPositive = { (x : Int) in x >= 0 } XCTAssertFalse(left.exists(isPositive)) XCTAssertTrue(right.exists(isPositive)) XCTAssertFalse(right.exists(not <<< isPositive)) } func testToOption() { let left = Either<String, Int>.left("Hello") let right = Either<String, Int>.right(5) XCTAssertEqual(left.toOption(), Option<Int>.none()) XCTAssertEqual(right.toOption(), Option<Int>.some(5)) } func testGetOrElse() { let left = Either<String, Int>.left("Hello") let right = Either<String, Int>.right(5) XCTAssertEqual(left.getOrElse(10), 10) XCTAssertEqual(right.getOrElse(10), 5) } func testFilterOrElse() { let left = Either<String, Int>.left("Hello") let right = Either<String, Int>.right(5) let isPositive = { (x : Int) in x >= 0 } XCTAssertEqual(left.filterOrElse(isPositive, "10"), Either<String, Int>.left("Hello")) XCTAssertEqual(right.filterOrElse(isPositive, "10"), Either<String, Int>.right(5)) XCTAssertEqual(right.filterOrElse(not <<< isPositive, "10"), Either<String, Int>.left("10")) } func testConversionToString() { let left = Either<String, Int>.left("Hello") let right = Either<String, Int>.right(5) XCTAssertEqual(left.description, "Left(Hello)") XCTAssertEqual(right.description, "Right(5)") } }
// // VideoEntity.swift // TRCarData // // Created by 98data on 2019/9/4. // Copyright © 2019 王德贵. All rights reserved. // import Foundation import SwiftyJSON class VideoEntity : NSObject { var v_id = 0 var user_id = 0 var isLike = 0 var isFollow = 0 var comment_count = 0 var like_count = 0 var share_count = 0 var width = 0 var height = 0 var status = 0 var cover = "" var file_url = "" var detail = "" var share_url = "" var addtime = "" // 临时添加的本地播放文件 var playerItem : WMPlayerModel? var userInfo : UserInfoEntity? static func initJsonArrayWithEntitys(jsonData:JSON) -> Array<VideoEntity> { var array = Array<VideoEntity>() for obj in jsonData.arrayValue { let entity = self.initJsonWithEntity(jsonData: obj) array.append(entity) } return array } static func initJsonWithEntity(jsonData:JSON) -> VideoEntity { GeneralObjects.jsondic = jsonData.dictionaryValue let entity = VideoEntity() entity.v_id = GeneralObjects().jsonValueToInt(key: "id") entity.user_id = GeneralObjects().jsonValueToInt(key: "user_id") entity.isLike = GeneralObjects().jsonValueToInt(key: "isLike") entity.isFollow = GeneralObjects().jsonValueToInt(key: "isFollow") entity.comment_count = GeneralObjects().jsonValueToInt(key: "comment_count") entity.like_count = GeneralObjects().jsonValueToInt(key: "like_count") entity.share_count = GeneralObjects().jsonValueToInt(key: "share_count") entity.width = GeneralObjects().jsonValueToInt(key: "width") entity.height = GeneralObjects().jsonValueToInt(key: "height") entity.status = GeneralObjects().jsonValueToInt(key: "status") entity.cover = GeneralObjects().jsonValueToString(key: "cover") entity.file_url = GeneralObjects().jsonValueToString(key: "file_url") entity.detail = GeneralObjects().jsonValueToString(key: "detail") entity.share_url = GeneralObjects().jsonValueToString(key: "share_url") entity.addtime = GeneralObjects().jsonValueToString(key: "addtime") if jsonData.dictionaryValue["user"] != nil { entity.userInfo = UserInfoEntity.initJsonWithEntity(jsonData: jsonData.dictionaryValue["user"]!) } return entity } }
// // UIViewControlleExtension.swift // PdfReader // // Created by CSS on 28/01/21. // Copyright © 2021 Sowmiya. All rights reserved. // import Foundation import UIKit enum Storyboard: String { case main = "Main" } extension UIViewController { class func instantiate<T: UIViewController>(appStoryboard: Storyboard) -> T { let storyboard = UIStoryboard(name: appStoryboard.rawValue, bundle: nil) let identifier = String(describing: self) return storyboard.instantiateViewController(withIdentifier: identifier) as! T } }
// // EmptySpace.swift // Login // // Created by Sujan Vaidya on 7/25/17. // Copyright © 2017 Sujan Vaidya. All rights reserved. // import UIKit public protocol EmptySpaceValidator: Validator { var error: Error { get } } public extension EmptySpaceValidator { func validate<T>(_ value: T) -> ValidationResult<T> { guard let stringValue = value as? String else { return .error(nil) } return !stringValue.hasEmptySpaceAtBeg ? .ok(value) : .error(self.error) } }
// // ViewController.swift // Rim // // Created by Chatan Konda on 9/10/17. // Copyright © 2017 Apple. All rights reserved. // import UIKit class loginViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func loginButton(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBOutlet weak var registerButton: UIButton! @IBAction func registerButton(_ sender: Any) { // dismiss(animated: true, completion: nil) } }
// // publicFunction.swift // SSASideMenuStoryboardExample // // Created by RAYW2 on 13/1/2017. // Copyright © 2017年 SebastianAndersen. All rights reserved. // import UIKit //Custome parameter let bgColor = "000E29" let titleSize = CGFloat(22) let barButtonSize = CGFloat(45) var signIned = false // Car park navigation map options var mapShowMyPoint = false var mapDirectedGraph = false var mapIsGoingToEntrance = false //ShareParkSpace var timeSlotList = [TimeSlot()] var myParkingSchdules : [ParkingSchedule] = [] var checkoutInvoiceRecord = ParkingRecord() // 0 = any hour, 1 .. 23 = 1 to 23 hour(s) let parkHour = Array(0...23) let pickerWeek = [ Date(), Calendar.current.date(byAdding: .day, value: 1, to: Date()), Calendar.current.date(byAdding: .day, value: 2, to: Date()), Calendar.current.date(byAdding: .day, value: 3, to: Date()), Calendar.current.date(byAdding: .day, value: 4, to: Date()), Calendar.current.date(byAdding: .day, value: 5, to: Date()), Calendar.current.date(byAdding: .day, value: 6, to: Date()) ] let pickerTime = [ "0000","0030","0100","0130","0200","0230","0300","0330","0400","0430","0500","0530","0600","0630", "0700","0730","0800","0830","0900","0930","1000","1030","1100","1130","1200","1230","1300","1330", "1400","1430","1500","1530","1600","1630","1700","1730","1800","1830","1900","1930","2000","2030", "2100","2130","2200","2230","2300","2330" ] let pickerEndTime = [ "0000","0030","0100","0130","0200","0230","0300","0330","0400","0430","0500","0530","0600","0630", "0700","0730","0800","0830","0900","0930","1000","1030","1100","1130","1200","1230","1300","1330", "1400","1430","1500","1530","1600","1630","1700","1730","1800","1830","1900","1930","2000","2030", "2100","2130","2200","2230","2300","2330","2400" ] var spaceID = [ "A001","A002","A003","A004","A005","A006","B001","B002","B003","B004","B005","B006","B007","B008", "B009","B010","C001","C002","C003","C004","C005","C006" ] var whatParkHourIndex: Int = 0 var whatDayIndex: Int = 0 var whatTimeIndex: Int = 0 var whatEndTimeIndex: Int = 1 var whatSpaceIndex: Int = 0 //Custom button let menuButton = UIButton(type: .custom) //hex color function func hexColor (hex:String) -> UIColor { var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (cString.hasPrefix("#")) { cString.remove(at: cString.startIndex) } if ((cString.characters.count) != 6) { return UIColor.gray } var rgbValue:UInt32 = 0 Scanner(string: cString).scanHexInt32(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } // Generic function to show popup error message // Usage: present(alertController, animated: true, completion: nil) func getErrorAlertCtrl(title:String, message:String) -> UIAlertController { let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) //Replace UIAlertControllerStyle.Alert by UIAlertControllerStyle.alert let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in print("OK") } alertController.addAction(okAction) return alertController } //blurEffect extension UIImageView { func addBlurEffect() { let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = self.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation self.addSubview(blurEffectView) } } //Color of placeholder extension UITextField{ @IBInspectable var placeHolderColor: UIColor? { get { return self.placeHolderColor } set { self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: newValue!]) } } } //tap gesture extension UIViewController{ func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard(){ view.endEditing(true) } } //UIImage with color public extension UIImage { public convenience init?(color: UIColor, size: CGSize = CGSize(width: 1, height: 1)) { let rect = CGRect(origin: .zero, size: size) UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0) color.setFill() UIRectFill(rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() guard let cgImage = image?.cgImage else { return nil } self.init(cgImage: cgImage) } }
// // Contacts.swift // ContactList // // Created by Максим Томилов on 10.11.2019. // Copyright © 2019 Tomily. All rights reserved. // import Foundation class Contacts { static let shared = Contacts() let userDefaults: UserDefaults = UserDefaults.standard var value: [Contact] = [] }
// // APIModels.swift // Gamification // // Created by Nurbek on 4/26/20. // Copyright © 2020 Nurbek. All rights reserved. // struct task: Decodable, Hashable { let id: Int var name: String? var link: String? } struct challenge: Decodable { var id: Int var name: String var price: Int var state: String var image_url: String? var url: String? } struct user: Decodable { var percent: Int var finished: Int var all: Int } struct postTasksModel: Encodable { var id: Int var result: Bool }
// // GameViewController.swift // Keepy Uppy // // Created by Matthew Allen Lin on 6/18/15. // Copyright (c) 2015 Matthew Allen Lin. All rights reserved. // import UIKit import QuartzCore import SceneKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func prefersStatusBarHidden() -> Bool { return true } }
import UIKit import CoreData @objc(TimeLine) public class TimeLine: _TimeLine { //Inicializador a partir del diccionario que devuelve el WS convenience init(aDict:NSDictionary){ self.init(managedObjectContext:coreDataStack.context)//Llamamos al constructor padre //Guardamos el userKey if let anUserKey = aDict.objectForKey("user_key") as? String{ userKey = anUserKey } //Guardamos el user_avatar if let dataImage = aDict.objectForKey("user_avatar") as? String{ if let decodedData = NSData(base64EncodedString: dataImage, options:NSDataBase64DecodingOptions.IgnoreUnknownCharacters){ userAvatar = decodedData } } //Guardamos el user_name if let anUserName = aDict.objectForKey("user_name") as? String{ userName = anUserName } //Guardamos el created if let aCreated = aDict.objectForKey("created") as? String{ created = aCreated } //Guardamos el content if let aContent = aDict.objectForKey("content") as? String{ content = aContent } coreDataStack.saveContext() } //Metodo que devuelve todo el listado de Post static func devolverListTimeLine() -> [TimeLineModel]{ var listadoTimeLine = [TimeLineModel]() let request = NSFetchRequest(entityName: TimeLine.entityName()) let miShorDescriptor = NSSortDescriptor(key: "created", ascending: false) request.sortDescriptors = [miShorDescriptor] request.returnsObjectsAsFaults = false let results = (try! coreDataStack.context.executeFetchRequest(request)) as! [TimeLine] for post in results{ let aux = TimeLineModel(modelo: post) listadoTimeLine.append(aux) } return listadoTimeLine } //Borramos todo el listado de Post static func borrarAllPost(){ let request = NSFetchRequest(entityName: TimeLine.entityName()) request.returnsObjectsAsFaults = false let allPosts = try! coreDataStack.context.executeFetchRequest(request) if allPosts.count > 0 { for result: AnyObject in allPosts{ coreDataStack.context.deleteObject(result as! NSManagedObject) } coreDataStack.saveContext() } } //Devolvemos los post de un userKey dado static func devolverPostUserKey(userKey:String) -> [TimeLineModel]{ var listadoTimeLine = [TimeLineModel]() let request = NSFetchRequest(entityName: TimeLine.entityName()) request.predicate = NSPredicate(format: "userKey = %@", userKey) let miShorDescriptor = NSSortDescriptor(key: "created", ascending: false) request.sortDescriptors = [miShorDescriptor] request.returnsObjectsAsFaults = false let results = (try! coreDataStack.context.executeFetchRequest(request)) as! [TimeLine] for post in results{ let aux = TimeLineModel(modelo: post) listadoTimeLine.append(aux) } return listadoTimeLine } }
// // DatabaseProtocol.swift // GonzagaCampusWalkingTour // // Created by Max Heinzelman on 2/9/20. // Copyright © 2020 Senior Design Group 8. All rights reserved. // import Foundation protocol DatabaseAccessible { func getStopsForTour(id: String, callback: @escaping ([Stop]) -> Void) func getAllTourInfo(callback: @escaping ([TourInfo]) -> Void) func getStopAssets(stopId: String, callback: @escaping ([Asset]) -> Void) func locallyDownloadAssets(stopId:String, callback: @escaping ([Asset]) -> Void) }
// // FeedRefreshController.swift // MVC // // Created by Stas Lee on 12/2/19. // Copyright © 2019 Stas Lee. All rights reserved. // import UIKit import Feed final class FeedRefreshViewController: NSObject { @IBOutlet weak var error: ErrorView! @IBOutlet weak var refreshView: UIRefreshControl! var feedLoader: FeedLoader? var onRefresh: (([FeedImage]) -> Void)? @IBAction func refresh() { refreshView?.beginRefreshing() error?.hideMessage() feedLoader?.load { [weak self] result in do { self?.onRefresh?(try result.get()) } catch { self?.error?.show(message: "message") } self?.refreshView?.endRefreshing() } } }
// // FriendsCell.swift // Mob_SMS // // Created by Steven on 14/11/21. // Copyright (c) 2014年 DevStore. All rights reserved. // import UIKit protocol FriendsCellDelegate:NSObjectProtocol { func FriendsCellClick (cell:FriendsCell) } class FriendsCell: UITableViewCell { var img:UIImage? var name:String? var nameDesc:String? var index:Int? var section:Int? @IBOutlet weak var imgView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var nameDescLabel: UILabel! @IBOutlet weak var button: UIButton! var delegate:FriendsCellDelegate? override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } @IBAction func btnClick(sender: AnyObject) { delegate?.FriendsCellClick(self) } }
// // SWBNewPropertyTableViewController.swift // SweepBright // // Created by Kaio Henrique on 2/3/16. // Copyright © 2016 madewithlove. All rights reserved. // import UIKit protocol SWBNewPropertyProtocol { var propertyService: SWBPropertyServiceProtocol {get} var negotiation: SWBPropertyNegotiation {get} } class SWBNewPropertyTableViewController: UITableViewController, SWBNewPropertyProtocol { var propertyService: SWBPropertyServiceProtocol = SWBPropertyService() var negotiation: SWBPropertyNegotiation = .ToLet override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) as! SWBNewPropertyTableViewCell guard let _ = cell.typeOfProperty else { return } let property: PropertyID = propertyService.createNewProperty(cell.typeOfProperty!, negotiation: self.negotiation, completionBlock: nil) SWBNewPropertyAddedNotification.dispatchNewPropertyHasBeenAdded(propertyWithId: property) self.dismissViewControllerAnimated(true, completion: { }) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "addProject" { let destination = segue.destinationViewController as! SWBNewProjectViewController destination.propertyViewController = self } super.prepareForSegue(segue, sender: sender) } }
// // NavView.swift // TemplateSwiftAPP // // Created by wenhua yu on 2018/3/28. // Copyright © 2018年 wenhua yu. All rights reserved. // import Foundation import UIKit class NavView: UIView { }
// // date.swift // OutlookCalendar // // Created by Pnina Eliyahu on 1/28/18. // Copyright © 2018 Pnina Eliyahu. All rights reserved. // import Foundation extension Date { // Returns the date's month symbol (using local timezone) var monthSymbol : String { let monthNumber = Calendar.current.component(.month, from: self) return DateFormatter().monthSymbols[monthNumber - 1] } // Returns the date's day symbol (using local timezone) var daySymbol : String { let dayNumber = Calendar.current.component(.weekday, from: self) return DateFormatter().weekdaySymbols[dayNumber - 1] } // Initialize a date from the given string and format (using local timezone) static func fromString(string: String, withFormat format: String) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.date(from: string) } // Convert the date into a string (using local timezone) func toString(format: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: self) } // Returns the amount of days from another date func days(from date: Date) -> Int { return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0 } // Returns the amount of hours from another date func hours(from date: Date) -> Int { return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0 } /// Returns the amount of minutes from another date func minutes(from date: Date) -> Int { return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0 } // Returns a time interval string description from another date, for example: "2d", "1h 30m", etc. func durationDescription(from date: Date) -> String { var duration = "" let daysOffset = days(from: date) let hoursOffset = hours(from: date) let minutesOffset = minutes(from: date) - 60 * hoursOffset if daysOffset > 0 { duration = "\(daysOffset)d" } else { if hoursOffset > 0 { duration = "\(hoursOffset)h " } if minutesOffset > 0 { duration += "\(minutesOffset)m" } } return duration } }
/* Copyright Airship and Contributors */ /** * - Note: For Internal use only :nodoc: */ class DeviceRegistrationEvent : NSObject, Event { init(channel: ChannelProtocol?, push: InternalPushProtocol?, privacyManager: PrivacyManager?) { var data: [AnyHashable : Any] = [:] if privacyManager?.isEnabled(.push) == true { data["device_token"] = push?.deviceToken } data["channel_id"] = channel?.identifier self._data = data } @objc public override convenience init() { self.init(channel: Airship.channel, push: Airship.push, privacyManager: Airship.shared.privacyManager) } @objc public var priority: EventPriority { get { return .normal } } @objc public var eventType : String { get { return "device_registration" } } private let _data : [AnyHashable : Any] @objc public var data: [AnyHashable : Any] { get { return self._data } } }
// // DifferentiableSectionedTableViewDataSourceTests.swift // RxDifferenceKitTests // // Created by Fumito Ito on 2018/10/17. // Copyright © 2018年 Fumito Ito. All rights reserved. // import XCTest class DifferentiableSectionedTableViewDataSourceTests: XCTestCase { var initialSections: [Section] = [] var secondarySections: [Section] = [] override func setUp() { let initialLiners = (0...5).map({ number in Liner.init(label: "\(number)") }) let secondaryLiners = (0...5).map({ number in Liner.init(label: "\(number)") }) + (0...5).map({ number in Liner.init(label: "\(number)") }) self.initialSections = [Section(label: "0", elements: initialLiners), Section(label: "1", elements: secondaryLiners)] self.secondarySections = [Section(label: "0", elements: initialLiners), Section(label: "0", elements: initialLiners), Section(label: "1", elements: secondaryLiners)] } override func tearDown() { } func testSectionedTableViewDataSource_duplicatableData() { let dataSource = DifferentiableSectionedTableViewDataSource<Section>(configureCell: { _, _, _, _ in UITableViewCell() }) dataSource.setItems(self.initialSections) XCTAssertEqual(dataSource.items.count, self.initialSections.count) XCTAssertEqual(dataSource.items[0].elements.count, self.initialSections[0].elements.count) XCTAssert(dataSource.items[0].isContentEqual(to: self.initialSections[0]), "\(dataSource.items[0]) and \(self.initialSections[0]) do not have content equality.") XCTAssert(dataSource.items[0].elements[0].isContentEqual(to: self.initialSections[0].elements[0]), "\(dataSource.items[0].elements[0]) and \(self.initialSections[0].elements[0]) do not have content equality.") dataSource.setItems(self.secondarySections) XCTAssertEqual(dataSource.items.count, self.secondarySections.count) XCTAssertEqual(dataSource.items[0].elements.count, self.secondarySections[0].elements.count) XCTAssert(dataSource.items[0].isContentEqual(to: self.secondarySections[0]), "\(dataSource.items[0]) and \(self.secondarySections[0]) do not have content equality.") XCTAssert(dataSource.items[0].elements[0].isContentEqual(to: self.secondarySections[0].elements[0]), "\(dataSource.items[0].elements[0]) and \(self.secondarySections[0].elements[0]) do not have content equality.") } func testSectionedTableViewDataSource_uniqueData() { let configuration = DifferentiableDataSourceConfiguration<Section>.init(rowAnimation: RowAnimation(), duplicationPolicy: .unique(handler: DuplicationPolicy.uniqueHandler)) let dataSource = DifferentiableSectionedTableViewDataSource<Section>(configureCell: { _, _, _, _ in UITableViewCell() }, configuration: configuration) dataSource.setItems(self.initialSections) XCTAssertEqual(dataSource.items.count, self.initialSections.count) XCTAssertEqual(dataSource.items[0].elements.count, self.initialSections[0].elements.count) XCTAssert(dataSource.items[0].isContentEqual(to: self.initialSections[0]), "\(dataSource.items[0]) and \(self.initialSections[0]) do not have content equality.") XCTAssert(dataSource.items[0].elements[0].isContentEqual(to: self.initialSections[0].elements[0]), "\(dataSource.items[0].elements[0]) and \(self.initialSections[0].elements[0]) do not have content equality.") dataSource.setItems(self.secondarySections) XCTAssertEqual(dataSource.items.count, self.secondarySections.count - 1) XCTAssertEqual(dataSource.items[0].elements.count, self.secondarySections[0].elements.count) XCTAssert(dataSource.items[0].isContentEqual(to: self.secondarySections[0]), "\(dataSource.items[0]) and \(self.secondarySections[0]) do not have content equality.") XCTAssert(dataSource.items[0].elements[0].isContentEqual(to: self.secondarySections[0].elements[0]), "\(dataSource.items[0].elements[0]) and \(self.secondarySections[0].elements[0]) do not have content equality.") } }
// // Constants.swift // TwoZeroFourEight // // Created by Adnan Zahid on 12/20/16. // Copyright © 2016 Adnan Zahid. All rights reserved. // let maxX = 3 let maxY = 3 enum Direction { case Up case Left case Right case Down } struct EvaluationMove { let direction: Direction? let evaluationValue: Int }
//: Playground - noun: a place where people can play import UIKit typealias Position = CGPoint typealias Distance = CGFloat func inRange1(target: Position, range: Distance) -> Bool { return sqrt(target.x * target.x + target.y * target.y) <= range } var x: CGFloat, y: CGFloat, range: CGFloat x = 1 y = 0 range = 1 inRange1(CGPointMake(x, y), range) // -> True y = 1 range = 1 inRange1(CGPointMake(x, y), range) // -> False range = 2 inRange1(CGPointMake(x, y), range) // -> True /** * But suppose the ship may be at a location, ownposition, other than the origin. */ func inRange2(target: Position, ownPosition: Position, range: Distance) -> Bool { let dx = ownPosition.x - target.x let dy = ownPosition.y - target.y let targetDistance = sqrt(dx * dx + dy * dy) return targetDistance <= range } /** * But now you realize that you also want to avoid targeting ships if they are too close to you. */ let minimumDistance: Distance = 2.0 func inRange3(target: Position, ownPosition: Position, range: Distance) -> Bool { let dx = ownPosition.x - target.x let dy = ownPosition.y - target.y let targetDistance = sqrt(dx * dx + dy * dy) return targetDistance <= range && targetDistance > minimumDistance } /** * Finally, you also need to avoid targeting ships that are too close to one of your other ships. */ func inRange4(target: Position, ownPosition: Position, friendly: Position, range: Distance) -> Bool { let dx = ownPosition.x - target.x let dy = ownPosition.y - target.y let targetDistance = sqrt(dx * dx + dy * dy) let friendlyDx = friendly.x - target.x let friendlyDy = friendly.y - target.y let friendlyDistance = sqrt(friendlyDx * friendlyDx + friendlyDy * friendlyDy) return targetDistance <= range && targetDistance > minimumDistance && friendlyDistance > minimumDistance } /** * As this code evolves, it becomes harder and harder to maintain. */ /** * First Class Functions * ====================== */ /** * The original problem boiled down to defining a function that determined when a point was in range * or not. */ typealias Region = Position -> Bool func circle(radius: Distance) -> Region { return { point in sqrt(point.x * point.x + point.y * point.y) <= radius } } /** * We could do this */ func circle2(radius: Distance, center: Position) -> Region { return { point in let shiftedPoint = Position(x: point.x - center.x, y: point.y - center.y) return sqrt(shiftedPoint.x * shiftedPoint.x + shiftedPoint.y * shiftedPoint.y) <= radius } } /** * But a more functional approach is to write a region transformer instead. */ func shift(offset: Position, region: Region) -> Region { return { point in let shiftedPoint = Position(x: point.x - offset.x, y: point.y - offset.y) return region(shiftedPoint) } } /** * For example, a circle that's centered at (5, 5) and has a radius of 10 can now be expressed as */ shift(Position(x: 5, y: 5), circle(10)) /** * We can also write functions that combine existing regions into larger, complex regions. */ func intersection(region1: Region, region2: Region) -> Region { return { point in region1(point) && region2(point) } } func union(region1: Region, region2: Region) -> Region { return { point in region1(point) || region2(point) } } func invert(region: Region) -> Region { return { point in !region(point) } } func difference(region: Region, minusRegion: Region) -> Region { return intersection(region, invert(minusRegion)) } /** * With this small library in place, we can now refactor the complicated inRange function as follows: */ func inRange(ownPosition: Position, target: Position, friendly: Position, range: Distance) -> Bool { let rangeRegion = difference(circle(range), circle(minimumDistance)); let targetRegion = shift(ownPosition, rangeRegion) let friendlyRegion = shift(friendly, circle(minimumDistance)) let resultRegion = difference(targetRegion, friendlyRegion) return resultRegion(target) }
// // UserInformationViewController.swift // SmokingMonitor // // Created by Minjiexie on 14/12/4. // Copyright (c) 2014年 MinjieXie. All rights reserved. // import UIKit class UserInformationViewController:UIViewController,UITextFieldDelegate{ @IBOutlet var GenderTextField: UITextField! @IBOutlet var AgeTextField: UITextField! @IBOutlet var WeightTextField: UITextField! @IBOutlet var SmokeAgeTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func CofirmBtn(sender: UIButton) { } //UITextField Delegate func textFieldShouldReturn(textField: UITextField) -> Bool{ textField.resignFirstResponder() return true } }
// // LogMoodVC.swift // MoodTracker // // Created by Julia Miller on 10/15/16. // Copyright © 2016 Julia Miller. All rights reserved. /* TO DOs: - to do: outlet for the textfield is customized so user can only write so much (create customTextField?) - to do: also need to remember to move view up when keyboard is showing up. commit: "Mood entities are being saved and displayed in day and week tab" */ import UIKit import CoreData class LogMoodVC: UIViewController, iCarouselDelegate, iCarouselDataSource, NSFetchedResultsControllerDelegate { //PROPERTIES--------------------------- @IBOutlet weak var carousel: iCarousel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! //will probably need a custom tf @IBOutlet weak var commentaryTF: UITextField! //All the Mood entities that you have in CoreData. static var loggedMoods = [Mood]() var frc: NSFetchedResultsController<Mood>? //Allow for a previous Mood from current day to be updated (like in SomeJunk app). var editMood: Mood? //FUNCTIONS---------------------------- override func viewDidLoad() { super.viewDidLoad() carousel.type = .coverFlow2 carousel.delegate = self carousel.dataSource = self //Actually might need this functions in viewWillAppear? Will see... if editMood != nil { //scrollToMood(updatePreviousMood) } //else scrollToMood(nil) //change scrollToMostRecentMood so that it takes in a Mood optional to account for updatePreviousMood scrollToMostRecentMoodScore() //This is fine in viewDidLoad because it will keep repeating updateDateAndTimeLabels() _ = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(self.updateDateAndTimeLabels), userInfo: nil, repeats: true) updateLoggedMoods() } @IBAction func saveMood(_ sender: AnyObject) { print("COMMENT save pressed.") //Save the most recent saved mood score to UserDefaults //so that carousel will scroll to this score next time the page loads. let index = carousel.currentItemIndex UserDefaults.standard.set(index, forKey: "MoodScore") var mood: Mood! //if updatePreviousMood is not nil then mood = updatedpreviousmood mood = Mood(context: delegate.persistentContainer.viewContext) mood.score = Int32(index) if let comment = commentaryTF.text { mood.commentary = comment } delegate.saveContext() updateLoggedMoods() //disable save button for three seconds? } func updateDateAndTimeLabels(){ let df = DateFormatter() df.timeStyle = .short let timeString = "\(df.string(from: Date()))" if timeString != timeLabel.text { timeLabel.text = timeString } df.timeStyle = .none df.dateStyle = .long let dateString = "\(df.string(from: Date()))" if dateString != timeLabel.text { dateLabel.text = dateString } } //Functions involving CoreData. func updateLoggedMoods(){ //Reset fetchedResultsController so that it is empty before you perform the fetch. resetFRC() do { try frc?.performFetch() } catch { let error = error as NSError print("COMMENT ERROR performFetch() was not successful. ", error.userInfo) return } guard let fetchedObjects = frc?.fetchedObjects else { print("COMMENT ERROR There are currently no moods saved.") return } LogMoodVC.loggedMoods.removeAll() for mood in fetchedObjects { LogMoodVC.loggedMoods.append(mood) let df = DateFormatter() df.timeStyle = .short let timeString = df.string(from: mood.date as! Date) print("COMMENT Time saved ", timeString) } print("COMMENT loggedMoods array count", LogMoodVC.loggedMoods.count) } func resetFRC() { let request = NSFetchRequest<Mood>(entityName: "Mood") let sortByDate = NSSortDescriptor(key: "date", ascending: true) request.sortDescriptors = [sortByDate] let controller = NSFetchedResultsController<Mood>(fetchRequest: request, managedObjectContext: delegate.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil) controller.delegate = self frc = controller } //Functions involving iCarousel. func scrollToMostRecentMoodScore(){ let launchedBefore = UserDefaults.standard.bool(forKey: "LaunchedBefore") if !launchedBefore { print("COMMENT This is first launch.") //first launch UserDefaults.standard.set(true, forKey: "LaunchedBefore") let index: Int = 4 UserDefaults.standard.set(index, forKey: "MoodScore") carousel.scrollToItem(at: index, animated: false) } else { let index = UserDefaults.standard.integer(forKey: "MoodScore") print("COMMENT last logged mood score is", index) carousel.scrollToItem(at: index, animated: false) } } func numberOfItems(in carousel: iCarousel) -> Int { return 9 } func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView { let view = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 150)) view.backgroundColor = UIColor.clear let imageView = UIImageView() imageView.image = UIImage(named: "\(index)") imageView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) view.addSubview(imageView) return view } func carousel(_ carousel: iCarousel, valueFor option: iCarouselOption, withDefault value: CGFloat) -> CGFloat { if option == iCarouselOption.spacing { return value * 1.1 } return value } }
import Foundation import CoreGraphics #if os(macOS) public func NSStringFromCGPoint(_ point: CGPoint) -> String! { return NSStringFromPoint(point) } public func CGPointFromString(_ string: String!) -> CGPoint { return NSPointFromString(string) as CGPoint } #else import UIKit #endif extension CGPoint { public var stringRepresentation: String { #if os(macOS) return NSStringFromCGPoint(self) #else return NSCoder.string(for: self) #endif } public init(string: String) { #if os(macOS) self = CGPointFromString(string) #else self = NSCoder.cgPoint(for: string) #endif } }
// // Video.swift // YouTubeAPI // // Created by Emiko Clark on 3/22/18. // Copyright © 2018 Emiko Clark. All rights reserved. // import Foundation class Video { var channelId: String? var channelTitle: String? var playlistId: String? var title: String? var description: String? var thumbnails: [Thumbnail]? init(channelId: String, channelTitle: String, playlistId: String, title: String, description: String, thumbnails: [Thumbnail]) { self.channelId = channelId self.channelTitle = channelTitle self.playlistId = playlistId self.title = title self.description = description self.thumbnails = thumbnails } } class Thumbnail { var url: String? var width: Int? var height: Int? init(url: String, width: Int, height: Int) { self.url = url self.width = width self.height = height } } //"channelId": "UCD5kT8GTKnbYl9WxgnLM0aA", //"title": "Argentine Tango Lessons", //"description": "", //"thumbnails": { // "default": { // "url": "https://i.ytimg.com/vi/jwz-q0TKz0Y/default.jpg", // "width": 120, // "height": 90 // }, // "medium": { // "url": "https://i.ytimg.com/vi/jwz-q0TKz0Y/mqdefault.jpg", // "width": 320, // "height": 180 // }, // "high": { // "url": "https://i.ytimg.com/vi/jwz-q0TKz0Y/hqdefault.jpg", // "width": 480, // "height": 360 // } //}, //"channelTitle": "Emiko Clark",
// // PurchaseScannerViewController.swift // DanceScanner // // Created by Michal Juscinski on 12/5/17. // Copyright © 2017 Michal Juscinski. All rights reserved. // import UIKit import AVFoundation import CloudKit class PurchaseScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate, UITabBarDelegate { var session: AVCaptureSession! var previewLayer: AVCaptureVideoPreviewLayer! var database = CKContainer.default().publicCloudDatabase var studentDictionary: NSDictionary! var altId = "" var url: URL! var isProm: Bool! override func viewDidLoad() { super.viewDidLoad() if isProm { self.navigationController?.navigationBar.barTintColor = .black } else { self.navigationController?.navigationBar.barTintColor = UIColor(red: 92.0/255.0, green: 60.0/255.0, blue: 31.0/255.0, alpha: 1) } // self.navigationController?.navigationBar.barStyle = UIBarStyle.blackTranslucent self.navigationController?.navigationBar.tintColor = .white //Set up the background for the scanner session = AVCaptureSession() let videoCaptureDevice = AVCaptureDevice.default(for: AVMediaType.video) let videoInput: AVCaptureDeviceInput? do { videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice!) } catch { return } //Adds input and output to session if (session.canAddInput(videoInput!)) { session.addInput(videoInput!) } else { scanningNotPossible() } let metadataOutput = AVCaptureMetadataOutput() if (session.canAddOutput(metadataOutput)) { session.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) metadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.code39] } else { scanningNotPossible() } //Presents camera for scanner previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer.frame = view.layer.bounds previewLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill view.layer.addSublayer(previewLayer) //Sets the appearance of the Tab Bar let appearance = UITabBarItem.appearance() let attributes = [NSAttributedStringKey.foregroundColor: UIColor.white] appearance.setTitleTextAttributes(attributes, for: .normal) appearance.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.blue.lighter(by: 30)!], for: .selected) //Creates the Tab Bar and displays it let tabBar = UITabBar(frame: CGRect(x: 0, y: 975, width: 770, height: 50)) tabBar.delegate = self if isProm == true { tabBar.barTintColor = .black } else { tabBar.barTintColor = UIColor(red: 92.0/255.0, green: 60.0/255.0, blue: 31.0/255.0, alpha: 1) } // tabBar.barStyle = .black let checkTabButton = UITabBarItem(title: "Check In/Out", image: nil, tag: 2) let listTabButton = UITabBarItem(title: "List", image: nil, tag: 3) tabBar.setItems([checkTabButton, listTabButton], animated: false) //Adds tab bar and runs scanning session view.addSubview(tabBar) session.startRunning() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) runSession() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) stopSession() } func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { //When the check button on the Tab Bar is pressed, segue to the checkVC if item.tag == 2 { print("check") self.performSegue(withIdentifier: "tabCheckSegue", sender: self) //Removes the current VC from the stack var navigationArray = self.navigationController?.viewControllers ?? [Any]() navigationArray.remove(at: 1) navigationController?.viewControllers = (navigationArray as? [UIViewController])! } //When the list button on the Tab Bar is pressed, segue to the listVC else if item.tag == 3 { print("list") self.performSegue(withIdentifier: "tabListSegue", sender: self) //Removes the current VC from the stack var navigationArray = self.navigationController?.viewControllers ?? [Any]() navigationArray.remove(at: 1) navigationController?.viewControllers = (navigationArray as? [UIViewController])! } } func getJSON(altID: String){ //Connects to JSON and pulls data //Old URL https://api.myjson.com/bins/16mtrl let predicate = NSPredicate(value: true) let query = CKQuery(recordType: "JSONurl", predicate: predicate) database.perform(query, inZoneWith: nil) { (records, error) in if let asset = records?.first?.object(forKey: "JSONData") as? CKAsset, let myData = NSData(contentsOf: asset.fileURL) { if let JSONObject = try? JSONSerialization.jsonObject(with: myData as Data, options: .allowFragments) as! NSDictionary { //Takes JSON information and places them into local varialbes guard let dictionary = JSONObject.object(forKey: altID) as? NSDictionary else { let alert = UIAlertController(title: "Error", message: "Student not Found", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Done", style: .default, handler: { (action) in self.runSession() })) self.present(alert, animated: true, completion: nil) return } self.studentDictionary = dictionary let firstName = self.studentDictionary.object(forKey: "FIRST") as! NSString let lastName = self.studentDictionary.object(forKey: "LAST") as! NSString let ID = self.studentDictionary.object(forKey: "ID") as! NSInteger let parentFirst = self.studentDictionary.object(forKey: "GRDFIRST") as! NSString let parentLast = self.studentDictionary.object(forKey: "GRDLAST") as! NSString let parentCell = self.studentDictionary.object(forKey: "GRDCELL") as! NSString let parentHouseHold = self.studentDictionary.object(forKey: "GRDHHOLD") as! NSString //Query the database for the altID that was scanned let predicate = NSPredicate(format: "altIDNumber = '\(altID)'") let query = CKQuery(recordType: "Students", predicate: predicate) self.database.perform(query, inZoneWith: nil, completionHandler: { (records, error) in if error != nil { //Inform the user of any error let alert = UIAlertController(title: "Error", message: error.debugDescription, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action) in self.runSession() }) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } else if (records?.count)! > 0 { //Inform the user that the student is already purchased let alert = UIAlertController(title: "Error", message: "The student already has a ticket", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action) in self.runSession() }) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } else { if self.isProm == false { //Creates an alert that allows the user to confirm the purchase with 3 buttons let purchaseTicketsAlert = UIAlertController(title: "Found an ID", message: "Student: \(firstName) \(lastName)\nStudent ID: \(ID)", preferredStyle: .alert) let purchaseTicketButton = UIAlertAction(title: "Purchase Ticket", style: .default, handler: { (action) in self.purchaseTicket(firstName: firstName as String, lastName: lastName as String, ID: String(ID), altID: String(altID), parentName: String(parentFirst) + " " + String(parentLast), parentCell: String(parentCell), parentHouseHold: String(parentHouseHold), foodChoice: "0") }) let addGuestButton = UIAlertAction(title: "Ticket with Guest", style: .default, handler: { (action) in self.performSegue(withIdentifier: "addGuestSegue", sender: self) }) let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) in self.runSession() }) //Adds all buttons and presents alert purchaseTicketsAlert.addAction(purchaseTicketButton) purchaseTicketsAlert.addAction(cancelAction) purchaseTicketsAlert.addAction(addGuestButton) self.present(purchaseTicketsAlert, animated: true, completion: nil) } else { //Creates an alert that allows the user to confirm the purchase with 3 buttons (Prom edition) let purchaseTicketsAlert = UIAlertController(title: "Found an ID", message: "Student: \(firstName) \(lastName)\nStudent ID: \(ID)\n", preferredStyle: .alert) let purchaseTicketButton = UIAlertAction(title: "Purchase Ticket", style: .default, handler: { (action) in //Creates an alert to check for food choices let fuudAlert = UIAlertController(title: "Select Food Choice", message: "Which food choice does the student want?", preferredStyle: .alert) let oneAction = UIAlertAction(title: "1", style: .default, handler: { (action) in //Purchases a ticket with food choice 1 self.purchaseTicket(firstName: firstName as String, lastName: lastName as String, ID: String(ID), altID: String(altID), parentName: String(parentFirst) + " " + String(parentLast), parentCell: String(parentCell), parentHouseHold: String(parentHouseHold), foodChoice: "1") }) let twoAction = UIAlertAction(title: "2", style: .default, handler: { (action) in //Purchases a ticket with food choice 2 self.purchaseTicket(firstName: firstName as String, lastName: lastName as String, ID: String(ID), altID: String(altID), parentName: String(parentFirst) + " " + String(parentLast), parentCell: String(parentCell), parentHouseHold: String(parentHouseHold), foodChoice: "2") }) let threeAction = UIAlertAction(title: "3", style: .default, handler: { (action) in //Purchases a ticket with food choice 3 self.purchaseTicket(firstName: firstName as String, lastName: lastName as String, ID: String(ID), altID: String(altID), parentName: String(parentFirst) + " " + String(parentLast), parentCell: String(parentCell), parentHouseHold: String(parentHouseHold), foodChoice: "3") }) let cancelButton = UIAlertAction(title: "Cancel", style: .default, handler: { (action) in self.runSession() }) //Adds all buttons and presents alert fuudAlert.addAction(oneAction) fuudAlert.addAction(twoAction) fuudAlert.addAction(threeAction) fuudAlert.addAction(cancelButton) self.present(fuudAlert, animated: true, completion: nil) }) let addGuestButton = UIAlertAction(title: "Ticket with Guest", style: .default, handler: { (action) in self.performSegue(withIdentifier: "addGuestSegue", sender: self) }) let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) in self.runSession() }) //Adds all buttons and presents alert purchaseTicketsAlert.addAction(purchaseTicketButton) purchaseTicketsAlert.addAction(cancelAction) purchaseTicketsAlert.addAction(addGuestButton) self.present(purchaseTicketsAlert, animated: true, completion: nil) }} }) } }} } func purchaseTicket(firstName: String, lastName: String, ID: String, altID: String, parentName: String, parentCell: String, parentHouseHold: String, foodChoice: String) { //Sets the information of the student on CloudKit let place = CKRecord(recordType: "Students") place.setObject(firstName as CKRecordValue, forKey: "firstName") place.setObject(lastName as CKRecordValue, forKey: "lastName") place.setObject(String(ID) as CKRecordValue, forKey: "idNumber") place.setObject(String(altID) as CKRecordValue, forKey: "altIDNumber") place.setObject("Purchased" as CKRecordValue, forKey: "checkedInOrOut") place.setObject("" as CKRecordValue, forKey: "checkInTime") place.setObject("" as CKRecordValue, forKey: "checkOutTime") place.setObject(parentHouseHold as CKRecordValue, forKey: "studentParentPhone") place.setObject(parentName as CKRecordValue, forKey: "studentParentName") place.setObject(parentCell as CKRecordValue, forKey: "studentParentCell") place.setObject("" as CKRecordValue, forKey: "guestName") place.setObject("" as CKRecordValue, forKey: "guestSchool") place.setObject("" as CKRecordValue, forKey: "guestParentPhone") place.setObject("" as CKRecordValue, forKey: "guestCheckIn") place.setObject("0" as CKRecordValue, forKey: "guestFoodChoice") place.setObject(foodChoice as CKRecordValue, forKey: "foodChoice") //Saves student and checks for error self.database.save(place) { (record, error) in if error != nil { let alert = UIAlertController(title: "Error", message: error.debugDescription, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action) in self.runSession() }) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } else { let alert = UIAlertController(title: "Purchase Successful", message: "This student now has a ticket", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: { (action) in self.runSession() }) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } } } func scanningNotPossible() { //Presents an alert if it is impossible to scan let alert = UIAlertController(title: "This device can't scan.", message: "How did you mess this up? It was only supposed to be sent to camera-equipped iPads!", preferredStyle: .alert) let closeButton = UIAlertAction(title: "Yeah, I really screwed this up", style: .destructive, handler: nil) alert.addAction(closeButton) present(alert, animated: true, completion: nil) } func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { //Places readable value of scanned barcode into the variable altID stopSession() if let barcodeData = metadataObjects.first { let barcodeReadable = barcodeData as? AVMetadataMachineReadableCodeObject if let readableCode = barcodeReadable{ self.altId = readableCode.stringValue! getJSON(altID: altId) } } } func runSession() { //Starts to run the session again if (session?.isRunning == false) { session.startRunning() } } func stopSession() { //Stops the session if (session?.isRunning == true) { session.stopRunning() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { //Shares information pulled from JSON with the addGuestVC if segue.identifier == "addGuestSegue" { let nvc = segue.destination as! addGuestViewController nvc.studentDictionary = studentDictionary nvc.altId = altId nvc.database = database nvc.isProm = isProm } else if segue.identifier == "tabCheckSegue" { let nvc = segue.destination as! checkViewController nvc.isProm = isProm } else if segue.identifier == "tabListSegue" { let nvc = segue.destination as! ListViewController nvc.isProm = isProm } } }
// // GroupTarget.swift // WatNi // // Created by 홍창남 on 2020/01/31. // Copyright © 2020 hcn1519. All rights reserved. // import Foundation import Moya enum GroupTarget: TargetType { /// 모임 생성 case createGroup(Encodable) /// 모임 초대코드 생성 case createInviteCode(Encodable, groupId: Int) /// 모임 참여 case applyGroup(Encodable) var baseURL: URL { return APIConfig.baseURL } var path: String { switch self { case .createGroup: return "api/group" case .createInviteCode(_, let groupId): return "api/group/\(groupId)/apply-way" case .applyGroup: return "api/group/accession" } } var method: Moya.Method { switch self { case .createGroup, .createInviteCode, .applyGroup: return .post } } var sampleData: Data { return Data() } var task: Moya.Task { switch self { case .createGroup(let body), .applyGroup(let body): return .requestJSONEncodable(body) case .createInviteCode(let body, _): return .requestJSONEncodable(body) } } var headers: [String: String]? { switch self { case .createGroup, .createInviteCode, .applyGroup: return ["Content-Type": "application/json", "Authorization": "Bearer \(MemberAccess.headerToken)"] } } }
// // PopupSegue.swift // LoLMessenger // // Created by Kim Young Rok on 2015. 11. 10.. // Copyright © 2015년 rokoroku. All rights reserved. // import UIKit import STPopup class PopupSegue : UIStoryboardSegue { var shouldPerform:Bool = true override func perform() { if shouldPerform { let screenSize = UIScreen.mainScreen().bounds.size var contentSize = CGSizeMake(screenSize.width - 32, screenSize.height/2) if contentSize.width > 340 { contentSize.width = 340 } if contentSize.height < 300 { contentSize.height = 300 } self.destinationViewController.contentSizeInPopup = contentSize self.destinationViewController.landscapeContentSizeInPopup = contentSize let popupController = STPopupController(rootViewController: self.destinationViewController) popupController.navigationBarHidden = true popupController.transitionStyle = .Fade popupController.cornerRadius = 16 Async.main { popupController.presentInViewController(self.sourceViewController) } } } }
// // Constants.swift // Nightscouter // // Created by Peter Ina on 11/18/15. // Copyright © 2015 Peter Ina. All rights reserved. // import Foundation public let AppDataManagerDidChangeNotification: String = "com.nothingonline.nightscouter.appDataManager.DidChange.Notification" public struct DefaultKey { public static let sitesArrayObjectsKey = "userSitesData" public static let currentSiteIndexKey = "currentSiteIndexInt" public static let modelArrayObjectsKey = "siteModelArray" public static let defaultSiteKey = "defaultSiteKey" public static let calibrations = "calibrations" public static let complicationModels = "complicationModels" public static let complicationLastUpdateStartDate = "lastUpdateStartDate" public static let complicationLastUpdateDidChangeComplicationDate = "lastUpdateDidChangeDate" public static let complicationNextRequestedStartDate = "nextRequestedStartDate" public static let complicationRequestedUpdateBudgetExhaustedDate = "requestedUpdateBudgetExhaustedDate" public static let complicationUpdateEndedOnDate = "complicationUpdateEndedOnDate" public static let osPlatform = "osPlatform" } public struct Constants { public struct StandardTimeFrame { public static let OneMinuteInSeconds: NSTimeInterval = 60.0 public static let TwoAndHalfMinutesInSeconds: NSTimeInterval = OneMinuteInSeconds * 2.5 public static let FourMinutesInSeconds: NSTimeInterval = OneMinuteInSeconds * 4 public static let TenMinutesInSeconds: NSTimeInterval = OneMinuteInSeconds * 10 public static let ThirtyMinutesInSeconds: NSTimeInterval = OneMinuteInSeconds * 30 public static let OneHourInSeconds: NSTimeInterval = OneMinuteInSeconds * 60 public static let TwoHoursInSeconds: NSTimeInterval = OneMinuteInSeconds * 120 } public struct NotableTime { public static let StaleDataTimeFrame = StandardTimeFrame.TenMinutesInSeconds public static let StandardRefreshTime = StandardTimeFrame.FourMinutesInSeconds } public struct EntryCount { public static let NumberForChart = 100 public static let NumberForComplication = 288 public static let LowerLimitForValidSGV = 39 public static let UpperLimitForValidSGV = 400 } }
// // ContentView.swift // NSUserActivity // // Created by Ataias Pereira Reis on 30/12/20. // import SwiftUI import SwiftUI import Intents // Remember to add this to the NSUserActivityTypes array in the Info.plist file let aType = "br.com.ataias.NSUserActivity.show-animal" struct Animal: Identifiable { let id: Int let name: String let image: String } let animals = [Animal(id: 1, name: "Lion", image: "lion"), Animal(id: 2, name: "Fox", image: "fox"), Animal(id: 3, name: "Panda", image: "panda-bear"), Animal(id: 4, name: "Elephant", image: "elephant")] struct ContentView: View { @State private var selection: Int? = nil var body: some View { NavigationView { List(animals) { animal in NavigationLink( destination: AnimalDetail(animal: animal), tag: animal.id, selection: $selection, label: { AnimalRow(animal: animal) }) } .navigationTitle("Animal Gallery") .onContinueUserActivity(aType, perform: { userActivity in self.selection = Int.random(in: 0...(animals.count - 1)) }) }.navigationViewStyle(StackNavigationViewStyle()) } } struct AnimalRow: View { let animal: Animal var body: some View { HStack { // Image(animal.image) // .resizable() // .frame(width: 60, height: 60) Text(animal.name) } } } struct AnimalDetail: View { @State private var showAddToSiri: Bool = false let animal: Animal let shortcut: INShortcut = { let activity = NSUserActivity(activityType: aType) activity.title = "Display a random animal" activity.suggestedInvocationPhrase = "Show Random Animal" return INShortcut(userActivity: activity) }() var body: some View { VStack(spacing: 20) { Text(animal.name) .font(.title) // Image(animal.image) // .resizable() // .scaledToFit() SiriButton(shortcut: shortcut).frame(height: 34) Spacer() } } }
// // Log.swift // SkyApp // // Created by Bruno Lopes on 31/08/20. // Copyright © 2020 Bruno. All rights reserved. // import Foundation /// Print /// /// - Parameter items: print items in environment development & homologation. func debug(_ items: Any, file: String = #file, function: String = #function, line: Int = #line) { let className = file.components(separatedBy: "/").last #if DEVELOPMENT || HOMOLOGATION print("----------------------------------------") print("\nDEBUG: File: \(className ?? ""), Function: \(function), Line: \(line)\n--->>> \(items)\n") print("----------------------------------------") #else debugPrint("----------------------------------------") debugPrint("DEBUG: File: \(className ?? "")") debugPrint("Function: \(function)") debugPrint("Line: \(line)") debugPrint("\(items)") debugPrint("----------------------------------------") #endif }
// // QuickSatisfactionView.swift // GTor // // Created by Safwan Saigh on 19/06/2020. // Copyright © 2020 Safwan Saigh. All rights reserved. // import SwiftUI struct DoneAction: Identifiable, Hashable { var id = UUID() var title: String var satisfaction: Double var type: ActionType } enum ActionType { case complete, pComplete, notComplete } let actions: [DoneAction] = [ .init(title: NSLocalizedString("completelyDone", comment: ""), satisfaction: 100, type: .complete), .init(title: NSLocalizedString("partiallyDone", comment: ""), satisfaction: 50, type: .pComplete),//TODO .init(title: NSLocalizedString("notDone", comment: ""), satisfaction: 0, type: .notComplete) ] struct QuickSatisfactionView: View { @ObservedObject var taskService = TaskService.shared @Binding var selectedTask: Task @State var updatedSatisfaction = "" @State var isHidingTextField = true @State var alertMessage = "" @State var isLoading = false @State var isShowingAlert = false var body: some View { ZStack { VStack { HStack { Button(action: { self.selectedTask = Task.dummy; self.isHidingTextField = true }) { Image(systemName: "xmark.circle.fill") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 25, height: 25) .foregroundColor(Color("Primary")) } .buttonStyle(PlainButtonStyle()) .offset(x: -8) Spacer() } Spacer() VStack(spacing: 10.0) { if self.isHidingTextField { ForEach(actions, id: \.self) { action in VStack { Button( action: { if action.type != .pComplete { self.isLoading = true self.selectedTask.satisfaction = action.satisfaction self.selectedTask.isSatisfied = true self.taskService.saveTask(task: self.selectedTask) { result in switch result { case .failure(let error): self.isLoading = false self.isShowingAlert = true self.alertMessage = error.localizedDescription case .success(()): self.isLoading = false self.selectedTask = Task.dummy } } }else { self.isHidingTextField = false } }) { Text(action.title) .font(.system(size: 13)) .frame(maxWidth: .infinity) .frame(height: 20) .padding(7) .foregroundColor(Color.black) .background(Color("Button")) .clipShape(RoundedRectangle(cornerRadius: 5)) } } } .buttonStyle(PlainButtonStyle()) }else { VStack { TextField("50%", text: $updatedSatisfaction) .font(.system(size: 13)) .frame(maxWidth: .infinity) .frame(height: 20) .padding(7) .foregroundColor(Color.black) .background(Color("Level 0")) .clipShape(RoundedRectangle(cornerRadius: 5)) .elevation() Spacer() Button(action: { self.isLoading = true if self.updatedSatisfaction.isEmpty || Double(self.updatedSatisfaction) == nil{ self.isLoading = false self.isShowingAlert = true self.alertMessage = NSLocalizedString("enterAValue", comment: "") return }else{ self.selectedTask.satisfaction = Double(self.updatedSatisfaction)! } self.selectedTask.isSatisfied = true self.taskService.saveTask(task: self.selectedTask) { result in switch result { case .failure(let error): self.isLoading = false self.isShowingAlert = true self.alertMessage = error.localizedDescription case .success(()): self.isLoading = false self.selectedTask = Task.dummy self.isHidingTextField = true self.updatedSatisfaction = "" } } }) { Text(NSLocalizedString("done", comment: "")) .font(.system(size: 13)) .frame(maxWidth: .infinity) .frame(height: 20) .padding(7) .foregroundColor(Color.black) .background(Color("Button")) .clipShape(RoundedRectangle(cornerRadius: 5)) } .buttonStyle(PlainButtonStyle()) Spacer() } .animation(.spring()) } } .padding() } .frame(width: 200, height: 170) .padding() .background(Color("Level 0")) .clipShape(RoundedRectangle(cornerRadius: 10)) .elevation() .animation(.easeInOut) .offset(y: self.selectedTask != Task.dummy ? 0 : screen.height) LoadingView(isLoading: $isLoading) } .alert(isPresented: self.$isShowingAlert) { Alert(title: Text(self.alertMessage)) } } } struct QuickSatisfactionView_Previews: PreviewProvider { static var previews: some View { QuickSatisfactionView(selectedTask: .constant(.init(uid: "", title: "Ti", note: "", satisfaction: 0, isSatisfied: false, linkedGoalsIds: [], importance: .none))) } }
// MARK: Frameworks import UIKit // MARK: ArticleViewController class ArticleViewController: UIViewController { // MARK: Outlets @IBOutlet var myTableView: UITableView! // MARK: Variables var articles: [Article] = [] // MARK: View Methods override func viewDidLoad() { super.viewDidLoad() ArticleRemote.retrieveArticles { articles in self.articles = articles.results DispatchQueue.main.async { self.myTableView.reloadData() } } } } // MARK: UITableViewDataSource Methods extension ArticleViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return articles.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell") let article = articles[indexPath.row] cell.textLabel?.text = article.title return cell } } // MARK: UITableViewDelegate Methods extension ArticleViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let article = articles[indexPath.row] openURL(article.url) } // MARK: Helper Methods private func openURL(_ url: URL) { guard UIApplication.shared.canOpenURL(url) == true else { return } UIApplication.shared.open(url, options: [:], completionHandler: nil) } }
// // ViewController.swift // HelloPhotos // // Created by goWhere on 2017/5/9. // Copyright © 2017年 iwhere. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var vcFlowLayout: UICollectionViewFlowLayout! var imgDatas = [Data?]() override func viewDidLoad() { super.viewDidLoad() vcFlowLayout.itemSize = CGSize(width: 80, height: 80) vcFlowLayout.minimumLineSpacing = 20 vcFlowLayout.minimumInteritemSpacing = 20 } @IBAction func oneAction(_ sender: UIButton) { imgDatas.removeAll() HsuPhotosManager.share.takePhotos(1, true, true) { (datas) in self.imgDatas.append(contentsOf: datas) DispatchQueue.main.async { self.collectionView.reloadData() } } } @IBAction func mutableAction(_ sender: UIButton) { imgDatas.removeAll() HsuPhotosManager.share.takePhotos(7, true, true) { (datas) in self.imgDatas.append(contentsOf: datas) DispatchQueue.main.async { self.collectionView.reloadData() } } } } extension ViewController: UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imgDatas.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CVCell.cellIdentifier, for: indexPath) as! CVCell cell.imageView.image = UIImage(data: imgDatas[indexPath.row] ?? Data()) return cell } } class CVCell: UICollectionViewCell { static let cellIdentifier = "cellIdentifier" @IBOutlet weak var imageView: UIImageView! }
// // TNLoginTableViewController.swift // TNAppForTraining // // Created by Prasobh Veluthakkal on 08/12/16. // Copyright © 2016 Focaloid. All rights reserved. // import UIKit class TNLoginTableViewController: UITableViewController { //MARK: - Variables @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var userId: UITextField! @IBOutlet weak var password: UITextField! //MARK: - View Methods override func viewDidLoad() { super.viewDidLoad() let backgroundImage = UIImageView(frame: UIScreen.mainScreen().bounds) backgroundImage.image = UIImage(named: "ic_login_bg") self.view.insertSubview(backgroundImage, atIndex: 0) self.loginButton.layer.borderColor = UIColor.whiteColor().CGColor self.loginButton.layer.borderWidth = 1 let paddingForFirst = UIView(frame: CGRectMake(0, 0, 15, self.userId.frame.size.height)) userId.leftView = paddingForFirst userId.leftViewMode = UITextFieldViewMode .Always let paddingForSecond = UIView(frame: CGRectMake(0, 0, 15, self.password.frame.height)) password.leftView = paddingForSecond password.leftViewMode = UITextFieldViewMode .Always self.navigationController?.navigationBarHidden = true } //MARK: - Actions @IBAction func login(sender: AnyObject) { login() } func login() { print("Login Success") } // MARK: - TextField Delegates func textFieldDidBeginEditing(textField: UITextField) { } func textFieldDidEndEditing(textField: UITextField) { } func textFieldShouldReturn(textField: UITextField) -> Bool { if textField == userId { password.becomeFirstResponder() }else if textField == password { textField.resignFirstResponder() login() } return true } //MARK: - System override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
import RxSwift import EthereumKit class AddErc20TokenInteractor { weak var delegate: IAddErc20TokenInteractorDelegate? private let coinManager: ICoinManager private let pasteboardManager: IPasteboardManager private let erc20ContractInfoProvider: IErc20ContractInfoProvider private var disposeBag = DisposeBag() init(coinManager: ICoinManager, pasteboardManager: IPasteboardManager, erc20ContractInfoProvider: IErc20ContractInfoProvider) { self.coinManager = coinManager self.pasteboardManager = pasteboardManager self.erc20ContractInfoProvider = erc20ContractInfoProvider } } extension AddErc20TokenInteractor: IAddErc20TokenInteractor { var valueFromPasteboard: String? { pasteboardManager.value } func validate(address: String) throws { try EthereumKit.Kit.validate(address: address) } func existingCoin(address: String) -> Coin? { coinManager.existingCoin(erc20Address: address) } func fetchCoin(address: String) { erc20ContractInfoProvider.coinSingle(address: address) .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated)) .observeOn(MainScheduler.instance) .subscribe( onSuccess: { [weak self] coin in self?.delegate?.didFetch(coin: coin) }, onError: { [weak self] error in self?.delegate?.didFailToFetchCoin(error: error) } ) .disposed(by: disposeBag) } func abortFetchingCoin() { disposeBag = DisposeBag() } func save(coin: Coin) { coinManager.save(coin: coin) } }
// 视频播放视图 // WGVideoView.swift // TXVideoDome // // Created by 98data on 2019/12/12. // Copyright © 2019 98data. All rights reserved. // import UIKit class WGVideoView: UIView { // 回调方法 var didClickAvater : ((_ videoView:WGVideoView,_ info:VideoEntity)->Void)? var didClickLike : ((_ videoView:WGVideoView,_ info:VideoEntity)->Void)? var didClickComment : ((_ videoView:WGVideoView,_ info:VideoEntity)->Void)? var didClickShare : ((_ videoView:WGVideoView,_ info:VideoEntity)->Void)? var didClickFollew : ((_ videoView:WGVideoView,_ info:VideoEntity)->Void)? // 数据源 var videos = [VideoEntity]() // 当前播放内容的索引 var currentPlayIndex = 0 // 控制播放的索引,不完全等于当前播放内容的索引 var index = 0 // 是否push 当前页面 var isPushed = false // 记录滑动前的播放状态 var isPlaying_beforeScroll = false // 是否在刷新状态 var isRefreshMore = false // 交流沟通 var interacting = false // 记录播放内容 var currentPlayId = "" var vc:UIViewController? var scrollView:UIScrollView? // 开始移动时的位置 var startLocationY:Float = 0.0 var startLocation = CGPoint.zero var startFrame = CGRect.zero var topView:WGVideoController? // 顶部 var ctrView:WGVideoController? // 中部 var btmView:WGVideoController? // 底部 // 创建方式 static func initWithCreate(vc:UIViewController,isPushed:Bool) -> WGVideoView { let view = WGVideoView() view.vc = vc view.isPushed = isPushed view.createUI(videoView: view) return view } } extension WGVideoView { func createUI(videoView:WGVideoView) { self.scrollView = UIScrollView() self.addSubview(self.scrollView!) self.scrollView?.mas_makeConstraints({ (make) in make!.edges.equalTo() }) if !self.isPushed { } else { } } // 暂停 func pause() { } // 继续播放 func resume() { } // 回收播放 func destoryPlayer() { } }
// // MainScene+Gloop.swift // gloop-drop iOS // // Created by Fernando Fernandes on 05.11.20. // import SwiftUI import SpriteKit extension MainScene { func spawnMultipleGloops() { hideMessage() setupDropNumber() setupDropSpeed() // Set up repeating action. let wait = SKAction.wait(forDuration: TimeInterval(dropSpeed)) let spawn = SKAction.run { [weak self] in self?.spawnGloop() } let dropGloopsSequence = SKAction.sequence([wait, spawn]) let dropGloopsRepeatingSequence = SKAction.repeat(dropGloopsSequence, count: numberOfDrops) run(dropGloopsRepeatingSequence, withKey: Constant.ActionKey.dropGloops) } func checkForRemainingDrops() { GloopDropApp.log("Drops collected: \(dropsCollected)", category: .gameLoop) GloopDropApp.log("Drops expected: \(dropsExpected)", category: .gameLoop) if dropsCollected == dropsExpected { nextLevel() } } } // MARK: - Private private extension MainScene { /// Sets the number of drops based on the level. func setupDropNumber() { switch level { case 1...5: numberOfDrops = level * 10 case 6: numberOfDrops = 75 case 7: numberOfDrops = 100 case 8: numberOfDrops = 150 default: numberOfDrops = 150 } dropsCollected = 0 dropsExpected = numberOfDrops } // Sets the drop speed based on the level. func setupDropSpeed() { dropSpeed = 1 / (CGFloat(level) + (CGFloat(level) / CGFloat(numberOfDrops))) if dropSpeed < minDropSpeed { dropSpeed = minDropSpeed } else if dropSpeed > maxDropSpeed { dropSpeed = maxDropSpeed } } func spawnGloop() { let collectible = Collectible(collectibleType: CollectibleType.gloop) // Set random position. let margin = collectible.size.width * 2 let dropRange = SKRange(lowerLimit: frame.minX + margin, upperLimit: frame.maxX - margin) var randomX = CGFloat.random(in: dropRange.lowerLimit...dropRange.upperLimit) enhanceDropMovement(margin: margin, randomX: &randomX) addNumberLabel(to: collectible) collectible.position = CGPoint(x: randomX, y: player.position.y * 2.5) addChild(collectible) collectible.drop(dropSpeed: TimeInterval(1.0), floorLevel: player.frame.minY) } /// Creates a "snake-like" pattern. func enhanceDropMovement(margin: CGFloat, randomX: inout CGFloat) { // Set a range. let randomModifier = SKRange(lowerLimit: 50 + CGFloat(level), upperLimit: 60 * CGFloat(level)) var modifier = CGFloat.random(in: randomModifier.lowerLimit...randomModifier.upperLimit) if modifier > 400 { modifier = 400 } // Set the previous drop location. if previousDropLocation == 0.0 { previousDropLocation = randomX } // Clamp its x-position. if previousDropLocation < randomX { randomX = previousDropLocation + modifier } else { randomX = previousDropLocation - modifier } // Make sure the collectible stays within the frame. if randomX <= (frame.minX + margin) { randomX = frame.minX + margin } else if randomX >= (frame.maxX - margin) { randomX = frame.maxX - margin } // Store the location. previousDropLocation = randomX } func addNumberLabel(to collectible: SKSpriteNode) { let numberLabel = SKLabelNode() numberLabel.name = "dropNumber" numberLabel.fontName = Constant.Font.Avenir.name numberLabel.fontColor = SKColor.yellow numberLabel.fontSize = Constant.Font.Avenir.size numberLabel.text = "\(numberOfDrops)" numberLabel.position = CGPoint(x: 0, y: 2) collectible.addChild(numberLabel) numberOfDrops -= 1 } func nextLevel() { showMessage(Constant.Label.Message.getReady) let nextLevel = level + 1 GloopDropApp.log("Level completed! Next level: \(nextLevel)", category: .gameLoop) let waitAction = SKAction.wait(forDuration: 2.25) run(waitAction) { [weak self] in self?.level = nextLevel self?.spawnMultipleGloops() } } }
// // StatusMessageChat.swift // HISmartPhone // // Created by DINH TRIEU on 1/11/18. // Copyright © 2018 MACOS. All rights reserved. // import Foundation enum StatusMessageChat { case new = true case seened = false }
// // DashboardViewController.swift // OnlineTutor // // Created by Rojan Bajracharya on 5/17/20. // Copyright © 2020 Rojan Bajracharya. All rights reserved. // import UIKit class DashboardViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource { @IBOutlet weak var collectionView: UICollectionView! var pageValue: PagesManager = PagesManager() let screenSize: CGRect = UIScreen.main.bounds override func viewDidLoad() { super.viewDidLoad() print("this is printing") setupUI() instantiatePages() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("view will appear") } func instantiatePages() { pageValue = PagesManager(storyboard: self.storyboard!) } func setupUI() { navigationController?.navigationBar.barTintColor = ColorForApp.shareInstance.colorPrimary() navigationItem.title = "Online Tutor" self.collectionView.register(UINib(nibName: "DashboardCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: DashboardCollectionViewCell.identifier) self.collectionView.delegate = self self.collectionView.dataSource = self } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pageValue.getPagesCount() } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DashboardCVC", for: indexPath) as! DashboardCollectionViewCell cell.lblName.text = self.pageValue.getPageName(dataNumber: indexPath.row) cell.lblName.textColor = ColorForApp.shareInstance.colorPrimary() cell.lblName.font = UIFont.boldSystemFont(ofSize: 24.0) cell.viewForCVC.layer.masksToBounds = true cell.viewForCVC.layer.cornerRadius = 10 cell.viewForCVC.layer.borderWidth = 3 cell.viewForCVC.layer.borderColor = ColorForApp.shareInstance.colorPrimary().cgColor cell.viewForCVC.backgroundColor = UIColor.white cell.imgIcon.image = UIImage.init(named: self.pageValue.getPageIcon(dataNumber: indexPath.row)) Design.shareInstance.addDropShadow(view: cell, shadowColor: UIColor.black, opacity: 0.5, shadowOffset: CGSize(width: 2, height: 2), radius: 2) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let vc = self.pageValue.getPageViewController(dataNumber: indexPath.row) // if self.pageValue.getPageName(dataNumber: indexPath.row) == "Test Yourself" { // (vc as! TestViewController).isAppearingFromHomePage = true // } self.navigationController?.pushViewController(vc, animated: true) } } extension DashboardViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: ((screenSize.width / 2.0) - 16), height: ((screenSize.width / 2.0) - 16)) } }
// // MainMenuViewControllerWithSearch.swift // FriarScoutVex // // Created by Matthew Krager on 8/16/15. // Copyright (c) 2015 Matthew Krager. All rights reserved. // import UIKit import Parse class MainMenuViewControllerWithSearch: UIViewController, UITableViewDelegate, UITableViewDataSource,UISearchBarDelegate, UISearchDisplayDelegate { var searchID = 0 var updatingSerach = true var circleAdded = false var myTeam: Team = Team() var curSeason = "NBN" var searchResults:[SearchResults] = [] var bookmarks = NSMutableArray() var statistics: [Statistic] = [] var robotSkills:NSMutableArray = NSMutableArray() var programmingSkills:NSMutableArray = NSMutableArray() var loadingIcon: UIActivityIndicatorView = UIActivityIndicatorView() struct cardCellsRows { static let myTeam = 0 static let favorites = 1 static let rs = 2 static let ps = 3 } struct SearchResults { var name: String! var additionalInfo: String! var isTeam: Bool! var comp:Competition! } struct defaultsKeys { static let myTeam = "myTeam" } struct Statistic { var stat:String var value:String } override func viewDidAppear(animated: Bool) { bookmarks = NSMutableArray() self.getBookmarks() println(self.bookmarks) self.getMainMenuCellForID("Favorites")?.tableView.reloadData() // Reload if changes in season or myTeam let defaults = NSUserDefaults.standardUserDefaults() if let stringOne = defaults.valueForKey(defaultsKeys.myTeam) as? String { if self.myTeam.num != stringOne || self.myTeam.season != self.curSeason{ self.myTeam.num = stringOne self.myTeam.season = self.curSeason self.title = self.curSeason self.myTeam = Team() // Make some tables hidden and Put loading icons in their places self.getMainMenuCellForID("MyTeam")?.tableView.hidden = true self.tableView.delegate = nil self.tableView.dataSource = nil self.clearCurrentData() self.getData() self.tableView.delegate = self self.tableView.dataSource = self self.tableView.reloadData() self.getMainMenuCellForID("MyTeam")?.tableView.hidden = false } } } @IBOutlet var tableView: UITableView! override func viewDidLoad() { self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "HelveticaNeue-Medium", size: 28)!] var settingsButton: UIBarButtonItem = UIBarButtonItem(title: "Settings", style: .Plain, target: self, action: "goToSetting") var moreButton: UIBarButtonItem = UIBarButtonItem(title: "More", style: .Plain, target: self, action: "goToMore") self.title = self.curSeason self.navigationItem.rightBarButtonItem = settingsButton self.navigationItem.leftBarButtonItem = moreButton self.getData() self.tableView.delegate = self self.tableView.dataSource = self self.searchDisplayController?.searchBar.barTintColor = Colors.colorWithHexString("#e1e1e1") self.searchDisplayController?.searchBar.layer.borderColor = UIColor.whiteColor().CGColor self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Home", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) } func clearCurrentData() { self.statistics = [] self.robotSkills = NSMutableArray() self.programmingSkills = NSMutableArray() self.bookmarks = NSMutableArray() self.circleAdded = false; } func getData() { // Bookmarks self.getBookmarks() // Team Information let defaults = NSUserDefaults.standardUserDefaults() if let stringOne = defaults.valueForKey(defaultsKeys.myTeam) as? String { self.myTeam.num = stringOne self.myTeam.season = self.curSeason dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { if let x = Team.loadTeam(self.myTeam) as Team? { self.myTeam = x }else { // Alert the user and bring them back to the main menu let alertController = UIAlertController(title: "Oh no! An Error!", message: "Your Team does not exist!", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: { () -> Void in }) } dispatch_async(dispatch_get_main_queue()) { self.updateMyTeamTable() } } } // Robot Skills var query = PFQuery(className:"rs") query.whereKey("season", equalTo:self.curSeason) query.limit = 3 query.orderByDescending("score") query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in if error != nil{ println(error?.localizedDescription) // Alert the user and bring them back to the main menu if (error!.localizedDescription as NSString).containsString("application performed") { let alertController = UIAlertController(title: "Too many requests!", message: "Try again in a few minutes! We are refreshing our data right now!", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok :(", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: { () -> Void in self.navigationController?.popViewControllerAnimated(true) }) }else { let alertController = UIAlertController(title: "Oh no! An Error!", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: { () -> Void in self.navigationController?.popViewControllerAnimated(true) }) } }else { for cur in objects as! [PFObject] { var s: Skills = Skills() s.rank = cur["rank"] as! String s.team = cur["team"] as! String s.score = cur["score"] as! NSInteger self.robotSkills.addObject(s) } var previousScore = -1 var curStreak = false var count = 0 var curRank = "T-1" for var i = 0; i < self.robotSkills.count; i = i + 1{ var cur = self.robotSkills.objectAtIndex(i) as! Skills if cur.score == previousScore { if curStreak { cur.rank = curRank }else { curStreak = true cur.rank = "T-\(i)" (self.robotSkills.objectAtIndex(i - 1) as! Skills).rank = "T-\(i)" curRank = "T-\(i)" } }else { curStreak = false } previousScore = cur.score } self.getMainMenuCellForID("RobotSkills")?.tableView.reloadData() //self.updateInternalCell(cardCellsRows.rs) } } query = PFQuery(className:"ps") query.whereKey("season", equalTo:self.curSeason) query.limit = 3 query.orderByDescending("score") query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]?, error:NSError?) -> Void in if error != nil{ println(error?.localizedDescription) // Alert the user and bring them back to the main menu let alertController = UIAlertController(title: "Oh no! An Error!", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: { () -> Void in self.navigationController?.popViewControllerAnimated(true) }) }else{ for cur in objects as! [PFObject] { var s: Skills = Skills() s.rank = cur["rank"] as! String s.team = cur["team"] as! String s.score = cur["score"] as! NSInteger println(s.team) self.programmingSkills.addObject(s) } // Fix the tie things var previousScore = 0 var curStreak = false var count = 0 var curRank = "T-1" for var i = 0; i < self.programmingSkills.count; i = i + 1{ var cur = self.programmingSkills.objectAtIndex(i) as! Skills if cur.score == previousScore { if curStreak { cur.rank = curRank }else { curStreak = true cur.rank = "T-\(i)" (self.programmingSkills.objectAtIndex(i - 1) as! Skills).rank = "T-\(i)" curRank = "T-\(i)" } }else { curStreak = false } previousScore = cur.score self.getMainMenuCellForID("ProgrammingSkills")?.tableView.reloadData() } } } } func updateSearchWithNewString(str:String!, id:Int) { var query = PFQuery(className:"Teams") query.limit = 10 query.whereKey("num", hasPrefix: str) var arrayOfTeams = query.findObjects() as! [PFObject] if id != self.searchID { return } // Find some comps query = PFQuery(className: "Competitions") query.limit = 10 query.whereKey("name", containsString: str.capitalizedString) query.whereKey("season", equalTo: self.curSeason) if id != self.searchID { return } var arrayOfComps = query.findObjects() as! [PFObject] self.updatingSerach = true self.searchResults = [] for x in arrayOfTeams { var curResults = SearchResults(name: (x["num"] as! String),additionalInfo: x["name"] as! String, isTeam: true, comp: nil) self.searchResults.append(curResults) } for x in arrayOfComps { var comp: Competition = Competition() comp.date = x["date"] as! String comp.name = x["name"] as! String comp.season = x["season"] as! String comp.compID = x.objectId var curResults = SearchResults(name: (x["name"] as! String), additionalInfo: "", isTeam: false, comp: comp) self.searchResults.append(curResults) } self.updatingSerach = false } func searchDisplayController(controller: UISearchDisplayController, shouldReloadTableForSearchString searchString: String!) -> Bool { dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { self.searchID++ self.updateSearchWithNewString(searchString, id: self.searchID) dispatch_async(dispatch_get_main_queue()) { self.searchDisplayController?.searchResultsTableView.reloadData() } } return false } func updateMyTeamTable() { // Overall Record var tie = "\(self.myTeam.tieMatchCount)" var win = "\(self.myTeam.winMatchCount) - " var loss = "\(self.myTeam.lostMatchCount) - " var record = Statistic(stat: "Record", value: "\(win)\(loss)\(tie)") self.statistics.append(record) var highScore = Statistic(stat: "High Score", value: "\(self.myTeam.highestScore)") self.statistics.append(highScore) var events = Statistic(stat: "Events", value: "\(self.myTeam.compCount)") self.statistics.append(events) dispatch_async(dispatch_get_main_queue()) { //self.getMainMenuCellForID("MyTeam")!.hidden = false self.getMainMenuCellForID("MyTeam")?.tableView.reloadData() } } func getBookmarks() { let defaults = NSUserDefaults.standardUserDefaults() if let curBookmarks = defaults.valueForKey("Bookmarks") as? NSArray { self.bookmarks.addObjectsFromArray(curBookmarks as [AnyObject]) } if let curBookmarks = defaults.valueForKey("Bookmarks Comp") as? NSArray { self.bookmarks.addObjectsFromArray(curBookmarks as [AnyObject]) } if self.bookmarks.count > 0 { self.getMainMenuCellForID("Favorites")?.tableView.hidden = false self.getMainMenuCellForID("Favorites")?.nothingLabel.hidden = true } } func goToSetting() { let vc = self.storyboard?.instantiateViewControllerWithIdentifier("Settings") as! UISettingsViewController vc.curSeason = self.curSeason self.showViewController(vc, sender: vc) } func goToMore() { let vc = MoreViewController() vc.curSeason = self.curSeason self.showViewController(vc, sender: vc) } // Give it a team, it moves to their profile func moveToTeamProfile(team: String!) { var team1 = team if team.isEmpty { team1 = "3309B" } let vc = self.storyboard?.instantiateViewControllerWithIdentifier("TeamProfile") as! UITabBarController // Destintation ViewController, set team let dest: OverviewTeamProfileViewController = vc.viewControllers?.first as! OverviewTeamProfileViewController var team2: Team! = Team() team2.num = team1.uppercaseString team2.season = self.curSeason as String dest.team = team2 // Set the title of the menuViewController vc.title = "Team \(team1)" // Present Profile self.showViewController(vc as UIViewController, sender: vc) } func moveToSkills() { let vc = self.storyboard?.instantiateViewControllerWithIdentifier("skills") as! UITabBarController vc.title = "Skills" // Destintation ViewController, set season let dest: SkillsViewController = vc.viewControllers?.first as! SkillsViewController dest.title = "Robot Skills" (vc.viewControllers?.last as! ProgrammingSkillsViewController).title = "Programming Skills" (vc.viewControllers?.last as! ProgrammingSkillsViewController).curSeason = self.curSeason as String dest.curSeason = self.curSeason as String // Present Main Menu self.showViewController(vc as UIViewController, sender: vc) } func moveToComp(comp: Competition!) { if comp.date == "League" { let vc = self.storyboard?.instantiateViewControllerWithIdentifier("CompFullProfile") as! UITabBarController // Set the title of the menuViewController vc.title = "\(comp.name)" // Destintation ViewController, set team let dest: OverviewCompetitionProfileViewController = vc.viewControllers?.first as! OverviewCompetitionProfileViewController dest.name = comp.name dest.comp.compID = comp.compID dest.season = comp.season // Present Profile self.showViewController(vc as UIViewController, sender: vc) }else { var formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM-dd" var cDate: NSDate = formatter.dateFromString(comp.date)! var dateComparisionResult:NSComparisonResult = cDate.compare(NSDate()) if(dateComparisionResult == NSComparisonResult.OrderedDescending) { let vc = self.storyboard?.instantiateViewControllerWithIdentifier("EmptyProfile") as! EmptyCompetitionProfileViewController // Set the title of the menuViewController vc.title = "\(comp.name)" vc.name = comp.name vc.season = comp.season vc.comp = comp // Destintation ViewController, set team // Present Profile self.showViewController(vc as UIViewController, sender: vc) }else { let vc = self.storyboard?.instantiateViewControllerWithIdentifier("CompFullProfile") as! UITabBarController // Set the title of the menuViewController vc.title = "\(comp.name)" // Destintation ViewController, set team let dest: OverviewCompetitionProfileViewController = vc.viewControllers?.first as! OverviewCompetitionProfileViewController dest.name = comp.name dest.season = comp.season dest.comp.compID = comp.compID // Present Profile self.showViewController(vc as UIViewController, sender: vc) } } } func moveToFavorites() { let vc = self.storyboard?.instantiateViewControllerWithIdentifier("fav") as! UITabBarController vc.title = "Favorites" // Destintation ViewController, set season let dest: TeamBookmarksViewController = vc.viewControllers?.first as! TeamBookmarksViewController dest.title = "Team Favorites" (vc.viewControllers?.last as! CompetitionBookmarkController).title = "Team Competitions" // Present Main Menu self.showViewController(vc as UIViewController, sender: vc) } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if tableView.isEqual(self.tableView) { switch indexPath.row { case cardCellsRows.myTeam: self.moveToTeamProfile(self.myTeam.num) case cardCellsRows.favorites: self.moveToFavorites() case cardCellsRows.rs: self.moveToSkills() case cardCellsRows.ps: self.moveToSkills() default: println("NOPE") } }else { if tableView.isEqual(self.searchDisplayController?.searchResultsTableView) { if (self.searchResults[indexPath.row].isTeam != nil && self.searchResults[indexPath.row].isTeam! ) { self.moveToTeamProfile(self.searchResults[indexPath.row].name) }else { self.moveToComp(self.searchResults[indexPath.row].comp) } }else if let title:String = (tableView.superview?.superview?.superview as! MainMenuTableCell).titleLabel.text{ switch title { case "My Team": self.moveToTeamProfile(self.myTeam.num) case "Favorites": if let team = (self.bookmarks.objectAtIndex(indexPath.row) as! NSDictionary).objectForKey("Num") as? String { self.moveToTeamProfile(team) }else if let compName = (self.bookmarks.objectAtIndex(indexPath.row) as! NSDictionary).objectForKey("Name") as? String { let vc = self.storyboard?.instantiateViewControllerWithIdentifier("CompFullProfile") as! UITabBarController // Set the title of the menuViewController // Destintation ViewController, set team let dest: OverviewCompetitionProfileViewController = vc.viewControllers?.first as! OverviewCompetitionProfileViewController dest.name = compName dest.comp.compID = (self.bookmarks.objectAtIndex(indexPath.row) as! NSDictionary).objectForKey("ID") as? String dest.season = (self.bookmarks.objectAtIndex(indexPath.row) as! NSDictionary).objectForKey("Season") as? String vc.title = "\(dest.name)" // Present Profile self.showViewController(vc as UIViewController, sender: vc) } case "Robot Skills": self.moveToTeamProfile((self.robotSkills.objectAtIndex(indexPath.row) as! Skills).team) case "Programming Skills": self.moveToTeamProfile((self.programmingSkills.objectAtIndex(indexPath.row) as! Skills).team) default: println("WHAT") } } } } func getMainMenuCellForID(string:String!) -> MainMenuTableCell?{ for var i:Int = 0; i < self.tableView.numberOfRowsInSection(0); i = i + 1 { if self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: i, inSection: 0))?.reuseIdentifier == string { return self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: i, inSection: 0)) as? MainMenuTableCell } } return nil } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if tableView.isEqual(self.tableView) { if (tableView.cellForRowAtIndexPath(indexPath) == nil) { switch indexPath.row { case cardCellsRows.myTeam: var cell = tableView.dequeueReusableCellWithIdentifier("MyTeam") as! MainMenuTableCell if cell.titleLabel.text == "My Team" || cell.titleLabel.text == "Title"{ cell.clearsContextBeforeDrawing = true cell.selectionStyle = UITableViewCellSelectionStyle.None cell.setUp() cell.tableView.delegate = self cell.tableView.dataSource = self cell.nothingLabel.hidden = true cell.backView.backgroundColor = Colors.colorWithHexString("F0F0F0") cell.tableView.backgroundColor = Colors.colorWithHexString("F0F0F0") cell.titleLabel.text = "My Team" cell.titleLabel.backgroundColor = Colors.colorWithHexString("#487da7") var teamCircle:CircleView = CircleView(frame: CGRectMake(25, 20, 90, 90), text: self.myTeam.numOnly,bottom: self.myTeam.letterOnly, innerColor: Colors.colorWithHexString("#3d3d3d").CGColor, rimColor: UIColor.grayColor().CGColor) cell.layer.shadowOffset = CGSizeMake(0, 10); cell.layer.shadowColor = UIColor.blackColor().CGColor; cell.layer.shadowRadius = 10 cell.layer.shadowOpacity = 0.35 cell.addSubview(teamCircle) if self.myTeam.num.isEmpty { cell.tableView.hidden = true cell.nothingLabel.hidden = false } } return cell case cardCellsRows.favorites: var cell = tableView.dequeueReusableCellWithIdentifier("Favorites") as! MainMenuTableCell cell.clearsContextBeforeDrawing = true cell.selectionStyle = UITableViewCellSelectionStyle.None cell.setUp() cell.tableView.delegate = self cell.tableView.dataSource = self cell.nothingLabel.hidden = true cell.tableView.hidden = false cell.backView.backgroundColor = Colors.colorWithHexString("F0F0F0") cell.tableView.backgroundColor = Colors.colorWithHexString("F0F0F0") cell.titleLabel.text = "Favorites" cell.titleLabel.backgroundColor = Colors.colorWithHexString("#c6ab3b") var teamCircle:CircleView = CircleView(frame: CGRectMake(self.view.frame.width - 110, 20, 90, 90), text: " ", innerColor: Colors.colorWithHexString("#3d3d3d").CGColor, rimColor: UIColor.grayColor().CGColor) var star: UIImageView = UIImageView(frame: CGRectMake(teamCircle.frame.origin.x + 5, teamCircle.frame.origin.y + 5, teamCircle.frame.width - 10, teamCircle.frame.height - 10) ) star.image = UIImage(named: "UnfavoritedIcon.png")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) star.tintColor = UIColor.whiteColor() cell.layer.shadowOffset = CGSizeMake(0, 10); cell.layer.shadowColor = UIColor.blackColor().CGColor; cell.layer.shadowRadius = 10 cell.layer.shadowOpacity = 0.35 cell.addSubview(teamCircle) cell.addSubview(star) circleAdded = true if self.bookmarks.count == 0 { cell.tableView.hidden = true cell.nothingLabel.hidden = false } return cell case cardCellsRows.rs: var cell = tableView.dequeueReusableCellWithIdentifier("RobotSkills") as! MainMenuTableCell cell.clearsContextBeforeDrawing = true cell.selectionStyle = UITableViewCellSelectionStyle.None cell.setUp() cell.tableView.delegate = self cell.tableView.dataSource = self cell.backView.backgroundColor = Colors.colorWithHexString("F0F0F0") cell.tableView.backgroundColor = Colors.colorWithHexString("F0F0F0") cell.titleLabel.text = "Robot Skills" cell.titleLabel.backgroundColor = Colors.colorWithHexString("#448660") cell.layer.shadowOffset = CGSizeMake(0, 10) cell.layer.shadowColor = UIColor.blackColor().CGColor; cell.layer.shadowRadius = 10 cell.layer.shadowOpacity = 0.35 return cell case cardCellsRows.ps: var cell = tableView.dequeueReusableCellWithIdentifier("ProgrammingSkills") as! MainMenuTableCell cell.clearsContextBeforeDrawing = true cell.selectionStyle = UITableViewCellSelectionStyle.None cell.setUp() cell.tableView.delegate = self cell.tableView.dataSource = self cell.backView.backgroundColor = Colors.colorWithHexString("F0F0F0") cell.tableView.backgroundColor = Colors.colorWithHexString("F0F0F0") cell.titleLabel.text = "Programming Skills" cell.titleLabel.backgroundColor = Colors.colorWithHexString("#9f5752") cell.layer.shadowOffset = CGSizeMake(0, 10) cell.layer.shadowColor = UIColor.blackColor().CGColor; cell.layer.shadowRadius = 10 cell.layer.shadowOpacity = 0.35 return cell default: println("FDSAF") //cell.titleLabel.text = "ERROR" } } }else { if tableView == self.searchDisplayController!.searchResultsTableView { if !updatingSerach { var cell = (self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as! MainMenuTableCell).tableView.dequeueReusableCellWithIdentifier("searchResultsCell") as! TeamBookmarkCell cell.teamLabel.text = self.searchResults[indexPath.row].name cell.seasonLabel.text = self.searchResults[indexPath.row].additionalInfo return cell }else { if let x = tableView.cellForRowAtIndexPath(indexPath) { return x }else { return UITableViewCell() } } // PUT SEARCH RESULTS ROW HERE }else if let title:String = (tableView.superview?.superview?.superview as! MainMenuTableCell).titleLabel.text { var col = Colors.colorWithHexString("#979797") switch title { case "My Team": var cell = tableView.dequeueReusableCellWithIdentifier("statCell") as! StatisticsTableCell cell.statisticLabel.textColor = col cell.valueLabel.textColor = col cell.statisticLabel.text = self.statistics[indexPath.row].stat cell.valueLabel.text = self.statistics[indexPath.row].value cell.selectionStyle = .None; return cell case "Favorites": var cell = tableView.dequeueReusableCellWithIdentifier("favTeamCell") as! TeamBookmarkCell cell.selectionStyle = .None; cell.teamLabel.textColor = col cell.seasonLabel.textColor = col if let team = (self.bookmarks.objectAtIndex(indexPath.row) as! NSDictionary).objectForKey("Num") as? String { cell.teamLabel.text = team }else if let compName = (self.bookmarks.objectAtIndex(indexPath.row) as! NSDictionary).objectForKey("Name") as? String { cell.teamLabel.text = compName } cell.seasonLabel.text = (self.bookmarks.objectAtIndex(indexPath.row) as! NSDictionary).objectForKey("Season") as? String return cell case "Robot Skills": var cell = tableView.dequeueReusableCellWithIdentifier("skillsCell") as! SkillsCell cell.selectionStyle = .None; cell.rankLabel.textColor = col cell.teamLabel.textColor = col cell.scoreLabel.textColor = col cell.rankLabel.text = (self.robotSkills.objectAtIndex(indexPath.row) as! Skills).rank cell.teamLabel.text = (self.robotSkills.objectAtIndex(indexPath.row) as! Skills).team cell.scoreLabel.text = "\((self.robotSkills.objectAtIndex(indexPath.row) as! Skills).score)" return cell case "Programming Skills": var cell = tableView.dequeueReusableCellWithIdentifier("skillsCell") as! SkillsCell cell.selectionStyle = .None; cell.rankLabel.textColor = col cell.teamLabel.textColor = col cell.scoreLabel.textColor = col cell.rankLabel.text = (self.programmingSkills.objectAtIndex(indexPath.row) as! Skills).rank cell.teamLabel.text = (self.programmingSkills.objectAtIndex(indexPath.row) as! Skills).team cell.scoreLabel.text = "\((self.programmingSkills.objectAtIndex(indexPath.row) as! Skills).score)" return cell default: return tableView.dequeueReusableCellWithIdentifier("skillsCell") as! SkillsCell } } return (self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as! MainMenuTableCell).tableView.dequeueReusableCellWithIdentifier("skillsCell") as! SkillsCell } return (self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as! MainMenuTableCell).tableView.dequeueReusableCellWithIdentifier("skillsCell") as! SkillsCell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == self.searchDisplayController!.searchResultsTableView { return self.searchResults.count }else if !tableView.isEqual(self.tableView) { if let title:String = (tableView.superview?.superview?.superview as! MainMenuTableCell).titleLabel.text { switch title { case "My Team": return self.statistics.count case "Favorites": if self.bookmarks.count > 3 { return 3 } return self.bookmarks.count case "Robot Skills": return self.robotSkills.count case "Programming Skills": return self.programmingSkills.count default: return 0 } } return 0 }else { return 4 } } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if tableView.isEqual(self.tableView) { (cell as! MainMenuTableCell).tableView.reloadData() } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } }
// // InfoScreenViewController.swift // Weather app // // Created by Sjors Roelofs on 13/08/15. // Copyright © 2015 Sjors Roelofs. All rights reserved. // import UIKit class InfoScreenViewController: UIViewController { @IBOutlet var swipeGestureRecognizer: UISwipeGestureRecognizer!; override func viewDidLoad() { super.viewDidLoad(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning(); } @IBAction func didSwiped(sender: AnyObject) { tabBarController?.selectedIndex = 0; } }
import Foundation extension Double { func format(f: String) -> String { return NSString(format: f, self) } } extension String { func doubleValue() -> Double { return (self as NSString).doubleValue } } extension NSDate { func toEpoch() -> Int { return Int(self.timeIntervalSince1970) } }
// // MasterViewController.swift // CBL Bug Demo // // Created by Basit Mustafa on 22/4/15. // Copyright (c) 2015 Basit Mustafa. All rights reserved. // import UIKit import FXForms class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var appDelegate : AppDelegate? @IBOutlet var dataSource: CBLUITableSource! override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewDidLoad() { super.viewDidLoad() let mainApplication = UIApplication.sharedApplication() if let delegate = mainApplication.delegate as? AppDelegate { self.appDelegate = delegate; } // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController } // Create a query sorted by descending date, i.e. newest items first: let query = self.appDelegate?.cblDatabase!.viewNamed("arbitraryObjects").createQuery().asLiveQuery() query!.descending = true // Plug the query into the CBLUITableSource, which will use it to drive the table view. // (The CBLUITableSource uses KVO to observe the query's .rows property.) self.dataSource = CBLUITableSource() self.dataSource.tableView = self.tableView self.tableView.dataSource = self.dataSource self.dataSource.query = query! self.dataSource.labelProperty = "aDateToInherit" // Document property to display in the cell label self.title = "Aribtrary Objects" self.tableView.delegate=self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { // Create New Object let db = self.appDelegate?.cblDatabase! let newCase = BMArbitraryObject(forNewDocumentInDatabase: db!) newCase.anArbitraryString = "So Random" newCase.aDateToInherit = NSDate() newCase.anAribtraryNSNumber = 42 // Duh, of course. var error: NSError? if !newCase.save(&error) { println(error) } } func couchTableSource( source: CBLUITableSource!, willUseCell cell: UITableViewCell!, forRow row: CBLQueryRow!) { // Set the cell background and font: // cell.backgroundColor = kBGColor // cell.selectionStyle = .Gray cell.textLabel!.font = UIFont(name: "Helvetica", size: 18.0) cell.textLabel!.backgroundColor = UIColor.clearColor() // let rowValue = row.value as? VTCase // Configure the cell contents. Our view's map function (above) copies the document properties // into its value, so we can read them from there without having to load the document. // cell.textLabel.text is already set, thanks to setting up labelProperty above. // cell.detailTextLabel!.text = "Some detial text!" } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let object = self.dataSource.rowAtIndexPath(indexPath)?.document let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = CBLModel(forDocument: object!) as? BMArbitraryObject controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // self.performSegueWithIdentifier("showDetail", sender: self) var caseVc = FXFormViewController() let object = self.dataSource.rowAtIndexPath(indexPath)?.document var caseObj = CBLModel(forDocument: object!) as? BMArbitraryObject caseVc.formController.form = caseObj caseVc.title = caseObj?.anArbitraryString self.navigationController?.pushViewController(caseVc, animated: true); } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } }
// SettingViewController.swift import UIKit import Firebase import FirebaseAuth class SettingViewController: UIViewController { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var idLabel: UILabel! // root/usersパス let usersRef = FIRDatabase.database().reference().child("users") var uid: String? override func viewDidLoad() { super.viewDidLoad() uid = FIRAuth.auth()?.currentUser?.uid idLabel.text = uid // ID、アカウント名をLabelに設定 let ud = NSUserDefaults.standardUserDefaults() var accountName = ud.valueForKey("DISPLAYNAME") as? String // アカウント名をNSUserDefaultsで取得できなかった場合 if accountName == nil { usersRef.child(uid!).observeEventType(.Value, withBlock: { snapshot in let valueDictionary = snapshot.value as! [String : AnyObject] accountName = valueDictionary["name"] as? String self.nameLabel.text = accountName }) } else { nameLabel.text = accountName } } func setUserInfo() { uid = FIRAuth.auth()?.currentUser?.uid idLabel.text = uid // ID、アカウント名をLabelに設定 let ud = NSUserDefaults.standardUserDefaults() var accountName = ud.valueForKey("DISPLAYNAME") as? String // アカウント名をNSUserDefaultsで取得できなかった場合 if accountName == nil { usersRef.child(uid!).observeEventType(.Value, withBlock: { snapshot in let valueDictionary = snapshot.value as! [String : AnyObject] accountName = valueDictionary["name"] as? String self.nameLabel.text = accountName }) } else { nameLabel.text = accountName } } // ログアウトボタンタップ @IBAction func tapLogoutButton(sender: AnyObject) { // ログアウト try! FIRAuth.auth()?.signOut() // ログイン画面を表示 let loginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("Login") self.presentViewController(loginViewController!, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
// // UIWindow.swift // carWash // // Created by Juliett Kuroyan on 29.01.2020. // Copyright © 2020 VooDooLab. All rights reserved. // import UIKit import SwiftEntryKit //MARK: Reachability extension UIWindow: ReachabilityObserverDelegate { func reachabilityChanged(_ isReachable: Bool) { DispatchQueue.main.async { [weak self] in if !isReachable { self?.showMessage() } } } func showMessageIfNotReachable() { DispatchQueue.main.async { [weak self] in guard let self = self else { return } if !self.isReachable(), !SwiftEntryKit.isCurrentlyDisplaying { self.showMessage() } } } private func showMessage() { var attributes = EKAttributes.topToast attributes.entryBackground = .color(color: EKColor(Constants.pink!)) attributes.entranceAnimation = .translation attributes.exitAnimation = .translation let widthConstraint = EKAttributes.PositionConstraints.Edge.constant(value: frame.width) let heightConstraint = EKAttributes.PositionConstraints.Edge.constant(value: Constants.reachabilityViewHeight) attributes.positionConstraints.size = .init(width: widthConstraint, height: heightConstraint) let titleLabel = UILabel() titleLabel.text = "Проверьте подключение к интернету" titleLabel.textAlignment = .center titleLabel.textColor = .white titleLabel.font = UIFont.systemFont(ofSize: 14) SwiftEntryKit.display(entry: titleLabel, using: attributes) } }
print("Welcome back to the UW Calculator") // Your job is to fill out Calculator so all the expressions // below both compile and return "true" class Calculator { func add(lhs: Int, rhs: Int) -> Int { return lhs + rhs } func add(_ array: [Int]) -> Int { var sum = 0 for value in array { sum += value } return sum } func add(lhs: (Int, Int), rhs: (Int, Int)) -> (Int, Int) { let first = lhs.0 + rhs.0 let second = lhs.1 + rhs.1 return (first, second) } func add(lhs: Dictionary<String, Int>, rhs: Dictionary<String, Int>) -> Dictionary<String, Int> { let xNum = lhs["x"]! + rhs["x"]! let yNum = lhs["y"]! + rhs["y"]! let result: [String: Int] = [ "x": xNum, "y": yNum ] return result } func subtract(lhs: Int, rhs: Int) -> Int { return lhs - rhs } func subtract(lhs: (Int, Int), rhs: (Int, Int)) -> (Int, Int) { let first = lhs.0 - rhs.0 let second = lhs.1 - rhs.1 return (first, second) } func subtract(lhs: Dictionary<String, Int>, rhs: Dictionary<String, Int>) -> Dictionary<String, Int> { let xNum = lhs["x"]! - rhs["x"]! let yNum = lhs["y"]! - rhs["y"]! let result: [String: Int] = [ "x": xNum, "y": yNum ] return result } func multiply(lhs: Int, rhs: Int) -> Int { return lhs * rhs } func multiply(_ array: [Int]) -> Int { var sum = 1 for value in array { sum = sum * value } return sum } func divide(lhs: Int, rhs: Int) -> Int { return lhs / rhs } func count(_ array: [Int]) -> Int { return array.count } func avg(_ array: [Int]) -> Int { var sum = 0 for value in array { sum += value } let total = array.count return sum / total } func mathOp(lhs: Int, rhs: Int, op: (Int, Int) -> Int) -> Int { return op(lhs, rhs) } func mathOp(args: [Int], beg: Int, op: (Int, Int) -> Int) -> Int { return args.reduce(beg, { (l, r) in op(l, r) }) } // func mathOp(lhs: Int, rhs: Int, op: (_ lhs : Int, _ rhs : Int) -> (Int)) -> Int { // print(op(lhs, rhs)) // return op(lhs, rhs) // } // // func mathOp(args: [Int], beg: Int, op: (_ lhs: Int, _ rhs: Int) -> (Int)) -> Int { // var sum = args[0] // let length = count(args) - 1 // for i in 1...length { // sum = op(sum, args[i]) // } // print(sum) // return sum // } } let calc = Calculator() // Don't change this declaration name; it's used in all the tests below // ====> Add your own tests here if you wish <==== //calc.mathOp(lhs: 5, rhs: 5, op: { (_ lhs: Int, _ rhs: Int) -> Int in (lhs + rhs) + (lhs * rhs) }) //calc.mathOp(args: [1, 2, 3], beg: 0, op: { $0 + $1 }) // ====> Do not modify code in this section <==== calc.add(lhs: 2, rhs: 2) == 4 calc.subtract(lhs: 2, rhs: 2) == 0 calc.multiply(lhs: 2, rhs: 2) == 4 calc.divide(lhs: 2, rhs: 2) == 1 calc.mathOp(lhs: 5, rhs: 5, op: { (lhs: Int, rhs: Int) -> Int in (lhs + rhs) + (lhs * rhs) }) == 35 // This style is one way of writing an anonymous function calc.mathOp(lhs: 10, rhs: -5, op: { ($0 + $1) + ($0 - $1) }) == 20 // This is the second, more terse, style; either works calc.add([1, 2, 3, 4, 5]) == 15 calc.multiply([1, 2, 3, 4, 5]) == 120 calc.count([1, 2, 3, 4, 5, 6, 7, 8]) == 8 calc.count([]) == 0 calc.avg([2, 2, 2, 2, 2, 2]) == 2 calc.avg([1, 2, 3, 4, 5]) == 3 calc.avg([1]) == 1 // calc.mathOp(args: [1, 2, 3], beg: 0, op: { $0 + $1 }) == 6 // this is (((0 op 1) op 2) op 3) calc.mathOp(args: [1, 2, 3, 4, 5], beg: 0, op: { $0 + $1 }) == 15 // this is (((((0 op 1) op 2) op 3) op 4) op 5) calc.mathOp(args: [1, 1, 1, 1, 1], beg: 1, op: { $0 * $1 }) == 1 // this is (((((1 op 1) op 1) op 1) op 1) op 1) let p1 = (5, 5) let p2 = (12, -27) let p3 = (-4, 4) let p4 = (0, 0) calc.add(lhs: p1, rhs: p2) == (17, -22) calc.subtract(lhs: p1, rhs: p2) == (-7, 32) calc.add(lhs: p4, rhs: p4) == (0, 0) calc.add(lhs: p3, rhs: p4) == (-4, 4) let pd1 = ["x": 5, "y": 5] let pd2 = ["x": -4, "y": 4] calc.add(lhs: pd1, rhs: pd2) == ["x": 1, "y": 9] calc.subtract(lhs: pd1, rhs: pd2) == ["x": 9, "y": 1]
// // Category.swift // RealmTodoListApp // // Created by shin seunghyun on 2020/02/20. // Copyright © 2020 shin seunghyun. All rights reserved. // import RealmSwift class Category: Object { @objc dynamic var name: String = "" @objc dynamic var hexColor: String = "" //relationship let items: List<Item> = List<Item>() }
// // view+style.swift // view+style // // Created by Sven Svensson on 27/08/2021. // import Foundation import SwiftUI enum CustomViewStyle { case title case smallTitle case label case mediumLabel case smallLabel case text case mediumText case smallText case textField case collumHeader } extension View { @ViewBuilder func style(_ style: CustomViewStyle) -> some View { switch style { case .title: self.font(.title).foregroundColor(.primary) case .smallTitle: self.font(.headline).foregroundColor(.primary) case .label: self.font(.body).foregroundColor(.primary) case .mediumLabel: self.font(.caption).foregroundColor(.primary) case .smallLabel: self.font(.system(size: 14.0, weight: .light, design: .default)).font(.subheadline).foregroundColor(.secondary) case .text: self.font(.body).foregroundColor(.secondary) case .mediumText: self.font(.caption).foregroundColor(.secondary) case .smallText: self.font(.subheadline).foregroundColor(.secondary) case .textField: self.font(.body).foregroundColor(.secondary).disableAutocorrection(true) // .textFieldStyle(RoundedBorderTextFieldStyle()) case .collumHeader: self.font(.caption2).foregroundColor(.secondary) } } }
// // PageFiveViewController.swift // Fast&Furios // // Created by Aldwin David on 4/15/21. // import UIKit class PageFiveViewController: UIViewController { @IBOutlet weak var textField: UITextField! @IBOutlet weak var nextButton: UIButton! { didSet { nextButton.backgroundColor = UIColor(rgb: 0x3D9EA0) nextButton.setTitleColor(.white, for: .normal) } } @IBAction func onNextClicked(_ sender: Any) { self.performSegue(withIdentifier: "showPageSix", sender: nil) } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.titleView = UIImageView(image: UIImage(named: "oneflare-ic")) addDoneButtonOnKeyboard() // Do any additional setup after loading the view. } func addDoneButtonOnKeyboard(){ let doneToolbar: UIToolbar = UIToolbar(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 50)) doneToolbar.barStyle = .default let flexSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(self.doneButtonAction)) let items = [flexSpace, done] doneToolbar.items = items doneToolbar.sizeToFit() textField.inputAccessoryView = doneToolbar } @objc func doneButtonAction(){ textField.resignFirstResponder() } }
// // NetworkPresenter.swift // WavesWallet-iOS // // Created by mefilt on 22/10/2018. // Copyright © 2018 Waves Platform. All rights reserved. // import Foundation import RxCocoa import RxFeedback import RxSwift import DomainLayer protocol NetworkSettingsModuleOutput: AnyObject { func networkSettingSavedSetting() } protocol NetworkSettingsModuleInput { var wallet: DomainLayer.DTO.Wallet { get } } protocol NetworkSettingsPresenterProtocol { typealias Feedback = (Driver<NetworkSettingsTypes.State>) -> Signal<NetworkSettingsTypes.Event> var moduleOutput: NetworkSettingsModuleOutput? { get set } var input: NetworkSettingsModuleInput! { get set } func system(feedbacks: [Feedback]) } final class NetworkSettingsPresenter: NetworkSettingsPresenterProtocol { fileprivate typealias Types = NetworkSettingsTypes weak var moduleOutput: NetworkSettingsModuleOutput? var input: NetworkSettingsModuleInput! private var accountSettingsRepository: AccountSettingsRepositoryProtocol = UseCasesFactory.instance.repositories.accountSettingsRepository private var environmentRepository: EnvironmentRepositoryProtocol = UseCasesFactory.instance.repositories.environmentRepository private let disposeBag: DisposeBag = DisposeBag() init(input: NetworkSettingsModuleInput) { self.input = input } func system(feedbacks: [Feedback]) { var newFeedbacks = feedbacks newFeedbacks.append(environmentsQuery()) newFeedbacks.append(deffaultEnvironmentQuery()) newFeedbacks.append(saveEnvironmentQuery()) newFeedbacks.append(handlerExternalQuery()) let initialState = self.initialState(wallet: input.wallet) let system = Driver.system(initialState: initialState, reduce: NetworkSettingsPresenter.reduce, feedback: newFeedbacks) system .drive() .disposed(by: disposeBag) } private func handlerExternalQuery() -> Feedback { return react(request: { state -> Bool? in if let query = state.query { switch query { case .successSaveEnvironments: return true default: return nil } } else { return nil } }, effects: { [weak self] address -> Signal<Types.Event> in self?.moduleOutput?.networkSettingSavedSetting() return Signal.just(.completedQuery) }) } private func environmentsQuery() -> Feedback { return react(request: { state -> String? in if state.displayState.isAppeared == true { return state.wallet.address } else { return nil } }, effects: { [weak self] address -> Signal<Types.Event> in guard let self = self else { return Signal.empty() } let environment = self .environmentRepository .walletEnvironment() let accountSettings = self.accountSettingsRepository .accountSettings(accountAddress: address) let accountEnvironment = self.accountSettingsRepository.accountEnvironment(accountAddress: address) return Observable.zip(environment, accountSettings, accountEnvironment) .map { Types.Event.setEnvironmets($0.0, $0.1, $0.2) } .asSignal(onErrorRecover: { error in return Signal.just(Types.Event.handlerError(error)) }) }) } private func deffaultEnvironmentQuery() -> Feedback { return react(request: { state -> String? in if let query = state.query, case .resetEnvironmentOnDeffault = query { return state.wallet.address } else { return nil } }, effects: { [weak self] address -> Signal<Types.Event> in guard let self = self else { return Signal.empty() } let environment = self .environmentRepository .deffaultEnvironment() return environment .map { Types.Event.setDeffaultEnvironmet($0) } .asSignal(onErrorRecover: { error in return Signal.just(Types.Event.handlerError(error)) }) }) } private struct SaveQuery: Equatable { let accountAddress: String let url: String let accountSettings: DomainLayer.DTO.AccountSettings } private func saveEnvironmentQuery() -> Feedback { return react(request: { state -> SaveQuery? in if let query = state.query, case .saveEnvironments = query { let isEnabledSpam = state.displayState.isSpam let spamUrl = state.displayState.spamUrl ?? "" var newAccountSettings = state.accountSettings ?? DomainLayer.DTO.AccountSettings(isEnabledSpam: false) newAccountSettings.isEnabledSpam = isEnabledSpam return SaveQuery(accountAddress: state.wallet.address, url: spamUrl, accountSettings: newAccountSettings) } else { return nil } }, effects: { [weak self] query -> Signal<Types.Event> in guard let self = self else { return Signal.empty() } let environment = self .accountSettingsRepository .setSpamURL(query.url, by: query.accountAddress) let accountSettings = query.accountSettings let saveAccountSettings = self .accountSettingsRepository .saveAccountSettings(accountAddress: query.accountAddress, settings: accountSettings) return Observable.zip(environment, saveAccountSettings) .map { _ in Types.Event.successSave } .asSignal(onErrorRecover: { error in return Signal.just(Types.Event.handlerError(error)) }) }) } } // MARK: Core State private extension NetworkSettingsPresenter { static func reduce(state: Types.State, event: Types.Event) -> Types.State { var newState = state reduce(state: &newState, event: event) return newState } static func reduce(state: inout Types.State, event: Types.Event) { switch event { case .readyView: state.displayState.isAppeared = true case .setEnvironmets(let environment, let accountSettings, let accountEnvironment): state.environment = environment state.accountSettings = accountSettings state.displayState.spamUrl = accountEnvironment?.spamUrl ?? environment.servers.spamUrl.absoluteString state.displayState.isSpam = accountSettings?.isEnabledSpam ?? false state.displayState.isEnabledSaveButton = true state.displayState.isEnabledSetDeffaultButton = true state.displayState.isEnabledSpamSwitch = true state.displayState.isEnabledSpamInput = true case .setDeffaultEnvironmet(let environment): state.environment = environment state.displayState.spamUrl = environment.servers.spamUrl.absoluteString state.displayState.isSpam = true state.displayState.isLoading = false state.displayState.isEnabledSaveButton = true state.displayState.isEnabledSetDeffaultButton = true state.query = nil case .handlerError: state.query = nil state.displayState.isLoading = false state.displayState.isEnabledSaveButton = true state.displayState.isEnabledSetDeffaultButton = true state.displayState.isEnabledSpamSwitch = true state.displayState.isEnabledSpamInput = true case .inputSpam(let url): state.displayState.spamUrl = url if url?.isValidUrl == false { state.displayState.spamError = "Error" state.displayState.isEnabledSaveButton = false } else { state.displayState.isEnabledSaveButton = true state.displayState.spamError = nil } case .switchSpam(let isOn): state.displayState.isSpam = isOn case .successSave: state.query = .successSaveEnvironments state.displayState.isLoading = false state.displayState.isEnabledSaveButton = true state.displayState.isEnabledSetDeffaultButton = true state.displayState.isEnabledSpamSwitch = true state.displayState.isEnabledSpamInput = true case .tapSetDeffault: state.query = .resetEnvironmentOnDeffault state.displayState.isLoading = true state.displayState.isEnabledSaveButton = false state.displayState.isEnabledSetDeffaultButton = false case .tapSave: state.query = .saveEnvironments state.displayState.isLoading = true state.displayState.isEnabledSaveButton = false state.displayState.isEnabledSetDeffaultButton = false state.displayState.isEnabledSpamSwitch = false state.displayState.isEnabledSpamInput = false case .completedQuery: state.query = nil } } } // MARK: UI State private extension NetworkSettingsPresenter { func initialState(wallet: DomainLayer.DTO.Wallet) -> Types.State { return Types.State(wallet: wallet, accountSettings: nil, environment: nil, displayState: initialDisplayState(), query: nil, isValidSpam: false) } func initialDisplayState() -> Types.DisplayState { return Types.DisplayState(spamUrl: "", isSpam: false, isAppeared: false, isLoading: false, isEnabledSaveButton: false, isEnabledSetDeffaultButton: false, isEnabledSpamSwitch: false, isEnabledSpamInput: false, spamError: nil) } }
// // SpokenLanguage.swift // TheMovies // // Created by Usman Ansari on 29/03/21. // import Foundation import ObjectMapper class SpokenLanguage: Mappable { var englishName: String? var ISO: String? var name: String? required init?(map: Map) { } // Mappable func mapping(map: Map) { englishName <- map["english_name"] ISO <- map["iso_639_1"] name <- map["name"] } }
// // AppActivityLogger.swift // KPCAppActivityLogger // // Created by Cédric Foellmi on 22/05/16. // Copyright © 2016 onekiloparsec. All rights reserved. // import Foundation import CocoaLumberjackSwift import AppKit @objc public protocol WindowHashing { func hash() -> String } public let AppActivityLoggerDidUpdateNotification = "AppActivityLoggerDidUpdateNotification" let AppNotifications = [NSApplicationDidBecomeActiveNotification, NSApplicationDidChangeScreenParametersNotification, NSApplicationDidFinishLaunchingNotification, NSApplicationDidHideNotification, NSApplicationDidResignActiveNotification, NSApplicationDidUnhideNotification, // NSApplicationDidUpdateNotification, NSApplicationWillBecomeActiveNotification, NSApplicationWillFinishLaunchingNotification, NSApplicationWillHideNotification, NSApplicationWillResignActiveNotification, NSApplicationWillTerminateNotification, NSApplicationWillUnhideNotification, // NSApplicationWillUpdateNotification, NSApplicationDidFinishRestoringWindowsNotification, NSApplicationDidChangeOcclusionStateNotification] let WindowNotifications = [NSWindowWillCloseNotification] public class AppActivityLogger: DDFileLogger { private var windowController: AppActivityWindowController? override init!(logFileManager: DDLogFileManager!) { super.init(logFileManager: logFileManager) self.rollingFrequency = 60 * 60 * 24 * 7 // weekly rolling for appNotification in AppNotifications { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(logUponAppNotification(_:)), name: appNotification, object: nil) } for appNotification in WindowNotifications { NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(logUponWindowNotification(_:)), name: appNotification, object: nil) } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override public func didAddLogger() { DDLogInfo("\n\n Activity Start \n\n") } @objc private func logUponAppNotification(notification: NSNotification) { DDLogInfo(notification.name) NSNotificationCenter.defaultCenter().postNotificationName(AppActivityLoggerDidUpdateNotification, object: self) } @objc private func logUponWindowNotification(notification: NSNotification) { var message = notification.name if notification.object?.conformsToProtocol(WindowHashing) == true { let window = notification.object as! WindowHashing message += " window." + window.hash() } DDLogInfo(message) NSNotificationCenter.defaultCenter().postNotificationName(AppActivityLoggerDidUpdateNotification, object: self) } public func logFinalQuit() { DDLogInfo("Final Quit") NSNotificationCenter.defaultCenter().postNotificationName(AppActivityLoggerDidUpdateNotification, object: self) } @IBAction public func openActivityLogger(sender: AnyObject?) { if self.windowController == nil { self.windowController = AppActivityWindowController.newWindowController(withLogger: self) } self.windowController!.showWindow(self) self.windowController!.window?.makeKeyAndOrderFront(self); } public func logError(message: String) { DDLogError(message); } public func logInfo(message: String) { DDLogInfo(message); } }
// // APIRequestConstants.swift // AmazePOC // // Created by Ashwani Kumar on 17/07/19. // Copyright © 2019 Djubo. All rights reserved. // import Foundation class APIRequestConstants{ // Base URL static let baseUrl = "http://134.119.179.58:90" static let carInfoUrl = "UserSubscription/GetUserMyAccount" }
// // File.swift // // // Created by 王兴彬 on 2021/4/10. // import Foundation struct PersonFixtures { static var simpleV1: PersonJSONVersionable { return PersonJSONVersionable(json: simple(version: 1)) } static var simpleV2: PersonJSONVersionable { return PersonJSONVersionable(json: simple(version: 2)) } static var simpleV3: PersonJSONVersionable { return PersonJSONVersionable(json: simple(version: 3)) } private static func simple(version: Int) -> [String: Any] { let testBundle = Bundle.module let filename = "simple-v\(version)" let url = testBundle.url(forResource: filename, withExtension: "json")! let data = try! Data(contentsOf: url) let json = try! JSONSerialization.jsonObject(with: data) as! [String: Any] return json } }
import PinKit class LockScreenPresenter { private let router: ILockScreenRouter init(router: ILockScreenRouter) { self.router = router } } extension LockScreenPresenter: IUnlockDelegate { func onUnlock() { router.dismiss() } func onCancelUnlock() { } }
// // BaseTestCase.swift // MerckWeather // // Created by Leo Mart on 2015-08-10. // Copyright (c) 2015 merckWeatherTestApp. All rights reserved. // import XCTest class BaseTestCase: XCTestCase { let defaultTimeout: NSTimeInterval = 10 override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } }
// // PlacesInteractor.swift // MusicBrainz // // Created BOGU$ on 20/05/2019. // Copyright © 2019 lyzkov. All rights reserved. // // import Foundation protocol PlaceAnnotationType: class, LocationType { var title: String? { get } var subtitle: String? { get } var lifespan: Int? { get } } final class PlaceAnnotation: NSObject, PlaceAnnotationType { let latitude: Double let longitude: Double let title: String? let subtitle: String? let lifespan: Int? init(from place: Place, lifespanSince: Date) { latitude = Double(place.coordinates.latitude) ?? 0 longitude = Double(place.coordinates.longitude) ?? 0 title = place.name subtitle = place.address lifespan = place.lifeSpan.lifeSpan(since: lifespanSince) } } final class PlacesInteractor: PlacesInteractorProtocol { weak var presenter: PlacesPresenterOutputProtocol? let apiDataManager: PlacesAPIDataManagerInputProtocol let locationDataManager: PlacesLocationDataManagerInputProtocol init(apiDataManager: PlacesAPIDataManagerInputProtocol = PlacesAPIDataManager(), locationDataManager: PlacesLocationDataManagerInputProtocol = PlacesLocationDataManager()) { self.apiDataManager = apiDataManager self.locationDataManager = locationDataManager } func loadRegion() { locationDataManager.region { [unowned self] result in switch result { case .success(let region): self.presenter?.present(region: region) case .failure(let error): self.presenter?.show(error: error) } } } func loadPlaces(region: RegionType, since: Date) { apiDataManager.fetchAll(region: region, since: since) { result in switch result { case .success(let places): let annotations = places.map { PlaceAnnotation(from: $0, lifespanSince: since) } self.presenter?.present(places: annotations) case .failure(let error): self.presenter?.show(error: error) } } } } extension PlacesInteractorProtocol { private static func sinceDate(_ since: String) -> Date { return shortFormatter.date(from: since)! } func loadPlaces(region: RegionType, since: Date = sinceDate("1990")) { loadPlaces(region: region, since: since) } }