repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dwcares/DragonDrone
iOS/DragonDrone/FPVViewController.swift
1
15223
// // FPVViewController.swift // iOS-FPVDemo-Swift // import UIKit import DJISDK import VideoPreviewer import CoreImage class FPVViewController: UIViewController, DJIVideoFeedListener, DJISDKManagerDelegate, DJIBaseProductDelegate, DJICameraDelegate { var isPreviewShowing = false var camera : DJICamera! let analyzeQueue = DispatchQueue(label: "TheRobot.DragonDrone.AnalyzeQueue") let faceDetectInterval = TimeInterval(1.00) var faceDetectLastUpdate = Date() var faceBoxes:[UIView] = [] var reuseFaceBoxes:[UIView] = [] @IBOutlet var analyzeButton: UIButton! @IBOutlet var fpvView: UIView! @IBOutlet var logLabel: UILabel! @IBOutlet var analyzePreviewImageView: UIImageView! override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) VideoPreviewer.instance().setView(self.fpvView) DJISDKManager.registerApp(with: self) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) VideoPreviewer.instance().setView(nil) DJISDKManager.videoFeeder()?.primaryVideoFeed.remove(self) } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // // Helpers // func fetchCamera() -> DJICamera? { let product = DJISDKManager.product() if (product == nil) { return nil } if (product!.isKind(of: DJIAircraft.self)) { return (product as! DJIAircraft).camera } else if (product!.isKind(of: DJIHandheld.self)) { return (product as! DJIHandheld).camera } return nil } func analyzeCameraFaces() { if (camera == nil) { return } VideoPreviewer.instance().snapshotPreview { (previewImage) in DispatchQueue.main.async(execute: { self.showPreview(previewImage: previewImage!) self.analyzeButton.setTitle("Back", for: UIControlState.normal) self.setDroneLEDs(setOn: false) self.analyzeFaces(previewImage: previewImage) }) } } func analyzeFaces(previewImage: UIImage?) { self.detectFacesCI(image: previewImage!, parentView: self.fpvView, withAnimation: true) FaceAPI.detectFaces(previewImage!) { (faces) in DispatchQueue.main.async(execute: { self.drawDetectedFaces(faces: faces, parentView: self.fpvView) }) FaceAPI.identifyFaceWithNames(faces, personGroupId: FaceAPI.FaceGroupID) { (error, foundFaces) in if (foundFaces != nil) { DispatchQueue.main.async(execute: { self.drawDetectedFaces(faces: foundFaces!, parentView: self.fpvView) if (self.isIdentityFound(faces: foundFaces!)) { self.setDroneLEDs(setOn: true) } print("Found faces identity: \(foundFaces!)") }) } else { DispatchQueue.main.async(execute: { if (error != nil) { self.clearFaceBoxes() print(error!) } }) } } } } func detectFacesRealTime() { if (self.intervalElapsed(interval: faceDetectInterval, lastUpdate: faceDetectLastUpdate) && !isPreviewShowing) { self.faceDetectLastUpdate = Date() } else { return } VideoPreviewer.instance().snapshotPreview { (previewImage) in if (previewImage != nil) { self.detectFacesCI(image: previewImage!, parentView: self.fpvView) } } } func detectFacesCI(image: UIImage, parentView: UIView, withAnimation: Bool = false) { // This is local face detection, not using Cognitive Services. guard let personciImage = CIImage(image: image) else { return } let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh] let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: accuracy) let faces = faceDetector?.features(in: personciImage) // For converting the Core Image Coordinates to UIView Coordinates let ciImageSize = personciImage.extent.size var transform = CGAffineTransform(scaleX: 1, y: -1) transform = transform.translatedBy(x: 0, y: -ciImageSize.height) clearFaceBoxes(reuseCount: faces!.count) for face in faces as! [CIFaceFeature] { print("Found bounds are \(face.bounds)") // Apply the transform to convert the coordinates var faceViewBounds = face.bounds.applying(transform) // Calculate the actual position and size of the rectangle in the image view let viewSize = view.bounds.size let scale = min(viewSize.width / ciImageSize.width, viewSize.height / ciImageSize.height) let offsetX = (viewSize.width - ciImageSize.width * scale) / 2 let offsetY = (viewSize.height - ciImageSize.height * scale) / 2 faceViewBounds = faceViewBounds.applying(CGAffineTransform(scaleX: scale, y: scale)) faceViewBounds.origin.x += offsetX faceViewBounds.origin.y += offsetY addFaceBoxToView(frame: faceViewBounds, view: parentView, color: UIColor.white.cgColor, withAnimation: withAnimation) } } func isIdentityFound(faces: [Face]) -> Bool { var found = false for face in faces { found = (face.faceIdentity != nil || found) } return found } func drawDetectedFaces(faces: [Face], parentView: UIView) { clearFaceBoxes(reuseCount: faces.count) let scale = CGFloat(analyzePreviewImageView.image!.cgImage!.height) / analyzePreviewImageView.layer.frame.height for face in faces { let faceRect = CGRect(x: CGFloat(face.left) / scale, y: CGFloat(face.top) / scale, width:CGFloat(face.width) / scale, height: CGFloat(face.width) / scale) let color = face.faceIdentity != nil ? UIColor.red.cgColor : UIColor.yellow.cgColor addFaceBoxToView(frame: faceRect, view: parentView, color: color, labelText: face.faceIdentityName) } } func addFaceBoxToView(frame:CGRect, view: UIView, color: CGColor, withAnimation: Bool = false, labelText: String? = nil) { let faceBox:UIView if (reuseFaceBoxes.count > 0) { faceBox = reuseFaceBoxes.first! reuseFaceBoxes.removeFirst() } else { faceBox = createFaceBox(frame: frame) view.addSubview(faceBox) } if (labelText != nil) { addFaceBoxLabel(labelText: labelText!, faceBox: faceBox) } faceBoxes.append(faceBox) UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseInOut, animations: { faceBox.layer.borderColor = color faceBox.layer.opacity = 0.6 faceBox.frame = frame }, completion: { (success:Bool) in if (withAnimation) { self.startFaceBoxScanAnimation(faceBox: faceBox) } }) } func createFaceBox(frame: CGRect) -> UIView { let faceBox = UIView() faceBox.isHidden = false faceBox.layer.borderWidth = 3 faceBox.layer.borderColor = UIColor.yellow.cgColor faceBox.layer.cornerRadius = 10 faceBox.backgroundColor = UIColor.clear faceBox.layer.opacity = 0.0 faceBox.layer.frame = frame return faceBox } func startFaceBoxScanAnimation(faceBox: UIView) { let scanFrame = CGRect(x: 0, y: 10, width: faceBox.frame.width, height: 2) let scanView = UIView(frame: scanFrame) scanView.layer.backgroundColor = UIColor.yellow.cgColor scanView.layer.opacity = 0.5 let scanFrame2 = CGRect(x: 0, y: faceBox.frame.height - 10, width: faceBox.frame.width, height: 2) let scanView2 = UIView(frame: scanFrame2) scanView2.layer.backgroundColor = UIColor.yellow.cgColor scanView2.layer.opacity = 0.5 faceBox.addSubview(scanView) faceBox.addSubview(scanView2) UIView.animate(withDuration: 1.0, delay: 0.0, options: .curveEaseInOut, animations: { scanView.layer.opacity = 1 let endScanFrame = CGRect(x: 0, y: faceBox.frame.height - 10, width: faceBox.frame.width, height: 2) scanView.frame = endScanFrame scanView2.layer.opacity = 1 let endScanFrame2 = CGRect(x: 0, y: 10, width: faceBox.frame.width, height: 2) scanView2.frame = endScanFrame2 }, completion: { (success:Bool) in UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseInOut, animations: { scanView.layer.opacity = 0 let endScanFrame = CGRect(x: 0, y: 10, width: faceBox.frame.width, height: 2) scanView.frame = endScanFrame scanView2.layer.opacity = 0 let endScanFrame2 = CGRect(x: 0, y: faceBox.frame.height - 10, width: faceBox.frame.width, height: 2) scanView2.frame = endScanFrame2 }, completion: { (success:Bool) in scanView.removeFromSuperview() }) }) } func addFaceBoxLabel(labelText: String, faceBox: UIView) { let labelFrame = CGRect(x: 0, y: faceBox.frame.height + 5, width: 0, height: 0) let label = UILabel(frame: labelFrame) label.text = labelText label.layer.backgroundColor = UIColor.red.cgColor label.textColor = UIColor.white label.sizeToFit() faceBox.addSubview(label) } func clearFaceBoxes(reuseCount:Int = 0) { for faceBox in faceBoxes { if (reuseFaceBoxes.count >= reuseCount) { faceBox.removeFromSuperview() } else { reuseFaceBoxes.append(faceBox) } for sub in faceBox.subviews { sub.removeFromSuperview() } } faceBoxes.removeAll() } func showPreview(previewImage: UIImage) { analyzePreviewImageView.image = previewImage analyzePreviewImageView.isHidden = false isPreviewShowing = true } func hidePreview() { analyzePreviewImageView.image = nil analyzePreviewImageView.isHidden = true isPreviewShowing = false } func intervalElapsed (interval: TimeInterval, lastUpdate: Date ) -> Bool { return (Int(Date().timeIntervalSince(lastUpdate)) >= Int(interval)) } // // Drone Helpers // func setDroneLEDs(setOn: Bool) { let product = DJISDKManager.product() if (product == nil) { return } if (product!.isKind(of: DJIAircraft.self)) { let controller = (product as! DJIAircraft).flightController if (controller != nil) { controller!.setLEDsEnabled(setOn) { (error) in } } } } // // DJIBaseProductDelegate // func productConnected(_ product: DJIBaseProduct?) { NSLog("Product Connected") if (product != nil) { product!.delegate = self camera = self.fetchCamera() if (camera != nil) { camera!.delegate = self VideoPreviewer.instance().start() } } } func productDisconnected() { NSLog("Product Disconnected") camera = nil VideoPreviewer.instance().clearVideoData() VideoPreviewer.instance().close() } // // DJISDKManagerDelegate // func appRegisteredWithError(_ error: Error?) { if (error != nil) { NSLog("Register app failed! Please enter your app key and check the network.") } else { NSLog("Register app succeeded!") } // DEBUG: Use bridge app instead of connected drone // DJISDKManager.enableBridgeMode(withBridgeAppIP: "192.168.2.12") DJISDKManager.startConnectionToProduct() DJISDKManager.videoFeeder()?.primaryVideoFeed.add(self, with: nil) } // // DJIVideoFeedListener // // This is called every time it receives a frame from the drone. func videoFeed(_ videoFeed: DJIVideoFeed, didUpdateVideoData rawData: Data) { let videoData = rawData as NSData let videoBuffer = UnsafeMutablePointer<UInt8>.allocate(capacity: videoData.length) videoData.getBytes(videoBuffer, length: videoData.length) VideoPreviewer.instance().push(videoBuffer, length: Int32(videoData.length)) detectFacesRealTime() } // // IBAction Methods // @IBAction func analyzeAction(_ sender: UIButton) { // // DEBUG: Use local image instead of drone image -- use 16:9 image // DispatchQueue.main.async(execute: { // self.showPreview(previewImage: #imageLiteral(resourceName: "TestImage")) // self.analyzeFaces(previewImage: #imageLiteral(resourceName: "TestImage")) // }) // return if (isPreviewShowing) { // This is the state when the button says "Back" DispatchQueue.main.async(execute: { self.setDroneLEDs(setOn: false) self.hidePreview() self.analyzeButton.setTitle("Analyze", for: UIControlState.normal) }) } else { // This is the state when the button says "Analyze" analyzeCameraFaces() } } }
mit
21a254d68430cae1a22e78657a3bd825
30.452479
166
0.550154
4.913815
false
false
false
false
kstaring/swift
test/SILGen/function_conversion_objc.swift
5
5925
// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen -verify | %FileCheck %s import Foundation // REQUIRES: objc_interop // ==== Metatype to object conversions // CHECK-LABEL: sil hidden @_TF24function_conversion_objc20convMetatypeToObjectFFCSo8NSObjectMS0_T_ func convMetatypeToObject(_ f: @escaping (NSObject) -> NSObject.Type) { // CHECK: function_ref @_TTRXFo_oCSo8NSObject_dXMTS__XFo_oS__oPs9AnyObject__ // CHECK: partial_apply let _: (NSObject) -> AnyObject = f } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_oCSo8NSObject_dXMTS__XFo_oS__oPs9AnyObject__ : $@convention(thin) (@owned NSObject, @owned @callee_owned (@owned NSObject) -> @thick NSObject.Type) -> @owned AnyObject { // CHECK: apply %1(%0) // CHECK: thick_to_objc_metatype {{.*}} : $@thick NSObject.Type to $@objc_metatype NSObject.Type // CHECK: objc_metatype_to_object {{.*}} : $@objc_metatype NSObject.Type to $AnyObject // CHECK: return @objc protocol NSBurrito {} // CHECK-LABEL: sil hidden @_TF24function_conversion_objc31convExistentialMetatypeToObjectFFPS_9NSBurrito_PMPS0__T_ func convExistentialMetatypeToObject(_ f: @escaping (NSBurrito) -> NSBurrito.Type) { // CHECK: function_ref @_TTRXFo_oP24function_conversion_objc9NSBurrito__dXPMTPS0___XFo_oPS0___oPs9AnyObject__ // CHECK: partial_apply let _: (NSBurrito) -> AnyObject = f } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_oP24function_conversion_objc9NSBurrito__dXPMTPS0___XFo_oPS0___oPs9AnyObject__ : $@convention(thin) (@owned NSBurrito, @owned @callee_owned (@owned NSBurrito) -> @thick NSBurrito.Type) -> @owned AnyObject // CHECK: apply %1(%0) // CHECK: thick_to_objc_metatype {{.*}} : $@thick NSBurrito.Type to $@objc_metatype NSBurrito.Type // CHECK: objc_existential_metatype_to_object {{.*}} : $@objc_metatype NSBurrito.Type to $AnyObject // CHECK: return // CHECK-LABEL: sil hidden @_TF24function_conversion_objc28convProtocolMetatypeToObjectFFT_MPS_9NSBurrito_T_ func convProtocolMetatypeToObject(_ f: @escaping () -> NSBurrito.Protocol) { // CHECK: function_ref @_TTRXFo__dXMtP24function_conversion_objc9NSBurrito__XFo__oCSo8Protocol_ // CHECK: partial_apply let _: () -> Protocol = f } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dXMtP24function_conversion_objc9NSBurrito__XFo__oCSo8Protocol_ : $@convention(thin) (@owned @callee_owned () -> @thin NSBurrito.Protocol) -> @owned Protocol // CHECK: apply %0() : $@callee_owned () -> @thin NSBurrito.Protocol // CHECK: objc_protocol #NSBurrito : $Protocol // CHECK: copy_value // CHECK: return // ==== Representation conversions // CHECK-LABEL: sil hidden @_TF24function_conversion_objc11funcToBlockFFT_T_bT_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> @owned @convention(block) () -> () // CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage // CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] // CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) () -> () // CHECK: return [[COPY]] func funcToBlock(_ x: @escaping () -> ()) -> @convention(block) () -> () { return x } // CHECK-LABEL: sil hidden @_TF24function_conversion_objc11blockToFuncFbT_T_FT_T_ : $@convention(thin) (@owned @convention(block) () -> ()) -> @owned @callee_owned () -> () // CHECK: [[COPIED:%.*]] = copy_block %0 // CHECK: [[COPIED_2:%.*]] = copy_value [[COPIED]] // CHECK: [[THUNK:%.*]] = function_ref @_TTRXFdCb___XFo___ // CHECK: [[FUNC:%.*]] = partial_apply [[THUNK]]([[COPIED_2]]) // CHECK: return [[FUNC]] func blockToFunc(_ x: @escaping @convention(block) () -> ()) -> () -> () { return x } // ==== Representation change + function type conversion // CHECK-LABEL: sil hidden @_TF24function_conversion_objc22blockToFuncExistentialFbT_SiFT_P_ : $@convention(thin) (@owned @convention(block) () -> Int) -> @owned @callee_owned () -> @out Any // CHECK: function_ref @_TTRXFdCb__dSi_XFo__dSi_ // CHECK: partial_apply // CHECK: function_ref @_TTRXFo__dSi_XFo__iP__ // CHECK: partial_apply // CHECK: return func blockToFuncExistential(_ x: @escaping @convention(block) () -> Int) -> () -> Any { return x } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFdCb__dSi_XFo__dSi_ : $@convention(thin) (@owned @convention(block) () -> Int) -> Int // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dSi_XFo__iP__ : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Any // C function pointer conversions class A : NSObject {} class B : A {} // CHECK-LABEL: sil hidden @_TF24function_conversion_objc18cFuncPtrConversionFcCS_1AT_cCS_1BT_ func cFuncPtrConversion(_ x: @escaping @convention(c) (A) -> ()) -> @convention(c) (B) -> () { // CHECK: convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> () // CHECK: return return x } func cFuncPtr(_ a: A) {} // CHECK-LABEL: sil hidden @_TF24function_conversion_objc19cFuncDeclConversionFT_cCS_1BT_ func cFuncDeclConversion() -> @convention(c) (B) -> () { // CHECK: function_ref @_TToF24function_conversion_objc8cFuncPtrFCS_1AT_ : $@convention(c) (A) -> () // CHECK: convert_function %0 : $@convention(c) (A) -> () to $@convention(c) (B) -> () // CHECK: return return cFuncPtr } func cFuncPtrConversionUnsupported(_ x: @escaping @convention(c) (@convention(block) () -> ()) -> ()) -> @convention(c) (@convention(c) () -> ()) -> () { return x // expected-error{{C function pointer signature '@convention(c) (@convention(block) () -> ()) -> ()' is not compatible with expected type '@convention(c) (@convention(c) () -> ()) -> ()'}} }
apache-2.0
cd818f55c2efa1b009bbc87173d64768
51.901786
275
0.643544
3.510071
false
false
false
false
SpoaLove/AlphaAcademy
AlphaAcademy/AlphaAcademy/Models/Lessons.swift
1
21407
// // Chapter1LessonViewController.swift // AlphaAcademy // // Created by Tengoku no Spoa on 2017/12/31. // Copyright © 2017年 Tengoku no Spoa. All rights reserved. // import UIKit import JSQMessagesViewController import AVKit /** * The Lessons class is a sub-class of JSQMessagesViewController * this class provides the nessesary templates for the lessons to inherit from */ class Lessons: JSQMessagesViewController { /** * Defines Users */ let achan = ChatUser(id: "1", name: "A-Chan") var user = ChatUser(id: "2", name: "You") let console = ChatUser(id: "3", name: "Console") let code = ChatUser(id: "4", name: "Code") /** * all possible user avatar images */ var userImages = [ #imageLiteral(resourceName: "userWhiteBeret"), #imageLiteral(resourceName: "userPinkBeret"), #imageLiteral(resourceName: "userRedBeret"), #imageLiteral(resourceName: "userOrangeBeret"), #imageLiteral(resourceName: "userYellowBeret"), #imageLiteral(resourceName: "userLimeBeret"), #imageLiteral(resourceName: "userGreenBeret"), #imageLiteral(resourceName: "userBlueBeret"), #imageLiteral(resourceName: "userBlackBeret") ] /** * Defines Conditions */ var atEndOfRoute = false var choosenRouteName:String = "" var finishedLesson = false var userCompleteQuiz = false var userHaveRecievedBeret = false /** * Defines the Current User */ var name:String { return user.name } var currentUser: ChatUser { return user } /** * Declare all the Messages */ var messages = [JSQMessage]() /** * Messages Variables: * 'currentMessages': queue of messages * 'messagesCount' : index of the current message */ var messageQueue = [JSQMessage]() var messagesCount=0 /** * Initializing Defaults Class */ let defaults = Defaults() /** * Defines the initial Messages, the first array of messages that will be put on the queue */ let tipMessage:[JSQMessage] = [ JSQMessage(senderId: "3", displayName: "Tip!", text: "please type in 'next' or 'n' and press the send button to start or continue the conversation or type 'help' or 'h' for help!") ] /** * Tip messages */ let continueTip = JSQMessage(senderId: "3", displayName: "Tip!", text: "please type 'next' or 'n' to continue") let endTip = JSQMessage(senderId: "3", displayName: "Tip!", text: "Please tap the arrow button on the left of the textbox to quit!") /** * Defines the avatar size */ let avatarSize = CGSize(width: kJSQMessagesCollectionViewAvatarSizeDefault, height: kJSQMessagesCollectionViewAvatarSizeDefault) /** * This funtion returns the quit seque identifier * * @return a string of the quit sequre identifier */ func quitSegueIdentifier()->String{ return "quit" } /** * This function quits the lesson to home if the user have reached the end of the script */ override func didPressAccessoryButton(_ sender: UIButton!) { if atEndOfRoute { performSegue(withIdentifier: quitSegueIdentifier(), sender: self) return }else{ quitLesson() } } /** * This function asks the user to confrim using an alert before quitting the lesson */ func quitLesson(){ let selector = UIAlertController(title: "Quit", message: "Do You Really Want to Quit? Progress will be lost!", preferredStyle: .actionSheet) let yes = UIAlertAction(title: "Yes", style: .default, handler: { (action:UIAlertAction) -> () in self.performSegue(withIdentifier: self.quitSegueIdentifier(), sender: self) }) let no = UIAlertAction(title: "no", style: .default, handler: { (action:UIAlertAction) -> () in }) selector.addAction(yes) selector.addAction(no) self.present(selector, animated: true, completion: nil) } /** * This array contains the list of commands that is valid in the chapter * Override this command List to add new commands to the chapter * Key is the keyword of command * Value is the desctiption of the function of the command */ var commandList:[String:String] = [ "Help":"Shows this help message", "H":"Shows this help message", "?":"Shows this help message", "Next":"Continue the Lesson", "N":"Continue the Lesson", "Quiz":"Start the Quiz of the Chapter", "Q":"Start the Quiz of the Chapter" ] /** * This function automaticlly generates a help message for all the valid commands */ func help(){ var helpMessage = """ Help! Command: Function """ for command in commandList { helpMessage += "\n\(command.key): \(command.value)" } appendMessage(text: helpMessage, senderId: "3", senderDisplayName: "Help!") } /** * This function appends messages from the queue if the queue is not empty * Overide this message to add flags or events during the conversation */ func next(){ print("Next is sent") if messagesCount<messageQueue.count { messages.append(messageQueue[messagesCount]) messagesCount += 1 // reach end of the Route }else if messagesCount==messageQueue.count && messagesCount != 0{ if finishedLesson{ appendMessageWithJSQMessage(message: endTip) atEndOfRoute = true } }else{ appendMessageWithJSQMessage(message: continueTip) } } /** * This function parse the quizStyle of the quiz and call corresponding functions to display the quiz * * @param quiz a Quiz under the quiz protocal that will be parsed and displayed */ func showQuiz(with quiz:Quiz){ switch quiz.quizStyle { case .MultipleChoice : showMultipleChoiceQuiz(with: quiz as! MultipleChoiceQuiz) case .YesOrNo: showYesOrNoQuiz(with: quiz as! YesOrNoQuiz) case .UserInputQuiz: showUserInputQuiz(with: quiz as! UserInputQuiz) case .TrueOrFalse: showTrueOrFalseQuiz(with: quiz as! TrueOrFalseQuiz) } } /** * This function checks if the user have answered the quiz correctlly * If the user answered correctlly the message correct will be appended * Else the message incorrect will be appended */ func checkAns(with answer:String, quiz:Quiz){ self.appendMessage(text: answer, senderId: user.id, senderDisplayName: user.name) if answer == quiz.correctAnswer { self.appendMessageWithJSQMessage(message: quiz.messageCorrect) correctResponse() } else { self.appendMessageWithJSQMessage(message: quiz.messageIncorrect) } } /** * This function shows a MultipleChoiceQuiz * * @param quiz a MultipleChoiceQuize that wull be displayed */ func showMultipleChoiceQuiz(with quiz:MultipleChoiceQuiz) { let selector = UIAlertController(title: "QUIZ!", message: quiz.questionText, preferredStyle: .actionSheet) let action1 = UIAlertAction(title: quiz.choice1, style: .default, handler: { (action:UIAlertAction) -> () in self.checkAns(with: quiz.choice1, quiz: quiz) selector.dismiss(animated: true, completion: nil) }) let action2 = UIAlertAction(title: quiz.choice2, style: .default, handler: { (action:UIAlertAction) -> () in self.checkAns(with: quiz.choice2, quiz: quiz) selector.dismiss(animated: true, completion: nil) }) let action3 = UIAlertAction(title: quiz.choice3, style: .default, handler: { (action:UIAlertAction) -> () in self.checkAns(with: quiz.choice3, quiz: quiz) selector.dismiss(animated: true, completion: nil) }) selector.addAction(action1) selector.addAction(action2) selector.addAction(action3) self.present(selector, animated: true, completion:nil) } /** * This function shows a Yes or No Quiz * * @param quiz a YesOrNoQuiz that wull be displayed */ func showYesOrNoQuiz(with quiz:YesOrNoQuiz) { let selector = UIAlertController(title: "QUIZ!", message: quiz.questionText, preferredStyle: .actionSheet) let action1 = UIAlertAction(title: "Yes", style: .default, handler: { (action:UIAlertAction) -> () in self.checkAns(with: "Yes", quiz: quiz) selector.dismiss(animated: true, completion: nil) }) let action2 = UIAlertAction(title: "No", style: .default, handler: { (action:UIAlertAction) -> () in self.checkAns(with: "No", quiz: quiz) selector.dismiss(animated: true, completion: nil) }) selector.addAction(action1) selector.addAction(action2) self.present(selector, animated: true, completion:nil) } /** * This function shows a User Input Quiz * * @param quiz a UserInputQuiz that wull be displayed */ func showUserInputQuiz(with quiz:UserInputQuiz) { let alert = UIAlertController(title: "QUIZ!", message: quiz.questionText, preferredStyle: .alert) alert.addTextField(configurationHandler: nil) alert.addAction(UIAlertAction(title: "Confrim", style: .default, handler:{ [weak alert] (_) in let textField = alert?.textFields![0].text! self.checkAns(with: textField!, quiz: quiz) })) self.present(alert, animated: true, completion: nil) } /** * This function shows a True or False Quiz * * @param quiz a TrueOrFalseQuiz that wull be displayed */ func showTrueOrFalseQuiz(with quiz:TrueOrFalseQuiz) { let selector = UIAlertController(title: "QUIZ!", message: quiz.questionText, preferredStyle: .actionSheet) let action1 = UIAlertAction(title: "True", style: .default, handler: { (action:UIAlertAction) -> () in self.checkAns(with: "True", quiz: quiz) selector.dismiss(animated: true, completion: nil) }) let action2 = UIAlertAction(title: "False", style: .default, handler: { (action:UIAlertAction) -> () in self.checkAns(with: "False", quiz: quiz) selector.dismiss(animated: true, completion: nil) }) selector.addAction(action1) selector.addAction(action2) self.present(selector, animated: true, completion:nil) } /** * This function is called when the quiz is answered correctly */ func correctResponse(){ // need to be implemented in sub classes } /** * This function shows the quizes of the chapter to the user * override this function to customize the quiz! */ func quiz(){ printMsg(text: "Quiz Is not Implemented") } /** * This function parse through the user input for commands * if the command is valid then the command will be executed * if the command is invalid a tips message will be appended * * @param message the user inputed string */ func reply(with message:String)->(){ for command in commandList{ if message.caseInsensitiveCompare(command.key)==ComparisonResult.orderedSame { return executeCommand(with:command.key) } } return appendMessageWithJSQMessage(message: continueTip) } /** * This function execute the user inputted command * @param the user inputed command String */ func executeCommand(with command:String)->(){ switch command { case "Help","H","?": help() case "Next","N": next() case "Quiz","Q": quiz() default: help() } finishSendingMessage() } /** * This function checks if the lesson reaches the end * if the lesson does reach the end the function returns * else the function pass the sented message to the 'reply' function */ override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) { guard !atEndOfRoute else{ atEndOfRoute = false return } reply(with: text) } // Collection View Stuff // Message sender Display Name override func collectionView(_ collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAt indexPath: IndexPath!) -> NSAttributedString! { let message = messages[indexPath.row] let messageUsername = message.senderDisplayName return NSAttributedString(string: messageUsername!) } // Message Bubble Height override func collectionView(_ collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForMessageBubbleTopLabelAt indexPath: IndexPath!) -> CGFloat { return 15 } // Message Bubble Image override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAt indexPath: IndexPath!) -> JSQMessageBubbleImageDataSource! { let bubbleFactory = JSQMessagesBubbleImageFactory() let message = messages[indexPath.row] switch message.senderId { case "2": return bubbleFactory?.outgoingMessagesBubbleImage(with: .blue) case "1": return bubbleFactory?.incomingMessagesBubbleImage(with: .red) case "3": return bubbleFactory?.incomingMessagesBubbleImage(with: .orange) case "4": return bubbleFactory?.incomingMessagesBubbleImage(with: .gray) default: return bubbleFactory?.incomingMessagesBubbleImage(with: .orange) } } // Message Avatar Image override func collectionView(_ collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAt indexPath: IndexPath!) -> JSQMessageAvatarImageDataSource! { let avatarImageFactory = JSQMessagesAvatarImageFactory.self let message = messages[indexPath.item] let userAvatar = getBeret() switch message.senderId { case "1": // Sender is A-Chan return avatarImageFactory.avatarImage(with: UIImage(named: "Title.png"), diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault)) case "2": // Sender is Yourself return avatarImageFactory.avatarImage(with: userAvatar, diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault)) case "3": // Sender is Console return JSQMessagesAvatarImageFactory.avatarImage(withUserInitials: ">_", backgroundColor: UIColor.black, textColor: UIColor.white, font: UIFont.systemFont(ofSize: 14), diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault)) case "4": // Sender is Code return JSQMessagesAvatarImageFactory.avatarImage(withUserInitials: ">_", backgroundColor: UIColor.orange, textColor: UIColor.black, font: UIFont.systemFont(ofSize: 14), diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault)) default: // Sender is Code return JSQMessagesAvatarImageFactory.avatarImage(withUserInitials: "?", backgroundColor: UIColor.white, textColor: UIColor.black, font: UIFont.systemFont(ofSize: 14), diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault)) } } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return messages.count } override func collectionView(_ collectionView: JSQMessagesCollectionView!, messageDataForItemAt indexPath: IndexPath!) -> JSQMessageData! { return messages[indexPath.row] } // Messages functions // set Chapter /** * This function appends the input [JSQMessage] into the messages queue * * @param chapter an array of JSQMessages that will be added into the messages queue */ func setChapter(chapter:[JSQMessage]){ messageQueue += chapter } /** * This function append a message to the collection view wirh * * @param text the text content of the message * @param senderId the user identifier of the selected sender * @param senderDisplayName the name of the sender */ func appendMessage(text: String!, senderId: String!, senderDisplayName: String!){ let message = JSQMessage(senderId: senderId, displayName: senderDisplayName, text: text) messages.append(message!) finishSendingMessage() } /** * This function append a messgae to the collection view using a JSQMessage * * @param message the JSQMessage that will be appended */ func appendMessageWithJSQMessage(message: JSQMessage!){ messages.append(message!) finishSendingMessage() } /** * This function prints a debug message into the messages * * @param text the String that will be printed */ func printMsg(text:String){ appendMessage(text: text, senderId: "3", senderDisplayName: "DEBUG") } /** * This function shows user a choice betweem two routes that can be appended into the queue * * @param title the title of the route choice alert * @param message the message of the route choice alert * @param action1title the button title of the first route * @param action2title the button title of the second route * @param route1 an array of JSQMessage for the first route * @param route2 an array of JSQMessage for the second route */ func selectRoute(title:String, message:String, action1title:String, action2title:String, route1:[JSQMessage], route2:[JSQMessage]){ let selector = UIAlertController(title: title, message: message, preferredStyle: .actionSheet) let action1 = UIAlertAction(title: action1title, style: .default, handler: { (action:UIAlertAction) -> () in self.additionalFunctionForRoute1() self.choosenRouteName = action1title self.appendMessage(text: action1title, senderId: "2", senderDisplayName: self.defaults.getName()) self.setChapter(chapter: route1) }) let action2 = UIAlertAction(title: action2title, style: .default, handler: { (action:UIAlertAction) -> () in self.additionalFunctionForRoute2() self.choosenRouteName = action2title self.appendMessage(text: action2title, senderId: "2", senderDisplayName: self.defaults.getName()) self.setChapter(chapter: route2) }) selector.addAction(action1) selector.addAction(action2) self.present(selector, animated: true, completion: nil) } /** * Additional functions that takes no arguments that can be called during a route selection */ func additionalFunctionForRoute1(){} func additionalFunctionForRoute2(){} /** * This function returns the user's chosen beret's image * * @return the corresponding UIImage of the beret id number */ func getBeret() -> UIImage { return userImages[defaults.getBeretNumber()] } /** * This function prompts a debug alert that shows that the Chapter is under development. * This function should not be used in the actual release */ func unimplemented(){ let selector = UIAlertController(title: "Alert!", message: "This Chapter is currentlly in Development!", preferredStyle: .actionSheet) let quit = UIAlertAction(title: "Quit", style: .default, handler: { (action:UIAlertAction) -> () in self.performSegue(withIdentifier: self.quitSegueIdentifier(), sender: self) }) selector.addAction(quit) self.present(selector, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() // tell JSQMessageViewController who is the current user senderId = currentUser.id senderDisplayName = currentUser.name // append initial messages user.name = defaults.getName() messages += tipMessage } /* * This function allows the return button on the keboard to act just like the send button on the right! */ override func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { didPressSend(nil, withMessageText: textView.text, senderId: user.id, senderDisplayName: user.name, date: nil) return false } return true } }
mit
bdad0737e57bd38b0841d0fbfd71c968
36.095321
241
0.634835
4.834877
false
false
false
false
huangboju/HYAlertController
HYAlertController/HYAlertController.swift
1
5104
// // HYAlertController.swift // Quick-Start-iOS // // Created by work on 2016/10/25. // Copyright © 2016年 hyyy. All rights reserved. // import UIKit public enum HYAlertControllerStyle: Int { case actionSheet case shareSheet case alert } // MARK: - Class public class HYAlertController: UIViewController { var alertStyle = HYAlertControllerStyle.alert fileprivate var alertTitle: String? fileprivate var alertMessage: String? fileprivate var actionArray: [[HYAlertAction]] = [] fileprivate var cancelAction: HYAlertAction? var pickerView: HYPickerView! lazy var dimBackgroundView: UIControl = { let control = UIControl(frame: CGRect(x: 0, y: 0, width: HYConstants.ScreenWidth, height: HYConstants.ScreenHeight)) control.backgroundColor = UIColor(white: 0, alpha: HYConstants.dimBackgroundAlpha) control.addTarget(self, action: #selector(clickedBgViewHandler), for: .touchDown) return control }() convenience init(title: String?, message: String?, style: HYAlertControllerStyle) { self.init() alertStyle = style alertTitle = title alertMessage = message // 自定义转场动画 transitioningDelegate = self modalPresentationStyle = .custom modalTransitionStyle = .coverVertical pickerView = HYPickerView.pickerView(for: alertStyle) pickerView.delegate = self view.addSubview(pickerView) } } // MARK: - LifeCycle extension HYAlertController { public override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.clear view.addSubview(dimBackgroundView) } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let cancelHight = cancelAction != nil ? HYAlertCell.cellHeight + 10 : 0 let tableHeight = HYAlertCell.cellHeight * CGFloat(actionArray.first?.count ?? 0) + cancelHight if alertStyle == .shareSheet { let tableHeight = HYShareTableViewCell.cellHeight * CGFloat(actionArray.count) + cancelHight let newTableFrame = CGRect(x: 0, y: HYConstants.ScreenHeight - tableHeight, width: HYConstants.ScreenWidth, height: tableHeight) pickerView.frame = newTableFrame } else if alertStyle == .actionSheet { let newTableFrame = CGRect(x: 0, y: HYConstants.ScreenHeight - tableHeight, width: HYConstants.ScreenWidth, height: tableHeight) pickerView.frame = newTableFrame } else { let newTableFrame = CGRect(x: 0, y: 0, width: HYConstants.ScreenWidth - HYConstants.alertSpec, height: tableHeight) pickerView.frame = newTableFrame pickerView.center = view.center } pickerView.set(title: alertTitle, message: alertMessage) } } // MARK: - Public Methods extension HYAlertController { open func add(_ action: HYAlertAction) { if action.style == .cancel { cancelAction = action } else { if actionArray.isEmpty { actionArray.append([action]) } else { actionArray[0].append(action) } } (pickerView as? DataPresenter)?.refresh(actionArray[0], cancelAction: cancelAction) } /// 添加必须是元素为HYAlertAction的数组,调用几次该方法,分享显示几行 open func addShare(_ actions: [HYAlertAction]) { actionArray += [actions] (pickerView as? HYShareView)?.refresh(actionArray) } } // MARK: - HYSheetViewDelegate extension HYAlertController: HYActionDelegate { func clickItemHandler() { dismiss() } } // MARK: - UIViewControllerTransitioningDelegate extension HYAlertController: UIViewControllerTransitioningDelegate { public func animationController(forPresented _: UIViewController, presenting _: UIViewController, source _: UIViewController) -> UIViewControllerAnimatedTransitioning? { return HYAlertPresentSlideUp() } public func animationController(forDismissed _: UIViewController) -> UIViewControllerAnimatedTransitioning? { return HYAlertDismissSlideDown() } } // MARK: - Events extension HYAlertController { /// 点击背景事件 @objc fileprivate func clickedBgViewHandler() { dismiss() } } // MARK: - Private Methods extension HYAlertController { // 取消视图显示和控制器加载 fileprivate func dismiss() { actionArray.removeAll() cancelAction = nil dismiss(animated: true, completion: nil) } }
mit
011af6e45c33e1e139ea1ff6b5109930
30.840764
173
0.608322
5.306794
false
false
false
false
egnwd/ic-bill-hack
quick-split/Pods/SwiftyJSONDecodable/SwiftyJSONDecodable/SwiftyJSONDecodable.swift
2
10900
// // SwiftyJSONDecodable.swift // SwiftyJSONDecodable // // Created by Mike Pollard on 21/01/2016. // Copyright © 2016 Mike Pollard. All rights reserved. // import Foundation import SwiftyJSON /// Conform to this if you can be instantiated from a json representation /// in the form of a SwiftyJSON.JSON public protocol SwiftyJSONDecodable { /// An initialiser that take a JSON and throws /// /// The intention here is that the implementation can `throw` if the json /// is malformatted, missing required fields etc. init(json: JSON) throws } /// An ErrorType encapsulating the various different failure states /// while decoding from json public indirect enum SwiftyJSONDecodeError : ErrorType { case NullValue case WrongType case InvalidValue(String?) case ErrorForKey(key: String, error: SwiftyJSONDecodeError) } extension SwiftyJSONDecodeError : CustomDebugStringConvertible { public var debugDescription: String { switch self { case NullValue : return "NullValue" case WrongType : return "WrongType" case InvalidValue(let s) : return "InvalidValue(" + (s ?? "nil") + ")" case ErrorForKey(let key, let error) : return key + "." + error.debugDescription } } } extension SwiftyJSONDecodeError : Equatable { } public func ==(lhs: SwiftyJSONDecodeError, rhs: SwiftyJSONDecodeError) -> Bool { switch (lhs, rhs) { case (.NullValue, .NullValue): return true case (.WrongType, .WrongType): return true case (.InvalidValue(let v1), .InvalidValue(let v2)): return v1 == v2 case (.ErrorForKey(let k1, let e1), .ErrorForKey(let k2, let e2)): return k1 == k2 && e1 == e2 default: return false } } extension Int : SwiftyJSONDecodable { public init(json: JSON) throws { guard json != JSON.null else { throw SwiftyJSONDecodeError.NullValue } guard json.type == .Number else { throw SwiftyJSONDecodeError.WrongType } guard json.stringValue == String(json.intValue) else { throw SwiftyJSONDecodeError.WrongType } guard let i = json.int else { throw SwiftyJSONDecodeError.WrongType } self.init(i) } } extension Double : SwiftyJSONDecodable { public init(json: JSON) throws { guard json != JSON.null else { throw SwiftyJSONDecodeError.NullValue } guard json.type == .Number else { throw SwiftyJSONDecodeError.WrongType } guard let d = json.double else { throw SwiftyJSONDecodeError.WrongType } self.init(d) } } extension String : SwiftyJSONDecodable { public init(json: JSON) throws { guard json != JSON.null else { throw SwiftyJSONDecodeError.NullValue } guard json.type == .String else { throw SwiftyJSONDecodeError.WrongType } guard let s = json.string else { throw SwiftyJSONDecodeError.WrongType } self.init(s) } } extension Bool : SwiftyJSONDecodable { public init(json :JSON) throws { guard json != JSON.null else { throw SwiftyJSONDecodeError.NullValue } guard json.type == .Bool else { throw SwiftyJSONDecodeError.WrongType } guard let b = json.bool else { throw SwiftyJSONDecodeError.WrongType } self.init(b) } } extension Array where Element: SwiftyJSONDecodable { public init(json: JSON) throws { guard json != JSON.null else { throw SwiftyJSONDecodeError.NullValue } guard let arrayJSON = json.array else { throw SwiftyJSONDecodeError.WrongType } var index = 0 var elements = [Element]() do { for elementJson in arrayJSON { let element = try Element(json: elementJson) elements.append(element) index = index + 1 } } catch let error as SwiftyJSONDecodeError { throw SwiftyJSONDecodeError.ErrorForKey(key: "["+String(index)+"]", error: error) } self.init(elements) } } extension Dictionary where Key : StringLiteralConvertible, Key.StringLiteralType == String, Value: SwiftyJSONDecodable { public init(json: JSON) throws { guard json != JSON.null else { throw SwiftyJSONDecodeError.NullValue } guard let dictJSON = json.dictionary else { throw SwiftyJSONDecodeError.WrongType } var result = [String:Value]() for (k, j) in dictJSON { let v : Value = try Value(json: j) result[k] = v } self.init() for (k, v) in result { let key = Key(stringLiteral: k) self[key] = v } } } public extension JSON { public func decodeArrayForKey<T: SwiftyJSONDecodable>(key: String) throws -> Array<T>? { guard self.type != .Null else { throw SwiftyJSONDecodeError.NullValue } guard self.type == .Dictionary else { throw SwiftyJSONDecodeError.WrongType } guard self[key] != JSON.null else { return nil } return try decodeArrayForKey(key) as Array<T> } public func decodeArrayForKey<T: SwiftyJSONDecodable>(key: String) throws -> Array<T> { guard self.type != .Null else { throw SwiftyJSONDecodeError.NullValue } guard self.type == .Dictionary else { throw SwiftyJSONDecodeError.WrongType } do { let json = self[key] return try Array<T>(json: json) } catch let error as SwiftyJSONDecodeError { throw SwiftyJSONDecodeError.ErrorForKey(key: key, error: error) } } public func decodeValueForKey<T: SwiftyJSONDecodable>(key: String) throws -> T? { guard self.type != .Null else { throw SwiftyJSONDecodeError.NullValue } guard self.type == .Dictionary else { throw SwiftyJSONDecodeError.WrongType } guard self[key] != JSON.null else { return nil } return try self.decodeValueForKey(key) as T } public func decodeValueForKey<T: SwiftyJSONDecodable>(key: String) throws -> T { guard self.type != .Null else { throw SwiftyJSONDecodeError.NullValue } guard self.type == .Dictionary else { throw SwiftyJSONDecodeError.WrongType } do { let json = self[key] return try json.decodeAsValue() } catch let error as SwiftyJSONDecodeError { throw SwiftyJSONDecodeError.ErrorForKey(key: key, error: error) } } public func decodeAsValue<T: SwiftyJSONDecodable>() throws -> T? { guard self != JSON.null else { return nil } return try T(json: self) } public func decodeAsValue<T: SwiftyJSONDecodable>() throws -> T { guard self != JSON.null else { throw SwiftyJSONDecodeError.NullValue } return try T(json: self) } public func decodeAsDictionaryForKey<V: SwiftyJSONDecodable>(key: String) throws -> Dictionary<String, V> { guard self.type != .Null else { throw SwiftyJSONDecodeError.NullValue } guard self.type == .Dictionary else { throw SwiftyJSONDecodeError.WrongType } do { let json = self[key] return try Dictionary<String, V>(json : json) } catch let error as SwiftyJSONDecodeError { throw SwiftyJSONDecodeError.ErrorForKey(key: key, error: error) } } } /// Make all RawRepresentables conform to SwiftyJSONDecodable where the associated RawValue is SwiftyJSONDecodable public extension SwiftyJSONDecodable where Self : RawRepresentable, Self.RawValue : SwiftyJSONDecodable { public init(json: JSON) throws { guard json != JSON.null else { throw SwiftyJSONDecodeError.NullValue } guard let rawValue = json.rawValue as? Self.RawValue else { throw SwiftyJSONDecodeError.WrongType } if let _ = Self(rawValue: rawValue) { self.init(rawValue: rawValue)! } else { throw SwiftyJSONDecodeError.InvalidValue(json.rawString()) } } } extension NSDate { public var toJsonDateTime : String { return JSONDate.dateFormatterNoMillis.stringFromDate(self) } } public final class JSONDate : NSDate, SwiftyJSONDecodable { public static var dateFormatter : NSDateFormatter = { let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" return formatter }() public static var dateFormatterNoMillis : NSDateFormatter = { let formatter = NSDateFormatter() formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return formatter }() private var _timeIntervalSinceReferenceDate : NSTimeInterval override public var timeIntervalSinceReferenceDate: NSTimeInterval { return _timeIntervalSinceReferenceDate } public convenience init(json: JSON) throws { if let dateString = json.string, date = JSONDate.dateFormatter.dateFromString(dateString) { self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate) } else if let dateString = json.string, date = JSONDate.dateFormatterNoMillis.dateFromString(dateString) { self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate) } else { throw SwiftyJSONDecodeError.InvalidValue(json.rawString()) } } override init(timeIntervalSinceReferenceDate ti: NSTimeInterval) { _timeIntervalSinceReferenceDate = ti super.init() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public final class JSONURL : NSURL, SwiftyJSONDecodable { public convenience init(json: JSON) throws { let urlString : String = try json.decodeAsValue() if let _ = NSURL(string: urlString) { self.init(string: urlString, relativeToURL: nil)! } else { throw SwiftyJSONDecodeError.InvalidValue(json.rawString()) } } override init?(string URLString: String, relativeToURL baseURL: NSURL?) { super.init(string: URLString, relativeToURL: baseURL) } public required convenience init(fileReferenceLiteral path: String) { fatalError("init(fileReferenceLiteral:) has not been implemented") } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
38f9f609d6f6c5369decc70730f8d0e6
31.831325
120
0.635838
5.112101
false
false
false
false
omaralbeik/SwifterSwift
Sources/Extensions/UIKit/UIViewControllerExtensions.swift
1
5457
// // UIViewControllerExtensions.swift // SwifterSwift // // Created by Emirhan Erdogan on 07/08/16. // Copyright © 2016 SwifterSwift // #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Properties public extension UIViewController { /// SwifterSwift: Check if ViewController is onscreen and not hidden. public var isVisible: Bool { // http://stackoverflow.com/questions/2777438/how-to-tell-if-uiviewcontrollers-view-is-visible return isViewLoaded && view.window != nil } } // MARK: - Methods public extension UIViewController { /// SwifterSwift: Assign as listener to notification. /// /// - Parameters: /// - name: notification name. /// - selector: selector to run with notified. public func addNotificationObserver(name: Notification.Name, selector: Selector) { NotificationCenter.default.addObserver(self, selector: selector, name: name, object: nil) } /// SwifterSwift: Unassign as listener to notification. /// /// - Parameter name: notification name. public func removeNotificationObserver(name: Notification.Name) { NotificationCenter.default.removeObserver(self, name: name, object: nil) } /// SwifterSwift: Unassign as listener from all notifications. public func removeNotificationsObserver() { NotificationCenter.default.removeObserver(self) } /// SwifterSwift: Helper method to display an alert on any UIViewController subclass. Uses UIAlertController to show an alert /// /// - Parameters: /// - title: title of the alert /// - message: message/body of the alert /// - buttonTitles: (Optional)list of button titles for the alert. Default button i.e "OK" will be shown if this paramter is nil /// - highlightedButtonIndex: (Optional) index of the button from buttonTitles that should be highlighted. If this parameter is nil no button will be highlighted /// - completion: (Optional) completion block to be invoked when any one of the buttons is tapped. It passes the index of the tapped button as an argument /// - Returns: UIAlertController object (discardable). @discardableResult public func showAlert(title: String?, message: String?, buttonTitles: [String]? = nil, highlightedButtonIndex: Int? = nil, completion: ((Int) -> Void)? = nil) -> UIAlertController { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) var allButtons = buttonTitles ?? [String]() if allButtons.count == 0 { allButtons.append("OK") } for index in 0..<allButtons.count { let buttonTitle = allButtons[index] let action = UIAlertAction(title: buttonTitle, style: .default, handler: { (_) in completion?(index) }) alertController.addAction(action) // Check which button to highlight if let highlightedButtonIndex = highlightedButtonIndex, index == highlightedButtonIndex { if #available(iOS 9.0, *) { alertController.preferredAction = action } } } present(alertController, animated: true, completion: nil) return alertController } /// SwifterSwift: Helper method to add a UIViewController as a childViewController. /// /// - Parameters: /// - child: the view controller to add as a child /// - containerView: the containerView for the child viewcontroller's root view. public func addChildViewController(_ child: UIViewController, toContainerView containerView: UIView) { addChild(child) containerView.addSubview(child.view) child.didMove(toParent: self) } /// SwifterSwift: Helper method to remove a UIViewController from its parent. public func removeViewAndControllerFromParentViewController() { guard parent != nil else { return } willMove(toParent: nil) removeFromParent() view.removeFromSuperview() } #if os(iOS) /// SwifterSwift: Helper method to present a UIViewController as a popover. /// /// - Parameters: /// - popoverContent: the view controller to add as a popover. /// - sourcePoint: the point in which to anchor the popover. /// - size: the size of the popover. Default uses the popover preferredContentSize. /// - delegate: the popover's presentationController delegate. Default is nil. /// - animated: Pass true to animate the presentation; otherwise, pass false. /// - completion: The block to execute after the presentation finishes. Default is nil. public func presentPopover(_ popoverContent: UIViewController, sourcePoint: CGPoint, size: CGSize? = nil, delegate: UIPopoverPresentationControllerDelegate? = nil, animated: Bool = true, completion: (() -> Void)? = nil) { popoverContent.modalPresentationStyle = .popover if let size = size { popoverContent.preferredContentSize = size } if let popoverPresentationVC = popoverContent.popoverPresentationController { popoverPresentationVC.sourceView = view popoverPresentationVC.sourceRect = CGRect(origin: sourcePoint, size: .zero) popoverPresentationVC.delegate = delegate } present(popoverContent, animated: animated, completion: completion) } #endif } #endif
mit
ffa24f4bfefd714333e29cb1aa4c78ea
41.96063
225
0.67357
5.047179
false
false
false
false
1170197998/SinaWeibo
SFWeiBo/SFWeiBo/Classes/Tools/NSDate+Category.swift
1
2493
// // NSDate+Category.swift // SFWeiBo // // Created by mac on 16/4/23. // Copyright © 2016年 ShaoFeng. All rights reserved. // import UIKit extension NSDate { class func dateWithString(time: String) -> NSDate { //将服务器下来的时间字符串转换为NSDate //创建formatter let formatter = NSDateFormatter() //设置时间格式 formatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy" //设置时间区域 formatter.locale = NSLocale(localeIdentifier: "en") //转换字符串 let creatDate = formatter.dateFromString(time) return creatDate! } /* 刚刚(一分钟内) x分钟(一小时内) x消失前(当天) 昨天 HH:mm(昨天) MM-dd HH:mm(一年内) yyyy-MM-dd HH:mm(更早期) */ var descDate: String { let calendar = NSCalendar.currentCalendar() //判断是否是今天 if calendar.isDateInToday(self) { //获取当前时间和系统时间的差距(单位是秒) //强制转换为Int let since = Int(NSDate().timeIntervalSinceDate(self)) // 是否是刚刚 if since < 60 { return "刚刚" } // 是否是分钟内 if since < 60 * 60 { return "\(since/60)分钟前" } // 是否是小时内 return "\(since / (60 * 60))小时前" } //判断是否是昨天 var formatterString = "HH:mm" if calendar.isDateInYesterday(self) { formatterString = "昨天" + formatterString } else { //判断是否是一年内 formatterString = "MM-dd" + formatterString //判断是否是更早期 let comps = calendar.components(NSCalendarUnit.Year, fromDate: self, toDate: NSDate(), options: NSCalendarOptions(rawValue: 0)) if comps.year >= 1 { formatterString = "yyyy-" + formatterString } } //按照指定的格式将日期转换为字符串 //创建formatter let formatter = NSDateFormatter() //设置时间格式 formatter.dateFormat = formatterString //设置时间区域 formatter.locale = NSLocale(localeIdentifier: "en") //格式化 return formatter.stringFromDate(self) } }
apache-2.0
569bc3ca6e48930a6582a2f87ed19ad5
25.121951
139
0.520075
4.344828
false
false
false
false
gilserrap/Bigotes
Pods/GRMustache.swift/Mustache/Goodies/NSFormatter.swift
2
6293
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /** GRMustache lets you use `NSFormatter` to format your values. */ extension NSFormatter { /** `NSFormatter` adopts the `MustacheBoxable` protocol so that it can feed Mustache templates. You should not directly call the `mustacheBox` property. Always use the `Box()` function instead: formatter.mustacheBox // Valid, but discouraged Box(formatter) // Preferred `NSFormatter` can be used as a filter: let percentFormatter = NSNumberFormatter() percentFormatter.numberStyle = .PercentStyle var template = try! Template(string: "{{ percent(x) }}") template.registerInBaseContext("percent", Box(percentFormatter)) // Renders "50%" try! template.render(Box(["x": 0.5])) `NSFormatter` can also format all variable tags in a Mustache section: template = try! Template(string: "{{# percent }}" + "{{#ingredients}}" + "- {{name}} ({{proportion}})\n" + "{{/ingredients}}" + "{{/percent}}") template.registerInBaseContext("percent", Box(percentFormatter)) // - bread (50%) // - ham (35%) // - butter (15%) var data = [ "ingredients":[ ["name": "bread", "proportion": 0.5], ["name": "ham", "proportion": 0.35], ["name": "butter", "proportion": 0.15]]] try! template.render(Box(data)) As seen in the example above, variable tags buried inside inner sections are escaped as well, so that you can render loop and conditional sections. However, values that can't be formatted are left untouched. Precisely speaking, "values that can't be formatted" are the ones for which the `-[NSFormatter stringForObjectValue:]` method return nil, as stated by NSFormatter documentation https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFormatter_Class/index.html#//apple_ref/occ/instm/NSFormatter/stringForObjectValue: Typically, `NSNumberFormatter` only formats numbers, and `NSDateFormatter`, dates: you can safely mix various data types in a section controlled by those well-behaved formatters. */ public override var mustacheBox: MustacheBox { // Return a multi-facetted box, because NSFormatter interacts in // various ways with Mustache rendering. return MustacheBox( // Let user extract the formatter out of the box: value: self, // This function is used for evaluating `formatter(x)` expressions. filter: Filter { (box: MustacheBox) in // NSFormatter documentation for stringForObjectValue: states: // // > First test the passed-in object to see if it’s of the // > correct class. If it isn’t, return nil; but if it is of the // > right class, return a properly formatted and, if necessary, // > localized string. if let object = box.value as? NSObject { return Box(self.stringForObjectValue(object)) } else { // Not the correct class: return nil, i.e. empty Box. return Box() } }, // This function lets formatter change values that are about to be // rendered to their formatted counterpart. // // It is activated as soon as the formatter enters the context // stack, when used in a section `{{# formatter }}...{{/ formatter }}`. willRender: { (tag: Tag, box: MustacheBox) in switch tag.type { case .Variable: // {{ value }} // Format the value if we can. // // NSFormatter documentation for stringForObjectValue: states: // // > First test the passed-in object to see if it’s of the correct // > class. If it isn’t, return nil; but if it is of the right class, // > return a properly formatted and, if necessary, localized string. // // So nil result means that object is not of the correct class. Leave // it untouched. if let object = box.value as? NSObject, let formatted = self.stringForObjectValue(object) { return Box(formatted) } else { return box } case .Section: // {{# value }}...{{/ value }} // {{^ value }}...{{/ value }} // Leave sections untouched, so that loops and conditions are not // affected by the formatter. return box } }) } }
mit
b46a3b604170180f44178ca2644ed0aa
41.459459
203
0.577817
5.197684
false
false
false
false
whitepixelstudios/Material
Sources/iOS/ChipBar.swift
1
11822
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Motion @objc(ChipItemStyle) public enum ChipItemStyle: Int { case pill } open class ChipItem: FlatButton { /// Configures the visual display of the chip. var chipItemStyle: ChipItemStyle { get { return associatedInstance.chipItemStyle } set(value) { associatedInstance.chipItemStyle = value layoutSubviews() } } open override func layoutSubviews() { super.layoutSubviews() layoutChipItemStyle() } open override func prepare() { super.prepare() pulseAnimation = .none } } fileprivate extension ChipItem { /// Lays out the chipItem based on its style. func layoutChipItemStyle() { if .pill == chipItemStyle { layer.cornerRadius = bounds.height / 2 } } } fileprivate struct AssociatedInstance { /// A ChipItemStyle value. var chipItemStyle: ChipItemStyle } /// A memory reference to the ChipItemStyle instance for ChipItem extensions. fileprivate var ChipKey: UInt8 = 0 fileprivate extension ChipItem { /// AssociatedInstance reference. var associatedInstance: AssociatedInstance { get { return AssociatedObject.get(base: self, key: &ChipKey) { return AssociatedInstance(chipItemStyle: .pill) } } set(value) { AssociatedObject.set(base: self, key: &ChipKey, value: value) } } } @objc(ChipBarDelegate) public protocol ChipBarDelegate { /** A delegation method that is executed when the chipItem will trigger the animation to the next chip. - Parameter chipBar: A ChipBar. - Parameter chipItem: A ChipItem. */ @objc optional func chipBar(chipBar: ChipBar, willSelect chipItem: ChipItem) /** A delegation method that is executed when the chipItem did complete the animation to the next chip. - Parameter chipBar: A ChipBar. - Parameter chipItem: A ChipItem. */ @objc optional func chipBar(chipBar: ChipBar, didSelect chipItem: ChipItem) } @objc(ChipBarStyle) public enum ChipBarStyle: Int { case auto case nonScrollable case scrollable } open class ChipBar: Bar { /// The total width of the chipItems. fileprivate var chipItemsTotalWidth: CGFloat { var w: CGFloat = 0 let q = 2 * chipItemsInterimSpace let p = q + chipItemsInterimSpace for v in chipItems { let x = v.sizeThatFits(CGSize(width: .greatestFiniteMagnitude, height: scrollView.bounds.height)).width w += x w += p } w -= chipItemsInterimSpace return w } /// An enum that determines the chip bar style. open var chipBarStyle = ChipBarStyle.auto { didSet { layoutSubviews() } } /// A reference to the scroll view when the chip bar style is scrollable. open let scrollView = UIScrollView() /// Enables and disables bouncing when swiping. open var isScrollBounceEnabled: Bool { get { return scrollView.bounces } set(value) { scrollView.bounces = value } } /// A delegation reference. open weak var delegate: ChipBarDelegate? /// The currently selected chipItem. open fileprivate(set) var selectedChipItem: ChipItem? /// A preset wrapper around chipItems contentEdgeInsets. open var chipItemsContentEdgeInsetsPreset: EdgeInsetsPreset { get { return contentView.grid.contentEdgeInsetsPreset } set(value) { contentView.grid.contentEdgeInsetsPreset = value } } /// A reference to EdgeInsets. @IBInspectable open var chipItemsContentEdgeInsets: EdgeInsets { get { return contentView.grid.contentEdgeInsets } set(value) { contentView.grid.contentEdgeInsets = value } } /// A preset wrapper around chipItems interimSpace. open var chipItemsInterimSpacePreset: InterimSpacePreset { get { return contentView.grid.interimSpacePreset } set(value) { contentView.grid.interimSpacePreset = value } } /// A wrapper around chipItems interimSpace. @IBInspectable open var chipItemsInterimSpace: InterimSpace { get { return contentView.grid.interimSpace } set(value) { contentView.grid.interimSpace = value } } /// Buttons. open var chipItems = [ChipItem]() { didSet { for b in oldValue { b.removeFromSuperview() } prepareChipItems() layoutSubviews() } } open override func layoutSubviews() { super.layoutSubviews() guard willLayout else { return } layoutScrollView() updateScrollView() } open override func prepare() { super.prepare() interimSpacePreset = .interimSpace3 contentEdgeInsetsPreset = .square1 chipItemsInterimSpacePreset = .interimSpace4 chipItemsContentEdgeInsetsPreset = .square2 chipItemsContentEdgeInsets.left = 0 chipItemsContentEdgeInsets.right = 0 prepareContentView() prepareScrollView() prepareDivider() } } fileprivate extension ChipBar { /// Prepares the divider. func prepareDivider() { dividerColor = Color.grey.lighten2 } /// Prepares the chipItems. func prepareChipItems() { for v in chipItems { v.grid.columns = 0 v.layer.cornerRadius = 0 v.contentEdgeInsets = .zero v.removeTarget(self, action: #selector(handle(chipItem:)), for: .touchUpInside) v.addTarget(self, action: #selector(handle(chipItem:)), for: .touchUpInside) } } /// Prepares the contentView. func prepareContentView() { contentView.layer.zPosition = 6000 } /// Prepares the scroll view. func prepareScrollView() { scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false centerViews = [scrollView] } } fileprivate extension ChipBar { /// Layout the scrollView. func layoutScrollView() { contentView.grid.reload() if .scrollable == chipBarStyle || (.auto == chipBarStyle && chipItemsTotalWidth > scrollView.bounds.width) { var w: CGFloat = 0 let q = 2 * chipItemsInterimSpace let p = q + chipItemsInterimSpace for v in chipItems { let x = v.sizeThatFits(CGSize(width: .greatestFiniteMagnitude, height: scrollView.bounds.height)).width v.frame.size.height = scrollView.bounds.height v.frame.size.width = x + q v.frame.origin.x = w w += x w += p if scrollView != v.superview { v.removeFromSuperview() scrollView.addSubview(v) } } w -= chipItemsInterimSpace scrollView.contentSize = CGSize(width: w, height: scrollView.bounds.height) } else { scrollView.grid.begin() scrollView.grid.views = chipItems scrollView.grid.axis.columns = chipItems.count scrollView.grid.contentEdgeInsets = chipItemsContentEdgeInsets scrollView.grid.interimSpace = chipItemsInterimSpace scrollView.grid.commit() scrollView.contentSize = scrollView.frame.size } } } fileprivate extension ChipBar { /// Handles the chipItem touch event. @objc func handle(chipItem: ChipItem) { animate(to: chipItem, isTriggeredByUserInteraction: true) } } extension ChipBar { /** Selects a given index from the chipItems array. - Parameter at index: An Int. - Paramater completion: An optional completion block. */ open func select(at index: Int, completion: ((ChipItem) -> Void)? = nil) { guard -1 < index, index < chipItems.count else { return } animate(to: chipItems[index], isTriggeredByUserInteraction: false, completion: completion) } /** Animates to a given chipItem. - Parameter to chipItem: A ChipItem. - Parameter completion: An optional completion block. */ open func animate(to chipItem: ChipItem, completion: ((ChipItem) -> Void)? = nil) { animate(to: chipItem, isTriggeredByUserInteraction: false, completion: completion) } } fileprivate extension ChipBar { /** Animates to a given chipItem. - Parameter to chipItem: A ChipItem. - Parameter isTriggeredByUserInteraction: A boolean indicating whether the state was changed by a user interaction, true if yes, false otherwise. - Parameter completion: An optional completion block. */ func animate(to chipItem: ChipItem, isTriggeredByUserInteraction: Bool, completion: ((ChipItem) -> Void)? = nil) { if isTriggeredByUserInteraction { delegate?.chipBar?(chipBar: self, willSelect: chipItem) } selectedChipItem = chipItem updateScrollView() } } fileprivate extension ChipBar { /// Updates the scrollView. func updateScrollView() { guard let v = selectedChipItem else { return } if !scrollView.bounds.contains(v.frame) { let contentOffsetX = (v.frame.origin.x < scrollView.bounds.minX) ? v.frame.origin.x : v.frame.maxX - scrollView.bounds.width let normalizedOffsetX = min(max(contentOffsetX, 0), scrollView.contentSize.width - scrollView.bounds.width) scrollView.setContentOffset(CGPoint(x: normalizedOffsetX, y: 0), animated: true) } } }
bsd-3-clause
b9a6208b8f6dc1d02cc8a2f23c6fbaa7
30.192612
136
0.626544
4.90743
false
false
false
false
kallahir/MarvelFinder
MarvelFinder/CharacterDetailViewController.swift
1
23008
// // CharacterDetailViewController.swift // MarvelFinder // // Created by Itallo Rossi Lucas on 08/01/17. // Copyright © 2017 Kallahir Labs. All rights reserved. // import UIKit import AlamofireImage class CharacterDetailViewController: UITableViewController, UICollectionViewDelegate, UICollectionViewDataSource { let requests = MarvelRequests() var character: Character! @IBOutlet weak var characterImage: UIImageView! @IBOutlet weak var characterName: UILabel! @IBOutlet weak var characterDescription: UITextView! @IBOutlet weak var comicsCollectionView: UICollectionView! var comicsCollection: Collection! var comicsOffset = 0 var comicsLoadMore = false var comicsLoadError = false @IBOutlet weak var seriesCollectionView: UICollectionView! var seriesCollection: Collection! var seriesOffset = 0 var seriesLoadMore = false var seriesLoadError = false @IBOutlet weak var storiesCollectionView: UICollectionView! var storiesCollection: Collection! var storiesOffset = 0 var storiesLoadMore = false var storiesLoadError = false @IBOutlet weak var eventsCollectionView: UICollectionView! var eventsCollection: Collection! var eventsOffset = 0 var eventsLoadMore = false var eventsLoadError = false var selectedCollectionItem: CollectionItem! var selectedCollectionTitle: String! var urls = Dictionary<String, String>() private let relatedLinksSection = 5 override func viewDidLoad() { super.viewDidLoad() let urlString = "\(self.character!.thumbnail!)/landscape_incredible.\(self.character!.thumbFormat!)" self.characterName.text = self.character!.name self.characterImage.af_setImage(withURL: URL(string: urlString)!, placeholderImage: UIImage(named: "placeholder_list"), imageTransition: UIImageView.ImageTransition.crossDissolve(0.3)) if (self.character!.description?.isEmpty)! { self.characterDescription.text = NSLocalizedString("Detail.noDescription", comment: "") } else { self.characterDescription.text = self.character!.description } for url in self.character!.urls! { urls[url.linkType!] = url.linkURL! } self.comicsCollectionView.delegate = self self.comicsCollectionView.dataSource = self self.seriesCollectionView.delegate = self self.seriesCollectionView.dataSource = self self.storiesCollectionView.delegate = self self.storiesCollectionView.dataSource = self self.eventsCollectionView.delegate = self self.eventsCollectionView.dataSource = self self.loadCollectionList(characterId: self.character.id!, collectionType: "comics", offset: self.comicsOffset) { (result) in self.comicsCollection = result self.refreshCollectionView("comics", loadMore: true, loadError: false, offset: self.comicsOffset) } self.loadCollectionList(characterId: self.character.id!, collectionType: "series", offset: self.seriesOffset) { (result) in self.seriesCollection = result self.refreshCollectionView("series", loadMore: true, loadError: false, offset: self.seriesOffset) } self.loadCollectionList(characterId: self.character.id!, collectionType: "stories", offset: self.storiesOffset) { (result) in self.storiesCollection = result self.refreshCollectionView("stories", loadMore: true, loadError: false, offset: self.storiesOffset) } self.loadCollectionList(characterId: self.character.id!, collectionType: "events", offset: self.eventsOffset) { (result) in self.eventsCollection = result self.refreshCollectionView("events", loadMore: true, loadError: false, offset: self.eventsOffset) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ShowCollectionItem" { let collectionDetailVC = segue.destination as! CollectionItemDetailViewController collectionDetailVC.collectionItem = self.selectedCollectionItem collectionDetailVC.collectionType = self.selectedCollectionTitle } let backItem = UIBarButtonItem() backItem.title = NSLocalizedString("Navigation.back", comment: "") navigationItem.backBarButtonItem = backItem } // MARK: Collection View func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.numberOfItems(collectionView: collectionView) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == self.comicsCollectionView { return getCell(collectionView: self.comicsCollectionView, collection: self.comicsCollection, indexPath: indexPath, loadError: self.comicsLoadError) } if collectionView == self.seriesCollectionView { return getCell(collectionView: self.seriesCollectionView, collection: self.seriesCollection, indexPath: indexPath, loadError: self.seriesLoadError) } if collectionView == self.storiesCollectionView { return getCell(collectionView: self.storiesCollectionView, collection: self.storiesCollection, indexPath: indexPath, loadError: self.storiesLoadError) } return getCell(collectionView: self.eventsCollectionView, collection: self.eventsCollection, indexPath: indexPath, loadError: self.eventsLoadError) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if collectionView == self.comicsCollectionView { if self.comicsCollection == nil || indexPath.row == self.comicsCollection.items!.count { if self.comicsLoadError { self.comicsLoadError = false self.comicsCollectionView.reloadData() self.loadCollectionList(characterId: self.character.id!, collectionType: "comics", offset: self.comicsOffset) { (result) in if self.comicsCollection == nil { self.comicsCollection = result } else { for item in (result?.items!)! { self.comicsCollection.items!.append(item) } } self.refreshCollectionView("comics", loadMore: true, loadError: false, offset: self.comicsOffset) } return } return } self.selectedCollectionItem = self.comicsCollection.items![indexPath.row] self.selectedCollectionTitle = "comics" self.performSegue(withIdentifier: "ShowCollectionItem", sender: self) return } if collectionView == self.seriesCollectionView { if self.seriesCollection == nil || indexPath.row == self.seriesCollection.items!.count { if self.seriesLoadError { self.seriesLoadError = false self.seriesCollectionView.reloadData() self.loadCollectionList(characterId: self.character.id!, collectionType: "series", offset: self.seriesOffset) { (result) in if self.seriesCollection == nil { self.seriesCollection = result } else { for item in (result?.items!)! { self.seriesCollection.items!.append(item) } } self.refreshCollectionView("series", loadMore: true, loadError: false, offset: self.seriesOffset) } return } return } self.selectedCollectionItem = self.seriesCollection.items![indexPath.row] self.selectedCollectionTitle = "series" self.performSegue(withIdentifier: "ShowCollectionItem", sender: self) return } if collectionView == self.storiesCollectionView { if self.storiesCollection == nil || indexPath.row == self.storiesCollection.items!.count { if self.storiesLoadError { self.storiesLoadError = false self.storiesCollectionView.reloadData() self.loadCollectionList(characterId: self.character.id!, collectionType: "stories", offset: self.storiesOffset) { (result) in if self.storiesCollection == nil { self.storiesCollection = result } else { for item in (result?.items!)! { self.storiesCollection.items!.append(item) } } self.refreshCollectionView("stories", loadMore: true, loadError: false, offset: self.storiesOffset) } return } return } self.selectedCollectionItem = self.storiesCollection.items![indexPath.row] self.selectedCollectionTitle = "stories" self.performSegue(withIdentifier: "ShowCollectionItem", sender: self) return } if self.eventsCollection == nil || indexPath.row == self.eventsCollection.items!.count { if self.eventsLoadError { self.eventsLoadError = false self.eventsCollectionView.reloadData() self.loadCollectionList(characterId: self.character.id!, collectionType: "events", offset: self.eventsOffset) { (result) in if self.eventsCollection == nil { self.eventsCollection = result } else { for item in (result?.items!)! { self.eventsCollection.items!.append(item) } } self.refreshCollectionView("events", loadMore: true, loadError: false, offset: self.eventsOffset) } return } return } self.selectedCollectionItem = self.eventsCollection.items![indexPath.row] self.selectedCollectionTitle = "events" self.performSegue(withIdentifier: "ShowCollectionItem", sender: self) } // MARK: Table View override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { return self.characterDescription.contentSize.height+15 } return super.tableView(tableView, heightForRowAt: indexPath) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.tableView.deselectRow(at: indexPath, animated: true) self.selectRelatedLink(indexPath: indexPath) } override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { self.selectRelatedLink(indexPath: indexPath) } // MARK: Load More override func scrollViewDidScroll(_ scrollView: UIScrollView) { let offset = scrollView.contentOffset.x let maxOffset = scrollView.contentSize.width - scrollView.frame.size.width if (maxOffset - offset) <= 55 { switch scrollView { case self.comicsCollectionView: self.loadMore(loadMore: &self.comicsLoadMore, offset: self.comicsOffset, collection: self.comicsCollection, collectionType: "comics", completion: { (result,offset) in if result != nil { for item in (result?.items!)! { self.comicsCollection.items!.append(item) } } self.refreshCollectionView("comics", loadMore: true, loadError: false, offset: offset) }) break case self.seriesCollectionView: self.loadMore(loadMore: &self.seriesLoadMore, offset: self.seriesOffset, collection: self.seriesCollection, collectionType: "series", completion: { (result,offset) in if result != nil { for item in (result?.items!)! { self.seriesCollection.items!.append(item) } } self.refreshCollectionView("series", loadMore: true, loadError: false, offset: offset) }) break case self.storiesCollectionView: self.loadMore(loadMore: &self.storiesLoadMore, offset: self.storiesOffset, collection: self.storiesCollection, collectionType: "stories", completion: { (result,offset) in if result != nil { for item in (result?.items!)! { self.storiesCollection.items!.append(item) } } self.refreshCollectionView("stories", loadMore: true, loadError: false, offset: offset) }) break case self.eventsCollectionView: self.loadMore(loadMore: &self.eventsLoadMore, offset: self.eventsOffset, collection: self.eventsCollection, collectionType: "events", completion: { (result,offset) in if result != nil { for item in (result?.items!)! { self.eventsCollection.items!.append(item) } } self.refreshCollectionView("events", loadMore: true, loadError: false, offset: offset) }) break default: break } } } func loadMore(loadMore: inout Bool, offset: Int, collection: Collection!, collectionType: String, completion: @escaping (_ result: Collection?, _ offset: Int) -> Void) { if loadMore == true { loadMore = false let offsetTemp = offset + 20 if collection != nil { if offsetTemp >= collection.total! { return } } self.loadCollectionList(characterId: self.character.id!, collectionType: collectionType, offset: offsetTemp, completion: { (result) in completion(result, offsetTemp) }) } } // MARK: Util func selectRelatedLink(indexPath: IndexPath) { if indexPath.section == self.relatedLinksSection { switch indexPath.row { case 0: self.openRelatedLink(linkType: "detail") break case 1: self.openRelatedLink(linkType: "wiki") break case 2: self.openRelatedLink(linkType: "comiclink") break default: break } } } func openRelatedLink(linkType: String) { if let relatedLink = self.urls[linkType] { UIApplication.shared.open(NSURL(string: relatedLink) as! URL, options: [:], completionHandler: nil) } else { UIApplication.shared.open(NSURL(string:"http://www.marvel.com/") as! URL, options: [:], completionHandler: nil) } } func numberOfItems(collectionView: UICollectionView) -> Int { var numberOfItems = 1 switch collectionView { case self.comicsCollectionView: if self.comicsCollection != nil { if self.comicsCollection.count! != 0 { numberOfItems = self.comicsCollection.items!.count if !(self.comicsCollection.items!.count >= self.comicsCollection.total!) { numberOfItems += 1 } } } break case self.seriesCollectionView: if self.seriesCollection != nil { if self.seriesCollection.count! != 0 { numberOfItems = self.seriesCollection.items!.count if !(self.seriesCollection.items!.count >= self.seriesCollection.total!) { numberOfItems += 1 } } } break case self.storiesCollectionView: if self.storiesCollection != nil { if self.storiesCollection.count! != 0 { numberOfItems = self.storiesCollection.items!.count if !(self.storiesCollection.items!.count >= self.storiesCollection.total!) { numberOfItems += 1 } } } break case self.eventsCollectionView: if self.eventsCollection != nil { if self.eventsCollection.count! != 0 { numberOfItems = self.eventsCollection.items!.count if !(self.eventsCollection.items!.count >= self.eventsCollection.total!) { numberOfItems += 1 } } } break default: break } return numberOfItems } // MARK: Collections cells func getCell<T>(collectionView: UICollectionView, collection: Collection!, indexPath: IndexPath, loadError: Bool) -> T { if collection != nil { if collection.items!.count == 0 { return self.noRecordsFoundCell(collectionView: collectionView, indexPath: indexPath, text: NSLocalizedString("Cell.noResults", comment: "")) as! T } if collection.items!.count == indexPath.row { if loadError { return self.retryCell(collectionView: collectionView, indexPath: indexPath, text: NSLocalizedString("Cell.tryAgain", comment: "")) as! T } return self.loadingCell(collectionView: collectionView, indexPath: indexPath) as! T } return collectionCell(collectionView: collectionView, indexPath: indexPath, item: collection.items![indexPath.row]) as! T } if collection == nil { if loadError { return self.retryCell(collectionView: collectionView, indexPath: indexPath, text: NSLocalizedString("Cell.tryAgain", comment: "")) as! T } } return self.loadingCell(collectionView: collectionView, indexPath: indexPath) as! T } func noRecordsFoundCell(collectionView: UICollectionView, indexPath: IndexPath, text: String) -> CharacterDetailCollectionMessageCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionMessageCell", for: indexPath) as! CharacterDetailCollectionMessageCell cell.messageLabel.text = text return cell } func retryCell(collectionView: UICollectionView, indexPath: IndexPath, text: String) -> CharacterDetailCollectionRetryCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionRetryCell", for: indexPath) as! CharacterDetailCollectionRetryCell cell.retryLabel.text = text return cell } func loadingCell(collectionView: UICollectionView, indexPath: IndexPath) -> CharacterDetailCollectionLoadingCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionLoadCell", for: indexPath) as! CharacterDetailCollectionLoadingCell cell.loadingIndicator.startAnimating() return cell } func collectionCell(collectionView: UICollectionView, indexPath: IndexPath, item: CollectionItem) -> CharacterDetailCollectionCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CharacterDetailCollectionCell let urlString = "\(item.thumbnail ?? "nothing")/portrait_xlarge.\(item.thumbFormat ?? "nothing")" cell.collectionImage.af_setImage(withURL: URL(string: urlString)!, placeholderImage: UIImage(named: "placeholder_collection"), imageTransition: UIImageView.ImageTransition.crossDissolve(0.3)) cell.collectionName.text = item.name return cell } // MARK: Request Util func loadCollectionList(characterId: Int, collectionType: String, offset: Int, completion: @escaping (_ result: Collection?) -> Void) { self.requests.getCollectionList(characterId: characterId, collectionType: collectionType, offset: offset, completion: { (result) in guard let result = result else { self.refreshCollectionView(collectionType, loadMore: false, loadError: true, offset: offset) return } completion(result) }) } func refreshCollectionView(_ collectionType: String, loadMore: Bool, loadError: Bool, offset: Int) { switch collectionType { case "comics": DispatchQueue.main.sync { self.comicsOffset = offset self.comicsLoadMore = loadMore self.comicsLoadError = loadError self.comicsCollectionView.reloadData() } break case "series": DispatchQueue.main.sync { self.seriesOffset = offset self.seriesLoadMore = loadMore self.seriesLoadError = loadError self.seriesCollectionView.reloadData() } break case "stories": DispatchQueue.main.sync { self.storiesOffset = offset self.storiesLoadMore = loadMore self.storiesLoadError = loadError self.storiesCollectionView.reloadData() } break case "events": DispatchQueue.main.sync { self.eventsOffset = offset self.eventsLoadMore = loadMore self.eventsLoadError = loadError self.eventsCollectionView.reloadData() } break default: break } } }
mit
627d1144e282352076d589a601a4822c
43.32948
199
0.586604
5.675136
false
false
false
false
SwiftGen/StencilSwiftKit
Sources/StencilSwiftKit/Filters.swift
1
3798
// // StencilSwiftKit // Copyright © 2022 SwiftGen // MIT Licence // import Foundation import Stencil /// Namespace for filters public enum Filters { typealias BooleanWithArguments = (Any?, [Any?]) throws -> Bool /// Possible filter errors public enum Error: Swift.Error { case invalidInputType case invalidOption(option: String) } /// Parses filter input value for a string value, where accepted objects must conform to /// `CustomStringConvertible` /// /// - Parameters: /// - value: an input value, may be nil /// - Throws: Filters.Error.invalidInputType public static func parseString(from value: Any?) throws -> String { if let losslessString = value as? LosslessStringConvertible { return String(describing: losslessString) } if let string = value as? String { return string } #if os(Linux) // swiftlint:disable:next legacy_objc_type if let string = value as? NSString { return String(describing: string) } #endif throw Error.invalidInputType } /// Parses filter arguments for a string value, where accepted objects must conform to /// `CustomStringConvertible` /// /// - Parameters: /// - arguments: an array of argument values, may be empty /// - index: the index in the arguments array /// - Throws: Filters.Error.invalidInputType public static func parseStringArgument(from arguments: [Any?], at index: Int = 0) throws -> String { guard index < arguments.count else { throw Error.invalidInputType } if let losslessString = arguments[index] as? LosslessStringConvertible { return String(describing: losslessString) } if let string = arguments[index] as? String { return string } throw Error.invalidInputType } // swiftlint:disable discouraged_optional_boolean /// Parses filter arguments for a boolean value, where true can by any one of: "true", "yes", "1", and /// false can be any one of: "false", "no", "0". If optional is true it means that the argument on the filter is /// optional and it's not an error condition if the argument is missing or not the right type /// /// - Parameters: /// - arguments: an array of argument values, may be empty /// - index: the index in the arguments array /// - required: If true, the argument is required and function throws if missing. /// If false, returns nil on missing args. /// - Throws: Filters.Error.invalidInputType public static func parseBool(from arguments: [Any?], at index: Int = 0, required: Bool = true) throws -> Bool? { guard index < arguments.count, let boolArg = arguments[index] as? String else { if required { throw Error.invalidInputType } else { return nil } } switch boolArg.lowercased() { case "false", "no", "0": return false case "true", "yes", "1": return true default: throw Error.invalidInputType } } // swiftlint:enable discouraged_optional_boolean /// Parses filter arguments for an enum value (with a String rawvalue). /// /// - Parameters: /// - arguments: an array of argument values, may be empty /// - index: the index in the arguments array /// - default: The default value should no argument be provided /// - Throws: Filters.Error.invalidInputType public static func parseEnum<T>( from arguments: [Any?], at index: Int = 0, default: T ) throws -> T where T: RawRepresentable, T.RawValue == String { guard index < arguments.count else { return `default` } let arg = arguments[index].map(String.init(describing:)) ?? `default`.rawValue guard let result = T(rawValue: arg) else { throw Self.Error.invalidOption(option: arg) } return result } }
mit
4f28ab7af315639df51d316f8f52603b
32.017391
114
0.663682
4.329532
false
false
false
false
DiabetesCompass/Diabetes_Compass
BGCompass/TrendViewController.swift
1
20779
// // TrendViewController.swift // BGCompass // // Created by Steve Baker on 12/10/16. // Copyright © 2016 Clif Alferness. All rights reserved. // import UIKit // https://github.com/core-plot/core-plot/blob/master/examples/CPTTestApp-iPhone/Classes/ScatterPlotController.swift class TrendViewController : UIViewController { enum Trend { case bg, ha1c } //TODO: Consider use DateComponents /// A rough scale, may be used to set axis label formats and tick mark intervals enum RangeScale { case hour, hour24, day, week, month } static let minutesPerWeek = Double(MINUTES_IN_ONE_HOUR * HOURS_IN_ONE_DAY * DAYS_IN_ONE_WEEK) /// margin for xAxis range before first data point and after last data point static let xAxisRangeMargin = 1000.0 var trendsAlgorithmModel: TrendsAlgorithmModel? private var scatterGraph: CPTXYGraph? = nil @IBOutlet var hostingView: CPTGraphHostingView! var trend: Trend? // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() trendsAlgorithmModel = TrendsAlgorithmModel.sharedInstance() as! TrendsAlgorithmModel? let newGraph = CPTXYGraph(frame: .zero) hostingView.backgroundColor = UIColor(red:85.0/255.0, green:150.0/255.0, blue:194.0/255.0, alpha:1) hostingView.hostedGraph = newGraph configurePaddings(graph: newGraph) if trend != nil { configurePlotSpace(graph: newGraph, trend: trend!) configureAxes(graph: newGraph, trend: trend!) let boundLinePlot = styledPlot(trend: trend!) boundLinePlot.dataSource = self newGraph.add(boundLinePlot) boundLinePlot.plotSymbol = TrendViewController.plotSymbol() } self.scatterGraph = newGraph } // MARK: - configuration func configurePaddings(graph: CPTXYGraph) { graph.paddingLeft = 10.0 graph.paddingRight = 10.0 graph.paddingTop = 10.0 graph.paddingBottom = 10.0 } /// set axes range start and length func configurePlotSpace(graph: CPTXYGraph, trend: Trend) { let plotSpace = graph.defaultPlotSpace as! CPTXYPlotSpace plotSpace.delegate = self plotSpace.allowsUserInteraction = true // limit scrolling? // http://stackoverflow.com/questions/18784140/coreplot-allow-horizontal-scrolling-in-positive-quadrant-only?rq=1 plotSpace.globalXRange = TrendViewController.globalXRange(trendsAlgorithmModel: trendsAlgorithmModel, trend: trend) // location is axis start, length is axis (end - start) plotSpace.xRange = TrendViewController.xRange(trendsAlgorithmModel: trendsAlgorithmModel, trend: trend) plotSpace.globalYRange = TrendViewController.globalYRange(trend: trend) plotSpace.yRange = plotSpace.globalYRange! } /** Typically bgArray and ha1cArray have same number of elements, with same timeStamps So globalXRange returns same range for either trend */ class func globalXRange(trendsAlgorithmModel: TrendsAlgorithmModel?, trend: Trend) -> CPTPlotRange { let rangeEmpty = CPTPlotRange(location: 0.0, length: 0.0) var dateFirst: Date? var dateLast: Date? switch trend { case .bg: dateFirst = trendsAlgorithmModel?.bgArrayReadingFirst()?.timeStamp dateLast = trendsAlgorithmModel?.bgArrayReadingLast()?.timeStamp case .ha1c: dateFirst = trendsAlgorithmModel?.ha1cArrayReadingFirst()?.timeStamp dateLast = trendsAlgorithmModel?.ha1cArrayReadingLast()?.timeStamp } guard let first = dateFirst, let last = dateLast else { return rangeEmpty } let minutesLastMinusFirst = last.timeIntervalSince(first) / Double(SECONDS_IN_ONE_MINUTE) let location = NSNumber(value: -xAxisRangeMargin) let length = NSNumber(value: minutesLastMinusFirst + (2 * xAxisRangeMargin)) let range = CPTPlotRange(location: location, length: length) return range } class func xRange(trendsAlgorithmModel: TrendsAlgorithmModel?, trend: Trend) -> CPTPlotRange { let rangeEmpty = CPTPlotRange(location: 0.0, length: 0.0) var dateFirst: Date? var dateLast: Date? switch trend { case .bg: dateFirst = trendsAlgorithmModel?.bgArrayReadingFirst()?.timeStamp dateLast = trendsAlgorithmModel?.bgArrayReadingLast()?.timeStamp case .ha1c: dateFirst = trendsAlgorithmModel?.ha1cArrayReadingFirst()?.timeStamp dateLast = trendsAlgorithmModel?.ha1cArrayReadingLast()?.timeStamp } guard let first = dateFirst, let last = dateLast else { return rangeEmpty } let minutesLastMinusFirst = last.timeIntervalSince(first) / Double(SECONDS_IN_ONE_MINUTE) let location = minutesLastMinusFirst - minutesPerWeek + xAxisRangeMargin let range = CPTPlotRange(location: NSNumber(value:location), length: NSNumber(value: minutesPerWeek)) return range } class func globalYRange(trend: Trend) -> CPTPlotRange { let location = NSNumber(value: TrendViewController.rangeMinimum(trend: trend) - xAxisLabelHeight(trend: trend)) let length = NSNumber(value:TrendViewController.rangeMaximum(trend: trend) - TrendViewController.rangeMinimum(trend: trend) + TrendViewController.xAxisLabelHeight(trend: trend)) let range = CPTPlotRange(location: location, length: length) return range } class func xAxisLabelHeight(trend: Trend) -> Double { var height = 0.0 switch trend { case .bg: if BGReading.shouldDisplayBgInMmolPerL() { height = 1.0 } else { height = 10.0 } case .ha1c: height = 0.5 } return height } class func rangeMaximum(trend: Trend) -> Double { var rangeMaximum = 0.0 switch trend { case .bg: if BGReading.shouldDisplayBgInMmolPerL() { rangeMaximum = 300.0 / Double(MG_PER_DL_PER_MMOL_PER_L) } else { rangeMaximum = 300.0 } case .ha1c: // TODO: set to maximum of all readings rangeMaximum = 11.0 } return rangeMaximum } class func rangeMinimum(trend: Trend) -> Double { switch trend { case .bg: return 0.0 case .ha1c: return 5.0 } } func configureAxes(graph: CPTXYGraph, trend: Trend) { let axisSet = graph.axisSet as! CPTXYAxisSet if let x = axisSet.xAxis { configureAxis(x: x, trend: trend) } if let y = axisSet.yAxis { configureAxis(y: y, trend: trend) } } func configureAxis(x: CPTXYAxis, trend: Trend) { x.delegate = self x.labelFormatter = xLabelFormatter(range: nil) x.labelTextStyle = TrendViewController.textStyleWhite() x.axisLineStyle = TrendViewController.lineStyleThinWhite() x.majorTickLineStyle = TrendViewController.lineStyleThinWhite() x.minorTickLineStyle = TrendViewController.lineStyleThinWhite() // x axis located at y coordinate == x.orthogonalPosition switch trend { case .bg: x.orthogonalPosition = 0.0 case .ha1c: x.orthogonalPosition = 5.0 } configureAxisIntervals(x: x, rangeScale: .day) } /** - parameter rangeScale: a RangeScale */ func configureAxisIntervals(x: CPTXYAxis, rangeScale: RangeScale) { x.labelExclusionRanges = [ //CPTPlotRange(location: 0.99, length: 0.02), //CPTPlotRange(location: 1.99, length: 0.02), //CPTPlotRange(location: 2.99, length: 0.02) ] x.minorTicksPerInterval = 1 var majorIntervalLength = TrendViewController.minutesPerWeek as NSNumber? print("rangeScale \(rangeScale)") switch rangeScale { case .month: //let dayPerMonth = 30 majorIntervalLength = NSNumber(value: Int(4 * DAYS_IN_ONE_WEEK * HOURS_IN_ONE_DAY * MINUTES_IN_ONE_HOUR)) case .week: majorIntervalLength = NSNumber(value: Int(DAYS_IN_ONE_WEEK * HOURS_IN_ONE_DAY * MINUTES_IN_ONE_HOUR)) case .day: majorIntervalLength = NSNumber(value: (DAYS_IN_ONE_WEEK * HOURS_IN_ONE_DAY * MINUTES_IN_ONE_HOUR)) case .hour24, .hour: majorIntervalLength = NSNumber(value: (HOURS_IN_ONE_DAY * MINUTES_IN_ONE_HOUR)) } x.majorIntervalLength = majorIntervalLength } func configureAxis(y: CPTXYAxis, trend: Trend) { y.delegate = self y.labelFormatter = yLabelFormatter(trend: trend) y.labelTextStyle = TrendViewController.textStyleWhite() y.axisLineStyle = TrendViewController.lineStyleThinWhite() y.majorTickLineStyle = TrendViewController.lineStyleThinWhite() y.minorTickLineStyle = TrendViewController.lineStyleThinWhite() // y axis located at x coordinate == y.orthogonalPosition // range.location is axis start, range.length is axis (end - start) let xRange = TrendViewController.xRange(trendsAlgorithmModel: trendsAlgorithmModel, trend: trend) y.orthogonalPosition = TrendViewController.yOrthogonalPosition(xRange: xRange) y.labelExclusionRanges = [ //CPTPlotRange(location: 0.99, length: 0.02), //CPTPlotRange(location: 1.99, length: 0.02), //CPTPlotRange(location: 3.99, length: 0.02) ] switch trend { case .bg: if BGReading.shouldDisplayBgInMmolPerL() { y.majorIntervalLength = 1 y.minorTicksPerInterval = 1 } else { y.majorIntervalLength = 20 y.minorTicksPerInterval = 1 } case .ha1c: y.majorIntervalLength = 1 y.minorTicksPerInterval = 1 } } /** typically caller will set y.orthogonalPosition = yOrthogonalPosition() - parameter xRangeLocation: axis start - parameter xRangeLength: axis (end - start) - returns: x cooridinate for y axis to cross x axis */ class func yOrthogonalPosition(xRange: CPTPlotRange) -> NSNumber { let xRangeLocation = xRange.location.doubleValue let xRangeLength = xRange.length.doubleValue let yAxisLabelWidth = 0.1 * xRangeLength let position = NSNumber(value:(xRangeLocation + yAxisLabelWidth)) return position } func styledPlot(trend: Trend) -> CPTScatterPlot { let plot = CPTScatterPlot(frame: .zero) plot.dataLineStyle = TrendViewController.lineStyleWhite() switch trend { case .bg: plot.identifier = NSString.init(string: "bg") case .ha1c: plot.identifier = NSString.init(string: "ha1c") } return plot } class func plotSymbol() -> CPTPlotSymbol { let symbolLineStyle = CPTMutableLineStyle() symbolLineStyle.lineColor = .white() let symbol = CPTPlotSymbol.ellipse() symbol.fill = CPTFill(color: .white()) symbol.lineStyle = symbolLineStyle symbol.size = CGSize(width: 4.0, height: 4.0) return symbol } class func lineStyleThinWhite() -> CPTMutableLineStyle { let lineStyle = CPTMutableLineStyle() lineStyle.lineColor = .white() lineStyle.lineWidth = 1.0 return lineStyle } class func lineStyleWhite() -> CPTMutableLineStyle { let lineStyle = CPTMutableLineStyle() lineStyle.lineColor = .white() lineStyle.lineWidth = 2.0 lineStyle.miterLimit = 2.0 return lineStyle } class func textStyleWhite() -> CPTMutableTextStyle { let textStyle = CPTMutableTextStyle() textStyle.color = .white() return textStyle } // MARK: - label formatters func xLabelFormatter(range: CPTPlotRange?) -> CPTCalendarFormatter { guard let firstReading = trendsAlgorithmModel?.ha1cArrayReadingFirst() else { return CPTCalendarFormatter() } let dateFormatter = DateFormatter() // e.g. "12/5/16" //dateFormatter.dateStyle = .short // e.g. "Dec 5, 2016" //dateFormatter.dateStyle = .medium // e.g. "12/05" let rangeScale = TrendViewController.rangeScale(range: range) let templateString = templateStringForRangeScale(rangeScale) let formatString = DateFormatter.dateFormat(fromTemplate: templateString, options:0, locale:NSLocale.current) dateFormatter.dateFormat = formatString let cptFormatter = CPTCalendarFormatter() cptFormatter.dateFormatter = dateFormatter cptFormatter.referenceDate = firstReading.timeStamp cptFormatter.referenceCalendarUnit = NSCalendar.Unit.minute return cptFormatter } class func rangeScale(range: CPTPlotRange?) -> RangeScale { guard let axisRange = range else { return .month } var scale: RangeScale = .month if axisRange.lengthDouble >= Double(MINUTES_IN_ONE_HOUR * HOURS_IN_ONE_DAY * DAYS_IN_ONE_WEEK * 8) { scale = .month } else if axisRange.lengthDouble >= Double(MINUTES_IN_ONE_HOUR * HOURS_IN_ONE_DAY * 4) { scale = .week } else if axisRange.lengthDouble >= Double(MINUTES_IN_ONE_HOUR * HOURS_IN_ONE_DAY * 2) { scale = .day } else { if UserDefaults.standard.bool(forKey: SETTING_MILITARY_TIME) { scale = .hour24 } else { scale = .hour } } return scale } /** - parameter rangeScale: a RangeScale - returns: a template string suitable for use by a date formatter */ func templateStringForRangeScale(_ rangeScale: RangeScale) -> String { var templateString = "MM/dd" switch rangeScale { case .month: templateString = "MM/dd" case .week: templateString = "MMM dd" case .day: templateString = "Md" case .hour24: templateString = "HH Md" case .hour: templateString = "hh a Md" } return templateString } func yLabelFormatter(trend: Trend) -> NumberFormatter { let formatter = NumberFormatter() switch trend { case .bg: if BGReading.shouldDisplayBgInMmolPerL() { formatter.minimumFractionDigits = 1 formatter.maximumFractionDigits = 1 } else { formatter.minimumFractionDigits = 0 formatter.maximumFractionDigits = 0 } case .ha1c: formatter.minimumFractionDigits = 1 formatter.maximumFractionDigits = 1 } return formatter } } // MARK: - CPTPlotDataSource extension TrendViewController: CPTPlotDataSource { /** @brief @required The number of data points for the plot. * @param plot The plot. * @return The number of data points for the plot. **/ func numberOfRecords(for plot: CPTPlot) -> UInt { guard let model: TrendsAlgorithmModel = trendsAlgorithmModel, let trendUnwrapped = trend else { return 0 } switch trendUnwrapped { case .bg: return UInt(model.bgArrayCount()) case .ha1c: //return UInt(model.ha1cArray.count) return UInt(model.ha1cArrayCount()) } } func number(for plot: CPTPlot, field: UInt, record: UInt) -> Any? { guard let model: TrendsAlgorithmModel = trendsAlgorithmModel, let trendUnwrapped = trend else { return nil } // plotField = CPTScatterPlotField(0) == .X // plotField = CPTScatterPlotField(1) == .Y let plotField = CPTScatterPlotField(rawValue: Int(field)) switch trendUnwrapped { case .bg: let reading = model.getFromBGArray(record) as BGReading let firstReading = model.bgArrayReadingFirst() if plotField == .X { guard let dateFirst = firstReading?.timeStamp else { return nil } let timeIntervalSeconds: TimeInterval = reading.timeStamp.timeIntervalSince(dateFirst) let timeIntervalMinutes: Double = timeIntervalSeconds / 60 return NSNumber(value: timeIntervalMinutes) } else if plotField == .Y { if BGReading.shouldDisplayBgInMmolPerL() { // display mmol/L return reading.quantity } else { // display mg/dL return MG_PER_DL_PER_MMOL_PER_L * reading.quantity.floatValue } } case .ha1c: let reading = model.getFromHa1cArray(record) as Ha1cReading let firstReading = model.ha1cArrayReadingFirst() if plotField == .X { guard let dateFirst = firstReading?.timeStamp else { return nil } let timeIntervalSeconds: TimeInterval = reading.timeStamp.timeIntervalSince(dateFirst) let timeIntervalMinutes: Double = timeIntervalSeconds / 60 return NSNumber(value: timeIntervalMinutes) } else if plotField == .Y { return reading.quantity } } return nil } } // MARK: - CPTAxisDelegate extension TrendViewController: CPTAxisDelegate { private func axis(_ axis: CPTAxis, shouldUpdateAxisLabelsAtLocations locations: NSSet!) -> Bool { if let formatter = axis.labelFormatter { let labelOffset = axis.labelOffset var newLabels = Set<CPTAxisLabel>() if let labelTextStyle = axis.labelTextStyle?.mutableCopy() as? CPTMutableTextStyle { for location in locations { if let tickLocation = location as? NSNumber { if tickLocation.doubleValue >= 0.0 { labelTextStyle.color = .green() } else { labelTextStyle.color = .red() } let labelString = formatter.string(for:tickLocation) let newLabelLayer = CPTTextLayer(text: labelString, style: labelTextStyle) let newLabel = CPTAxisLabel(contentLayer: newLabelLayer) newLabel.tickLocation = tickLocation newLabel.offset = labelOffset newLabels.insert(newLabel) } } axis.axisLabels = newLabels } } return false } } // MARK: - CPTPlotSpaceDelegate extension TrendViewController: CPTPlotSpaceDelegate { func plotSpace(_ space: CPTPlotSpace, willDisplaceBy: CGPoint) -> CGPoint { // translate horizontally but not vertically return CGPoint(x: 1.5 * willDisplaceBy.x, y: 0) } func plotSpace(_ space: CPTPlotSpace, willChangePlotRangeTo newRange: CPTPlotRange, for coordinate: CPTCoordinate) -> CPTPlotRange? { var range: CPTPlotRange = CPTMutablePlotRange(location: newRange.location, length:newRange.length) let axisSet: CPTXYAxisSet = space.graph!.axisSet as! CPTXYAxisSet if coordinate == CPTCoordinate.X { axisSet.yAxis?.orthogonalPosition = TrendViewController.yOrthogonalPosition(xRange: range) axisSet.xAxis?.labelFormatter = xLabelFormatter(range: range) if let xAxis = axisSet.xAxis { let rangeScale = TrendViewController.rangeScale(range: range) configureAxisIntervals(x: xAxis, rangeScale: rangeScale) } } else if (coordinate == CPTCoordinate.Y) && (trend != nil) { // keep original range, don't change to newRange range = TrendViewController.globalYRange(trend: trend!) } return range } }
mit
3196fb279c4d89df2cb9e59deaf08250
33.979798
121
0.604822
4.466466
false
false
false
false
ZackKingS/Tasks
task/Classes/LoginRegist/Controller/ZBRegistViewController.swift
1
3328
// // ZBRegistViewController.swift // task // // Created by 柏超曾 on 2017/9/26. // Copyright © 2017年 柏超曾. All rights reserved. // import Foundation import UIKit import SVProgressHUD import SwiftyJSON class ZBRegistViewController: UIViewController ,UITextFieldDelegate { @IBOutlet weak var phoneNumL: UITextField! @IBOutlet weak var smsTF: UITextField! @IBOutlet weak var nickTF: UITextField! @IBOutlet weak var nextBtn: UIButton! @IBOutlet weak var nextBottonCons: NSLayoutConstraint! var count = 1 override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) let image = UIImage.init(named: "tintColor") navigationController?.navigationBar.setBackgroundImage(image, for: .default) //会有黑线 } override func viewDidLoad() { super.viewDidLoad() setConfig() phoneNumL.delegate = self nickTF.delegate = self smsTF.delegate = self } func textFieldDidBeginEditing(_ textField: UITextField) { if count != 1 { return } if isIPhone6 { UIView.animate(withDuration: 0.3, animations: { self.nextBottonCons.constant = self.nextBottonCons.constant + 200 }) }else if isIPhone6P{ UIView.animate(withDuration: 0.3, animations: { self.nextBottonCons.constant = self.nextBottonCons.constant + 150 }) } count = count + 1 } @IBOutlet weak var sentSMS: UIButton! @IBAction func sentSMS(_ sender: CountDownBtn) { if phoneNumL.text!.characters.count < 10{ self.showHint(hint: "请输入手机号") return } // todo 手机号正则过滤 let str = API_GETSMS_URL + "?tel=\(phoneNumL.text!)&action=0" NetworkTool.getMesa( url: str ){ (result) in SVProgressHUD.showSuccess(withStatus: "") SVProgressHUD.dismiss(withDelay: TimeInterval.init(1)) print(result ?? "213") let json = result as! JSON let errorno = json["data"].stringValue if errorno != "20013"{ //没有注册的话 sender.startCountDown() } } } @IBAction func next(_ sender: Any) { let pwd = ZBSetPwdController() pwd.typecase = 1 pwd.phone = phoneNumL.text pwd.sms = smsTF.text pwd.nickName = nickTF.text navigationController?.pushViewController(pwd, animated: true) } func setConfig(){ navigationController?.navigationBar.titleTextAttributes = [ NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.systemFont(ofSize: 18) ] //UIFont(name: "Heiti SC", size: 24.0)! navigationItem.title = "注册"; nextBtn.layer.cornerRadius = kLcornerRadius nextBtn.layer.masksToBounds = true } }
apache-2.0
7030a512589e72847beb2cde317bd91f
23.17037
92
0.543059
4.943939
false
false
false
false
jkolb/Swiftish
Sources/Swiftish/Bounds2.swift
1
5991
/* The MIT License (MIT) Copyright (c) 2015-2017 Justin Kolb Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ public struct Bounds2<T: Vectorable> : Hashable { public var center: Vector2<T> public var extents: Vector2<T> public init() { self.init(center: Vector2<T>(), extents: Vector2<T>()) } public init(minimum: Vector2<T>, maximum: Vector2<T>) { precondition(minimum.x <= maximum.x) precondition(minimum.y <= maximum.y) let center = (maximum + minimum) / 2 let extents = (maximum - minimum) / 2 self.init(center: center, extents: extents) } public init(center: Vector2<T>, extents: Vector2<T>) { precondition(extents.x >= 0) precondition(extents.y >= 0) self.center = center self.extents = extents } public init(union: [Bounds2<T>]) { var minmax = [Vector2<T>]() for other in union { if !other.isNull { minmax.append(other.minimum) minmax.append(other.maximum) } } self.init(containingPoints: minmax) } public init(containingPoints points: [Vector2<T>]) { if points.count == 0 { self.init() return } var minimum = Vector2<T>(+T.greatestFiniteMagnitude, +T.greatestFiniteMagnitude) var maximum = Vector2<T>(-T.greatestFiniteMagnitude, -T.greatestFiniteMagnitude) for point in points { if point.x < minimum.x { minimum.x = point.x } if point.x > maximum.x { maximum.x = point.x } if point.y < minimum.y { minimum.y = point.y } if point.y > maximum.y { maximum.y = point.y } } self.init(minimum: minimum, maximum: maximum) } public var minimum: Vector2<T> { return center - extents } public var maximum: Vector2<T> { return center + extents } public var isNull: Bool { return center == Vector2<T>() && extents == Vector2<T>() } public func contains(point: Vector2<T>) -> Bool { if point.x < minimum.x { return false } if point.y < minimum.y { return false } if point.x > maximum.x { return false } if point.y > maximum.y { return false } return true } /// If `other` bounds intersects current bounds, return their intersection. /// A `null` Bounds2 object is returned if any of those are `null` or if they don't intersect at all. /// /// - Note: A Bounds2 object `isNull` if it's center and extents are zero. /// - Parameter other: The second Bounds2 object to intersect with. /// - Returns: A Bounds2 object intersection. public func intersection(other: Bounds2<T>) -> Bounds2<T> { if isNull { return self } else if other.isNull { return other } else if minimum.x <= other.maximum.x && other.minimum.x <= maximum.x && maximum.y <= other.minimum.y && other.maximum.y <= minimum.y { let minX = max(minimum.x, other.minimum.x) let minY = max(minimum.y, other.minimum.y) let maxX = min(maximum.x, other.maximum.x) let maxY = min(maximum.y, other.maximum.y) return Bounds2<T>(minimum: Vector2<T>(minX, minY), maximum: Vector2<T>(maxX, maxY)) } return Bounds2<T>() } public func union(other: Bounds2<T>) -> Bounds2<T> { if isNull { return other } else if other.isNull { return self } else { return Bounds2<T>(containingPoints: [minimum, maximum, other.minimum, other.maximum]) } } public func union(others: [Bounds2<T>]) -> Bounds2<T> { var minmax = [Vector2<T>]() if !isNull { minmax.append(minimum) minmax.append(maximum) } for other in others { if !other.isNull { minmax.append(other.minimum) minmax.append(other.maximum) } } if minmax.count == 0 { return self } else { return Bounds2<T>(containingPoints: minmax) } } public var description: String { return "{\(center), \(extents)}" } public var corners: [Vector2<T>] { let max: Vector2<T> = maximum let corner0: Vector2<T> = max * Vector2<T>(+1, +1) let corner1: Vector2<T> = max * Vector2<T>(+1, -1) let corner2: Vector2<T> = max * Vector2<T>(-1, +1) let corner3: Vector2<T> = max * Vector2<T>(-1, -1) return [corner0, corner1, corner2, corner3] } }
mit
b53ee9e02bd4a35c253d7cb32e25d771
31.383784
111
0.566683
4.146021
false
false
false
false
biohazardlover/ByTrain
ByTrain/Entities/TicketType.swift
1
884
import Foundation public let TicketTypeIdentifierAdult = "AdultTicket" public let TicketTypeIdentifierChild = "ChildTicket" public let TicketTypeIdentifierStudent = "StudentTicket" public let TicketTypeIdentifierDisabledOrMilitary = "DisabledOrMilitaryTicket" public let sTicketTypeDescriptions = [ TicketTypeIdentifierAdult: "成人票", TicketTypeIdentifierChild: "儿童票", TicketTypeIdentifierStudent: "学生票", TicketTypeIdentifierDisabledOrMilitary: "残军票" ] public class TicketType: NSObject { public private(set) var identifier: String? public private(set) var ticketTypeDescription: String? public var ticketTypeName: String? public convenience init(identifier: String) { self.init() self.identifier = identifier ticketTypeDescription = sTicketTypeDescriptions[identifier] } }
mit
3aebe96bbbc443b5e43250d9dbef4e24
28.655172
78
0.752326
4.550265
false
false
false
false
pman215/ONH305
Sources/ONH305SvrLib/Mailer.swift
1
1752
#if os(Linux) import LinuxBridge import Dispatch #else import Darwin import Foundation #endif import Foundation import PerfectLogger import PerfectSMTP class ContactMailer { let mailQueue = DispatchQueue(label: "com.onh305.mailqueue") let client = SMTPClient(url: "smtps://smtp.gmail.com", username: "yourusername", password:"yourpassword") let recepient = Recipient(name: "yourusername", address: "youremail") func emailLead(contactInfo: [(String,String)]) { var _contactInfo = [String : String]() contactInfo.forEach { _contactInfo[$0.0] = $0.1 } let nameValue = _contactInfo["name"] ?? "Empty name" let emailValue = _contactInfo["email"] ?? "Empty email" let phoneValue = _contactInfo["phone"] ?? "Empty phone" let dateValue = _contactInfo["date"] ?? "Empty date" let timeValue = _contactInfo["time"] ?? "Empty time" let commentsValue = _contactInfo["comments"] ?? "Empty comments" var email = EMail(client: client) email.from = recepient email.to.append(email.from) email.subject = "\(nameValue) - New Lead" email.content = "<ul><li>Name: \(nameValue)</li>" + "<li>Email: \(emailValue)</li>" + "<li>Phone: \(phoneValue)</li>" + "<li>Date:\(dateValue)</li>" + "<li>Time:\(timeValue)</li>" + "<li>Comments:\(commentsValue)</li></ul>" mailQueue.async { do { LogFile.debug("Sending email") try email.send { code, header, body in LogFile.debug("Email response code: \(code)") LogFile.debug("Email response header: \(header)") LogFile.debug("Email sent with body: \(body)") } }catch(let err) { LogFile.error("Failed to send email with error \(err)") LogFile.error("Failed to send email for new lead") } } } }
apache-2.0
54f00f6c24e0a3ad0be6b72b00a13614
26.375
70
0.651256
3.26257
false
false
false
false
jjochen/JJFloatingActionButton
Example/Tests/JJFloatingActionButtonPlacementSpec.swift
1
2167
// // JJFloatingActionButtonPlacementSpecs.swift // // Copyright (c) 2017-Present Jochen Pfeiffer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation @testable import JJFloatingActionButton import Nimble import Nimble_Snapshots import Quick class JJFloatingActionButtonPlacementSpec: QuickSpec { override func spec() { describe("JJFloatingActionButton") { var actionButton: JJFloatingActionButton! var viewController: UIViewController! beforeEach { viewController = UIViewController() let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = viewController window.makeKeyAndVisible() viewController.view.backgroundColor = .white actionButton = JJFloatingActionButton() } it("looks correct when placed in view controller") { actionButton.display(inViewController: viewController) expect(viewController.view).to(haveValidDeviceAgnosticSnapshot()) } } } }
mit
569d6a52a3b86925f3e291e7e2f742b6
38.4
81
0.702353
5.159524
false
false
false
false
CryptoKitten/CryptoEssentials
Sources/Random.swift
1
2312
#if os(Linux) import Glibc #else import Darwin #endif public func generateNumber(between first: Int32, and second: Int32) -> Int32 { var low : Int32 var high : Int32 if first <= second { low = first high = second } else { low = second high = first } let modular = UInt32((high - low) + 1) #if os(Linux) let random = UInt32(bitPattern: rand()) #else let random = arc4random() #endif return Int32(random % modular) + low } public func generateNumberSequenceBetween(_ first: Int32, and second: Int32, ofLength length: Int, withUniqueValues unique: Bool) -> [Int32] { if length < 1 { return [Int32]() } var sequence : [Int32] = [Int32](repeating: 0, count: length) if unique { if (first <= second && (length > (second - first) + 1)) || (first > second && (length > (first - second) + 1)) { return [Int32]() } var loop : Int = 0 while loop < length { let number = generateNumber(between: first, and: second) // If the number is unique, add it to the sequence if !isNumber(number: number, inSequence: sequence, ofLength: loop) { sequence[loop] = number loop += 1 } } } else { // Repetitive values are allowed for i in 0..<length { sequence[i] = generateNumber(between: first, and: second) } } return sequence } public func generateRandomSignedData(length: Int) -> [Int8] { guard length >= 1 else { return [] } var sequence = generateNumberSequenceBetween(-128, and: 127, ofLength: length, withUniqueValues: false) var randomData : [Int8] = [Int8](repeating: 0, count: length) for i in 0 ..< length { randomData[i] = Int8(sequence[i]) } return randomData } public func isNumber(number: Int32, inSequence sequence: [Int32], ofLength length: Int) -> Bool { if length < 1 || length > sequence.count { return false } for i in 0 ..< length where sequence[i] == number { return true } // The number was not found, return false return false }
mit
3d6ee489b8a498db3688d6901441c7b4
24.977528
142
0.551038
4.027875
false
false
false
false
apatronl/Left
Left/View Controller/FavoritesCollectionView.swift
1
6121
// // FavoritesCollectionView.swift // Left // // Created by Alejandrina Patron on 8/3/16. // Copyright © 2016 Ale Patrón. All rights reserved. // import Foundation import SwiftyDrop class FavoritesCollectionView: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIViewControllerPreviewingDelegate, UITabBarControllerDelegate { @IBOutlet var collectionView: UICollectionView! let favoritesManager = FavoritesManager.shared override func viewDidLoad() { super.viewDidLoad() // collectionView.register(UINib(nibName: "LFTReviewCollectionCell", bundle: nil), forCellWithReuseIdentifier: "LFTReviewCollectionCell") // self.tabBarController?.delegate = self if (traitCollection.forceTouchCapability == .available) { registerForPreviewing(with: self, sourceView: self.collectionView) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) collectionView.reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tabBarController?.tabBar.isHidden = false } // MARK: Collection View Delegate func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return favoritesManager.recipeCount() } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // let index = indexPath.row // if index == favoritesManager.recipeCount() { // let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LFTReviewCollectionCell", for: indexPath) // return cell // } let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RecipeCell", for: indexPath as IndexPath) as! RecipeCollectionCell let recipe = favoritesManager.recipeAtIndex(index: indexPath.row) cell.recipe = recipe // Handle delete button action cell.actionButton?.layer.setValue(indexPath.row, forKey: "index") cell.actionButton.addTarget(self, action: #selector(FavoritesCollectionView.deleteRecipe), for: UIControlEvents.touchUpInside) // Handle label tap action let labelTap = UITapGestureRecognizer(target: self, action: #selector(FavoritesCollectionView.openRecipeUrl)) labelTap.numberOfTapsRequired = 1 cell.recipeName.addGestureRecognizer(labelTap) // Handle photo tap action let photoTap = UITapGestureRecognizer(target: self, action: #selector(FavoritesCollectionView.openRecipeUrl)) photoTap.numberOfTapsRequired = 1 cell.recipePhoto.addGestureRecognizer(photoTap) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { var height = (UIScreen.main.bounds.width / 2) - 15 if height > 250 { height = (UIScreen.main.bounds.width / 3) - 15 } return CGSize(width: height, height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 10 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 10 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(10, 10, 10, 10) } // MARK: UIViewControllerPreviewingDelegate func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = collectionView.indexPathForItem(at: location) else { return nil } guard let cell = collectionView.cellForItem(at: indexPath) as? RecipeCollectionCell else { return nil } guard let webView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "RecipeWebView") as? RecipeWebView else { return nil } webView.recipe = cell.recipe webView.preferredContentSize = CGSize(width: 0.0, height: self.view.frame.height * 0.8) let cellAttributes = collectionView.layoutAttributesForItem(at: indexPath) previewingContext.sourceRect = cellAttributes?.frame ?? cell.frame return webView } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { show(viewControllerToCommit, sender: self) } // MARK: Helper func deleteRecipe(sender: UIButton) { let index: Int = (sender.layer.value(forKey: "index")) as! Int if let recipe = favoritesManager.recipeAtIndex(index: index) { recipe.removeFromDefaults(index: index) } favoritesManager.deleteRecipeAtIndex(index: index) collectionView.reloadData() Drop.down("Recipe removed from your favorites", state: Custom.Left) // Haptic feedback (available iOS 10+) if #available(iOS 10.0, *) { let savedRecipeFeedbackGenerator = UIImpactFeedbackGenerator(style: .heavy) savedRecipeFeedbackGenerator.impactOccurred() } } func openRecipeUrl(sender: UITapGestureRecognizer) { let cell = sender.view?.superview?.superview as! RecipeCollectionCell let webView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "RecipeWebView") as! RecipeWebView webView.recipe = cell.recipe self.navigationController?.pushViewController(webView, animated: true) } }
mit
962f304408472e627d2eeb6f352a287b
41.79021
177
0.696682
5.613761
false
false
false
false
nsriram/No-Food-Waste
ios/NoFoodWaster/NoFoodWaster/AvailableDonationsController.swift
1
3538
// // AvailableDonationsController.swift // NoFoodWaste // // Created by Ravi Shankar on 29/11/15. // Copyright © 2015 Ravi Shankar. All rights reserved. // import UIKit class AvailableDonationsController: UIViewController { let cellIdentifier = "availableDonationsCell" @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var tableView: UITableView! var donates = [Donate]() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self navigationItem.title = "Available Dontations" descriptionLabel.backgroundColor = backgroundColor view.backgroundColor = backgroundColor resetChecks() let serviceMgr = ServiceManager() serviceMgr.delegate = self serviceMgr.getDonateList() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableViewStyle(cell: UITableViewCell) { cell.contentView.backgroundColor = backgroundColor cell.backgroundColor = backgroundColor cell.textLabel?.font = UIFont(name: "HelveticaNeue-Medium", size: 15) cell.textLabel?.textColor = textColor cell.textLabel?.backgroundColor = backgroundColor cell.textLabel?.numberOfLines = 2 cell.detailTextLabel?.font = UIFont.boldSystemFontOfSize(15) cell.detailTextLabel?.textColor = UIColor.grayColor() cell.detailTextLabel?.backgroundColor = backgroundColor } } extension AvailableDonationsController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return donates.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) let donate = donates[indexPath.row] cell.textLabel?.text = donate.address cell.detailTextLabel?.text = "\(8 + indexPath.row)\" Kms from Current Location" tableViewStyle(cell) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let cell = tableView.cellForRowAtIndexPath(indexPath) { resetChecks() if cell.accessoryType == .Checkmark { cell.accessoryType = .None } else { cell.accessoryType = .Checkmark } } } func resetChecks() { if donates.count > 0 { for i in 0...tableView.numberOfSections-1 { for j in 0...tableView.numberOfRowsInSection(i)-1 { if let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i)) { cell.accessoryType = .None } } } } } } extension AvailableDonationsController: DonateDelegate { func downloadDonateComplete(donate: Donate) { dispatch_async(dispatch_get_main_queue()) { () -> Void in self.donates.append(donate) self.tableView.reloadData() } } }
apache-2.0
ea2cf0609030f17fc2b223601d979a44
28.974576
109
0.609839
5.587678
false
false
false
false
davidrauch/mds
mds/Processing/Document.swift
1
889
import Foundation // The Document class Document { // The text of the document, one line per item let text: [String] // The structure of the document let headers: [Header] /** Initializes a new Document with a given text - Parameters: - withText: The text of the document - Returns: A Document object */ init(withText: String) { // Store the text self.text = withText.components(separatedBy: "\n") // Process the document and store the structure let lexer = Lexer(input: withText) let tokens = lexer.tokenize() let parser = Parser(tokens: tokens) self.headers = parser.parse() } /** Returns a header at a given index - Parameters: - atIndex: The index of the header, e.g. 0 for the first header - Returns: The header at the given index */ func getHeader(atIndex: Int) -> Header? { return self.headers[safe: atIndex] } }
mit
4ee68e0eefa43c534bed1dc2d9299d65
19.674419
66
0.673791
3.513834
false
false
false
false
ytakzk/Fusuma
Sources/FSImageCropView.swift
1
3511
// // FZImageCropView.swift // Fusuma // // Created by Yuta Akizuki on 2015/11/16. // Copyright © 2015年 ytakzk. All rights reserved. // import UIKit final class FSImageCropView: UIScrollView, UIScrollViewDelegate { var imageView = UIImageView() var imageSize: CGSize? var image: UIImage! = nil { didSet { guard image != nil else { imageView.image = nil return } if !imageView.isDescendant(of: self) { imageView.alpha = 1.0 addSubview(imageView) } guard fusumaCropImage else { imageView.frame = frame imageView.contentMode = .scaleAspectFit isUserInteractionEnabled = false imageView.image = image return } let imageSize = self.imageSize ?? image.size let ratioW = frame.width / imageSize.width // 400 / 1000 => 0.4 let ratioH = frame.height / imageSize.height // 300 / 500 => 0.6 if ratioH > ratioW { imageView.frame = CGRect( origin: CGPoint.zero, size: CGSize(width: imageSize.width * ratioH, height: frame.height) ) } else { imageView.frame = CGRect( origin: CGPoint.zero, size: CGSize(width: frame.width, height: imageSize.height * ratioW) ) } contentOffset = CGPoint( x: imageView.center.x - center.x, y: imageView.center.y - center.y ) contentSize = CGSize(width: imageView.frame.width + 1, height: imageView.frame.height + 1) imageView.image = image zoomScale = 1.0 } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! backgroundColor = fusumaBackgroundColor frame.size = CGSize.zero clipsToBounds = true imageView.alpha = 0.0 imageView.frame = CGRect(origin: CGPoint.zero, size: CGSize.zero) maximumZoomScale = 2.0 minimumZoomScale = 0.8 showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false bouncesZoom = true bounces = true scrollsToTop = false delegate = self } func changeScrollable(_ isScrollable: Bool) { isScrollEnabled = isScrollable } // MARK: UIScrollViewDelegate Protocol func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { let boundsSize = scrollView.bounds.size var contentsFrame = imageView.frame if contentsFrame.size.width < boundsSize.width { contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0 } else { contentsFrame.origin.x = 0.0 } if contentsFrame.size.height < boundsSize.height { contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0 } else { contentsFrame.origin.y = 0.0 } imageView.frame = contentsFrame } func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) { contentSize = CGSize(width: imageView.frame.width + 1, height: imageView.frame.height + 1) } }
mit
99fb230ca10adf70c915cb3c0b8c8a94
28.982906
106
0.56699
4.990043
false
false
false
false
ALiOSDev/ALTableView
ALTableViewSwift/TestALTableView/TestALTableView/Master/MasterHeaderFooter.swift
1
1060
// // MasterHeaderFooter.swift // ALTableView // // Created by lorenzo villarroel perez on 22/3/18. // Copyright © 2018 lorenzo villarroel perez. All rights reserved. // import UIKit import ALTableView class MasterHeaderFooter: UITableViewHeaderFooterView, ALHeaderFooterProtocol { static let nib = "MasterHeaderFooter" static let reuseIdentifier = "MasterHeaderFooterReuseIdentifier" @IBOutlet weak var labelText: UILabel! /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ func viewCreated(dataObject: Any?) { if let title: String = dataObject as? String { self.labelText.text = title } if #available(iOS 10.0, *) { self.contentView.backgroundColor = .green } else { self.backgroundView = UIView() self.backgroundView?.backgroundColor = .green } } }
mit
0a5cc5279fd4de0836f9498526e4fdfc
26.153846
79
0.646837
4.604348
false
false
false
false
grandiere/box
box/Firebase/Database/Model/FDbUser.swift
1
880
import Foundation class FDbUser:FDbProtocol { let items:[String:FDbUserItem] required init?(snapshot:Any) { var items:[String:FDbUserItem] = [:] if let snapshotDict:[String:Any] = snapshot as? [String:Any] { let snapshotKeys:[String] = Array(snapshotDict.keys) for userId:String in snapshotKeys { guard let snapshotUser:Any = snapshotDict[userId], let userItem:FDbUserItem = FDbUserItem(snapshot:snapshotUser) else { continue } items[userId] = userItem } } self.items = items } func json() -> Any? { return nil } }
mit
5d4d2daf2b8469754996f7b4cd2d854e
22.157895
81
0.439773
5.333333
false
false
false
false
gribozavr/swift
test/IRGen/big_types_corner_cases.swift
1
18035
// XFAIL: CPU=powerpc64le // XFAIL: CPU=s390x // RUN: %target-swift-frontend -enable-large-loadable-types %s -emit-ir | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize // REQUIRES: optimized_stdlib // UNSUPPORTED: CPU=powerpc64le public struct BigStruct { var i0 : Int32 = 0 var i1 : Int32 = 1 var i2 : Int32 = 2 var i3 : Int32 = 3 var i4 : Int32 = 4 var i5 : Int32 = 5 var i6 : Int32 = 6 var i7 : Int32 = 7 var i8 : Int32 = 8 } func takeClosure(execute block: () -> Void) { } class OptionalInoutFuncType { private var lp : BigStruct? private var _handler : ((BigStruct?, Error?) -> ())? func execute(_ error: Error?) { var p : BigStruct? var handler: ((BigStruct?, Error?) -> ())? takeClosure { p = self.lp handler = self._handler self._handler = nil } handler?(p, error) } } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} i32 @main(i32, i8**) // CHECK: call void @llvm.lifetime.start // CHECK: call void @llvm.memcpy // CHECK: call void @llvm.lifetime.end // CHECK: ret i32 0 let bigStructGlobalArray : [BigStruct] = [ BigStruct() ] // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal swiftcc void @"$s22big_types_corner_cases21OptionalInoutFuncTypeC7executeyys5Error_pSgFyyXEfU_"(%T22big_types_corner_cases9BigStructVSg* nocapture dereferenceable({{.*}}), %T22big_types_corner_cases21OptionalInoutFuncTypeC*, %T22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_Sg* nocapture dereferenceable({{.*}}) // CHECK: call void @"$s22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_SgWOe // CHECK: call void @"$s22big_types_corner_cases9BigStructVSgs5Error_pSgIegcg_SgWOy // CHECK: ret void public func f1_returns_BigType(_ x: BigStruct) -> BigStruct { return x } public func f2_returns_f1() -> (_ x: BigStruct) -> BigStruct { return f1_returns_BigType } public func f3_uses_f2() { let x = BigStruct() let useOfF2 = f2_returns_f1() let _ = useOfF2(x) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10f3_uses_f2yyF"() // CHECK: call swiftcc void @"$s22big_types_corner_cases9BigStructVACycfC"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret // CHECK: call swiftcc { i8*, %swift.refcounted* } @"$s22big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF"() // CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK: ret void public func f4_tuple_use_of_f2() { let x = BigStruct() let tupleWithFunc = (f2_returns_f1(), x) let useOfF2 = tupleWithFunc.0 let _ = useOfF2(x) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18f4_tuple_use_of_f2yyF"() // CHECK: [[TUPLE:%.*]] = call swiftcc { i8*, %swift.refcounted* } @"$s22big_types_corner_cases13f2_returns_f1AA9BigStructVADcyF"() // CHECK: [[TUPLE_EXTRACT:%.*]] = extractvalue { i8*, %swift.refcounted* } [[TUPLE]], 0 // CHECK: [[CAST_EXTRACT:%.*]] = bitcast i8* [[TUPLE_EXTRACT]] to void (%T22big_types_corner_cases9BigStructV*, %T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[CAST_EXTRACT]](%T22big_types_corner_cases9BigStructV* noalias nocapture sret {{.*}}, %T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) {{.*}}, %swift.refcounted* swiftself %{{.*}}) // CHECK: ret void public class BigClass { public init() { } public var optVar: ((BigStruct)-> Void)? = nil func useBigStruct(bigStruct: BigStruct) { optVar!(bigStruct) } } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases8BigClassC03useE6Struct0aH0yAA0eH0V_tF"(%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}), %T22big_types_corner_cases8BigClassC* swiftself) // CHECK: [[BITCAST:%.*]] = bitcast i8* {{.*}} to void (%T22big_types_corner_cases9BigStructV*, %swift.refcounted*)* // CHECK: call swiftcc void [[BITCAST]](%T22big_types_corner_cases9BigStructV* noalias nocapture dereferenceable({{.*}}) %0, %swift.refcounted* swiftself // CHECK: ret void public struct MyStruct { public let a: Int public let b: String? } typealias UploadFunction = ((MyStruct, Int?) -> Void) -> Void func takesUploader(_ u: UploadFunction) { } class Foo { func blam() { takesUploader(self.myMethod) // crash compiling this } func myMethod(_ callback: (MyStruct, Int) -> Void) -> Void { } } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} linkonce_odr hidden swiftcc { i8*, %swift.refcounted* } @"$s22big_types_corner_cases3FooC8myMethodyyyAA8MyStructV_SitXEFTc"(%T22big_types_corner_cases3FooC*) // CHECK: getelementptr inbounds %T22big_types_corner_cases3FooC, %T22big_types_corner_cases3FooC* // CHECK: getelementptr inbounds void (i8*, %swift.opaque*, %T22big_types_corner_cases3FooC*)*, void (i8*, %swift.opaque*, %T22big_types_corner_cases3FooC*)** // CHECK: call noalias %swift.refcounted* @swift_allocObject(%swift.type* getelementptr inbounds (%swift.full_boxmetadata, %swift.full_boxmetadata* // CHECK: ret { i8*, %swift.refcounted* } public enum LargeEnum { public enum InnerEnum { case simple(Int64) case hard(Int64, String?, Int64) } case Empty1 case Empty2 case Full(InnerEnum) } public func enumCallee(_ x: LargeEnum) { switch x { case .Full(let inner): print(inner) case .Empty1: break case .Empty2: break } } // CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10enumCalleeyAA9LargeEnumOF"(%T22big_types_corner_cases9LargeEnumO* noalias nocapture dereferenceable({{.*}})) #0 { // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO05InnerF0O // CHECK-64: alloca %T22big_types_corner_cases9LargeEnumO // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: call void @llvm.memcpy.p0i8.p0i8.i64 // CHECK-64: $ss5print_9separator10terminatoryypd_S2StF // CHECK-64: ret void // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} internal swiftcc void @"$s22big_types_corner_cases8SuperSubC1fyyFAA9BigStructVycfU_"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret, %T22big_types_corner_cases8SuperSubC*) // CHECK-64: [[ALLOC1:%.*]] = alloca %T22big_types_corner_cases9BigStructV // CHECK-64: [[ALLOC2:%.*]] = alloca %T22big_types_corner_cases9BigStructV // CHECK-64: [[ALLOC3:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg // CHECK-64: call swiftcc void @"$s22big_types_corner_cases9SuperBaseC4boomAA9BigStructVyF"(%T22big_types_corner_cases9BigStructV* noalias nocapture sret [[ALLOC1]], %T22big_types_corner_cases9SuperBaseC* swiftself {{.*}}) // CHECK: ret void class SuperBase { func boom() -> BigStruct { return BigStruct() } } class SuperSub : SuperBase { override func boom() -> BigStruct { return BigStruct() } func f() { let _ = { nil ?? super.boom() } } } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases10MUseStructV16superclassMirrorAA03BigF0VSgvg"(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret, %T22big_types_corner_cases10MUseStructV* noalias nocapture swiftself dereferenceable({{.*}})) // CHECK: [[ALLOC:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg // CHECK: [[LOAD:%.*]] = load %swift.refcounted*, %swift.refcounted** %.callInternalLet.data // CHECK: call swiftcc void %7(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret [[ALLOC]], %swift.refcounted* swiftself [[LOAD]]) // CHECK: ret void public struct MUseStruct { var x = BigStruct() public var superclassMirror: BigStruct? { return callInternalLet() } internal let callInternalLet: () -> BigStruct? } // CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18stringAndSubstringSS_s0G0VtyF"(<{ %TSS, %Ts9SubstringV }>* noalias nocapture sret) #0 { // CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases18stringAndSubstringSS_s0G0VtyF"(<{ %TSS, [4 x i8], %Ts9SubstringV }>* noalias nocapture sret) #0 { // CHECK: alloca %TSs // CHECK: alloca %TSs // CHECK: ret void public func stringAndSubstring() -> (String, Substring) { let s = "Hello, World" let a = Substring(s).dropFirst() return (s, a) } func bigStructGet() -> BigStruct { return BigStruct() } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases11testGetFuncyyF"() // CHECK: ret void public func testGetFunc() { let testGetPtr: @convention(thin) () -> BigStruct = bigStructGet } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases7TestBigC4testyyF"(%T22big_types_corner_cases7TestBigC* swiftself) // CHECK: [[CALL1:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$sSayy22big_types_corner_cases9BigStructVcSgGMD" // CHECK: [[CALL2:%.*]] = call i8** @"$sSayy22big_types_corner_cases9BigStructVcSgGSayxGSlsWl // CHECK: call swiftcc void @"$sSlsE10firstIndex5where0B0QzSgSb7ElementQzKXE_tKF"(%TSq.{{.*}}* noalias nocapture sret {{.*}}, i8* bitcast (i1 (%T22big_types_corner_cases9BigStructVytIegnr_Sg*, %swift.refcounted*, %swift.error**)* @"$s22big_types_corner_cases9BigStructVIegy_SgSbs5Error_pIggdzo_ACytIegnr_SgSbsAE_pIegndzo_TRTA" to i8*), %swift.opaque* {{.*}}, %swift.type* [[CALL1]], i8** [[CALL2]], %swift.opaque* noalias nocapture swiftself // CHECK: ret void // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases7TestBigC5test2yyF"(%T22big_types_corner_cases7TestBigC* swiftself) // CHECK: [[CALL1:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$sSaySS2ID_y22big_types_corner_cases9BigStructVcSg7handlertGMD" // CHECK: [[CALL2:%.*]] = call i8** @"$sSaySS2ID_y22big_types_corner_cases9BigStructVcSg7handlertGSayxGSlsWl" // CHECK: call swiftcc void @"$sSlss16IndexingIteratorVyxG0B0RtzrlE04makeB0ACyF"(%Ts16IndexingIteratorV{{.*}}* noalias nocapture sret {{.*}}, %swift.type* [[CALL1]], i8** [[CALL2]], %swift.opaque* noalias nocapture swiftself {{.*}}) // CHECK: ret void class TestBig { typealias Handler = (BigStruct) -> Void func test() { let arr = [Handler?]() let d = arr.firstIndex(where: { _ in true }) } func test2() { let arr: [(ID: String, handler: Handler?)] = [] for (_, handler) in arr { takeClosure { handler?(BigStruct()) } } } } struct BigStructWithFunc { var incSize : BigStruct var foo: ((BigStruct) -> Void)? } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s22big_types_corner_cases20UseBigStructWithFuncC5crashyyF"(%T22big_types_corner_cases20UseBigStructWithFuncC* swiftself) // CHECK: call swiftcc void @"$s22big_types_corner_cases20UseBigStructWithFuncC10callMethod // CHECK: ret void class UseBigStructWithFunc { var optBigStructWithFunc: BigStructWithFunc? func crash() { guard let bigStr = optBigStructWithFunc else { return } callMethod(ptr: bigStr.foo) } private func callMethod(ptr: ((BigStruct) -> Void)?) -> () { } } struct BiggerString { var str: String var double: Double } struct LoadableStructWithBiggerString { public var a1: BiggerString public var a2: [String] public var a3: [String] } class ClassWithLoadableStructWithBiggerString { public func f() -> LoadableStructWithBiggerString { return LoadableStructWithBiggerString(a1: BiggerString(str:"", double:0.0), a2: [], a3: []) } } //===----------------------------------------------------------------------===// // SR-8076 //===----------------------------------------------------------------------===// public typealias sr8076_Filter = (BigStruct) -> Bool public protocol sr8076_Query { associatedtype Returned } public protocol sr8076_ProtoQueryHandler { func forceHandle_1<Q: sr8076_Query>(query: Q) -> Void func forceHandle_2<Q: sr8076_Query>(query: Q) -> (Q.Returned, BigStruct?) func forceHandle_3<Q: sr8076_Query>(query: Q) -> (Q.Returned, sr8076_Filter?) func forceHandle_4<Q: sr8076_Query>(query: Q) throws -> (Q.Returned, sr8076_Filter?) } public protocol sr8076_QueryHandler: sr8076_ProtoQueryHandler { associatedtype Handled: sr8076_Query func handle_1(query: Handled) -> Void func handle_2(query: Handled) -> (Handled.Returned, BigStruct?) func handle_3(query: Handled) -> (Handled.Returned, sr8076_Filter?) func handle_4(query: Handled) throws -> (Handled.Returned, sr8076_Filter?) } public extension sr8076_QueryHandler { // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_15queryyqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself) // CHECK: call swiftcc void {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK: ret void func forceHandle_1<Q: sr8076_Query>(query: Q) -> Void { guard let body = handle_1 as? (Q) -> Void else { fatalError("handler \(self) is expected to handle query \(query)") } body(query) } // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_25query8ReturnedQyd___AA9BigStructVSgtqd___tAA0e1_F0Rd__lF"(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself) // CHECK: [[ALLOC:%.*]] = alloca %T22big_types_corner_cases9BigStructVSg // CHECK: call swiftcc void {{.*}}(%T22big_types_corner_cases9BigStructVSg* noalias nocapture sret [[ALLOC]], %swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK: ret void func forceHandle_2<Q: sr8076_Query>(query: Q) -> (Q.Returned, BigStruct?) { guard let body = handle_2 as? (Q) -> (Q.Returned, BigStruct?) else { fatalError("handler \(self) is expected to handle query \(query)") } return body(query) } // CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc { i64, i64 } @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_35query8ReturnedQyd___SbAA9BigStructVcSgtqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself) // CHECK-64: {{.*}} = call swiftcc { i64, i64 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK-64: ret { i64, i64 } // CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc { i32, i32} @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_35query8ReturnedQyd___SbAA9BigStructVcSgtqd___tAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself) // CHECK-32: {{.*}} = call swiftcc { i32, i32 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}) // CHECK-32: ret { i32, i32 } func forceHandle_3<Q: sr8076_Query>(query: Q) -> (Q.Returned, sr8076_Filter?) { guard let body = handle_3 as? (Q) -> (Q.Returned, sr8076_Filter?) else { fatalError("handler \(self) is expected to handle query \(query)") } return body(query) } // CHECK-LABEL-64: define{{( dllexport)?}}{{( protected)?}} swiftcc { i64, i64 } @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_45query8ReturnedQyd___SbAA9BigStructVcSgtqd___tKAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself, %swift.error** swifterror) // CHECK-64: {{.*}} = call swiftcc { i64, i64 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}, %swift.error** noalias nocapture swifterror {{.*}}) // CHECK-64: ret { i64, i64 } // CHECK-LABEL-32: define{{( dllexport)?}}{{( protected)?}} swiftcc { i32, i32} @"$s22big_types_corner_cases19sr8076_QueryHandlerPAAE13forceHandle_45query8ReturnedQyd___SbAA9BigStructVcSgtqd___tKAA0e1_F0Rd__lF"(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type*{{.*}}, %swift.type*{{.*}}, i8** {{.*}}.sr8076_QueryHandler, i8** {{.*}}.sr8076_Query, %swift.opaque* noalias nocapture swiftself, %swift.error** swifterror) // CHECK-32: {{.*}} = call swiftcc { i32, i32 } {{.*}}(%swift.opaque* noalias nocapture {{.*}}, %swift.opaque* noalias nocapture {{.*}}, %swift.refcounted* swiftself {{.*}}, %swift.error** noalias nocapture {{.*}}) // CHECK-32: ret { i32, i32 } func forceHandle_4<Q: sr8076_Query>(query: Q) throws -> (Q.Returned, sr8076_Filter?) { guard let body = handle_4 as? (Q) throws -> (Q.Returned, sr8076_Filter?) else { fatalError("handler \(self) is expected to handle query \(query)") } return try body(query) } } public func foo() -> Optional<(a: Int?, b: Bool, c: (Int?)->BigStruct?)> { return nil } public func dontAssert() { let _ = foo() }
apache-2.0
40251200c8b9d7e5b4d198e8f2573424
49.377095
472
0.679789
3.477632
false
false
false
false
qutheory/fluent
Sources/Fluent/Fluent+Pagination.swift
2
1581
import FluentKit import Vapor struct RequestPaginationKey: StorageKey { typealias Value = RequestPagination } struct RequestPagination { let pageSizeLimit: PageLimit? } struct AppPaginationKey: StorageKey { typealias Value = AppPagination } struct AppPagination { let pageSizeLimit: Int? } extension Request.Fluent { public var pagination: Pagination { .init(fluent: self) } public struct Pagination { let fluent: Request.Fluent } } extension Request.Fluent.Pagination { /// The maximum amount of elements per page. The default is `nil`. public var pageSizeLimit: PageLimit? { get { storage[RequestPaginationKey.self]?.pageSizeLimit } nonmutating set { storage[RequestPaginationKey.self] = .init(pageSizeLimit: newValue) } } var storage: Storage { get { self.fluent.request.storage } nonmutating set { self.fluent.request.storage = newValue } } } extension Application.Fluent.Pagination { /// The maximum amount of elements per page. The default is `nil`. public var pageSizeLimit: Int? { get { storage[AppPaginationKey.self]?.pageSizeLimit } nonmutating set { storage[AppPaginationKey.self] = .init(pageSizeLimit: newValue) } } var storage: Storage { get { self.fluent.application.storage } nonmutating set { self.fluent.application.storage = newValue } } }
mit
0e026c00d6c7dc187c90c3b71f32e281
21.585714
79
0.620493
4.609329
false
false
false
false
juergen/_Playgrounds
TideInterpolation.playground/section-1.swift
1
9501
// Playground - noun: a place where people can play import UIKit import Foundation import Darwin // for pi import XCPlayground let pi = M_PI extension String { // func split(separator:String) -> [NSString] { // return self.componentsSeparatedByString(separator) as [NSString] // } func split(separator:String) -> [String] { return self.componentsSeparatedByString(separator) as [String] } func trim() -> String { return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } func parseDate(format:String="yyyy-MM-dd") -> NSDate? { let dateFmt = NSDateFormatter() dateFmt.timeZone = NSTimeZone.defaultTimeZone() //NSTimeZone.localTimeZone() dateFmt.dateFormat = format if let date = dateFmt.dateFromString(self) { return date } return nil } func replaceAll(replaceMe:String, replacement:String) -> String { return self.stringByReplacingOccurrencesOfString(replaceMe, withString: replacement, options: NSStringCompareOptions.LiteralSearch, range: nil) } func toFloat() -> Float? { if self.isEmpty { return nil } // we need to ignore e.g. "60 - 80" values if self.trim().rangeOfString(" ") != nil { return nil } let s = self.trim().replaceAll(",", replacement: ".") return (NSString(string: s).floatValue) } func substringBetween(first: String, last: String) -> String? { if let start = self.rangeOfString(first)?.startIndex { if let end = self.rangeOfString(last, options:NSStringCompareOptions.BackwardsSearch)?.endIndex { return self.substringWithRange(start ..< end) } } return nil } func substringBetweenExclude(first: String, last: String) -> String? { if let start = self.rangeOfString(first)?.endIndex { if let end = self.rangeOfString(last, options:NSStringCompareOptions.BackwardsSearch)?.startIndex { return self.substringWithRange(start ..< end) } } return nil } func substringBefore(before: String) -> String? { if let end = self.rangeOfString(before, options:NSStringCompareOptions.BackwardsSearch)?.startIndex { return self.substringWithRange(self.startIndex ..< end) } return nil } func substringAfter(after: String) -> String? { if let start = self.rangeOfString(after)?.startIndex { return self.substringWithRange(start ..< self.endIndex) } return nil } func leftPad(count:Int, pad:String) -> String { if count > self.characters.count { return (pad + self).leftPad(count, pad: pad) } return self } } extension Int { func leftPad(count:Int, pad:String) -> String { let intAsString = "\(self)" if count > intAsString.characters.count { return (pad + intAsString).leftPad(count, pad: pad) } return intAsString } } // set default timezone NSTimeZone.setDefaultTimeZone(NSTimeZone(forSecondsFromGMT: +0)) let yearMonth: String = "2015-02-" let testParse = yearMonth + "1 6:29 AM" let pattern = "yyyy-MM-dd h:mm a" //println("\(testParse.parseDate(pattern))") // Day High Low High Low High Moon let header: String = "Day\tHigh\tLow\tHigh\tLow\tHigh\tMoon" let headers: [String] = header.split("\t") let info: String = "Sun 1\t6:29 AM EST / 3.11 ft\t12:50 PM EST / 0.77 ft\t6:41 PM EST / 2.69 ft\t\t\t\n" + "Mon 2\t\t12:42 AM EST / 0.66 ft\t7:11 AM EST / 3.14 ft\t1:30 PM EST / 0.74 ft\t7:23 PM EST / 2.77 ft\t\n" + "Tue 3\t\t1:24 AM EST / 0.66 ft\t7:48 AM EST / 3.16 ft\t2:07 PM EST / 0.73 ft\t8:01 PM EST / 2.83 ft\tFull Moon\n" + "Wed 4\t\t2:03 AM EST / 0.68 ft\t8:22 AM EST / 3.15 ft\t2:40 PM EST / 0.74 ft\t8:37 PM EST / 2.87 ft\t\n" + "Thu 5\t\t2:41 AM EST / 0.73 ft\t8:54 AM EST / 3.12 ft\t3:12 PM EST / 0.77 ft\t9:11 PM EST / 2.89 ft\t\n" + "Fri 6\t\t3:16 AM EST / 0.80 ft\t9:25 AM EST / 3.07 ft\t3:43 PM EST / 0.81 ft\t9:44 PM EST / 2.90 ft\t\n" + "Sat 7\t\t3:51 AM EST / 0.89 ft\t9:56 AM EST / 3.00 ft\t4:13 PM EST / 0.86 ft\t10:17 PM EST / 2.90 ft\t\n" + "Sun 8\t\t4:27 AM EST / 0.98 ft\t10:28 AM EST / 2.92 ft\t4:43 PM EST / 0.91 ft\t10:51 PM EST / 2.89 ft\t\n" + "Mon 9\t\t5:05 AM EST / 1.08 ft\t11:03 AM EST / 2.84 ft\t5:17 PM EST / 0.96 ft\t11:29 PM EST / 2.89 ft\t\n" + "Tue 10\t\t5:48 AM EST / 1.17 ft\t11:43 AM EST / 2.76 ft\t5:56 PM EST / 0.99 ft\t\t" enum Tide: String { case High = "High" case Low = "Low" } enum Moon: String { case FullMoon = "Full Moon" case LastQuarter = "Last Quarter" case NewMoon = "New Moon" case FirstQuarter = "First Quarter" } class MeterPoint : CustomStringConvertible { var level: Float? var date: NSDate? var tide:Tide? var moon:Moon? init(level:Float, date:NSDate, tide:Tide) { self.level = level self.date = date self.tide = tide } func display() -> String { return description; } var description: String { return "\(date!) \(level!) \(tide!.rawValue) " + (moon?.rawValue ?? "") } } class Checkpoint { var meterPoints: [MeterPoint] = [] } func parseTide(dayString: String, timeAndTide: String, tide: Tide) -> MeterPoint? { if let time = timeAndTide.substringBefore(" EST") { if let dateTime = (dayString + " " + time).parseDate(pattern) { if let tideString = timeAndTide.substringBetweenExclude("/ ", last: " ft") { if let level = tideString.toFloat() { //println("\(dateTime) tide: \(level) \(tide.rawValue)") return MeterPoint(level: level, date: dateTime, tide:tide) } } } } return nil } func parseLine(checkpoint:Checkpoint, line:String) { let elements: [String] = line.split("\t") var dayString: String = yearMonth for (index, element) in elements.enumerate() { switch headers[index] { case "Day": dayString = yearMonth + (element as NSString).substringFromIndex(4) case "High": if let meterPoint = parseTide(dayString, timeAndTide: element, tide: Tide.High) { checkPoint.meterPoints.append(meterPoint) } case "Low": if let meterPoint = parseTide(dayString, timeAndTide: element, tide: Tide.Low) { checkPoint.meterPoints.append(meterPoint) } case "Moon": checkPoint.meterPoints.last?.moon = Moon(rawValue: element) default: () } } } var checkPoint = Checkpoint() for (index, line) in (info.split("\n")).enumerate() { parseLine(checkPoint, line: line) } var previous:MeterPoint? for (index, meterPoint) in checkPoint.meterPoints.enumerate() { if index == 0 { previous = meterPoint continue } var levelDif: Float = meterPoint.level! - previous!.level! var timeDif: Int = Int(meterPoint.date!.timeIntervalSince1970 - previous!.date!.timeIntervalSince1970) var hours = timeDif / 3600 if (hours > 0) { var hourSeconds = hours * 3600 timeDif = timeDif - hourSeconds } var minutes = timeDif / 60 let timeDifInfo = " " + hours.leftPad(2, pad: "0") + ":" + minutes.leftPad(2, pad: "0") previous = meterPoint } func interpolatedHeight(d : NSDate, tideData: Checkpoint) -> Float? { let tidesFiltered = { (predicate : (NSTimeInterval -> Bool)) -> [MeterPoint] in tideData.meterPoints.filter({(meterPoint: MeterPoint) -> Bool in if let dt = meterPoint.date?.timeIntervalSinceDate(d) { return predicate(dt) } else { return false } }) } let tidesSortedByAbsTimeDiffToReferenceDate = { (referenceDate: NSDate, tideList : [MeterPoint]) -> [MeterPoint] in tideList.sort( { (m0: MeterPoint, m1: MeterPoint) -> Bool in let dt0 = abs(m0.date!.timeIntervalSinceDate(referenceDate)) let dt1 = abs(m1.date!.timeIntervalSinceDate(referenceDate)) return dt0 < dt1 }) } // 14 hours time difference to select high/low tide near given dateTime d for any tide types let timeDiff_nearTides : NSTimeInterval = 14 * 3600 let tidesBefore : [MeterPoint] = tidesFiltered({-$0 >= 0 && -$0 < timeDiff_nearTides}) let tidesBeforeSorted = tidesSortedByAbsTimeDiffToReferenceDate(d, tidesBefore) let tidesAfter = tidesFiltered({$0 > 0 && $0 < timeDiff_nearTides}) let tidesAfterSorted = tidesSortedByAbsTimeDiffToReferenceDate(d, tidesAfter) if let tideBefore = tidesBeforeSorted.first { if let tideAfter = tidesAfterSorted.first { let height_before = tideBefore.level! let height_after = tideAfter.level! let height_average : Float = (height_before + height_after)/2 let height_diff = (height_before - height_after) let dt_beforeToAfter : Double = tideAfter.date!.timeIntervalSinceDate(tideBefore.date!) let dt_beforeToNow : Double = d.timeIntervalSinceDate(tideBefore.date!) let height_interpolated : Float = height_average+0.5*height_diff*Float(cos(dt_beforeToNow/dt_beforeToAfter*pi)) return height_interpolated } } print("error: Not enough data in meterPoints of checkPoint \(tideData) to interpolate tide at date \(d)") return nil } func print_tides() { checkPoint.meterPoints.map({ print($0.description) }) } print_tides() var d = "2015-02-05 18:03".parseDate("yyyy-MM-dd HH:mm") print("height: for date \(d!): \(interpolatedHeight(d!, tideData: checkPoint))") let startDate = "2015-02-05 18:03".parseDate("yyyy-MM-dd HH:mm") for var dt_hours: Double = 0; dt_hours<93; dt_hours+=1 { let value = interpolatedHeight(startDate!.dateByAddingTimeInterval(dt_hours*3600.0), tideData: checkPoint)! XCPlaygroundPage.currentPage.captureValue(value, withIdentifier:"h") }
mit
11fd046c9d2840c230d2ca314f044f12
30.564784
145
0.664351
3.157527
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Rules/RedundantSetAccessControlRule.swift
1
3160
import Foundation import SourceKittenFramework public struct RedundantSetAccessControlRule: ASTRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "redundant_set_access_control", name: "Redundant Set Access Control Rule", description: "Property setter access level shouldn't be explicit if " + "it's the same as the variable access level.", kind: .idiomatic, minSwiftVersion: .fourDotOne, nonTriggeringExamples: [ "private(set) public var foo: Int", "public let foo: Int", "public var foo: Int", "var foo: Int", """ private final class A { private(set) var value: Int } """ ], triggeringExamples: [ "↓private(set) private var foo: Int", "↓fileprivate(set) fileprivate var foo: Int", "↓internal(set) internal var foo: Int", "↓public(set) public var foo: Int", """ open class Foo { ↓open(set) open var bar: Int } """, """ class A { ↓internal(set) var value: Int } """, """ fileprivate class A { ↓fileprivate(set) var value: Int } """ ] ) public func validate(file: File, kind: SwiftDeclarationKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { guard SwiftDeclarationKind.variableKinds.contains(kind), dictionary.setterAccessibility == dictionary.accessibility else { return [] } let explicitSetACL = dictionary.swiftAttributes.first { dict in return dict.attribute?.hasPrefix("source.decl.attribute.setter_access") ?? false } guard let offset = explicitSetACL?.offset else { return [] } let aclAttributes: Set<SwiftDeclarationAttributeKind> = [.private, .fileprivate, .internal, .public, .open] let explicitACL = dictionary.swiftAttributes.first { dict in guard let attribute = dict.attribute.flatMap(SwiftDeclarationAttributeKind.init) else { return false } return aclAttributes.contains(attribute) } // if it's an inferred `private`, it means the variable is actually inside a fileprivate structure if dictionary.accessibility.flatMap(AccessControlLevel.init(identifier:)) == .private, explicitACL?.offset == nil, dictionary.setterAccessibility.flatMap(AccessControlLevel.init(identifier:)) == .private { return [] } return [ StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, byteOffset: offset)) ] } }
mit
2469a2318ee31de57d3941897d586262
35.16092
115
0.563573
5.414802
false
false
false
false
tid-kijyun/QiitaWatch
QiitaWatch WatchKit Extension/Qiita.swift
1
5348
// // Qiita.swift // QiitaWatch // // Created by tid on 2014/11/23. // Copyright (c) 2014年 tid. All rights reserved. // import Foundation public class Qiita { struct API { static let URL = "https://qiita.com/api/v1" } enum StatusCode : Int { case OK = 200 case Created = 201 case NoContent = 204 case BadRequest = 400 case Unauthorized = 401 case Forbidden = 403 case NotFound = 404 case InternalServerError = 500 } public typealias FailureHandler = ((response: NSURLResponse!, data: NSData!, error: NSError!) -> Void) public class func getToken(name: String, pass: String, success: ((token: String) -> Void)?, failure: FailureHandler? = nil) { let request = NSMutableURLRequest(URL: NSURL(string: "\(API.URL)/auth?url_name=\(name)&password=\(pass)")!) request.HTTPMethod = "POST" NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode == StatusCode.OK.rawValue { var jerror: NSError? if let dic = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: &jerror) as? NSDictionary { if jerror == nil { let token = dic["token"] as String success?(token: token) return } } } } failure?(response: response, data: data, error: error) } } public class func getTagItems(token: String?, tag: String, page: Int, parPage: Int, success: ((articles: [Article])->Void)?, failure: FailureHandler? = nil) { let request = NSMutableURLRequest(URL: NSURL(string: "\(API.URL)/tags/\(tag)/items?token=\(token!)")!) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode == StatusCode.OK.rawValue && error == nil { var articles : [Article] = [] var jerror: NSError? if let ary = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: &jerror) as? NSArray { if jerror == nil { for item in ary { if let dic = item as? NSDictionary { let uuid = dic["uuid"] as String let title = dic["title"] as String let author = dic["user"]!["url_name"] as String let authorImgUrl = dic["user"]!["profile_image_url"] as String let isStock = dic["stocked"] as? Bool ?? false let article = Article( uuid: uuid, title: title, author: author, authorImgUrl: authorImgUrl) article.isStock = isStock articles.append(article) } } success?(articles: articles) return } } } } failure?(response: response, data: data, error: error) } } public class func stock(token: String, itemId: String, stock: Bool, success: (() -> Void)?, failure: FailureHandler? = nil) { let request = NSMutableURLRequest(URL: NSURL(string: "\(API.URL)/items/\(itemId)/stock?token=\(token)")!) request.HTTPMethod = (stock) ? "DELETE" : "PUT" NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in if let httpResponse = response as? NSHTTPURLResponse { if httpResponse.statusCode == StatusCode.NoContent.rawValue { success?() return } } failure?(response: response, data: data, error: error) } } } public class Article { var uuid: String var title: String var author: String var authorImgUrl: String var isStock: Bool = false init(uuid: String, title: String, author: String, authorImgUrl: String) { self.uuid = uuid self.title = title self.author = author self.authorImgUrl = authorImgUrl } } extension Article : Printable { public var description: String { return "uuid: \(self.uuid)" + "title: \(self.title)\n" + "author: \(self.author)\n" + "authorImgUrl: \(self.authorImgUrl)" } }
mit
8ae0ed534849e60584b1ccedef23781f
42.112903
162
0.493079
5.36747
false
false
false
false
huyouare/Emoji-Search-Keyboard
Keyboard/Shapes.swift
1
13981
// // Shapes.swift // TastyImitationKeyboard // // Created by Alexei Baboulevitch on 10/5/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit // TODO: these shapes were traced and as such are erratic and inaccurate; should redo as SVG or PDF /////////////////// // SHAPE OBJECTS // /////////////////// class BackspaceShape: Shape { override func drawCall(color: UIColor) { drawBackspace(self.bounds, color) } } class ShiftShape: Shape { var withLock: Bool = false { didSet { self.overflowCanvas.setNeedsDisplay() } } override func drawCall(color: UIColor) { drawShift(self.bounds, color, self.withLock) } } class GlobeShape: Shape { override func drawCall(color: UIColor) { drawGlobe(self.bounds, color) } } class Shape: UIView { var color: UIColor? { didSet { if let color = self.color { self.overflowCanvas.setNeedsDisplay() } } } // in case shapes draw out of bounds, we still want them to show var overflowCanvas: OverflowCanvas! convenience override init() { self.init(frame: CGRectZero) } override required init(frame: CGRect) { super.init(frame: frame) self.opaque = false self.clipsToBounds = false self.overflowCanvas = OverflowCanvas(shape: self) self.addSubview(self.overflowCanvas) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var oldBounds: CGRect? override func layoutSubviews() { if self.bounds.width == 0 || self.bounds.height == 0 { return } if oldBounds != nil && CGRectEqualToRect(self.bounds, oldBounds!) { return } oldBounds = self.bounds super.layoutSubviews() let overflowCanvasSizeRatio = CGFloat(1.25) let overflowCanvasSize = CGSizeMake(self.bounds.width * overflowCanvasSizeRatio, self.bounds.height * overflowCanvasSizeRatio) self.overflowCanvas.frame = CGRectMake( CGFloat((self.bounds.width - overflowCanvasSize.width) / 2.0), CGFloat((self.bounds.height - overflowCanvasSize.height) / 2.0), overflowCanvasSize.width, overflowCanvasSize.height) self.overflowCanvas.setNeedsDisplay() } func drawCall(color: UIColor) { /* override me! */ } class OverflowCanvas: UIView { unowned var shape: Shape init(shape: Shape) { self.shape = shape super.init(frame: CGRectZero) self.opaque = false } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { let ctx = UIGraphicsGetCurrentContext() let csp = CGColorSpaceCreateDeviceRGB() CGContextSaveGState(ctx) let xOffset = (self.bounds.width - self.shape.bounds.width) / CGFloat(2) let yOffset = (self.bounds.height - self.shape.bounds.height) / CGFloat(2) CGContextTranslateCTM(ctx, xOffset, yOffset) self.shape.drawCall(shape.color != nil ? shape.color! : UIColor.blackColor()) CGContextRestoreGState(ctx) } } } ///////////////////// // SHAPE FUNCTIONS // ///////////////////// func getFactors(fromSize: CGSize, toRect: CGRect) -> (xScalingFactor: CGFloat, yScalingFactor: CGFloat, lineWidthScalingFactor: CGFloat, fillIsHorizontal: Bool, offset: CGFloat) { var xSize = { () -> CGFloat in let scaledSize = (fromSize.width / CGFloat(2)) if scaledSize > toRect.width { return (toRect.width / scaledSize) / CGFloat(2) } else { return CGFloat(0.5) } }() var ySize = { () -> CGFloat in let scaledSize = (fromSize.height / CGFloat(2)) if scaledSize > toRect.height { return (toRect.height / scaledSize) / CGFloat(2) } else { return CGFloat(0.5) } }() let actualSize = min(xSize, ySize) return (actualSize, actualSize, actualSize, false, 0) } func centerShape(fromSize: CGSize, toRect: CGRect) { let xOffset = (toRect.width - fromSize.width) / CGFloat(2) let yOffset = (toRect.height - fromSize.height) / CGFloat(2) let ctx = UIGraphicsGetCurrentContext() CGContextSaveGState(ctx) CGContextTranslateCTM(ctx, xOffset, yOffset) } func endCenter() { let ctx = UIGraphicsGetCurrentContext() CGContextRestoreGState(ctx) } func drawBackspace(bounds: CGRect, color: UIColor) { let factors = getFactors(CGSizeMake(44, 32), bounds) let xScalingFactor = factors.xScalingFactor let yScalingFactor = factors.yScalingFactor let lineWidthScalingFactor = factors.lineWidthScalingFactor centerShape(CGSizeMake(44 * xScalingFactor, 32 * yScalingFactor), bounds) //// Color Declarations let color = color let color2 = UIColor.grayColor() // TODO: //// Bezier Drawing var bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPointMake(16 * xScalingFactor, 32 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 32 * yScalingFactor)) bezierPath.addCurveToPoint(CGPointMake(44 * xScalingFactor, 26 * yScalingFactor), controlPoint1: CGPointMake(38 * xScalingFactor, 32 * yScalingFactor), controlPoint2: CGPointMake(44 * xScalingFactor, 32 * yScalingFactor)) bezierPath.addCurveToPoint(CGPointMake(44 * xScalingFactor, 6 * yScalingFactor), controlPoint1: CGPointMake(44 * xScalingFactor, 22 * yScalingFactor), controlPoint2: CGPointMake(44 * xScalingFactor, 6 * yScalingFactor)) bezierPath.addCurveToPoint(CGPointMake(36 * xScalingFactor, 0 * yScalingFactor), controlPoint1: CGPointMake(44 * xScalingFactor, 6 * yScalingFactor), controlPoint2: CGPointMake(44 * xScalingFactor, 0 * yScalingFactor)) bezierPath.addCurveToPoint(CGPointMake(16 * xScalingFactor, 0 * yScalingFactor), controlPoint1: CGPointMake(32 * xScalingFactor, 0 * yScalingFactor), controlPoint2: CGPointMake(16 * xScalingFactor, 0 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(0 * xScalingFactor, 18 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(16 * xScalingFactor, 32 * yScalingFactor)) bezierPath.closePath() color.setFill() bezierPath.fill() //// Bezier 2 Drawing var bezier2Path = UIBezierPath() bezier2Path.moveToPoint(CGPointMake(20 * xScalingFactor, 10 * yScalingFactor)) bezier2Path.addLineToPoint(CGPointMake(34 * xScalingFactor, 22 * yScalingFactor)) bezier2Path.addLineToPoint(CGPointMake(20 * xScalingFactor, 10 * yScalingFactor)) bezier2Path.closePath() UIColor.grayColor().setFill() bezier2Path.fill() color2.setStroke() bezier2Path.lineWidth = 2.5 * lineWidthScalingFactor bezier2Path.stroke() //// Bezier 3 Drawing var bezier3Path = UIBezierPath() bezier3Path.moveToPoint(CGPointMake(20 * xScalingFactor, 22 * yScalingFactor)) bezier3Path.addLineToPoint(CGPointMake(34 * xScalingFactor, 10 * yScalingFactor)) bezier3Path.addLineToPoint(CGPointMake(20 * xScalingFactor, 22 * yScalingFactor)) bezier3Path.closePath() UIColor.redColor().setFill() bezier3Path.fill() color2.setStroke() bezier3Path.lineWidth = 2.5 * lineWidthScalingFactor bezier3Path.stroke() endCenter() } func drawShift(bounds: CGRect, color: UIColor, withRect: Bool) { let factors = getFactors(CGSizeMake(38, (withRect ? 34 + 4 : 32)), bounds) let xScalingFactor = factors.xScalingFactor let yScalingFactor = factors.yScalingFactor let lineWidthScalingFactor = factors.lineWidthScalingFactor centerShape(CGSizeMake(38 * xScalingFactor, (withRect ? 34 + 4 : 32) * yScalingFactor), bounds) //// Color Declarations let color2 = color //// Bezier Drawing var bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPointMake(28 * xScalingFactor, 18 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 18 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(38 * xScalingFactor, 18 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(19 * xScalingFactor, 0 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(0 * xScalingFactor, 18 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(0 * xScalingFactor, 18 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(10 * xScalingFactor, 18 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(10 * xScalingFactor, 28 * yScalingFactor)) bezierPath.addCurveToPoint(CGPointMake(14 * xScalingFactor, 32 * yScalingFactor), controlPoint1: CGPointMake(10 * xScalingFactor, 28 * yScalingFactor), controlPoint2: CGPointMake(10 * xScalingFactor, 32 * yScalingFactor)) bezierPath.addCurveToPoint(CGPointMake(24 * xScalingFactor, 32 * yScalingFactor), controlPoint1: CGPointMake(16 * xScalingFactor, 32 * yScalingFactor), controlPoint2: CGPointMake(24 * xScalingFactor, 32 * yScalingFactor)) bezierPath.addCurveToPoint(CGPointMake(28 * xScalingFactor, 28 * yScalingFactor), controlPoint1: CGPointMake(24 * xScalingFactor, 32 * yScalingFactor), controlPoint2: CGPointMake(28 * xScalingFactor, 32 * yScalingFactor)) bezierPath.addCurveToPoint(CGPointMake(28 * xScalingFactor, 18 * yScalingFactor), controlPoint1: CGPointMake(28 * xScalingFactor, 26 * yScalingFactor), controlPoint2: CGPointMake(28 * xScalingFactor, 18 * yScalingFactor)) bezierPath.closePath() color2.setFill() bezierPath.fill() if withRect { //// Rectangle Drawing let rectanglePath = UIBezierPath(rect: CGRectMake(10 * xScalingFactor, 34 * yScalingFactor, 18 * xScalingFactor, 4 * yScalingFactor)) color2.setFill() rectanglePath.fill() } endCenter() } func drawGlobe(bounds: CGRect, color: UIColor) { let factors = getFactors(CGSizeMake(41, 40), bounds) let xScalingFactor = factors.xScalingFactor let yScalingFactor = factors.yScalingFactor let lineWidthScalingFactor = factors.lineWidthScalingFactor centerShape(CGSizeMake(41 * xScalingFactor, 40 * yScalingFactor), bounds) //// Color Declarations let color = color //// Oval Drawing var ovalPath = UIBezierPath(ovalInRect: CGRectMake(0 * xScalingFactor, 0 * yScalingFactor, 40 * xScalingFactor, 40 * yScalingFactor)) color.setStroke() ovalPath.lineWidth = 1 * lineWidthScalingFactor ovalPath.stroke() //// Bezier Drawing var bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPointMake(20 * xScalingFactor, -0 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(20 * xScalingFactor, 40 * yScalingFactor)) bezierPath.addLineToPoint(CGPointMake(20 * xScalingFactor, -0 * yScalingFactor)) bezierPath.closePath() color.setStroke() bezierPath.lineWidth = 1 * lineWidthScalingFactor bezierPath.stroke() //// Bezier 2 Drawing var bezier2Path = UIBezierPath() bezier2Path.moveToPoint(CGPointMake(0.5 * xScalingFactor, 19.5 * yScalingFactor)) bezier2Path.addLineToPoint(CGPointMake(39.5 * xScalingFactor, 19.5 * yScalingFactor)) bezier2Path.addLineToPoint(CGPointMake(0.5 * xScalingFactor, 19.5 * yScalingFactor)) bezier2Path.closePath() color.setStroke() bezier2Path.lineWidth = 1 * lineWidthScalingFactor bezier2Path.stroke() //// Bezier 3 Drawing var bezier3Path = UIBezierPath() bezier3Path.moveToPoint(CGPointMake(21.63 * xScalingFactor, 0.42 * yScalingFactor)) bezier3Path.addCurveToPoint(CGPointMake(21.63 * xScalingFactor, 39.6 * yScalingFactor), controlPoint1: CGPointMake(21.63 * xScalingFactor, 0.42 * yScalingFactor), controlPoint2: CGPointMake(41 * xScalingFactor, 19 * yScalingFactor)) bezier3Path.lineCapStyle = kCGLineCapRound; color.setStroke() bezier3Path.lineWidth = 1 * lineWidthScalingFactor bezier3Path.stroke() //// Bezier 4 Drawing var bezier4Path = UIBezierPath() bezier4Path.moveToPoint(CGPointMake(17.76 * xScalingFactor, 0.74 * yScalingFactor)) bezier4Path.addCurveToPoint(CGPointMake(18.72 * xScalingFactor, 39.6 * yScalingFactor), controlPoint1: CGPointMake(17.76 * xScalingFactor, 0.74 * yScalingFactor), controlPoint2: CGPointMake(-2.5 * xScalingFactor, 19.04 * yScalingFactor)) bezier4Path.lineCapStyle = kCGLineCapRound; color.setStroke() bezier4Path.lineWidth = 1 * lineWidthScalingFactor bezier4Path.stroke() //// Bezier 5 Drawing var bezier5Path = UIBezierPath() bezier5Path.moveToPoint(CGPointMake(6 * xScalingFactor, 7 * yScalingFactor)) bezier5Path.addCurveToPoint(CGPointMake(34 * xScalingFactor, 7 * yScalingFactor), controlPoint1: CGPointMake(6 * xScalingFactor, 7 * yScalingFactor), controlPoint2: CGPointMake(19 * xScalingFactor, 21 * yScalingFactor)) bezier5Path.lineCapStyle = kCGLineCapRound; color.setStroke() bezier5Path.lineWidth = 1 * lineWidthScalingFactor bezier5Path.stroke() //// Bezier 6 Drawing var bezier6Path = UIBezierPath() bezier6Path.moveToPoint(CGPointMake(6 * xScalingFactor, 33 * yScalingFactor)) bezier6Path.addCurveToPoint(CGPointMake(34 * xScalingFactor, 33 * yScalingFactor), controlPoint1: CGPointMake(6 * xScalingFactor, 33 * yScalingFactor), controlPoint2: CGPointMake(19 * xScalingFactor, 22 * yScalingFactor)) bezier6Path.lineCapStyle = kCGLineCapRound; color.setStroke() bezier6Path.lineWidth = 1 * lineWidthScalingFactor bezier6Path.stroke() endCenter() }
bsd-3-clause
99a8557ba9ee0347774e0261b5bf4d97
38.383099
241
0.684286
4.381385
false
false
false
false
SereivoanYong/Charts
Source/Charts/Highlight/Highlight.swift
1
5374
// // Highlight.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation /// Contains information needed to determine the highlighted value. open class Highlight: Equatable, CustomStringConvertible { /// The x-value of the highlighted value /// /// **default**: .nan open let x: CGFloat //= .nan /// The y-value of the highlighted value /// /// **default**: .nan open let y: CGFloat //= .nan /// The x-pixel of the highlight /// /// **default**: .nan open let xPx: CGFloat //= .nan /// The y-pixel of the highlight /// /// **default**: .nan open let yPx: CGFloat //= .nan /// The index of the data object - in case it refers to more than one /// /// **default**: -1 open var dataIndex: Int //= -1 /// The index of the dataset the highlighted value is in /// /// **default**: 0 open let dataSetIndex: Int //= 0 /// Index which value of a stacked bar entry is highlighted /// /// **default**: -1 open let stackIndex: Int //= -1 open var isStacked: Bool { return stackIndex >= 0 } /// The axis the highlighted value belongs to open let axis: YAxis.AxisDependency /// The position (pixels) on which this highlight object was last drawn open var drawPosition: CGPoint = .zero /// - Parameters: /// - x: The x-value of the highlighted value /// - y: The y-value of the highlighted value /// - xPx: The x-pixel of the highlighted value /// - yPx: The y-pixel of the highlighted value /// - dataIndex: The index of the Data the highlighted value belongs to /// - dataSetIndex: The index of the DataSet the highlighted value belongs to /// - stackIndex: References which value of a stacked-bar entry has been selected /// - axis: The axis the highlighted value belongs to fileprivate init(x: CGFloat, y: CGFloat, xPx: CGFloat, yPx: CGFloat, dataIndex: Int, dataSetIndex: Int, stackIndex: Int, axis: YAxis.AxisDependency) { self.x = x self.y = y self.xPx = xPx self.yPx = yPx self.dataIndex = dataIndex self.dataSetIndex = dataSetIndex self.stackIndex = stackIndex self.axis = axis } /// - Parameters: /// - x: The x-value of the highlighted value /// - y: The y-value of the highlighted value /// - xPx: The x-pixel of the highlighted value /// - yPx: The y-pixel of the highlighted value /// - dataSetIndex: The index of the DataSet the highlighted value belongs to /// - stackIndex: References which value of a stacked-bar entry has been selected /// - axis: The axis the highlighted value belongs to public convenience init(x: CGFloat, y: CGFloat, xPx: CGFloat, yPx: CGFloat, dataSetIndex: Int, stackIndex: Int, axis: YAxis.AxisDependency) { self.init(x: x, y: y, xPx: xPx, yPx: yPx, dataIndex: -1, dataSetIndex: dataSetIndex, stackIndex: stackIndex, axis: axis) } /// - Parameters /// - x: The x-value of the highlighted value /// - y: The y-value of the highlighted value /// - xPx: The x-pixel of the highlighted value /// - yPx: The y-pixel of the highlighted value /// - dataIndex: The index of the Data the highlighted value belongs to /// - dataSetIndex: The index of the DataSet the highlighted value belongs to /// - stackIndex: References which value of a stacked-bar entry has been selected /// - axis: The axis the highlighted value belongs to public convenience init(x: CGFloat, y: CGFloat, xPx: CGFloat, yPx: CGFloat, dataSetIndex: Int, axis: YAxis.AxisDependency) { self.init(x: x, y: y, xPx: xPx, yPx: yPx, dataIndex: -1, dataSetIndex: dataSetIndex, stackIndex: -1, axis: axis) } /// - Parameters /// - x: The x-value of the highlighted value /// - dataSetIndex: The index of the DataSet the highlighted value belongs to /// - stackIndex: References which value of a stacked-bar entry has been selected public convenience init(x: CGFloat, dataSetIndex: Int, stackIndex: Int) { self.init(x: x, y: .nan, xPx: .nan, yPx: .nan, dataIndex: -1, dataSetIndex: dataSetIndex, stackIndex: stackIndex, axis: .left) } /// - Parameters: /// - x: The x-value of the highlighted value /// - y: The y-value of the highlighted value /// - dataSetIndex: The index of the DataSet the highlighted value belongs to public convenience init(x: CGFloat, y: CGFloat, dataSetIndex: Int) { self.init(x: x, y: y, xPx: .nan, yPx: .nan, dataIndex: -1, dataSetIndex: dataSetIndex, stackIndex: -1, axis: .left) } // MARK: Equatable public static func ==(lhs: Highlight, rhs: Highlight) -> Bool { if lhs === rhs { return true } if type(of: lhs) != type(of: rhs) { return false } return lhs.x == rhs.x && lhs.y == rhs.y && lhs.dataIndex == rhs.dataIndex && lhs.dataSetIndex == rhs.dataSetIndex && lhs.stackIndex == rhs.stackIndex } // MARK: CustomStringConvertible open var description: String { return "Highlight, x: \(x), y: \(y), dataIndex (combined charts): \(dataIndex), dataSetIndex: \(dataSetIndex), stackIndex (only stacked barentry): \(stackIndex)" } } extension CGPoint { public func reversed() -> CGPoint { return CGPoint(x: y, y: x) } }
apache-2.0
45c015032b5cbafc8968672f47774d85
35.067114
165
0.653517
3.911208
false
false
false
false
Vienta/kuafu
kuafu/kuafu/src/Manager/KFLocalPushManager.swift
1
9777
// // KFLocalPushManager.swift // kuafu // // Created by Vienta on 15/7/5. // Copyright (c) 2015年 www.vienta.me. All rights reserved. // import UIKit import DAAlertController import AudioToolbox private let sharedInstance = KFLocalPushManager() class KFLocalPushManager: NSObject { class var sharedManager: KFLocalPushManager { return sharedInstance } func registerLocaPushWithEvent(event: KFEventDO) -> Bool { if event.starttime != nil && event.starttime.doubleValue > 0 { var alertDate: NSDate = KFUtil.dateFromTimeStamp(event.starttime.doubleValue) as NSDate var alertBody: String = event.content self.registerLocalPushWithFireDate(alertDate, alertBody: alertBody, and: event.eventid, with: KF_LOCAL_NOTIFICATION_CATEGORY_REMIND) } if event.endtime != nil && event.endtime.doubleValue > 0 { if (event.endtime.doubleValue - NSDate().timeIntervalSince1970) > 300000 { var dueToDate: NSDate = KFUtil.dateFromTimeStamp(event.endtime.doubleValue - 300000) as NSDate var dueToBody: String = "KF_TASK_DUE_AFTER_FIVE_MIN".localized + ": " + event.content self.registerLocalPushWithFireDate(dueToDate, alertBody: dueToBody, and: event.eventid, with: KF_LOCAL_NOTIFICATION_CATEGORY_REMIND) } } if event.endtime != nil && event.endtime.doubleValue > 0 { var dueToDate: NSDate = KFUtil.dateFromTimeStamp(event.endtime.doubleValue) as NSDate var dueToBody: String = "KF_ALREADY_DUE".localized + ": " + event.content self.registerLocalPushWithFireDate(dueToDate, alertBody: dueToBody, and: event.eventid, with: KF_LOCAL_NOTIFICATION_CATEGORY_COMPLETE) } return true } func registerLocalPushWithFireDate(fireDate: NSDate, alertBody: String, and eventid: NSNumber!, with type: String) -> Void { var localNoti: UILocalNotification = UILocalNotification() localNoti.fireDate = fireDate localNoti.timeZone = NSTimeZone.defaultTimeZone() localNoti.alertBody = alertBody localNoti.soundName = UILocalNotificationDefaultSoundName var userDict: NSDictionary? if eventid.longLongValue <= 0 { userDict = ["content": "\(fireDate)\(alertBody)"] } else { userDict = ["content": "\(fireDate)\(alertBody)","eventid": eventid] } localNoti.userInfo = userDict as? [NSObject : AnyObject] localNoti.category = type UIApplication.sharedApplication().scheduleLocalNotification(localNoti) } func allLocalPush() -> NSArray { return UIApplication.sharedApplication().scheduledLocalNotifications } func cancelAllLocal() -> Void { UIApplication.sharedApplication().cancelAllLocalNotifications() } func deleteLocalPushWithEvent(event: KFEventDO) -> Bool { var targetNotifications: NSMutableArray = NSMutableArray(capacity: 0) as NSMutableArray for notifcation in UIApplication.sharedApplication().scheduledLocalNotifications as! [UILocalNotification] { var userDict: NSDictionary = notifcation.userInfo! var eventid: NSNumber = userDict.objectForKey("eventid") as! NSNumber if eventid.longLongValue > 0 { if eventid.longLongValue == event.eventid.longLongValue { targetNotifications.addObject(notifcation) } } } if targetNotifications.count > 0 { for targetNoti in targetNotifications { UIApplication.sharedApplication().cancelLocalNotification(targetNoti as! UILocalNotification) } return true } else { return false } } func getEventByNotification(notification: UILocalNotification) -> KFEventDO { var userDict: NSDictionary = notification.userInfo! var eventid: NSNumber = userDict.objectForKey("eventid") as! NSNumber var event: KFEventDO = KFEventDAO.sharedManager.getEventById(eventid)! return event } func localNotificationSettingsCategories() -> NSSet { let completeAction = UIMutableUserNotificationAction() completeAction.identifier = "COMPLETE_TODO"; completeAction.title = "KF_LOCALNOTIFICATION_COMPLETE".localized completeAction.activationMode = .Background completeAction.authenticationRequired = false completeAction.destructive = true let getitAction = UIMutableUserNotificationAction() getitAction.identifier = "GET_IT_TODO" getitAction.title = "KF_LOCALNOTIFICATION_GET_IT".localized getitAction.activationMode = .Background getitAction.destructive = false let deleteAction = UIMutableUserNotificationAction() deleteAction.identifier = "DELETE_TODO" deleteAction.title = "KF_DELETE".localized deleteAction.activationMode = .Background deleteAction.destructive = false let delayAction = UIMutableUserNotificationAction() delayAction.identifier = "DELAY_TODO" delayAction.title = "KF_LOCALNOTIFICATION_FIVE_MIN_AFTER".localized delayAction.activationMode = .Background deleteAction.destructive = false let remindCategory = UIMutableUserNotificationCategory() remindCategory.identifier = KF_LOCAL_NOTIFICATION_CATEGORY_REMIND remindCategory.setActions([getitAction, deleteAction], forContext: .Default) let completeCategory = UIMutableUserNotificationCategory() completeCategory.identifier = KF_LOCAL_NOTIFICATION_CATEGORY_COMPLETE completeCategory.setActions([delayAction, completeAction, deleteAction], forContext: .Default) var categoriesSet: NSSet = NSSet(array: [remindCategory, completeCategory]) return categoriesSet } func handleNotification(notification: UILocalNotification) -> Void { AudioServicesPlaySystemSound(SystemSoundID(UInt32(kSystemSoundID_Vibrate))) var rootViewController: UITabBarController = UIApplication.sharedApplication().delegate?.window?!.rootViewController as! UITabBarController var eventViewController: UIViewController! = rootViewController.selectedViewController if (notification.category == KF_LOCAL_NOTIFICATION_CATEGORY_COMPLETE) { var remindAfterAction: DAAlertAction = DAAlertAction(title: "KF_LOCALNOTIFICATION_FIVE_MIN_AFTER".localized, style: DAAlertActionStyle.Default, handler: { () -> Void in var event: KFEventDO = KFLocalPushManager.sharedManager.getEventByNotification(notification) let alertBody: String = "KF_ALREADY_DUE".localized + ": " + event.content event.endtime = NSDate().dateByAddingTimeInterval(5 * 60).timeIntervalSince1970 KFEventDAO.sharedManager.saveEvent(event) KFLocalPushManager.sharedManager.registerLocalPushWithFireDate(NSDate().dateByAddingTimeInterval(5 * 60), alertBody: alertBody, and: event.eventid, with: KF_LOCAL_NOTIFICATION_CATEGORY_COMPLETE) self.postNotificationEventsChanged() }) var markAsReadAction: DAAlertAction = DAAlertAction(title: "KF_LOCALNOTIFICATION_COMPLETE".localized, style: DAAlertActionStyle.Default, handler: { () -> Void in var event: KFEventDO = KFLocalPushManager.sharedManager.getEventByNotification(notification) event.status = NSNumber(integerLiteral: KEventStatus.Achieve.rawValue) KFEventDAO.sharedManager.saveEvent(event) self.postNotificationEventsChanged() }) var deleteAction: DAAlertAction = DAAlertAction(title: "KF_DELETE".localized, style: DAAlertActionStyle.Destructive, handler: { () -> Void in var event: KFEventDO = KFLocalPushManager.sharedManager.getEventByNotification(notification) event.status = NSNumber(integerLiteral: KEventStatus.Delete.rawValue) KFEventDAO.sharedManager.saveEvent(event) self.postNotificationEventsChanged() }) DAAlertController.showAlertViewInViewController(eventViewController, withTitle: notification.alertBody, message: nil, actions: [remindAfterAction,markAsReadAction,deleteAction]) } else { var kownitAction: DAAlertAction = DAAlertAction(title: "KF_LOCALNOTIFICATION_GET_IT".localized, style: DAAlertActionStyle.Default, handler: { () -> Void in self.postNotificationEventsChanged() }) var deleteAction: DAAlertAction = DAAlertAction(title: "KF_DELETE".localized, style: DAAlertActionStyle.Destructive, handler: { () -> Void in var event: KFEventDO = KFLocalPushManager.sharedManager.getEventByNotification(notification) event.status = NSNumber(integerLiteral: KEventStatus.Delete.rawValue) KFEventDAO.sharedManager.saveEvent(event) self.postNotificationEventsChanged() }) DAAlertController.showAlertViewInViewController(eventViewController, withTitle: notification.alertBody, message: nil, actions: [kownitAction,deleteAction]) } } func postNotificationEventsChanged() -> Void { dispatch_async(dispatch_get_main_queue(), { () -> Void in NSNotificationCenter.defaultCenter().postNotificationName(KF_NOTIFICATION_UPDATE_TASK, object: nil) }) } }
mit
968aeddcf225022937494ebcd9b4a0ff
48.872449
210
0.675192
5.207778
false
false
false
false
khizkhiz/swift
test/Parse/ConditionalCompilation/language_version.swift
8
1907
// RUN: %target-parse-verify-swift #if swift(>=1.0) let w = 1 #else // This shouldn't emit any diagnostics. asdf asdf asdf asdf #endif #if swift(>=1.2) #if os(iOS) let z = 1 #else let z = 1 #endif #else // This shouldn't emit any diagnostics. asdf asdf asdf asdf #if os(iOS) // This shouldn't emit any diagnostics. asdf asdf asdf asdf #else // This shouldn't emit any diagnostics. asdf asdf asdf asdf #endif // This shouldn't emit any diagnostics. asdf asdf asdf asdf #endif #if !swift(>=1.0) // This shouldn't emit any diagnostics. $#%^*& #endif #if swift(">=7.1") // expected-error {{unexpected platform condition argument: expected a unary comparison, such as '>=2.2'}} #endif #if swift(">=2n.2") // expected-error {{unexpected platform condition argument: expected a unary comparison, such as '>=2.2'}} #endif #if swift("") // expected-error {{unexpected platform condition argument: expected a unary comparison, such as '>=2.2'}} #endif // We won't expect three version components to work for now. #if swift(>=2.2.1) // expected-error {{expected named member of numeric literal}} #endif #if swift(>=2.0, *) // expected-error {{expected only one argument to platform condition}} #endif #if swift(>=, 2.0) // expected-error {{expected only one argument to platform condition}} #endif protocol P { #if swift(>=2.2) associatedtype Index #else // There should be no warning here. typealias Index // There should be no error here. adsf asdf asdf $#%^*& func foo(sdfsdfdsf adsf adsf asdf adsf adsf) #endif } #if swift(>=2.2) func foo() {} #else // There should be no error here. func foo(sdfsdfdsf adsf adsf asdf adsf adsf) #endif struct S { #if swift(>=2.2) let x: Int #else // There should be no error here. let x: @#$()%&*)@#$(%&* #endif } #if swift(>=2.2) var zzz = "zzz" #else // There should be no error here. var zzz = zzz #endif
apache-2.0
0de7f2081cce4705d8f903fbcdb15136
19.956044
126
0.667541
3.065916
false
false
false
false
jorisvervuurt/JVSUIButton
JVSUIButton.swift
1
2590
// // JVSUIButton.swift // JVSUIButton // // Created by Joris Vervuurt on 30-06-15. // Copyright (c) 2015 Joris Vervuurt Software. All rights reserved. // // The MIT License (MIT) // // Copyright (c) 2015 Joris Vervuurt Software // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit /// Subclass of UIButton, adding the ability to set a minimum hit target size. class JVSUIButton: UIButton { // MARK: - Properties /// A value that indicates whether the hit target should be extended in case it is smaller than the minimum hit target size. @IBInspectable var extendHitTargetIfNeeded: Bool = false /// The minimum hit target width. @IBInspectable var minimumHitTargetWidth: CGFloat = 44 /// The minimum hit target height. @IBInspectable var minimumHitTargetHeight: CGFloat = 44 // MARK: - Functions override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { if !self.extendHitTargetIfNeeded { return super.pointInside(point, withEvent: event) } else { let initialBounds: CGRect = self.bounds let additionalHitTargetWidth: CGFloat = self.bounds.width < self.minimumHitTargetWidth ? (self.minimumHitTargetWidth - self.bounds.width) / 2 : 0 let additionalHitTargetHeight: CGFloat = self.bounds.height < self.minimumHitTargetHeight ? (self.minimumHitTargetHeight - self.bounds.height) / 2 : 0 let extendedBounds: CGRect = CGRectInset(self.bounds, -additionalHitTargetWidth, -additionalHitTargetHeight) return CGRectContainsPoint(extendedBounds, point) } } }
mit
d80a604c0fedcf1c2f8ac9b8d8622670
39.46875
153
0.74749
4.059561
false
false
false
false
srn214/Floral
Floral/Pods/CleanJSON/CleanJSON/Classes/_CleanJSONDecoder.swift
1
4001
// // _CleanJSONDecoder.swift // CleanJSON // // Created by Pircate([email protected]) on 2018/10/10 // Copyright © 2018 Pircate. All rights reserved. // import Foundation final class _CleanJSONDecoder: CleanDecoder { /// The decoder's storage. var storage: CleanJSONDecodingStorage /// Options set on the top-level decoder. let options: CleanJSONDecoder.Options /// The path to the current point in encoding. public var codingPath: [CodingKey] /// Contextual user-provided information for use during encoding. public var userInfo: [CodingUserInfoKey : Any] { return self.options.userInfo } // MARK: - Initialization /// Initializes `self` with the given top-level container and options. init(referencing container: Any, at codingPath: [CodingKey] = [], options: CleanJSONDecoder.Options) { self.storage = CleanJSONDecodingStorage() self.storage.push(container: container) self.codingPath = codingPath self.options = options } // MARK: - Decoder Methods public func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> { guard !(self.storage.topContainer is NSNull) else { switch options.nestedContainerDecodingStrategy.valueNotFound { case .throw: throw DecodingError.Nested.valueNotFound( KeyedDecodingContainer<Key>.self, codingPath: codingPath, debugDescription: "Cannot get keyed decoding container -- found null value instead.") case .useEmptyContainer: let container = CleanJSONKeyedDecodingContainer<Key>(referencing: self, wrapping: [:]) return KeyedDecodingContainer(container) } } guard let topContainer = self.storage.topContainer as? [String : Any] else { switch options.nestedContainerDecodingStrategy.typeMismatch { case .throw: throw DecodingError._typeMismatch( at: codingPath, expectation: [String : Any].self, reality: storage.topContainer) case .useEmptyContainer: let container = CleanJSONKeyedDecodingContainer<Key>(referencing: self, wrapping: [:]) return KeyedDecodingContainer(container) } } let container = CleanJSONKeyedDecodingContainer<Key>(referencing: self, wrapping: topContainer) return KeyedDecodingContainer(container) } public func unkeyedContainer() throws -> UnkeyedDecodingContainer { guard !(self.storage.topContainer is NSNull) else { switch options.nestedContainerDecodingStrategy.valueNotFound { case .throw: throw DecodingError.Nested.valueNotFound( UnkeyedDecodingContainer.self, codingPath: codingPath, debugDescription: "Cannot get unkeyed decoding container -- found null value instead.") case .useEmptyContainer: return CleanJSONUnkeyedDecodingContainer(referencing: self, wrapping: []) } } guard let topContainer = self.storage.topContainer as? [Any] else { switch options.nestedContainerDecodingStrategy.typeMismatch { case .throw: throw DecodingError._typeMismatch( at: codingPath, expectation: [Any].self, reality: storage.topContainer) case .useEmptyContainer: return CleanJSONUnkeyedDecodingContainer(referencing: self, wrapping: []) } } return CleanJSONUnkeyedDecodingContainer(referencing: self, wrapping: topContainer) } public func singleValueContainer() throws -> SingleValueDecodingContainer { return self } }
mit
9fabb444a370f055abc18b3d69a4f1d5
38.60396
107
0.62175
5.891016
false
false
false
false
iOSDevLog/InkChat
InkChat/Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationCubeTransition.swift
1
3143
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationCubeTransition: ActivityIndicatorAnimating { // MARK: Properties fileprivate let duration: CFTimeInterval = 1.6 fileprivate let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) fileprivate var deltaX: CGFloat = 0 fileprivate var deltaY: CGFloat = 0 // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let squareSize = size.width / 5 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [0, -0.8] deltaX = size.width - squareSize deltaY = size.height - squareSize for i in 0 ..< 2 { let square = ActivityIndicatorShape.rectangle.makeLayer(size: CGSize(width: squareSize, height: squareSize), color: color) let frame = CGRect(x: x, y: y, width: squareSize, height: squareSize) animation.beginTime = beginTime + beginTimes[i] square.frame = frame square.add(animation, forKey: "animation") layer.addSublayer(square) } } } // MARK: - Setup private extension ActivityIndicatorAnimationCubeTransition { var animation: CAAnimationGroup { let animation = CAAnimationGroup() animation.animations = [scaleAnimation, translateAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } var rotateAnimation: CAKeyframeAnimation { let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = scaleAnimation.timingFunctions rotateAnimation.values = [0, -CGFloat.pi / 2, -CGFloat.pi, -1.5 * CGFloat.pi, -2 * CGFloat.pi] rotateAnimation.duration = duration return rotateAnimation } var scaleAnimation: CAKeyframeAnimation { let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.25, 0.5, 0.75, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction, timingFunction, timingFunction] scaleAnimation.values = [1, 0.5, 1, 0.5, 1] scaleAnimation.duration = duration return scaleAnimation } var translateAnimation: CAKeyframeAnimation { let translateAnimation = CAKeyframeAnimation(keyPath: "transform.translation") translateAnimation.keyTimes = scaleAnimation.keyTimes translateAnimation.timingFunctions = scaleAnimation.timingFunctions translateAnimation.values = [ NSValue(cgSize: CGSize(width: 0, height: 0)), NSValue(cgSize: CGSize(width: deltaX, height: 0)), NSValue(cgSize: CGSize(width: deltaX, height: deltaY)), NSValue(cgSize: CGSize(width: 0, height: deltaY)), NSValue(cgSize: CGSize(width: 0, height: 0)) ] translateAnimation.duration = duration return translateAnimation } }
apache-2.0
4021e35e65a7807b59f3213558b3b13f
35.126437
128
0.728921
4.747734
false
false
false
false
hikelee/cinema
Sources/App/Models/BasicModel.swift
1
4271
import Fluent import Vapor import HTTP import Foundation public protocol RestModel : Model { var id : Node? {get set} var exists: Bool {get set} func validate(isCreate: Bool) throws ->[String:String] func makeNode(context: Context) throws -> Node func makeLeafNode() throws -> Node func makeNode() throws -> Node } public protocol ChannelBasedModel : RestModel { var channelId :Node? {get set} } extension ChannelBasedModel { public static func all(channelId:Int) throws ->[Self]{ let query = try Self.query() if channelId>0 { try query.filter("channel_id",channelId) } return try query.sort("id",.descending).all() } public static func first(channelId:Int) throws -> Self?{ let query = try Self.query() if channelId>0 { try query.filter("channel_id",channelId) } return try query.first() } public static func firstNode(channelId:Int) throws -> Node?{ return try first(channelId:channelId)?.makeNode() } public static func firstLeafNode(channelId:Int) throws -> Node?{ return try first(channelId:channelId)?.makeNode() } public static func allNodes(channelId:Int) throws ->[Node] { return try all(channelId:channelId).map{try $0.makeNode()} } public static func allLeafNodes(channelId:Int) throws ->[Node]{ return try all(channelId:channelId).map{try $0.makeLeafNode()} } } extension RestModel { public static func prepare(_ database: Database) throws {} public static func revert(_ database: Database) throws {} public func makeLeafNode() throws ->Node { return try makeNode() } public func makeNode(context: Context) throws -> Node { return try makeNode() } } extension RestModel{ public static func node(_ id: NodeRepresentable?) throws ->Node? { return try load(id)?.makeNode() } public static func leafNode(_ id: NodeRepresentable?) throws ->Node? { return try load(id)?.makeLeafNode() } public static func load(_ id: NodeRepresentable?) throws ->Self?{ if id == nil {return nil } return try Self.find(id!) } public static func load(_ field:String, _ value: NodeRepresentable?) throws ->Self?{ if value == nil {return nil} return try Self.query().filter(field, .equals, value!).first() } } extension RestModel { public static func all( _ field: String = "id", _ direction: Sort.Direction = .descending) throws ->[Self]{ return try Self.query().sort(field,direction).all() } public static func allNodes( _ field: String = "id", _ direction: Sort.Direction = .descending) throws ->[Node]{ return try all(field,direction).map {try $0.makeLeafNode()} } public static func allNode( _ field: String = "id", _ direction: Sort.Direction = .descending) throws ->Node{ return try allNodes(field,direction).makeNode() } } extension RestModel { public static func rawQueryCount(_ query :String, _ params:[Node]=[]) throws -> Int { let tableName = entity let sql = "select count(1) as c from \(tableName) \(query)" log(sql) return try database?.driver.raw(sql,params) [0]?.object?["c"]?.int ?? 0 } public static func rawQuery(sql :String, params:[Node]=[]) throws -> [Self]{ var array :[Self] = [] if let rows = try database?.driver.raw(sql,params),let nodeArray = rows.nodeArray { try nodeArray.forEach{array.append(try Self(node:$0))} } return array } public static func rawQuery(_ query :String, _ params:[Node]=[]) throws -> [Self]{ let tableName = entity let sql = "select * from \(tableName) \(query) " log(sql) var array :[Self] = [] if let rows = try database?.driver.raw(sql,params),let nodeArray = rows.nodeArray { try nodeArray.forEach{array.append(try Self(node:$0))} } return array } public static func rawQueryToLeafNodes(_ query :String, _ params:[Node]=[]) throws -> [Node]{ return try rawQuery(query,params).map(){try $0.makeLeafNode()} } }
mit
4b4b35d260210e29cad0049baa57ea5d
30.404412
97
0.618825
4.150632
false
false
false
false
delba/Log
Source/Logger.swift
1
8974
// // Logger.swift // // Copyright (c) 2015-2019 Damien (http://delba.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation private let benchmarker = Benchmarker() public enum Level: Int { case trace, debug, info, warning, error var description: String { return String(describing: self).uppercased() } } extension Level: Comparable { public static func < (lhs: Level, rhs: Level) -> Bool { return lhs.rawValue < rhs.rawValue } } open class Logger { /// The logger state. open var enabled: Bool = true /// The logger formatter. open var formatter: Formatter { didSet { formatter.logger = self } } /// The logger theme. open var theme: Theme? /// The minimum level of severity. open var minLevel: Level /// The logger format. open var format: String { return formatter.description } /// The logger colors open var colors: String { return theme?.description ?? "" } /// The queue used for logging. private let queue = DispatchQueue(label: "delba.log") /** Creates and returns a new logger. - parameter formatter: The formatter. - parameter theme: The theme. - parameter minLevel: The minimum level of severity. - returns: A newly created logger. */ public init(formatter: Formatter = .default, theme: Theme? = nil, minLevel: Level = .trace) { self.formatter = formatter self.theme = theme self.minLevel = minLevel formatter.logger = self } /** Logs a message with a trace severity level. - parameter items: The items to log. - parameter separator: The separator between the items. - parameter terminator: The terminator of the log message. - parameter file: The file in which the log happens. - parameter line: The line at which the log happens. - parameter column: The column at which the log happens. - parameter function: The function in which the log happens. */ open func trace(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) { log(.trace, items, separator, terminator, file, line, column, function) } /** Logs a message with a debug severity level. - parameter items: The items to log. - parameter separator: The separator between the items. - parameter terminator: The terminator of the log message. - parameter file: The file in which the log happens. - parameter line: The line at which the log happens. - parameter column: The column at which the log happens. - parameter function: The function in which the log happens. */ open func debug(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) { log(.debug, items, separator, terminator, file, line, column, function) } /** Logs a message with an info severity level. - parameter items: The items to log. - parameter separator: The separator between the items. - parameter terminator: The terminator of the log message. - parameter file: The file in which the log happens. - parameter line: The line at which the log happens. - parameter column: The column at which the log happens. - parameter function: The function in which the log happens. */ open func info(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) { log(.info, items, separator, terminator, file, line, column, function) } /** Logs a message with a warning severity level. - parameter items: The items to log. - parameter separator: The separator between the items. - parameter terminator: The terminator of the log message. - parameter file: The file in which the log happens. - parameter line: The line at which the log happens. - parameter column: The column at which the log happens. - parameter function: The function in which the log happens. */ open func warning(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) { log(.warning, items, separator, terminator, file, line, column, function) } /** Logs a message with an error severity level. - parameter items: The items to log. - parameter separator: The separator between the items. - parameter terminator: The terminator of the log message. - parameter file: The file in which the log happens. - parameter line: The line at which the log happens. - parameter column: The column at which the log happens. - parameter function: The function in which the log happens. */ open func error(_ items: Any..., separator: String = " ", terminator: String = "\n", file: String = #file, line: Int = #line, column: Int = #column, function: String = #function) { log(.error, items, separator, terminator, file, line, column, function) } /** Logs a message. - parameter level: The severity level. - parameter items: The items to log. - parameter separator: The separator between the items. - parameter terminator: The terminator of the log message. - parameter file: The file in which the log happens. - parameter line: The line at which the log happens. - parameter column: The column at which the log happens. - parameter function: The function in which the log happens. */ private func log(_ level: Level, _ items: [Any], _ separator: String, _ terminator: String, _ file: String, _ line: Int, _ column: Int, _ function: String) { guard enabled && level >= minLevel else { return } let date = Date() let result = formatter.format( level: level, items: items, separator: separator, terminator: terminator, file: file, line: line, column: column, function: function, date: date ) queue.async { Swift.print(result, separator: "", terminator: "") } } /** Measures the performance of code. - parameter description: The measure description. - parameter n: The number of iterations. - parameter file: The file in which the measure happens. - parameter line: The line at which the measure happens. - parameter column: The column at which the measure happens. - parameter function: The function in which the measure happens. - parameter block: The block to measure. */ open func measure(_ description: String? = nil, iterations n: Int = 10, file: String = #file, line: Int = #line, column: Int = #column, function: String = #function, block: () -> Void) { guard enabled && .debug >= minLevel else { return } let measure = benchmarker.measure(description, iterations: n, block: block) let date = Date() let result = formatter.format( description: measure.description, average: measure.average, relativeStandardDeviation: measure.relativeStandardDeviation, file: file, line: line, column: column, function: function, date: date ) queue.async { Swift.print(result) } } }
mit
a280300bacf14f9b7bf2867d170c856e
38.017391
190
0.631937
4.51863
false
false
false
false
webstersx/DataStructures
DataStructuresKit/DataStructuresKit/LinkedList2.swift
1
2600
// // LinkedList2.swift // DataStructuresKit // // Created by Shawn Webster on 26/08/2015. // Copyright © 2015 Shawn Webster. All rights reserved. // import Foundation public class LinkedNode2<T:Equatable> { public var value : T public var next : LinkedNode2<T>? = nil public var prev : LinkedNode2<T>? = nil public init(value:T) { self.value = value } } public class LinkedList2<T:Equatable>: CustomStringConvertible { /* add(value) append(node) prepend(node) remove(node) (node) nodeAtPosition(index) replace(node, value) (bool)isEmpty (string)description */ private(set) public var head : LinkedNode2<T>? private(set) public var tail : LinkedNode2<T>? private(set) public var length : Int = 0 public var description : String { var d : String = "" if let n = head { d += "\(n.value)" var m = n.next while (m != nil) { d += " -> \(m!.value)" m = m!.next } } else { d = "[ empty ]" } return d } public init() { head = nil tail = nil } public func isEmpty() -> Bool { return length == 0 } public func add(value : T) { append(LinkedNode2<T>(value: value)) } public func append(node: LinkedNode2<T>) { tail?.next = node node.prev = tail tail = node if isEmpty() { head = node } length++ } public func prepend(node: LinkedNode2<T>) { node.next = head head?.prev = node head = node if isEmpty() { tail = node } length++ } public func remove(node: LinkedNode2<T>) { node.prev?.next = node.next node.next?.prev = node.prev if node === head { head = node.next } if node === tail { tail = node.prev } length-- } public func removeHead() { if let h = head { self.remove(h) } } public func removeTail() { if let t = tail { self.remove(t) } } public func nodeAtPosition(index : Int) -> LinkedNode2<T>? { var n = head for var i=index; i>0; i-- { n = n?.next } return n } }
mit
ff45a16e4d57b57796637553cb9eb9e6
18.548872
64
0.454021
4.274671
false
false
false
false
ArinaYauk/WetterApp
GesturesTutorial/GesturesTutorial/GesturesViewController.swift
1
3204
// // ViewController.swift // GesturesTutorial // // Copyright (c) 2015 . All rights reserved. // import UIKit class GesturesViewController: UIViewController { @IBOutlet weak var gestureName: UILabel! @IBOutlet weak var tapView: UIView! @IBOutlet weak var rotateView: UIView! @IBOutlet weak var longPressView: UIView! @IBOutlet weak var pinchView: UIView! @IBOutlet weak var panView: UIView! @IBOutlet weak var swipeView: UIView! var rotation = CGFloat() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let tap = UITapGestureRecognizer(target: self, action: "tappedView:") tap.numberOfTapsRequired = 1 tapView.addGestureRecognizer(tap) let longPress = UILongPressGestureRecognizer(target: self, action: "longPressedView:"); longPressView.addGestureRecognizer(longPress) let pinch = UIPinchGestureRecognizer(target: self, action: "pinchedView:"); pinchView.addGestureRecognizer(pinch) let swipe = UISwipeGestureRecognizer(target: self, action: "swipedView:"); swipeView.addGestureRecognizer(swipe) } func tappedView() { } func tappedView(recognizer : UITapGestureRecognizer) { //message: "tapped" print("tapped") showGestureName("Tapped") } func swipedView(recognizer : UISwipeGestureRecognizer) { //message: "Swiped" showGestureName("Swiped") } func longPressedView(recognizer : UILongPressGestureRecognizer) { //message: "longpress" showGestureName("LongPress") } func rotatedView(sender: UIRotationGestureRecognizer) { showGestureName("Rotated") } func draggedView(sender: UIPanGestureRecognizer) { showGestureName("Dragged") } @IBAction func longPressView(sender: UILongPressGestureRecognizer) { print("Long Press ") showGestureName("Long Press") } @IBAction func rotationView(sender: UIRotationGestureRecognizer) { print("Rotation ") showGestureName("Rotation") rotateView.transform = CGAffineTransformMakeRotation(CGFloat(rotation)) rotation += CGFloat(M_PI/180.0); } @IBAction func pinchView(sender: UIPinchGestureRecognizer) { print("Pinch ") showGestureName("Pinch") } func showAlertViewControllerWith(title: String, message: String) { let tapAlert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert) tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil)) self.presentViewController(tapAlert, animated: true, completion: nil) } func showGestureName(name: String) { gestureName.text = name UIView.animateWithDuration(1.0, animations: { self.gestureName.alpha = 1.0 }, completion: { _ in UIView.animateWithDuration(1.0) { self.gestureName.alpha = 0 } }) } }
apache-2.0
dd86437ab197b36bc9aff38e58cdc88b
30.106796
118
0.644195
5.15942
false
false
false
false
eminemoholic/SoruVA
soru/SettingsController.swift
1
3803
// // SettingsController.swift // soru // // Created by Aditya Gurjar on 6/25/17. // Copyright © 2017 IBM. All rights reserved. // import UIKit class SettingsController : UIViewController, UITableViewDelegate, UITableViewDataSource{ let items = ["Primary Color", "Secondary Color", "User Chat Bubble", "Watson Chat Bubble"] var currentCell : SettingsCell! var ceesd : UITextView! override func viewDidLoad() { super.viewDidLoad() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SettingsCell cell.settingTitle.setTitle(items[indexPath.row], for: .normal) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as! SettingsCell var itemType = "" switch(indexPath.row){ case 0: itemType = "primary" case 1: itemType = "accent" case 2: itemType = "user" case 3: itemType = "watson" default: itemType = "primary" } let themeAlert = UIAlertController(title: "Select theme", message: "Choose a theme to customize", preferredStyle: UIAlertControllerStyle.actionSheet) themeAlert.addAction(UIAlertAction(title: "Red", style: .default, handler: { (action: UIAlertAction!) in cell.settingTile.backgroundColor = getColor(color: "red",itemType: itemType) self.changeTheme("red",indexPath.row) })) themeAlert.addAction(UIAlertAction(title: "Green", style: .default, handler: { (action: UIAlertAction!) in cell.settingTile.backgroundColor = getColor(color: "green",itemType: itemType) self.changeTheme("green",indexPath.row) })) themeAlert.addAction(UIAlertAction(title: "Blue", style: .default, handler: { (action: UIAlertAction!) in cell.settingTile.backgroundColor = getColor(color: "blue",itemType: itemType) self.changeTheme("blue",indexPath.row) })) themeAlert.addAction(UIAlertAction(title: "Black", style: .default, handler: { (action: UIAlertAction!) in cell.settingTile.backgroundColor = getColor(color: "black",itemType: itemType) self.changeTheme("black",indexPath.row) })) themeAlert.addAction(UIAlertAction(title: "White", style: .default, handler: { (action: UIAlertAction!) in cell.settingTile.backgroundColor = getColor(color: "white",itemType: itemType) self.changeTheme("white",indexPath.row) })) present(themeAlert, animated: true, completion: nil) } func changeTheme(_ theme : String ,_ currentIndex : Int){ print("Index",currentIndex) switch(currentIndex){ case 0 : print("Primary") UserDefaults.standard.set(theme, forKey: "primary") break case 1 : print("Accent") UserDefaults.standard.set(theme, forKey: "accent") break case 2 : UserDefaults.standard.set(theme, forKey: "user") break case 3 : UserDefaults.standard.set(theme, forKey: "watson") break default : break } } }
mit
34311052fd61aa22cfe06153a518a6bc
31.220339
157
0.586007
5.015831
false
false
false
false
criticalmaps/criticalmaps-ios
CriticalMapsKit/Sources/Styleguide/NavigationBar.swift
1
3067
import SwiftUI public enum NavPresentationStyle { case modal case navigation } public extension View { func navigationStyle<Title: View, Trailing: View>( backgroundColor: Color = Color(.backgroundSecondary), foregroundColor: Color = Color(.textPrimary), title: Title, navPresentationStyle: NavPresentationStyle = .navigation, trailing: Trailing, onDismiss: @escaping () -> Void = {} ) -> some View { NavigationBar( backgroundColor: backgroundColor, content: self, foregroundColor: foregroundColor, navPresentationStyle: navPresentationStyle, onDismiss: onDismiss, title: title, trailing: trailing ) } func navigationStyle<Title: View>( backgroundColor: Color = Color(.backgroundSecondary), foregroundColor: Color = Color(.textPrimary), title: Title, navPresentationStyle: NavPresentationStyle = .navigation, onDismiss: @escaping () -> Void = {} ) -> some View { navigationStyle( backgroundColor: backgroundColor, foregroundColor: foregroundColor, title: title, navPresentationStyle: navPresentationStyle, trailing: EmptyView(), onDismiss: onDismiss ) } } private struct NavigationBar<Title: View, Content: View, Trailing: View>: View { let backgroundColor: Color let content: Content let foregroundColor: Color let navPresentationStyle: NavPresentationStyle let onDismiss: () -> Void @Environment(\.presentationMode) @Binding var presentationMode let title: Title let trailing: Trailing var body: some View { VStack { ZStack { self.title .font(.pageTitle) HStack { if self.navPresentationStyle == .navigation { Button(action: self.dismiss) { Image(systemName: "arrow.left") } } Spacer() if self.navPresentationStyle == .modal { Button(action: self.dismiss) { Image(systemName: "xmark") .font(Font.system(size: 22, weight: .medium)) } } else { self.trailing } } } .padding() self.content } .background(self.backgroundColor.ignoresSafeArea()) .foregroundColor(self.foregroundColor) .navigationBarHidden(true) } func dismiss() { onDismiss() presentationMode.dismiss() } } public extension View { func dismissable() -> some View { modifier(DismissableModifier()) } } public struct DismissableModifier: ViewModifier { @Environment(\.presentationMode) var presentationMode public func body(content: Content) -> some View { content .toolbar { ToolbarItem( placement: .cancellationAction, content: { Button( action: { self.presentationMode.wrappedValue.dismiss() }, label: { Image(systemName: "xmark") .font(Font.system(size: 22).weight(.medium)) } ) } ) } } }
mit
93a5b22f0b410f1d970cdc786aa0cc9c
24.773109
80
0.617216
4.970827
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Settings/SettingsParameters.swift
1
6280
// // SettingsParameters.swift // // // Created by Vladislav Fitc on 19/11/2020. // import Foundation public protocol SettingsParameters: CommonParameters { // MARK: - Attributes /** The complete list of attributes that will be used for searching. - Engine default: [] - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/searchableAttributes/?language=swift) */ var searchableAttributes: [SearchableAttribute]? { get set } /** The complete list of attributes that will be used for faceting. - Engine default: [] - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/attributesForFaceting/?language=swift) */ var attributesForFaceting: [AttributeForFaceting]? { get set } /** List of attributes that cannot be retrieved at query time. - Engine default: [] - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/unretrievableAttributes/?language=swift) */ var unretrievableAttributes: [Attribute]? { get set } // MARK: - Ranking /** Controls the way results are sorted. - Engine default: [.typo, .geo, .words, .filters, .proximity, .attribute, .exact, .custom] - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/ranking/?language=swift) */ var ranking: [RankingCriterion]? { get set } /** Specifies the [CustomRankingCriterion]. - Engine default: [] - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/customRanking/?language=swift) */ var customRanking: [CustomRankingCriterion]? { get set } /** Creates replicas, exact copies of an index. - Engine default: [] - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/replicas/?language=swift) */ var replicas: [IndexName]? { get set } // MARK: - Pagination /** Set the maximum number of hits accessible via pagination. - Engine default: 1000 - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/paginationlimitedto/?language=swift) */ var paginationLimitedTo: Int? { get set } // MARK: - Typos /** List of words on which you want to disable typo tolerance. - Engine default: [] - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/disableTypoToleranceOnWords/?language=swift) */ var disableTypoToleranceOnWords: [String]? { get set } /** Control which separators are indexed. Separators are all non-alphanumeric characters except space. - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/separatorsToIndex/?language=swift) */ var separatorsToIndex: String? { get set } // MARK: - Languages /** Specify on which attributes to apply transliteration. Transliteration refers to the ability of finding results in a given alphabet with a query in another alphabet. For example, in Japanese, transliteration enables users to find results indexed in Kanji or Katakana with a query in Hiragana. - Engine default: [*] - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/attributesToTransliterate/?language=swift) */ var attributesToTransliterate: [Attribute]? { get set } /** List of [Attribute] on which to do a decomposition of camel case words. - Engine default: [] - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/camelCaseAttributes/?language=swift) */ var camelCaseAttributes: [Attribute]? { get set } /** Specify on which [Attribute] in your index Algolia should apply word-splitting (“decompounding”). - Engine default: [] - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/decompoundedAttributes/?language=swift) */ var decompoundedAttributes: DecompoundedAttributes? { get set } /** Characters that should not be automatically normalized by the search engine. - Engine default: "&quot;&quot;" - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/keepDiacriticsOnCharacters/?language=swift) */ var keepDiacriticsOnCharacters: String? { get set } /** Override the custom normalization handled by the engine. */ var customNormalization: [String: [String: String]]? { get set } /** This parameter configures the segmentation of text at indexing time. - Accepted value: Language.japanese - Input data to index is treated as the given language(s) for segmentation. */ var indexLanguages: [Language]? { get set } // MARK: - Query strategy /** List of [Attribute] on which you want to disable prefix matching. - Engine default: [] - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/disablePrefixOnAttributes/?language=swift) */ var disablePrefixOnAttributes: [Attribute]? { get set } // MARK: - Performance /** List of [NumericAttributeFilter] that can be used as numerical filters. - Engine default: null - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/?language=swift) */ var numericAttributesForFiltering: [NumericAttributeFilter]? { get set } /** Enables compression of large integer arrays. - Engine default: false - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/allowCompressionOfIntegerArray/?language=swift) */ var allowCompressionOfIntegerArray: Bool? { get set } // MARK: - Advanced /** Name of the de-duplication [Attribute] to be used with the [distinct] feature. - Engine default: null - [Documentation](https://www.algolia.com/doc/api-reference/api-parameters/attributeForDistinct/?language=swift) */ var attributeForDistinct: Attribute? { get set } /** Content defining how the search interface should be rendered. This is set via the settings for a default value and can be overridden via rules */ var renderingContent: RenderingContent? { get set } /** Lets you store custom data in your indices. */ var userData: JSON? { get set } /** Settings version. */ var version: Int? { get set } /** This parameter keeps track of which primary index (if any) a replica is connected to. */ var primary: IndexName? { get set } }
mit
259667dd7e5bc6cbbbbc7b4d85ec8c08
33.674033
240
0.713512
4.067401
false
false
false
false
PedroTrujilloV/TIY-Assignments
18--Mary-Samsonite/MuttCuttsHitsTheRoad/MuttCuttsHitsTheRoad/PopoverAddCityViewController.swift
1
2330
// // PopoverAddCityViewController.swift // MuttCuttsHitsTheRoad // // Created by Pedro Trujillo on 10/28/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit class PopoverAddCityViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var cityTextFiled: UITextField! @IBOutlet weak var stateTextField: UITextField! var delegator:PopoverViewControllerProtocol! var cityAndStateArray = Array<String>() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. cityTextFiled.text = "" stateTextField.text = "" cityTextFiled.becomeFirstResponder() //delegator?.operatorWasChosen(selectedOperation) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func cityEditingDidEnd(sender: UITextField) { if sender.text != "" { cityAndStateArray.append(sender.text!) stateTextField.becomeFirstResponder() } } @IBAction func stateEditionDidEnd(sender: UITextField) { if sender.text != "" { cityAndStateArray.append(sender.text!) let searchString = cityAndStateArray.joinWithSeparator(", ") delegator?.cityWasChosen(searchString) cityAndStateArray = [] } //sender.resignFirstResponder() } //MARK: - UITextField Delegate func textFieldShouldReturn(textField: UITextField) -> Bool { var rc = false if textField.text != "" { rc = true //cityAndStateArray.append(textField.text!) textField.resignFirstResponder() } return rc } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
cc0-1.0
2625c67e0da822c577c1dc72aa6f6ece
25.168539
106
0.613139
5.317352
false
false
false
false
lmihalkovic/WWDC-tvOS
WWDC/DetailViewController.swift
1
4367
// // DetailViewController.swift // WWDC // // Created by Guilherme Rambo on 20/11/15. // Copyright © 2015 Guilherme Rambo. All rights reserved. // import UIKit import AVFoundation import AVKit protocol DetailViewControllerDelegate:class { } class DetailViewController: UIViewController { var session: Session! { didSet { updateUI() } } @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var descriptionView: UILabel! @IBOutlet weak var watchButton: UIButton! @IBOutlet weak var favButton: UIButton! weak var delegate: DetailViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() favButton.showSystemAppearance() favButton.hidden = true watchButton.hidden = true titleLabel.hidden = true subtitleLabel.hidden = true descriptionView.hidden = true updateUI() } override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) { if (context.nextFocusedView == self.favButton) { favButton.showFocusOn() } else if (context.previouslyFocusedView == self.favButton) { favButton.showFocusOff() } } private func updateUI() { guard session != nil else { return } guard titleLabel != nil else { return } titleLabel.text = session.title subtitleLabel.text = session.subtitle descriptionView.text = session.summary watchButton.hidden = false titleLabel.hidden = false subtitleLabel.hidden = false descriptionView.hidden = false favButton.hidden = true // if(session.favorite) { // let img = Star.imageOfStarFilled // favButton.setImage(img.imageWithRenderingMode(.AlwaysTemplate), forState:.Normal); // favButton.accessibilityLabel = NSLocalizedString("Remove from Favourites", comment:""); // } else { // let img = Star.imageOfStarStroked // favButton.setImage(img.imageWithRenderingMode(.AlwaysTemplate), forState:.Normal); // favButton.accessibilityLabel = NSLocalizedString("Add to Favourites", comment:""); // } } // MARK: Favourites @IBAction func toggleFavorite(sender: AnyObject?) { WWDCDatabase.sharedDatabase.doChanges({ [unowned self] in self.session.favorite = !self.session.favorite self.updateUI() }) } // MARK: Playback var player: AVPlayer? var timeObserver: AnyObject? // TODO: cleanup // func dissmissVideoPlayer(sender: AnyObject?) { // player?.currentItem = nil; // } @IBAction func watch(sender: AnyObject?) { let (playerController, newPlayer) = PlayerBuilder.buildPlayerViewController(session.ATVURL.absoluteString, title: session.title, description: session.summary) player = newPlayer // let menuTouchRecognizer = UITapGestureRecognizer(target: self, action: "dissmissVideoPlayer:") // menuTouchRecognizer.allowedPressTypes = [UIPressType.Menu.rawValue] // playerController.view.addGestureRecognizer(menuTouchRecognizer) presentViewController(playerController, animated: true) { [unowned self] in self.timeObserver = self.player?.addPeriodicTimeObserverForInterval(CMTimeMakeWithSeconds(5, 1), queue: dispatch_get_main_queue()) { currentTime in let progress = Double(CMTimeGetSeconds(currentTime)/CMTimeGetSeconds(self.player!.currentItem!.duration)) WWDCDatabase.sharedDatabase.doChanges { self.session!.progress = progress self.session!.currentPosition = CMTimeGetSeconds(currentTime) } } if self.session.currentPosition > 0 { self.player?.seekToTime(CMTimeMakeWithSeconds(self.session.currentPosition, 1)) } playerController.player?.play() } } deinit { if let observer = timeObserver { player?.removeTimeObserver(observer) } } }
bsd-2-clause
52175bcf7365902aa39903503c88e3fa
31.58209
166
0.631699
5.203814
false
false
false
false
tutsplus/unit-testing-with-swift-and-xctest
SimpleTipCalculator/SimpleTipCalculatorViewController.swift
1
4050
// // SimpleTipCalculatorViewController.swift // SimpleTipCalculator // // Created by Derek Jensen on 5/3/15. // Copyright (c) 2015 Derek Jensen. All rights reserved. // import UIKit class SimpleTipCalculatorViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var txtBillAmount: UITextField! @IBOutlet weak var txtTaxPercentage: UITextField! @IBOutlet weak var swtichIncludeTax: UISwitch! @IBOutlet weak var sliderTipPercentage: UISlider! @IBOutlet weak var lblBillAmount: UILabel! @IBOutlet weak var lblTaxAmount: UILabel! @IBOutlet weak var lblTipAmount: UILabel! @IBOutlet weak var lblTotalAmount: UILabel! @IBOutlet weak var lblNotes: UILabel! @IBOutlet weak var lblCurrentTipPercentage: UILabel! let tipCalc = TipCalculator() var billAmount: Float? = 0 var taxPercentage: Float? = 0 var tipPercentage: Float? = 20 override func viewDidLoad() { super.viewDidLoad() txtBillAmount.delegate = self txtTaxPercentage.delegate = self txtBillAmount.addTarget(self, action: "txtBillAmountDidChange:", forControlEvents: .EditingChanged) txtTaxPercentage.addTarget(self, action: "txtTaxPercentageDidChange:", forControlEvents: .EditingChanged) } func txtBillAmountDidChange(textField: UITextField) { billAmount = (textField.text as NSString).floatValue validateInput() updateValues() } func txtTaxPercentageDidChange(textField: UITextField) { taxPercentage = (textField.text as NSString).floatValue / 100 validateInput() updateValues() } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let inverseSet = NSCharacterSet(charactersInString:"0123456789.").invertedSet let components = string.componentsSeparatedByCharactersInSet(inverseSet) let filtered = join("", components) return string == filtered } func veryImportantFunc() -> Bool { return true } private func validateInput() { if billAmount! < 0 { txtBillAmount.backgroundColor = UIColor.redColor() }else { txtBillAmount.backgroundColor = UIColor.greenColor() } if taxPercentage! < 0 { txtTaxPercentage.backgroundColor = UIColor.redColor() }else { txtTaxPercentage.backgroundColor = UIColor.greenColor() } } private func updateValues() { lblBillAmount.text = String(format: "$%.2f", billAmount!) var taxAmount = (taxPercentage! * billAmount!) lblTaxAmount.text = String(format: "$%.2f", taxAmount) lblCurrentTipPercentage.text = "\(Int(tipPercentage!))%" var tipPercentageString = String(format: "%.2f", tipPercentage!) var tipAmount = tipCalc.calculateTip(billAmount, taxPercentage: taxPercentage, tipPercentage: Float(tipPercentage!) / 100) lblTipAmount.text = String(format: "$%.2f", tipAmount!) var total = billAmount! + taxAmount + tipAmount! lblTotalAmount.text = String(format: "$%.2f", total) } @IBAction func sliderValueChanged(sender: UISlider) { tipPercentage = Float(sender.value) updateValues() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
bsd-2-clause
878dc8f301edfc323a2a886a2fa0af87
31.4
130
0.648889
5.25974
false
false
false
false
vasarhelyia/SwiftySheetsDemo
SwiftySheetsDemo/UIViewStyleExtensions.swift
1
1369
// // UIViewStyleExtensions.swift // SwiftySheetsDemo // // Created by Agnes Vasarhelyi on 03/07/16. // Copyright © 2016 Agnes Vasarhelyi. All rights reserved. // import Foundation import UIKit @objc(SWStyle) class Style: NSObject { var font: UIFont? var fontColor: UIColor? var fontColorAndState: (UIColor, UIControlState)? var textAlignment: NSTextAlignment? } extension UIView { @objc class func setStyle(style: Style, viewClass: AnyClass) { } } extension UILabel { override class func setStyle(style: Style, viewClass: AnyClass) { if let font = style.font { self.appearanceWhenContainedInInstancesOfClasses([viewClass]).font = font } if let fontColor = style.fontColor { self.appearanceWhenContainedInInstancesOfClasses([viewClass]).textColor = fontColor } if let textAlignment = style.textAlignment { self.appearanceWhenContainedInInstancesOfClasses([viewClass]).textAlignment = textAlignment } } } extension UIButton { override class func setStyle(style: Style, viewClass: AnyClass) { if let font = style.font { self.appearanceWhenContainedInInstancesOfClasses([viewClass]).titleLabel?.font = font } if let fontColor = style.fontColorAndState?.0, let state = style.fontColorAndState?.1 { self.appearanceWhenContainedInInstancesOfClasses([viewClass]).setTitleColor(fontColor, forState: state) } } }
mit
5dba44efa9dcd6f585bdda985b223d27
23.872727
106
0.754386
4.047337
false
false
false
false
Sadmansamee/quran-ios
Quran/JuzTableViewHeaderFooterView.swift
1
1584
// // JuzTableViewHeaderFooterView.swift // Quran // // Created by Mohamed Afifi on 4/22/16. // Copyright © 2016 Quran.com. All rights reserved. // import UIKit class JuzTableViewHeaderFooterView: UITableViewHeaderFooterView { let titleLabel: UILabel = UILabel() let subtitleLabel: UILabel = UILabel() let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer() var object: Any? var onTapped: (() -> Void)? override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) setUp() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setUp() } fileprivate func setUp() { addGestureRecognizer(tapGesture) tapGesture.addTarget(self, action: #selector(onViewTapped)) contentView.backgroundColor = UIColor(rgb: 0xEEEEEE) titleLabel.textColor = UIColor(rgb: 0x323232) titleLabel.font = UIFont.boldSystemFont(ofSize: 15) contentView.addAutoLayoutSubview(titleLabel) _ = contentView.pinParentVertical(titleLabel) _ = contentView.addParentLeadingConstraint(titleLabel, value: 20) subtitleLabel.textColor = UIColor(rgb: 0x4B4B4B) subtitleLabel.font = UIFont.systemFont(ofSize: 12) subtitleLabel.textAlignment = .right contentView.addAutoLayoutSubview(subtitleLabel) _ = contentView.pinParentVertical(subtitleLabel) _ = contentView.addParentTrailingConstraint(subtitleLabel, value: 10) } func onViewTapped() { onTapped?() } }
mit
4001335e05a34bf672dc2c9fae1e5643
27.781818
77
0.686039
4.683432
false
false
false
false
TelerikAcademy/Mobile-Applications-with-iOS
demos/OopDemos/OopDemos/main.swift
1
1264
// // main.swift // OopDemos // // Created by Doncho Minkov on 3/15/17. // Copyright © 2017 Doncho Minkov. All rights reserved. // import Foundation typealias A = Animal //let namelessAnimal = Animal() //namelessAnimal.sayName() // //let gosho = Animal(withName: "G", andAge: 17) //gosho.name = "Gesha" // //gosho.name = "Gosho 2" //print(gosho.name) //gosho.sayName() //animal.age = 5 //animal.name = "Sharo" // //class DerivedAnimal: Animal { // //} // //let animals: [Animal] = [ // Animal(), // DerivedAnimal(), // Cat(withName: "Gosho", // age: 3, // andGender: .other), // WildCat(withName: "Goshka", // age: 5, // andGender: .female) //] //for a in animals { // a.sayName() //} // // // //let cat = Cat(withName: "Stamat", // age: 2, // andGender: .male) // //cat.sayName() // //let mauables: [Mauable] = [ // Cat(withName: "Gosho", age: 2, gender: .male, andMausCount: 5), // WildCat(withName: "Goshka", age: 3, andGender: .female), // Cat(withName: "John", age: 5, andGender: .other) //] // //for mauable in mauables { // mauable.mau() //} let animal = Cat(withName: "Pesho", age: 3, andGender: .male) print(animal.toDict())
mit
b6dc08a0fd389f1acce025dab6ebf805
18.136364
69
0.555028
2.647799
false
false
false
false
double-y/ios_swift_practice
ios_swift_practice/ViewController.swift
1
1795
// // ViewController.swift // ios_swift_practice // // Created by 安田洋介 on 7/8/15. // Copyright © 2015 安田洋介. All rights reserved. // import UIKit import WatchConnectivity import Charts import CoreData class ViewController: UIViewController{ var managedObjectContext: NSManagedObjectContext! = nil @IBOutlet weak var dataSetCount: UILabel! var happinessData = [NSManagedObject]() var angerData = [NSManagedObject]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. /*print(WCSession.isSupported()) session = WCSession.defaultSession() session?.delegate = self session?.activateSession()*/ managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext } override func viewWillAppear(animated: Bool) { let emotionDataSets = (try! EmotionDataSet.fetchAll(managedObjectContext)) if emotionDataSets?.count > 0 { dataSetCount.text = "\(emotionDataSets!.count)" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let vc = segue.destinationViewController as? YYAddEmotionDataNavigationController{ let emotion = try! Emotion.fetchAll(managedObjectContext) if(emotion == nil){ }else{ vc.emotionIndex = 0 vc.emotions = emotion! vc.emotionDataSet = try! EmotionDataSet.create(managedObjectContext) } } } }
mit
786c3cb0c3d8c53d42ae2c25ef05e32d
29.135593
112
0.652981
5.19883
false
false
false
false
iMetalk/TCZKit
TCZKitDemo/TCZKit/Views/Cells/标题+输入框+图标 TCZTitleTextFieldImageCell/TCZTitleTextFieldImageCell.swift
1
1446
// // TCZTitleTextFieldImageCell.swift // Dormouse // // Created by 田向阳 on 2017/8/11. // Copyright © 2017年 WangSuyan. All rights reserved. // import UIKit class TCZTitleTextFieldImageCell: TCZTitleTextFieldCell { override func tczConfigureData(aItem: TCZTableViewData) { titleLabel.text = aItem.title rightImageView.image = aItem.image } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) createSubUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: createUI func createSubUI() { contentView.addSubview(rightImageView) rightImageView.snp.makeConstraints { (make) in make.right.equalToSuperview().offset(-kLeftEdge) make.centerY.equalToSuperview() make.size.equalTo(CGSize(width: 20, height: 20)) } textField.snp.remakeConstraints { (make) in make.left.equalTo(titleLabel.snp.right).offset(kLeftEdge) make.bottom.top.equalToSuperview() make.right.equalTo(rightImageView.snp.left).offset(-kLeftEdge) } } //MARK:lazy lazy var rightImageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView }() }
mit
a869be8d2f388a21bddb548329798fec
28.9375
74
0.649965
4.448916
false
false
false
false
myandy/shi_ios
shishi/DB/Yun.swift
1
2225
// // Yun.swift // shishi // // Created by andymao on 2017/4/15. // Copyright © 2017年 andymao. All rights reserved. // import Foundation import FMDB public class Yun { var tone: Int! var glys: String! var section_desc: String! var tone_name: String! } class YunDB { private static let YUNSHU = ["zhonghuaxinyun", "pingshuiyun", "cilinzhengyun"] private static var yunList = [Yun]() public class func getArray(_ rs: FMResultSet) -> [Yun]{ var array = [Yun]() while rs.next() { let model = Yun() model.tone = Int(rs.int(forColumn: "tone")) model.glys = rs.string(forColumn: "glys") model.section_desc = rs.string(forColumn: "section_desc") model.tone_name = rs.string(forColumn: "tone_name") array.append(model) } return array } public class func getAll() -> [Yun] { let db = DBManager.shared.getDatabase() let sql = "select * from ".appending(YUNSHU[UserDefaultUtils.getYunshu()]) var array = [Yun]() let rs : FMResultSet do { try rs = db.executeQuery(sql,values: []) array = getArray(rs) } catch{ print(error) } return array } private class func getYunList(){ if yunList.isEmpty{ yunList = getAll() } } /** * 获取平仄 */ public class func getWordStone(_ word: Character) -> Int { getYunList() var tones=[Int]() for item in yunList{ if (item.glys.characters.contains(word)) { tones.append(Int(item.tone)) } } if (tones.count == 1) { return tones[0]; } else { return 30; } } /** * 获取同韵字 */ public class func getSameYun(_ word: Character) -> [Yun] { getYunList() var yuns=[Yun]() for item in yunList{ if (item.glys.characters.contains(word)) { yuns.append(item) } } return yuns } }
apache-2.0
429a8d7bcbc3eb22f108f8d79a217f89
21.721649
82
0.495009
3.859895
false
false
false
false
ibm-wearables-sdk-for-mobile/ios
RecordApp/RecordApp/FileUtils.swift
2
1808
/* * © Copyright 2015 IBM Corp. * * Licensed under the Mobile Edge iOS Framework License (the "License"); * you may not use this file except in compliance with the License. You may find * a copy of the license in the license.txt file in this package. * * 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 Foundation class FileUtils { //get file path of a gesture file by name static func getFilePath(name:String) -> String{ return (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("\(name).js") } //get all the gesture file names static func getJsFileNames() -> [String]{ var fileNames = [String]() let filemanager = NSFileManager() let files = filemanager.enumeratorAtPath(NSTemporaryDirectory()) while let file = files?.nextObject() { let nameWithoutExtension = String((file as! String).characters.dropLast(3)) fileNames.append(nameWithoutExtension) } return fileNames } //get all gestures file paths static func getAllFilePaths() -> [String]{ var filePaths = [String]() for name in getJsFileNames(){ filePaths.append(getFilePath(name)) } return filePaths } //delete gesture file by name static func deleteJSFile(name:String){ let filemanager = NSFileManager() try! filemanager.removeItemAtPath(getFilePath(name)) } }
epl-1.0
d38cc494a86caa104792f6d8815e8314
30.172414
96
0.645822
4.950685
false
false
false
false
justindarc/firefox-ios
AccountTests/TokenServerClientTests.swift
2
5368
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ @testable import Account import FxA import Shared import UIKit import XCTest private let ProductionTokenServerEndpointURL = URL(string: "https://token.services.mozilla.com/1.0/sync/1.5")! // Testing client state is so delicate that I'm not going to test this. The test below does two // requests; we would need a third, and a guarantee of the server state, to test this completely. // The rule is: if you turn up with a never-before-seen client state; you win. If you turn up with // a seen-before client state, you lose. class TokenServerClientTests: LiveAccountTest { func testErrorOutput() { // Make sure we don't hide error details. let error = NSError(domain: "test", code: 123, userInfo: nil) XCTAssertEqual( "<TokenServerError.Local Error Domain=test Code=123 \"The operation couldn’t be completed. (test error 123.)\">", TokenServerError.local(error).description) } func testAudienceForEndpoint() { func audienceFor(_ endpoint: String) -> String { return TokenServerClient.getAudience(forURL: URL(string: endpoint)!) } // Sub-domains and path components. XCTAssertEqual("http://sub.test.com", audienceFor("http://sub.test.com")) XCTAssertEqual("http://test.com", audienceFor("http://test.com/")) XCTAssertEqual("http://test.com", audienceFor("http://test.com/path/component")) XCTAssertEqual("http://test.com", audienceFor("http://test.com/path/component/")) // No port and default port. XCTAssertEqual("http://test.com", audienceFor("http://test.com")) XCTAssertEqual("http://test.com:80", audienceFor("http://test.com:80")) XCTAssertEqual("https://test.com", audienceFor("https://test.com")) XCTAssertEqual("https://test.com:443", audienceFor("https://test.com:443")) // Ports that are the default ports for a different scheme. XCTAssertEqual("https://test.com:80", audienceFor("https://test.com:80")) XCTAssertEqual("http://test.com:443", audienceFor("http://test.com:443")) // Arbitrary ports. XCTAssertEqual("http://test.com:8080", audienceFor("http://test.com:8080")) XCTAssertEqual("https://test.com:4430", audienceFor("https://test.com:4430")) } func testTokenSuccess() { let audience = TokenServerClient.getAudience(forURL: ProductionTokenServerEndpointURL) withCertificate { expectation, emailUTF8, keyPair, certificate in let assertion = JSONWebTokenUtils.createAssertionWithPrivateKeyToSign(with: keyPair.privateKey, certificate: certificate, audience: audience) let client = TokenServerClient(url: ProductionTokenServerEndpointURL) client.token(assertion!).upon { result in if let token = result.successValue { XCTAssertNotNil(token.id) XCTAssertNotNil(token.key) XCTAssertNotNil(token.api_endpoint) XCTAssertNotNil(token.hashedFxAUID) XCTAssertTrue(token.uid >= 0) XCTAssertTrue(token.api_endpoint.hasSuffix(String(token.uid))) let expectedRemoteTimestamp: Timestamp = 1429121686000 XCTAssertTrue(token.remoteTimestamp >= expectedRemoteTimestamp) // Not a special timestamp; just a sanity check. } else { XCTAssertEqual(result.failureValue!.description, "") } expectation.fulfill() } } self.waitForExpectations(timeout: 100, handler: nil) } func testTokenFailure() { withVerifiedAccount { _, _ in // Account details aren't used, but we want to skip when we're not running live tests. let e = self.expectation(description: "") let assertion = "BAD ASSERTION" let client = TokenServerClient(url: ProductionTokenServerEndpointURL) client.token(assertion).upon { result in if let token = result.successValue { XCTFail("Got token: \(token)") } else { if let error = result.failureValue as? TokenServerError { switch error { case let .remote(code, status, remoteTimestamp): XCTAssertEqual(code, Int32(401)) // Bad auth. XCTAssertEqual(status!, "error") XCTAssertFalse(remoteTimestamp == nil) let expectedRemoteTimestamp: Timestamp = 1429121686000 XCTAssertTrue(remoteTimestamp! >= expectedRemoteTimestamp) // Not a special timestamp; just a sanity check. case let .local(error): XCTAssertNil(error) } } else { XCTFail("Expected TokenServerError") } } e.fulfill() } } self.waitForExpectations(timeout: 10, handler: nil) } }
mpl-2.0
428e37eed14e8eb0443099225a782313
46.486726
135
0.605852
5.000932
false
true
false
false
IBM-MIL/IBM-Ready-App-for-Insurance
PerchReadyApp/apps/Perch/iphone/native/Perch/Views/PerchAlertView/PerchAlertViewManager.swift
1
5497
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /** This class manages the Perch Alert View. Anywhere that an alert view needs to be displayed, this manager is what should be used to display it. */ public class PerchAlertViewManager: NSObject { private var perchAlertView: PerchAlertView! private var alertDisplayed = false /** Create the singleton instance of the manager */ public class var sharedInstance : PerchAlertViewManager { struct Singleton { static let instance = PerchAlertViewManager() } return Singleton.instance } override init() { super.init() } /** Creates an instance of the alert and sets the appropriate frame */ private func createAlert() { if let _ = perchAlertView { return } perchAlertView = PerchAlertView.instanceFromNib() as PerchAlertView perchAlertView.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height) perchAlertView.alpha = 0.0 } /** If the alert currently isn't shown, animate the alpha to 0 and then animate the alert on screen */ private func showAlert() { if !alertDisplayed { UIApplication.sharedApplication().keyWindow?.addSubview(perchAlertView) UIView.animateWithDuration(0.4, animations: { () -> Void in self.perchAlertView.alpha = 1.0 }, completion: { (completed) -> Void in if completed { self.perchAlertView.show() self.alertDisplayed = true } }) } else { perchAlertView.show() } } /** Creates the default instance of the Pin Alert which has a text prompt, textField, and two buttons */ func displayDefaultPinAlert() { createAlert() self.displayPinAlert(NSLocalizedString("Unable to connect to sensors. \nTry again or sync with a new pin.", comment: ""), rightButtonText: nil, leftButtonText: nil, rightButtonCallback: perchAlertView.syncNewPin, leftButtonCallback: perchAlertView.retrySync) } /** Creates an instance of the Pin Alert which has a text prompt, textField, and two buttons */ func displayPinAlert(alertText: String, rightButtonText: String?, leftButtonText: String?, rightButtonCallback: (()->())?, leftButtonCallback: (()->())?) { createAlert() perchAlertView.makePinAlert(alertText, rightButtonText: rightButtonText, leftButtonText: leftButtonText, rightButtonCallback: rightButtonCallback, leftButtonCallback: leftButtonCallback) showAlert() } /** Creates a default simple alert with text and two buttons. */ func displayDefaultSimpleAlertTwoButtons(leftButtonCallback: (()->())?, rightButtonCallback: (()->())?) { let alertText = NSLocalizedString("Unable to connect with the server, please try again", comment: "") let leftButtonText = NSLocalizedString("Try Again", comment: "") let rightButtonText = NSLocalizedString("Dismiss", comment: "") createAlert() self.displaySimpleAlertTwoButtons(alertText, leftButtonText: leftButtonText, rightButtonText: rightButtonText, leftButtonCallback: leftButtonCallback, rightButtonCallback: rightButtonCallback) } /** Creates a simple alert with text and two buttons */ func displaySimpleAlertTwoButtons(alertText: String, leftButtonText: String, rightButtonText: String, leftButtonCallback: (()->())?, rightButtonCallback: (()->())?) { createAlert() perchAlertView.makeSimpleAlertTwoButtons(alertText, leftButtonText: leftButtonText, rightButtonText: rightButtonText, leftButtonCallback: leftButtonCallback, rightButtonCallback: rightButtonCallback) showAlert() } /** Creates a simple alert with text and a single button */ func displaySimpleAlertSingleButton(alertText: String, buttonText: String, callback: (()->())?) { createAlert() if let _ = callback { perchAlertView.makeSimpleAlertSingleButton(alertText, buttonText: buttonText, buttonCallback: callback) } else { perchAlertView.makeSimpleAlertSingleButton(alertText, buttonText: buttonText, buttonCallback: hideAlertView) } showAlert() } /** Tells the alert view to animate off screen and show the loading icon */ func showLoadingScreen(loadingText: String) { perchAlertView.showSyncingAnimation(loadingText) } /** Removes the alertview from the screen and sets to nil */ func hideAlertView() { if alertDisplayed { alertDisplayed = false UIView.animateWithDuration(0.3, animations: { () -> Void in self.perchAlertView.alpha = 0.0 }, completion: { (completed) -> Void in if completed { self.perchAlertView.removeFromSuperview() self.perchAlertView.leftCallback = nil self.perchAlertView.rightCallback = nil self.perchAlertView.simpleCallback = nil self.perchAlertView = nil //self.perchAlertView.resetAlert() } }) } } }
epl-1.0
96c86a0a0788785d050eb168acf4619a
37.978723
266
0.642103
5.112558
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/DelegatedSelfCustody/Sources/DelegatedSelfCustodyData/Subscriptions/SubscriptionsService.swift
1
3955
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainNamespace import Combine import CryptoSwift import DelegatedSelfCustodyDomain import Foundation import Localization final class SubscriptionsService: DelegatedCustodySubscriptionsServiceAPI { private let accountRepository: AccountRepositoryAPI private let authClient: AuthenticationClientAPI private let authenticationDataRepository: AuthenticationDataRepositoryAPI private let subscriptionsClient: SubscriptionsClientAPI private let subscriptionsStateService: SubscriptionsStateServiceAPI init( accountRepository: AccountRepositoryAPI, authClient: AuthenticationClientAPI, authenticationDataRepository: AuthenticationDataRepositoryAPI, subscriptionsClient: SubscriptionsClientAPI, subscriptionsStateService: SubscriptionsStateServiceAPI ) { self.accountRepository = accountRepository self.authClient = authClient self.authenticationDataRepository = authenticationDataRepository self.subscriptionsClient = subscriptionsClient self.subscriptionsStateService = subscriptionsStateService } func subscribe() -> AnyPublisher<Void, Error> { subscriptionsStateService.isValid .flatMap { [authenticateAndSubscribeAccounts] isValid -> AnyPublisher<Void, Error> in guard !isValid else { return .just(()) } return authenticateAndSubscribeAccounts } .eraseToAnyPublisher() } private var authenticateAndSubscribeAccounts: AnyPublisher<Void, Error> { authenticate .flatMap { [subscribeAccounts] _ -> AnyPublisher<Void, Error> in subscribeAccounts } .eraseToAnyPublisher() } private var authenticate: AnyPublisher<Void, Error> { authenticationDataRepository.initialAuthenticationData .eraseError() .flatMap { [authClient] authenticationData -> AnyPublisher<Void, Error> in authClient.auth( guid: authenticationData.guid, sharedKeyHash: authenticationData.sharedKeyHash ) .eraseError() } .eraseToAnyPublisher() } private var subscribeAccounts: AnyPublisher<Void, Error> { accounts .zip(authenticationDataRepository.authenticationData.eraseError()) .flatMap { [subscriptionsClient, subscriptionsStateService] accounts, authenticationData -> AnyPublisher<Void, Error> in subscriptionsClient.subscribe( guidHash: authenticationData.guidHash, sharedKeyHash: authenticationData.sharedKeyHash, subscriptions: accounts ) .eraseError() .flatMap { [subscriptionsStateService] _ -> AnyPublisher<Void, Error> in subscriptionsStateService .recordSubscription(accounts: accounts.map(\.currency)) .eraseError() } .eraseToAnyPublisher() } .eraseToAnyPublisher() } private var accounts: AnyPublisher<[SubscriptionEntry], Error> { accountRepository .accounts .map { accounts -> [SubscriptionEntry] in accounts.map { account -> SubscriptionEntry in SubscriptionEntry( currency: account.coin.code, account: .init(index: 0, name: LocalizationConstants.Account.myWallet), pubKeys: [ .init(pubKey: account.publicKey.toHexString(), style: account.style, descriptor: 0) ] ) } } .eraseToAnyPublisher() } }
lgpl-3.0
94d95894250ad1f08e5b718f74c0735e
38.54
132
0.623672
6.27619
false
false
false
false
wujianguo/GitHubKit
Sources/WebLinking.swift
1
5330
import Foundation /// A structure representing a RFC 5988 link. public struct Link: Equatable, Hashable { /// The URI for the link public let uri: String /// The parameters for the link public let parameters: [String: String] /// Initialize a Link with a given uri and parameters public init(uri: String, parameters: [String: String]? = nil) { self.uri = uri self.parameters = parameters ?? [:] } /// Returns the hash value public var hashValue: Int { return uri.hashValue } /// Relation type of the Link. public var relationType: String? { return parameters["rel"] } /// Reverse relation of the Link. public var reverseRelationType: String? { return parameters["rev"] } /// A hint of what the content type for the link may be. public var type: String? { return parameters["type"] } } /// Returns whether two Link's are equivalent public func == (lhs: Link, rhs: Link) -> Bool { return lhs.uri == rhs.uri && lhs.parameters == rhs.parameters } // MARK: HTML Element Conversion /// An extension to Link to provide conversion to a HTML element extension Link { /// Encode the link into a HTML element public var html: String { let components = parameters.map { key, value in "\(key)=\"\(value)\"" } + ["href=\"\(uri)\""] let elements = components.joinWithSeparator(" ") return "<link \(elements) />" } } // MARK: Header link conversion /// An extension to Link to provide conversion to and from a HTTP "Link" header extension Link { /// Encode the link into a header public var header: String { let components = ["<\(uri)>"] + parameters.map { key, value in "\(key)=\"\(value)\"" } return components.joinWithSeparator("; ") } /*** Initialize a Link with a HTTP Link header - parameter header: A HTTP Link Header */ public init(header: String) { let (uri, parametersString) = takeFirst(separateBy(";")(header)) let parameters = parametersString.map(split("=")).map { parameter in [parameter.0: trim("\"", "\"")(parameter.1)] } self.uri = trim("<", ">")(uri) self.parameters = parameters.reduce([:], combine: +) } } /*** Parses a Web Linking (RFC5988) header into an array of Links - parameter header: RFC5988 link header. For example `<?page=3>; rel=\"next\", <?page=1>; rel=\"prev\"` :return: An array of Links */ public func parseLinkHeader(header: String) -> [Link] { return separateBy(",")(header).map { string in return Link(header: string) } } /// An extension to NSHTTPURLResponse adding a links property extension NSHTTPURLResponse { /// Parses the links on the response `Link` header public var links: [Link] { if let linkHeader = allHeaderFields["Link"] as? String { return parseLinkHeader(linkHeader).map { link in var uri = link.uri /// Handle relative URIs if let baseURL = self.URL, URL = NSURL(string: uri, relativeToURL: baseURL) { uri = URL.absoluteString } return Link(uri: uri, parameters: link.parameters) } } return [] } /// Finds a link which has matching parameters public func findLink(parameters: [String: String]) -> Link? { for link in links { if link.parameters ~= parameters { return link } } return nil } /// Find a link for the relation public func findLink(relation relation: String) -> Link? { return findLink(["rel": relation]) } } /// MARK: Private methods (used by link header conversion) /// Merge two dictionaries together func +<K,V>(lhs: [K:V], rhs: [K:V]) -> [K:V] { var dictionary = [K:V]() for (key, value) in rhs { dictionary[key] = value } for (key, value) in lhs { dictionary[key] = value } return dictionary } /// LHS contains all the keys and values from RHS func ~=(lhs: [String: String], rhs: [String: String]) -> Bool { for (key, value) in rhs { if lhs[key] != value { return false } } return true } /// Separate a trim a string by a separator func separateBy(separator: String) -> (String) -> [String] { return { input in return input.componentsSeparatedByString(separator).map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } } } /// Split a string by a separator into two components func split(separator: String) -> (String) -> (String, String) { return { input in let range = input.rangeOfString(separator, options: NSStringCompareOptions(rawValue: 0), range: nil, locale: nil) if let range = range { let lhs = input.substringToIndex(range.startIndex) let rhs = input.substringFromIndex(range.endIndex) return (lhs, rhs) } return (input, "") } } /// Separate the first element in an array from the rest func takeFirst(input: [String]) -> (String, ArraySlice<String>) { if let first = input.first { let items = input[input.startIndex.successor() ..< input.endIndex] return (first, items) } return ("", []) } /// Trim a prefix and suffix from a string func trim(lhs: Character, _ rhs: Character) -> (String) -> String { return { input in if input.hasPrefix("\(lhs)") && input.hasSuffix("\(rhs)") { return input[input.startIndex.successor()..<input.endIndex.predecessor()] } return input } }
mit
93bf6907c4e2c9624eb80f6df035f560
25.522388
117
0.643527
4.013554
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/GDPerformanceView-Swift/GDPerformanceView-Swift/GDPerformanceMonitoring/LinkedFramesList.swift
3
3272
// // Copyright © 2017 Gavrilov Daniil // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // MARK: Class Definition /// Linked list node. Represents frame timestamp. internal class FrameNode { // MARK: Public Properties var next: FrameNode? weak var previous: FrameNode? private(set) var timestamp: TimeInterval /// Initializes linked list node with parameters. /// /// - Parameter timeInterval: Frame timestamp. public init(timestamp: TimeInterval) { self.timestamp = timestamp } } // MARK: Class Definition /// Linked list. Each node represents frame timestamp. /// The only function is append, which will add a new frame and remove all frames older than a second from the last timestamp. /// As a result, the number of items in the list will represent the number of frames for the last second. internal class LinkedFramesList { // MARK: Private Properties private var head: FrameNode? private var tail: FrameNode? // MARK: Public Properties private(set) var count = 0 } // MARK: Public Methods internal extension LinkedFramesList { /// Appends new frame with parameters. /// /// - Parameter timestamp: New frame timestamp. func append(frameWithTimestamp timestamp: TimeInterval) { let newNode = FrameNode(timestamp: timestamp) if let lastNode = self.tail { newNode.previous = lastNode lastNode.next = newNode self.tail = newNode } else { self.head = newNode self.tail = newNode } self.count += 1 self.removeFrameNodes(olderThanTimestampMoreThanSecond: timestamp) } } // MARK: Support Methods private extension LinkedFramesList { func removeFrameNodes(olderThanTimestampMoreThanSecond timestamp: TimeInterval) { while let firstNode = self.head { guard timestamp - firstNode.timestamp > 1.0 else { break } let nextNode = firstNode.next nextNode?.previous = nil firstNode.next = nil self.head = nextNode self.count -= 1 } } }
mit
3a81ae960ed6ac9f892a47757e71aa22
31.386139
126
0.673189
4.782164
false
false
false
false
KaushalElsewhere/MockingBird
MockingBird/Controllers/DashboardCoordinator.swift
1
1606
// // DashboardCoordinator.swift // MockingBird // // Created by Kaushal Elsewhere on 03/08/16. // Copyright © 2016 Elsewhere. All rights reserved. // import UIKit import Firebase import FirebaseAuth extension DashboardCoordinator: DashboardControllerDelegate { func dashboardDidLogout() { do { try FIRAuth.auth()?.signOut() } catch let error { print(error) return } loginController.delegate = self dashboardController.presentViewController(loginController, animated: true, completion: nil) } func dashboardDidRequireLogin() { loginController.delegate = self dashboardController.presentViewController(loginController, animated: true, completion: nil) } } extension DashboardCoordinator: LoginControllerDelegate { func loginControllerDidRegisterUser() { dashboardController.dismissViewControllerAnimated(true, completion: nil) } func loginControllerDidLoginUser() { dashboardController.dismissViewControllerAnimated(true, completion: nil) } } class DashboardCoordinator: NSObject { let navController: UINavigationController let dashboardController: DashboardController let loginController = LoginController() init(navController: UINavigationController, rootViewController controller: DashboardController) { self.navController = navController self.dashboardController = controller super.init() self.dashboardController.delegate = self } }
mit
ada51d34a7006ee5ad7d75ba9f6601ac
25.311475
101
0.690343
5.857664
false
false
false
false
Palleas/GIF-Keyboard
AdventCalendar/AppDelegate.swift
1
1127
// // AppDelegate.swift // AdventCalendar // // Created by Romain Pouclet on 2015-11-28. // Copyright © 2015 Perfectly-Cooked. All rights reserved. // import UIKit import AWSS3 import Keys @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let keys = AdventcalendarKeys() let credentialsProvider = AWSStaticCredentialsProvider(accessKey: keys.amazonS3AccessKey(), secretKey: keys.amazonS3SecretSecret()) let configuration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: credentialsProvider) AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: .Default) UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().translucent = true UINavigationBar.appearance().tintColor = .whiteColor() return true } }
mit
370c2c562ac80b720a3e025538ad019e
31.171429
139
0.742451
5.439614
false
true
false
false
suzuki-0000/CountdownLabel
CountdownLabel/LTMorphingLabel/LTEasing.swift
1
1632
// // LTEasing.swift // LTMorphingLabelDemo // // Created by Lex on 7/1/14. // Copyright (c) 2015 lexrus.com. All rights reserved. // import Foundation // http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js // t = currentTime // b = beginning // c = change // d = duration public struct LTEasing { public static func easeOutQuint(_ t: Float, _ b: Float, _ c: Float, _ d: Float = 1.0) -> Float { return { return c * ($0 * $0 * $0 * $0 * $0 + 1.0) + b }(t / d - 1.0) } public static func easeInQuint(_ t: Float, _ b: Float, _ c: Float, _ d: Float = 1.0) -> Float { return { let x = c * $0 return x * $0 * $0 * $0 * $0 + b }(t / d) } public static func easeOutBack(_ t: Float, _ b: Float, _ c: Float, _ d: Float = 1.0) -> Float { let s: Float = 2.70158 let t2: Float = t / d - 1.0 return Float(c * (t2 * t2 * ((s + 1.0) * t2 + s) + 1.0)) + b } public static func easeOutBounce(_ t: Float, _ b: Float, _ c: Float, _ d: Float = 1.0) -> Float { return { if $0 < 1 / 2.75 { return c * 7.5625 * $0 * $0 + b } else if $0 < 2 / 2.75 { let t = $0 - 1.5 / 2.75 return c * (7.5625 * t * t + 0.75) + b } else if $0 < 2.5 / 2.75 { let t = $0 - 2.25 / 2.75 return c * (7.5625 * t * t + 0.9375) + b } else { let t = $0 - 2.625 / 2.75 return c * (7.5625 * t * t + 0.984375) + b } }(t / d) } }
mit
05178f834a23ddbc4ca5d505117e2d24
28.672727
101
0.429534
2.983547
false
false
false
false
haawa799/WaniKit2
Sources/WaniKit/Model/LevelProgressionInfo.swift
3
948
// // LevelProgressionInfo.swift // Pods // // Created by Andriy K. on 12/10/15. // // import Foundation public struct LevelProgressionInfo { // Dictionary keys private static let keyRadicalsProgress = "radicals_progress" private static let keyRadicalsTotal = "radicals_total" private static let keyKanjiProgress = "kanji_progress" private static let keyKanjiTotal = "kanji_total" // public var radicalsProgress: Int? public var radicalsTotal: Int? public var kanjiProgress: Int? public var kanjiTotal: Int? } extension LevelProgressionInfo: DictionaryInitialization { public init(dict: NSDictionary) { radicalsProgress = (dict[LevelProgressionInfo.keyRadicalsProgress] as? Int) radicalsTotal = (dict[LevelProgressionInfo.keyRadicalsTotal] as? Int) kanjiProgress = (dict[LevelProgressionInfo.keyKanjiProgress] as? Int) kanjiTotal = (dict[LevelProgressionInfo.keyKanjiTotal] as? Int) } }
mit
f2d7c536111d3768726d8e5e726c67a5
25.333333
79
0.744726
3.703125
false
false
false
false
Eonil/Monolith.Swift
Standards/Sources/RFC4627/RFC4627.Extensions.swift
3
1701
// // RFC4627.Extensions.swift // Monolith // // Created by Hoon H. on 10/21/14. // // import Foundation // // Fragment description is missing due to lack of implementation in Cocoa. // We need to implement our own generator and parser. // ///// MARK: //extension RFC4627.Value: Printable { // public var description:Swift.String { // get { // // // switch self { // case let .Object(s): return "{}" // case let .Array(s): return "[]" // case let .String(s): return "\"\"" // case let .Number(s): return "" // case let .Boolean(s): return "" // case let .Null: return "null" // } // //// let d1 = JSON.serialise(self) //// let s2 = NSString(data: d1!, encoding: NSUTF8StringEncoding) as Swift.String //// return s2 // } // } //} //private func escapeString(s:String) -> String { // func shouldEscape(ch1:Character) -> (shouldPrefix:Bool, specifier:Character) { // switch ch1 { // case "\u{0022}": return (true, "\"") // case "\u{005C}": return (true, "\\") // case "\u{002F}": return (true, "/") // case "\u{0008}": return (true, "b") // case "\u{000C}": return (true, "f") // case "\u{000A}": return (true, "n") // case "\u{000D}": return (true, "r") // case "\u{0009}": return (true, "t") // default: return (false, ch1) // } // } // typealias Step = () -> Cursor // enum Cursor { // case None // case Available(Character, Step) // // static func restep(s:String) -> (Character, Step) { // let first = s[s.startIndex] as Character // let rest = s[s.startIndex.successor()..<s.endIndex] // let step = Cursor.restep(rest) // return (first, step) // } // } // // return step1 //}
mit
8ef5eeba8e9cb1bf8a7e60e177a489ad
13.538462
83
0.563786
2.573374
false
false
false
false
darrarski/DRNet
DRNet/DRNet/RequestParameters/RequestQueryStringParameters.swift
1
2525
// // RequestQueryStringParameters.swift // DRNet // // Created by Dariusz Rybicki on 21/10/14. // Copyright (c) 2014 Darrarski. All rights reserved. // import Foundation public class RequestQueryStringParameters: RequestParameters { public let parameters: [String: AnyObject] public init(_ parameters: [String: AnyObject]) { self.parameters = parameters } // MARK: - RequestParameters protocol public func setParametersInRequest(request: NSURLRequest) -> NSURLRequest { var mutableURLRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest setParametersInRequest(mutableURLRequest) return request.copy() as NSURLRequest } public func setParametersInRequest(request: NSMutableURLRequest) { if let URLComponents = NSURLComponents(URL: request.URL!, resolvingAgainstBaseURL: false) { URLComponents.percentEncodedQuery = (URLComponents.query != nil ? URLComponents.query! + "&" : "") + query(parameters) request.URL = URLComponents.URL } else { assertionFailure("Unable to set Query String parameters in request") } } // MARK: - func query(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in sorted(Array(parameters.keys), <) { let value: AnyObject! = parameters[key] components += queryComponents(key, value) } return join("&", components.map{"\($0)=\($1)"} as [String]) } func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: AnyObject] { for (nestedKey, value) in dictionary { components += queryComponents("\(key)[\(nestedKey)]", value) } } else if let array = value as? [AnyObject] { for value in array { components += queryComponents("\(key)[]", value) } } else { components.extend([(escape(key), escape("\(value)"))]) } return components } func escape(string: String) -> String { let allowedCharacters = NSCharacterSet(charactersInString:" =\"#%/<>?@\\^`{}[]|&").invertedSet return string.stringByAddingPercentEncodingWithAllowedCharacters(allowedCharacters) ?? string } }
mit
8f2f8430fefb32a1235f48c888074c19
32.68
130
0.599604
5.121704
false
false
false
false
Vostro162/VaporTelegram
Sources/App/Game.swift
1
715
// // Game.swift // VaporTelegramBot // // Created by Marius Hartig on 08.05.17. // // import Foundation public struct Game { let title: String let description: String let photos: [PhotoSize] let textEntities: [MessageEntity] let text: String? let animation: Animation? public init(title: String, description: String, photos: [PhotoSize] = [PhotoSize](), textEntities: [MessageEntity] = [MessageEntity](), text: String? = nil, animation: Animation? = nil) { self.title = title self.description = description self.photos = photos self.textEntities = textEntities self.text = text self.animation = animation } }
mit
eda83df0ff51002e7c8fde8d5fd37c3a
22.833333
191
0.632168
4.016854
false
false
false
false
ashfurrow/FunctionalReactiveAwesome
Pods/Moya/Moya+RxSwift.swift
1
3041
// // Moya+RxSwift.swift // Moya // // Created by Andre Carvalho on 2015-06-05 // Copyright (c) 2015 Ash Furrow. All rights reserved. // import Foundation import RxSwift /// Subclass of MoyaProvider that returns Observable instances when requests are made. Much better than using completion closures. public class RxMoyaProvider<T where T: MoyaTarget>: MoyaProvider<T> { /// Current requests that have not completed or errored yet. /// Note: Do not access this directly. It is public only for unit-testing purposes (sigh). public var inflightRequests = Dictionary<Endpoint<T>, Observable<MoyaResponse>>() /// Initializes a reactive provider. override public init(endpointsClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping(), endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution(), stubResponses: Bool = false, stubBehavior: MoyaStubbedBehavior = MoyaProvider.DefaultStubBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil) { super.init(endpointsClosure: endpointsClosure, endpointResolver: endpointResolver, stubResponses: stubResponses, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure) } /// Designated request-making method. public func request(token: T) -> Observable<MoyaResponse> { let endpoint = self.endpoint(token) return defer { [weak self] () -> Observable<MoyaResponse> in if let existingObservable = self?.inflightRequests[endpoint] { return existingObservable } let observable: Observable<MoyaResponse> = AnonymousObservable { observer in let cancellableToken = self?.request(token) { (data, statusCode, response, error) -> () in if let error = error { if let statusCode = statusCode { observer.on(.Error(NSError(domain: error.domain, code: statusCode, userInfo: error.userInfo))) } else { observer.on(.Error(error)) } } else { if let data = data { observer.on(.Next(RxBox(MoyaResponse(statusCode: statusCode!, data: data, response: response)))) } observer.on(.Completed) } } return AnonymousDisposable { if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = nil cancellableToken?.cancel() objc_sync_exit(weakSelf) } } } if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = observable objc_sync_exit(weakSelf) } return observable } } }
mit
753d821b5719a4fe8e6a51aeffccea46
44.38806
349
0.59487
5.684112
false
false
false
false
velvetroom/columbus
Source/Controller/Abstract/ControllerParent+Transitions.swift
1
9238
import UIKit extension ControllerParent { //MARK: private private func slide(controller:UIViewController, left:CGFloat) { guard let view:ViewParent = self.view as? ViewParent, let currentController:UIViewController = childViewControllers.last, let newView:ViewProtocol = controller.view as? ViewProtocol, let currentView:ViewProtocol = currentController.view as? ViewProtocol else { return } currentController.removeFromParentViewController() addChildViewController(controller) controller.beginAppearanceTransition(true, animated:true) currentController.beginAppearanceTransition(false, animated:true) view.slide( currentView:currentView, newView:newView, left:left) { controller.endAppearanceTransition() currentController.endAppearanceTransition() } } //MARK: internal func slideTo( horizontal:ControllerTransition.Horizontal, controller:UIViewController) { let viewWidth:CGFloat = -view.bounds.maxX let left:CGFloat = viewWidth * horizontal.rawValue slide( controller:controller, left:left) } func mainController(controller:UIViewController) { addChildViewController(controller) guard let view:ViewParent = self.view as? ViewParent, let newView:ViewProtocol = controller.view as? ViewProtocol else { return } view.mainView(view:newView) } func push( controller:UIViewController, horizontal:ControllerTransition.Horizontal = ControllerTransition.Horizontal.none, vertical:ControllerTransition.Vertical = ControllerTransition.Vertical.none, background:Bool = true, completion:(() -> ())? = nil) { guard let view:ViewParent = self.view as? ViewParent, let currentController:UIViewController = childViewControllers.last, let newView:ViewProtocol = controller.view as? ViewProtocol else { return } let width:CGFloat = view.bounds.maxX let height:CGFloat = view.bounds.maxY let left:CGFloat = width * horizontal.rawValue let top:CGFloat = height * vertical.rawValue addChildViewController(controller) controller.beginAppearanceTransition( true, animated:true) currentController.beginAppearanceTransition( false, animated:true) view.push( newView:newView, left:left, top:top, background:background) { controller.endAppearanceTransition() currentController.endAppearanceTransition() completion?() } } func animateOver(controller:UIViewController) { guard let view:ViewParent = self.view as? ViewParent, let currentController:UIViewController = childViewControllers.last, let newView:ViewProtocol = controller.view as? ViewProtocol else { return } addChildViewController(controller) controller.beginAppearanceTransition( true, animated:true) currentController.beginAppearanceTransition( false, animated:true) view.animateOver(newView:newView) { controller.endAppearanceTransition() currentController.endAppearanceTransition() } } func centreOver(controller:UIViewController) { guard let view:ViewParent = self.view as? ViewParent, let currentController:UIViewController = childViewControllers.last, let newView:ViewProtocol = controller.view as? ViewProtocol else { return } addChildViewController(controller) controller.beginAppearanceTransition( true, animated:true) currentController.beginAppearanceTransition( false, animated:true) view.centreOver(newView:newView) controller.endAppearanceTransition() currentController.endAppearanceTransition() } func removeBetweenFirstAndLast() { var controllers:Int = childViewControllers.count - 1 while controllers > 1 { controllers -= 1 let controller:UIViewController = childViewControllers[controllers] controller.beginAppearanceTransition( false, animated:false) controller.view.removeFromSuperview() controller.endAppearanceTransition() controller.removeFromParentViewController() } } func removeAllButLast() { var controllers:Int = childViewControllers.count - 1 while controllers > 0 { controllers -= 1 let controller:UIViewController = childViewControllers[controllers] controller.beginAppearanceTransition( false, animated:false) controller.view.removeFromSuperview() controller.endAppearanceTransition() controller.removeFromParentViewController() } } func pop( horizontal:ControllerTransition.Horizontal = ControllerTransition.Horizontal.none, vertical:ControllerTransition.Vertical = ControllerTransition.Vertical.none, completion:(() -> ())? = nil) { let width:CGFloat = view.bounds.maxX let height:CGFloat = view.bounds.maxY let left:CGFloat = width * horizontal.rawValue let top:CGFloat = height * vertical.rawValue let controllers:Int = childViewControllers.count if controllers > 1 { let currentController:UIViewController = childViewControllers[controllers - 1] let previousController:UIViewController = childViewControllers[controllers - 2] currentController.removeFromParentViewController() guard let view:ViewParent = self.view as? ViewParent, let currentView:ViewProtocol = currentController.view as? ViewProtocol else { return } currentController.beginAppearanceTransition( false, animated:true) previousController.beginAppearanceTransition( true, animated:true) view.pop( currentView:currentView, left:left, top:top) { previousController.endAppearanceTransition() currentController.endAppearanceTransition() completion?() } } } func popSilent(removeIndex:Int) { let controllers:Int = childViewControllers.count if controllers > removeIndex { let removeController:UIViewController = childViewControllers[removeIndex] guard let removeView:ViewProtocol = removeController.view as? ViewProtocol else { return } removeView.pushBackground?.removeFromSuperview() removeController.view.removeFromSuperview() removeController.removeFromParentViewController() } } func dismissAnimateOver(completion:(() -> ())?) { guard let view:ViewParent = self.view as? ViewParent, let currentController:UIViewController = childViewControllers.last else { return } currentController.removeFromParentViewController() guard let previousController:UIViewController = childViewControllers.last else { return } currentController.beginAppearanceTransition( false, animated:true) previousController.beginAppearanceTransition( true, animated:true) view.dismissAnimateOver(currentView:currentController.view) { currentController.endAppearanceTransition() previousController.endAppearanceTransition() completion?() } } }
mit
9f7e4226af1cba696111941bce70384f
27.689441
91
0.555099
6.87863
false
false
false
false
LeeWongSnail/Swift
DesignBox/DesignBox/ArtKit/pageViewController/ArtPageViewController.swift
1
10464
// // ArtPageViewController.swift // DesignBox // // Created by LeeWong on 2017/8/28. // Copyright © 2017年 LeeWong. All rights reserved. // import UIKit protocol ArtPageHeaderViewProtocol { //表示变量是可读可写的 var currentIndex:Int {get set} } class ArtPageViewController: UIViewController { //MARK: - Properties var pageDoingScroll: Bool = false var isCurrentPage: Bool = false var pageHeaderView:ArtPageHeaderViewProtocol? var workFilterModel: ArtFilterModel? var scrollTab: ArtScrollTab? var initialIndex:Int = 0 //MARK: - Functions func cleanAll() -> Void { if self.pageHeaderView != nil { (self.pageHeaderView as! UIView).removeFromSuperview() self.pageHeaderView = nil } if self.scrollTab != nil { self.scrollTab?.removeFromSuperview() self.scrollTab = nil } self.pageDoingScroll = false self.isCurrentPage = false self.workFilterModel = nil self.pageViewController.view.removeFromSuperview() self.pageViewController.removeFromParentViewController() } //MARK: - Build View func buildMainView() -> Void { cleanAll() self.workFilterModel = ArtFilterModel() self.workFilterModel?.maxCachedCount = maxCachedCount() self.workFilterModel?.categoryList = self.categoryList! if !customPageHeaderView() { self.scrollTab = ArtScrollTab() self.scrollTab?.delegate = self self.view.addSubview(self.scrollTab!) self.scrollTab?.snp.makeConstraints({ (make) in make.left.right.top.equalTo(self.view) make.height.equalTo((self.scrollTab?.tabHeight())!) }) self.scrollTab?.curIndexDidChangeBlock = { (index) -> Void in self.scrollTabCurIndexDidChange(aIndex: index) } if let view = scrollTabRightView() { self.view.addSubview(view) view.snp.makeConstraints({ (make) in make.top.bottom.equalTo(self.scrollTab!) make.left.equalTo((self.scrollTab?.snp.right)!) make.right.equalTo(self.view.snp.right) }) } self.scrollTab?.setTabBarItems(items: (self.workFilterModel?.categoryList)!, index: self.initialIndex) self.pageHeaderView = scrollTab if !artScrollTabDividerHidden() { let sepLine = UIView() sepLine.backgroundColor = UIColor.red self.view.addSubview(sepLine) sepLine.snp.makeConstraints({ (make) in make.left.right.equalTo(self.view) make.bottom.equalTo((self.scrollTab?.snp.bottom)!) make.height.equalTo(1.0/SCREEN_SCALE) }) } } else { self.pageHeaderView = customHeaderView() self.view.addSubview(self.pageHeaderView as! UIView) (self.pageHeaderView as! UIView).snp.makeConstraints({ (make) in make.top.left.right.equalTo(self.view) make.height.equalTo(heightForHeaderView()) }) } self.workFilterModel?.categoryListIndex = self.initialIndex self.workFilterModel?.contentVCBlock = {(_ currentIndex:Int) -> (UIViewController) in return self.createControllerByIndex(index: currentIndex)! } createPageViewPageIndex(index: self.initialIndex) if !pageViewControllerScrollEnabled() { self.findScrollView()?.isScrollEnabled = false } } func scrollTabCurIndexDidChange(aIndex:Int) -> Void { let idx = self.workFilterModel?.indexOfPageController(viewController: (self.pageViewController.viewControllers?.first)!) if idx != aIndex { self.pageDoingScroll = true let vc = self.workFilterModel?.pageControllerAtIndex(aIndex: aIndex) guard vc != nil else { self.pageDoingScroll = false return } self.pageViewController.setViewControllers([vc!], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: { (finish) in self.pageDoingScroll = false }) } else { if !self.isCurrentPage { } else { self.isCurrentPage = false } } self.workFilterModel?.categoryListIndex = aIndex } func createPageViewPageIndex(index:Int) -> Void { self.pageViewController.dataSource = self self.addChildViewController(self.pageViewController) let viewController = self.workFilterModel?.pageControllerAtIndex(aIndex: index) guard viewController != nil else { return } self.pageViewController.setViewControllers([viewController!], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil) self.pageViewController.didMove(toParentViewController: self) let view = self.pageViewController.view self.view.addSubview(view!) view?.snp.makeConstraints({ (make) in make.top.equalTo(((self.pageHeaderView as! UIView).snp.bottom)) make.left.right.bottom.equalTo(self.view) }) } override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false; // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Lazy Load lazy var categoryList:[ArtScrollTabDelegate]? = { let namelist = self.categoryNameList() if namelist?.count == 0 { return nil } var list:[ArtScrollTabDelegate] = [ArtScrollTabDelegate]() var index:Int = 0 for name in namelist! { let item = ArtScrollTabItem() let cate = ArtUserConfig.shared.reqCategory![index] item.tabTitle = name item.tabId = cate["_id"] as? String list.append(item) index+=1 } return list }() lazy var pageViewController:UIPageViewController = { let options = [UIPageViewControllerOptionSpineLocationKey:UIPageViewControllerSpineLocation.min] let tempPageVC = UIPageViewController.init(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal, options: options) tempPageVC.dataSource = self tempPageVC.delegate = self return tempPageVC }() } //MARK: Build View extension ArtPageViewController { func scrollTabRightView() -> UIView? { return nil } func artScrollTabDividerHidden() -> Bool { return true } func customHeaderView() -> ArtPageHeaderViewProtocol? { return nil } func heightForHeaderView() -> CGFloat { return 0 } func createControllerByIndex(index:Int) -> UIViewController? { return nil } } extension ArtPageViewController { //这里面 的信息是需要子类去重写的 func maxCachedCount() -> Int { return 3 } func customPageHeaderView() -> Bool { return false } func pageViewControllerScrollEnabled() -> Bool { return true } func categoryNameList() -> [String]? { return nil } } extension ArtPageViewController: UIPageViewControllerDelegate,UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if let idx = self.workFilterModel?.indexOfPageController(viewController: viewController) { return self.workFilterModel?.pageControllerAtIndex(aIndex: idx+1) } return nil } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if let idx = self.workFilterModel?.indexOfPageController(viewController: viewController) { return self.workFilterModel?.pageControllerAtIndex(aIndex: idx-1) } return nil } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if finished && !pageDoingScroll { isCurrentPage = true if let idx = self.workFilterModel?.indexOfPageController(viewController:(pageViewController.viewControllers?.first!)!) { self.scrollTab?.currentIndex = idx } } } func findScrollView() -> UIScrollView? { var scrollView:UIScrollView? for subview in self.pageViewController.view.subviews { if subview is UIScrollView { scrollView = subview as? UIScrollView } } return scrollView } } extension ArtPageViewController: ArtScrollTabDelegate { func artScrollTabHeight(scrollTab:ArtScrollTab) -> CGFloat { return 39 } func artScrollTabIndicatorBottomMargin() -> CGFloat { return 3 } func artScrollTabItemShowType(scrollTab:ArtScrollTab) -> Int { return 1 } func artScrollTabItemControlLimitWidth(scrollTab:ArtScrollTab) -> CGFloat { return 80 } func artScrollTabItemOffset(scrollTab:ArtScrollTab) -> CGFloat { return 0 } func artScrollTabItemNormalColor(scrollTab:ArtScrollTab) -> UIColor { return UIColor.gray } func artScrollTabItemSelectedColorColor(scrollTab:ArtScrollTab) -> UIColor { return UIColor.red } func artScrollTabIndicatorViewHidden() -> Bool { return false } }
mit
809a8469ff1e9c339a92c20f0447cec9
30.83792
206
0.61339
5.2003
false
false
false
false
mathcamp/swiftz
swiftz/StringExt.swift
2
744
// // StringExt.swift // swiftz // // Created by Maxwell Swadling on 8/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // import Foundation extension String { public func lines() -> [String] { var xs: [String] = [] var line: String = "" // loop school for x in self { if x == "\n" { xs.append(line) line = "" } else { line.append(x) } } if line != "" { xs.append(line) } return xs } public static func unlines(xs: [String]) -> String { return xs.reduce("", combine: { "\($0)\($1)\n" } ) } public static func lines() -> Iso<String, String, [String], [String]> { return Iso(get: { $0.lines() }, inject: unlines) } }
bsd-3-clause
df5b7d14d3c6ce13a90bf1b320649d0b
19.108108
73
0.532258
3.351351
false
false
false
false
sucrewar/SwiftUEx
SwiftEx/Classes/UIViewExtension.swift
1
866
// // UIViewExtension.swift // smiity // // Created by João Borges on 16/06/16. // Copyright © 2016 Mobinteg. All rights reserved. // import Foundation public extension UIView { public func fadeIn(duration: NSTimeInterval = 1.0, delay: NSTimeInterval = 0.0, completion: ((Bool) -> Void) = {(finished: Bool) -> Void in}) { UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.alpha = 1.0 }, completion: completion) } public func fadeOut(duration: NSTimeInterval = 1.0, delay: NSTimeInterval = 0.0, completion: (Bool) -> Void = {(finished: Bool) -> Void in}) { UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.alpha = 0.0 }, completion: completion) } }
mit
e7156ea036978d644014814eaa14eff3
38.272727
148
0.66088
4.056338
false
false
false
false
tehprofessor/SwiftyFORM
Source/Cells/ButtonCell.swift
1
1419
// // ButtonCell.swift // SwiftyFORM // // Created by Simon Strandgaard on 08/11/14. // Copyright (c) 2014 Simon Strandgaard. All rights reserved. // import UIKit public struct ButtonCellModel { var title: String = "" var subtitle: String = "" var textAlignment: NSTextAlignment = NSTextAlignment.Left var detailAlignment: NSTextAlignment = NSTextAlignment.Right var styleBlock: ((ButtonCell) -> Void)? = nil var action: Void -> Void = { DLog("action") } } public class ButtonCell: UITableViewCell, SelectRowDelegate { public let model: ButtonCellModel public init(model: ButtonCellModel) { self.model = model super.init(style: UITableViewCellStyle.Default, reuseIdentifier: nil) loadWithModel(model) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func loadWithModel(model: ButtonCellModel) { textLabel?.text = model.title textLabel?.textAlignment = model.textAlignment detailTextLabel?.text = model.subtitle detailTextLabel?.textAlignment = model.detailAlignment // Apply styles model.styleBlock?(self) } public func form_didSelectRow(indexPath: NSIndexPath, tableView: UITableView) { // hide keyboard when the user taps this kind of row tableView.form_firstResponder()?.resignFirstResponder() model.action() tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
30edc81ac520e2811a13ac8af90c8845
25.277778
80
0.737844
4.089337
false
false
false
false
dasmer/Paste
Paste/SearchTextFieldView.swift
1
2882
// // SearchTextFieldView.swift // Paste // // Created by Dasmer Singh on 12/20/15. // Copyright © 2015 Dastronics Inc. All rights reserved. // import UIKit protocol SearchTextFieldViewDelegate: class { func searchTextFieldView(searchTextFieldView: SearchTextFieldView, didChangeText text: String) func searchTextFieldViewWillClearText(searchTextFieldView: SearchTextFieldView) } final class SearchTextFieldView: UIView { // MARK: - Properties weak var delegate: SearchTextFieldViewDelegate? var text: String? { get { return textField.text } set { textField.text = newValue } } var placeholder: String? { get { return textField.placeholder } set { textField.placeholder = newValue } } private let textField: UITextField = { let textField = UITextField(frame: .zero) textField.translatesAutoresizingMaskIntoConstraints = false textField.clearButtonMode = .WhileEditing textField.autocapitalizationType = .None textField.autocorrectionType = .No return textField }() // MARK: - Initializers override init(frame: CGRect) { super.init(frame: frame) addSubview(textField) let constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textField]-|", options: [], metrics: nil, views: ["textField":textField]) + [NSLayoutConstraint(item: textField, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0)] NSLayoutConstraint.activateConstraints(constraints) textField.addTarget(self, action: "textFieldDidChange:", forControlEvents: .EditingChanged) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private @objc private func textFieldDidChange(sender: AnyObject?) { delegate?.searchTextFieldView(self, didChangeText: textField.text ?? "") } } extension SearchTextFieldView: UITextFieldDelegate { func textFieldShouldClear(textField: UITextField) -> Bool { delegate?.searchTextFieldViewWillClearText(self) return true } } extension SearchTextFieldView { // MARK: - UIResponder override func canBecomeFirstResponder() -> Bool { return textField.canBecomeFirstResponder() } override func becomeFirstResponder() -> Bool { return textField.becomeFirstResponder() } override func canResignFirstResponder() -> Bool { return textField.canResignFirstResponder() } override func resignFirstResponder() -> Bool { return textField.resignFirstResponder() } override func isFirstResponder() -> Bool { return textField.isFirstResponder() } }
mit
2db72e7233094c40146526abd3657ac1
25.675926
158
0.669559
5.305709
false
false
false
false
brentdax/swift
test/SILGen/objc_init_ref_delegation.swift
2
1337
// RUN: %target-swift-emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -enable-sil-ownership -enable-objc-interop | %FileCheck %s import gizmo extension Gizmo { // CHECK-LABEL: sil hidden @$sSo5GizmoC24objc_init_ref_delegationE{{[_0-9a-zA-Z]*}}fC convenience init(int i: Int) { // CHECK: bb0([[I:%[0-9]+]] : @trivial $Int, [[SELF_META:%[0-9]+]] : @trivial $@thick Gizmo.Type): // CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Gizmo } // CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[SELF_OBJC_META:%.*]] = thick_to_objc_metatype [[SELF_META]] // CHECK: [[ORIG_SELF:%.*]] = alloc_ref_dynamic [objc] [[SELF_OBJC_META]] // CHECK: [[INIT_DELEG:%[0-9]+]] = objc_method [[ORIG_SELF]] : $Gizmo, #Gizmo.init!initializer.1.foreign : (Gizmo.Type) -> (Int) -> Gizmo?, $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo> // CHECK: [[SELF_RET:%[0-9]+]] = apply [[INIT_DELEG]]([[I]], [[ORIG_SELF]]) : $@convention(objc_method) (Int, @owned Gizmo) -> @owned Optional<Gizmo> // CHECK: [[SELF4:%.*]] = load [copy] [[PB_BOX]] // CHECK: destroy_value [[MARKED_SELF_BOX]] // CHECK: return [[SELF4]] : $Gizmo self.init(bellsOn:i) } }
apache-2.0
4577f7cca6f8e4f039fd0871e0ccd8c9
62.666667
217
0.589379
3.038636
false
false
false
false
auth0/Lock.swift
LockTests/InputFieldSpec.swift
1
14835
// InputFieldSpec.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Quick import Nimble @testable import Lock class InputFieldSpec: QuickSpec { override func spec() { describe("delegate") { var input: InputField! var text: UITextField! var didTextChange: Bool! var didReturn: Bool! var didBegin: Bool! var didEnd: Bool! beforeEach { didTextChange = false didReturn = false didBegin = false didEnd = false input = InputField() input.onReturn = { _ in didReturn = true } input.onTextChange = { _ in didTextChange = true } input.onBeginEditing = { _ in didBegin = true } input.onEndEditing = { _ in didEnd = true } text = UITextField() text.text = "test" } describe("delegate") { it("on return editing called") { expect(input.textFieldShouldReturn(text)).to(beTrue()) expect(didReturn).to(beTrue()) expect(didTextChange).to(beTrue()) } it("on begin editing called") { input.textFieldDidBeginEditing(text) expect(didBegin).to(beTrue()) } it("on end editing called") { input.textFieldDidEndEditing(text) expect(didEnd).to(beTrue()) } } describe("text change") { it("text updated") { input.textChanged(text) expect(didTextChange).to(beTrue()) } } } describe("keyboard type") { var input: InputField! var text: UITextField! beforeEach { input = InputField() text = input.textField } it("should assign email type") { input.type = .email expect(text.keyboardType) == UIKeyboardType.emailAddress } it("should assign username type") { input.type = .username expect(text.keyboardType) == UIKeyboardType.default } it("should assign emailOrUsername type") { input.type = .emailOrUsername expect(text.keyboardType) == UIKeyboardType.emailAddress } it("should assign password type") { input.type = .password expect(text.keyboardType) == UIKeyboardType.default } it("should assign phone type") { input.type = .phone expect(text.keyboardType) == UIKeyboardType.phonePad } it("should assign oneTimePassword type") { input.type = .oneTimePassword expect(text.keyboardType) == UIKeyboardType.decimalPad } it("should assign custom type") { input.type = .custom(name: "test", placeholder: "", defaultValue: nil, storage: .userMetadata, icon: nil, keyboardType: .twitter, autocorrectionType: .no, autocapitalizationType: .none, secure: false, hidden: false, contentType: nil) expect(text.keyboardType) == UIKeyboardType.twitter } } describe("autocorrect type") { var input: InputField! var text: UITextField! beforeEach { input = InputField() text = input.textField } it("should assign email type") { input.type = .email expect(text.autocorrectionType) == .no } it("should assign username type") { input.type = .username expect(text.autocorrectionType) == .no } it("should assign emailOrUsername type") { input.type = .emailOrUsername expect(text.autocorrectionType) == .no } it("should assign password type") { input.type = .password expect(text.autocorrectionType) == .no } it("should assign phone type") { input.type = .phone expect(text.autocorrectionType) == .no } it("should assign oneTimePassword type") { input.type = .oneTimePassword expect(text.autocorrectionType) == .no } it("should assign custom type") { input.type = .custom(name: "test", placeholder: "", defaultValue: nil, storage: .userMetadata, icon: nil, keyboardType: .default, autocorrectionType: .yes, autocapitalizationType: .none, secure: false, hidden: false, contentType: nil) expect(text.autocorrectionType) == .yes } } describe("autocapitalization type") { var input: InputField! var text: UITextField! beforeEach { input = InputField() text = input.textField } it("should assign email type") { input.type = .email expect(text.autocapitalizationType) == UITextAutocapitalizationType.none } it("should assign username type") { input.type = .username expect(text.autocapitalizationType) == UITextAutocapitalizationType.none } it("should assign emailOrUsername type") { input.type = .emailOrUsername expect(text.autocapitalizationType) == UITextAutocapitalizationType.none } it("should assign password type") { input.type = .password expect(text.autocapitalizationType) == UITextAutocapitalizationType.none } it("should assign phone type") { input.type = .phone expect(text.autocapitalizationType) == UITextAutocapitalizationType.none } it("should assign oneTimePassword type") { input.type = .oneTimePassword expect(text.autocapitalizationType) == UITextAutocapitalizationType.none } it("should assign custom type") { input.type = .custom(name: "test", placeholder: "", defaultValue: nil, storage: .userMetadata, icon: nil, keyboardType: .default, autocorrectionType: .default, autocapitalizationType: .words, secure: false, hidden: false, contentType: nil) expect(text.autocapitalizationType) == .words } } describe("default value") { var input: InputField! var text: UITextField! beforeEach { input = InputField() text = input.textField } it("should assign email value") { input.type = .email expect(text.text?.isEmpty ?? true) == true } it("should assign username value") { input.type = .username expect(text.text?.isEmpty ?? true) == true } it("should assign emailOrUsername value") { input.type = .emailOrUsername expect(text.text?.isEmpty ?? true) == true } it("should assign password value") { input.type = .password expect(text.text?.isEmpty ?? true) == true } it("should assign phone value") { input.type = .phone expect(text.text?.isEmpty ?? true) == true } it("should assign oneTimePassword value") { input.type = .oneTimePassword expect(text.text?.isEmpty ?? true) == true } it("should assign custom value") { input.type = .custom(name: "test", placeholder: "", defaultValue: "Default Value", storage: .userMetadata, icon: nil, keyboardType: .default, autocorrectionType: .default, autocapitalizationType: .none, secure: true, hidden: false, contentType: nil) expect(text.text) == "Default Value" } } describe("secure value") { var input: InputField! var text: UITextField! beforeEach { input = InputField() text = input.textField } it("should assign email value") { input.type = .email expect(text.isSecureTextEntry) == false } it("should assign username value") { input.type = .username expect(text.isSecureTextEntry) == false } it("should assign emailOrUsername value") { input.type = .emailOrUsername expect(text.isSecureTextEntry) == false } it("should assign password value") { input.type = .password expect(text.isSecureTextEntry) == true } it("should assign phone value") { input.type = .phone expect(text.isSecureTextEntry) == false } it("should assign oneTimePassword value") { input.type = .oneTimePassword expect(text.isSecureTextEntry) == false } it("should assign custom value") { input.type = .custom(name: "test", placeholder: "", defaultValue: nil, storage: .userMetadata, icon: nil, keyboardType: .default, autocorrectionType: .default, autocapitalizationType: .words, secure: true, hidden: false, contentType: nil) expect(text.isSecureTextEntry) == true } } describe("hidden value") { var input: InputField! beforeEach { input = InputField() } it("should assign email value") { input.type = .email expect(input.isHidden) == false } it("should assign username value") { input.type = .username expect(input.isHidden) == false } it("should assign emailOrUsername value") { input.type = .emailOrUsername expect(input.isHidden) == false } it("should assign password value") { input.type = .password expect(input.isHidden) == false } it("should assign phone value") { input.type = .phone expect(input.isHidden) == false } it("should assign oneTimePassword value") { input.type = .oneTimePassword expect(input.isHidden) == false } it("should assign custom value") { input.type = .custom(name: "test", placeholder: "", defaultValue: nil, storage: .userMetadata, icon: nil, keyboardType: .default, autocorrectionType: .default, autocapitalizationType: .words, secure: false, hidden: true, contentType: nil) expect(input.isHidden) == true } } describe("content type") { var input: InputField! var text: UITextField! beforeEach { input = InputField() text = input.textField } if #available(iOS 10.0, *) { it("should assign email type") { input.type = .email expect(text.textContentType) == UITextContentType.emailAddress } } if #available(iOS 11.0, *) { it("should assign username type") { input.type = .username expect(text.textContentType) == UITextContentType.username } } if #available(iOS 10.0, *) { it("should assign emailOrUsername type") { input.type = .emailOrUsername expect(text.textContentType) == UITextContentType.emailAddress } } if #available(iOS 11.0, *) { it("should assign password type") { input.type = .password expect(text.textContentType) == UITextContentType.password } } if #available(iOS 10.0, *) { it("should assign phone type") { input.type = .phone expect(text.textContentType) == UITextContentType.telephoneNumber } } #if swift(>=4.0) if #available(iOS 12.0, *) { it("should assign oneTimePassword type") { input.type = .oneTimePassword expect(text.textContentType) == UITextContentType.oneTimeCode } } #endif if #available(iOS 10.0, *) { it("should assign custom type") { input.type = .custom(name: "test", placeholder: "", defaultValue: nil, storage: .userMetadata, icon: nil, keyboardType: .default, autocorrectionType: .no, autocapitalizationType: .none, secure: false, hidden: false, contentType: .name) expect(text.textContentType) == UITextContentType.name } } } } }
mit
cc89f8fbcc18aeb4518a50fae26f86ff
34.746988
265
0.522481
5.47215
false
false
false
false
jessesquires/swift-proposal-analyzer
swift-proposal-analyzer.playground/Pages/SE-0169.xcplaygroundpage/Contents.swift
1
7996
/*: # Improve Interaction Between `private` Declarations and Extensions * Proposal: [SE-0169](0169-improve-interaction-between-private-declarations-and-extensions.md) * Authors: [David Hart](http://github.com/hartbit), [Chris Lattner](https://github.com/lattner) * Review Manager: [Doug Gregor](https://github.com/DougGregor) * Status: **Implemented (Swift 4)** * Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution-announce/2017-April/000357.html) * Previous Revision: [1][Revision 1] * Bug: [SR-4616](https://bugs.swift.org/browse/SR-4616) ## Introduction In Swift 3, a declaration marked `private` may be accessed by anything nested in the scope of the private declaration. For example, a private property or method defined on a struct may be accessed by other methods defined within that struct. This model was introduced by [SE-0025](0025-scoped-access-level.md) and with nearly a year of experience using this model, it has worked well in almost all cases. The primary case it falls down is when the implementation of a type is split into a base definition and a set of extensions. Because of the SE-0025 model, extensions to the type are not allowed to access private members defined on that type. This proposal recommends extending `private` access control so that members defined in an extension of a type have the same access as members defined on the type itself, so long as the type and extension are in the same source file. We expect this to dramatically reduce the number of uses of `fileprivate` in practice. ## Motivation [SE-0025](0025-scoped-access-level.md) defined the `private` access control level to be used for scoped access, and introduced `fileprivate` for the case when a declaration needs to be visible across declarations, but not only within a file. The goal of the proposal was for `fileprivate` to be used rarely. However, that goal of the proposal has not been realized: Swift encourages developers to use extensions as a logical grouping mechanism and requires them for conditional conformances. Because of this, the SE-0025 design makes `fileprivate` more necessary than expected, and reduces the appeal of using extensions. The prevalence of `fileprivate` in practice has caused mixed reactions from Swift developers, culminating in proposal [SE-0159](0159-fix-private-access-levels.md) which suggested reverting the access control model to Swift 2’s design. That proposal was rejected for two reasons: scoped access is something that many developers use and value, and because it was seen as too large of a change given Swift 4’s source compatibility goals. In contrast to SE-0159, this proposal is an extremely narrow change (which is almost completely additive) to the SE-0025 model, which embraces the extension-oriented design of Swift. The authors believe that this change will not preclude introduction of submodules in the future. ## Detailed Design For purposes of access control, extensions to any given type `T` within a file are considered to be a single access control scope, and if `T` is defined within the file, the extensions use the same access control scope as `T`. This has two ramifications: * Declarations in one of these extensions get access to the `private` members of the type. * If the declaration in the extension itself is defined as `private`, then they are accessible to declarations in the type, and other extensions of that type (in the same file). Here is a simple code example that demonstrates this: ```swift struct S { private var p: Int func f() { use(g()) // ok, g() is accessible within S } } extension S { private func g() { use(p) // ok, g() has access to p, since it is in an extension on S. } } extension S { func h() { use(g()) // Ok, h() has access to g() since it defined in the access control scope for S. } } ``` Please note: * This visibility does **not** extend to subclasses of a class in the same file, it only affects extensions of the type itself. * Constrained extensions are extensions, so this visibility **does** extend to them as well. For example, the body of `extension Optional where Wrapped == String { }` would have access to `private` members of Optional, assuming the extension is defined in the same file as `Optional`. * This proposal does change the behavior of extensions that are not in the same file as the type - those extensions are merged together into a single access control scope: ```swift // FileA.swift struct A { private var aMember : Int } // FileB.swift extension A { private func foo() { bar() // ok, foo() does have access to bar() } } extension A { private func bar() { aMember = 42 // not ok, private members may not be accessed outside their file. } } ``` * This proposal does not change access control behavior for types nested within each other. As in Swift 3, inner types have access to the private members of outer types, but outer types cannot refer to private members of inner types. For example: ```swift struct Outer { private var outerValue = 42 struct Inner { private var innerValue = 57 func innerTest(_ o: Outer) { print(o.outerValue) // still ok. } } func test(_ i: Inner) { print(i.innerValue) // still an error } } ``` ## Source Compatibility In Swift 3 compatibility mode, the compiler will continue to treat `private` as before. In Swift 4 mode, the compiler will modify the semantics of `private` to follow the rules of this proposal. No migration will be necessary as this proposal merely broadens the visibility of `private`. Cases where a type had `private` declarations with the same signature in the same type/extension but in different scopes will produce a compiler error in Swift 4. For example, the following piece of code compiles in Swift 3 compatibilty mode but generates a `Invalid redeclaration of 'bar()'` error in Swift 4 mode: ```swift struct Foo { private func bar() {} } extension Foo { private func bar() {} } ``` ## Alternatives Considered Access control has been hotly debated on the swift-evolution mailing list, both in the Swift 3 cycle (leading to [SE-0025](0025-scoped-access-level.md) and most recently in Swift 4 which led to [SE-0159](0159-fix-private-access-levels.md). There have been too many proposals to summarize here, including the introduction of a `scoped` keyword. The core team has made it clear that most of those proposals are not in scope for discussion in Swift 4 (or any later release), given the significant impact on source compatibility. This is the primary reason for this narrow scope proposal. A future direction that may be interesting to consider and debate (as a separate proposal, potentially after Swift 4) is whether extensions within the same file as a type should be treated as parts of the extended type **in general**. This would allow idioms like this, for example: ```swift struct Foo { var x: Int } // ... extension Foo { var y: Int } ``` However, this is specifically **not** part of this proposal at this time. It is merely a possible avenue to consider in the future. Another alternative considered is to allow `private` members of a type to be accessible to extensions outside of the current source file: either within the current module, or anywhere in the program. This is rejected because it violates an important principle of our access control system: that `private` is narrower than `fileprivate`. Allowing `private` to be narrower in some ways, but broader in other ways (allow access across files) would lead to a more confusing and fractured model. [Revision 1]: https://github.com/apple/swift-evolution/blob/e0e04f785dbf5bff138b75e9c47bf94e7db28447/proposals/0169-improve-interaction-between-private-declarations-and-extensions.md ---------- [Previous](@previous) | [Next](@next) */
mit
6634323545c1ade7a481098ad1780d9d
46.571429
623
0.746496
4.147379
false
false
false
false
Ming-Lau/DouyuTV
DouyuTV/DouyuTV/Classes/Main/View/PageContentView.swift
1
5338
// // PageContentView.swift // DouyuTV // // Created by 刘明 on 16/10/25. // Copyright © 2016年 刘明. All rights reserved. // import UIKit private let collectionViewIdenfier = "collectionViewIdenfier" protocol PageContentViewDelegate : class { func pageContentView(pageContentView : PageContentView , progress : CGFloat , sourceInde : Int ,targetIndex : Int) } class PageContentView: UIView { //MARK: - 定义属性 var childVcs :[UIViewController] weak var delegate : PageContentViewDelegate? //是否调用滚动的代理方法 var isUseScrollDelegate : Bool = false weak var persentVc: UIViewController? var startOffsetX : CGFloat = 0 //MARK: - 懒加载 lazy var collectionView : UICollectionView = {[weak self] in //创建流水布局 let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal //创建collectionView let collection = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collection.showsHorizontalScrollIndicator = false collection.isPagingEnabled = true collection.bounces = false collection.dataSource = self collection.delegate = self collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: collectionViewIdenfier) return collection }() init(frame: CGRect , childVCs:[UIViewController],persentVC:UIViewController?) { self.childVcs = childVCs self.persentVc = persentVC super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageContentView{ func setupUI() { //将自控制器添加到父控制器中 for child in childVcs{ persentVc?.addChildViewController(child) } //添加collectionView addSubview(collectionView) collectionView.frame = bounds } } //MARK: - 数据源 extension PageContentView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewIdenfier, for: indexPath) //移除之前的所有试图 for view in cell.contentView.subviews { view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.bounds cell.contentView.addSubview(childVc.view) return cell } } //MARK: - collection代理 extension PageContentView : UICollectionViewDelegate{ //滑动结束 func scrollViewDidScroll(_ scrollView: UIScrollView) { if isUseScrollDelegate { return } //滑动的进度 var progress :CGFloat = 0 //当前的视图 var sourceIndex :Int = 0 //滑动目标视图 var targetIndex :Int = 0 let scrollViewW = scrollView.bounds.width //判断滑动方向 let currentOffsetX = scrollView.contentOffset.x if currentOffsetX > startOffsetX {//向左 //计算滑动进度 progress = currentOffsetX/scrollViewW - floor(currentOffsetX/scrollViewW) sourceIndex = Int(currentOffsetX/scrollViewW) targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } //滑动完毕 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } }else{//向右 progress = 1-(currentOffsetX/scrollViewW - floor(currentOffsetX/scrollViewW)) targetIndex = Int(currentOffsetX/scrollViewW) sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } //滑动完毕 if startOffsetX - currentOffsetX == scrollViewW { progress = 1 sourceIndex = targetIndex } } //将计算结果传递出去 // print("p= \(progress) s= \(sourceIndex) t= \(targetIndex)") delegate?.pageContentView(pageContentView: self, progress: progress, sourceInde: sourceIndex, targetIndex: targetIndex) } //开始滑动 func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isUseScrollDelegate = false startOffsetX = scrollView.contentOffset.x } } //MARK: - 处理点击头部的滚动 extension PageContentView { func setScrollCollectionView(currentIndex : Int) { //禁止代理 isUseScrollDelegate = true let offSetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x:offSetX , y: 0), animated: false) } }
mit
4a610d7de2d27a532e65df383e3ae7bf
32.622517
127
0.634036
5.355485
false
false
false
false
codePrincess/playgrounds
GreatStuffWithThePencil.playground/Sources/EmotionHelpers.swift
1
5371
import Foundation import UIKit public class EmotionHelpers : NSObject { var preview : UIImageView! /** Method for putting an emoji with a matching emotion over each detected face in a photo. - parameters: - photo: The photo on which faces and it's emotion shall be detected - withFaceRect: If TRUE then the face rectangle is drawn into the photo - completion: UIImage as new photo with added emojis for the detected emotion over each face in fitting size and with face framing rectangles if declared. Image is the same size as the original. */ public func makeEmojiFromEmotionOnPhoto (photo : UIImageView!, withFaceRect: Bool, completion: @escaping (UIImage) -> (Void)) { let manager = CognitiveServices() manager.retrievePlausibleEmotionsForImage(photo.image!) { (result, error) -> (Void) in DispatchQueue.main.async(execute: { if let _ = error { print("omg something bad happened") } else { print("seems like all went well: \(String(describing: result))") } if (result?.count)! > 0 { print("1..2.. Emoji!\n\((result?.count)!) emotions detected") } else { print("Seems like no emotions were detected :(") } let photoWithEmojis = self.drawEmojisFor(emotions: result, withFaceRect: withFaceRect, image: photo.image!) completion(photoWithEmojis) }) } } public func emojisFor (emotion: CognitiveServicesEmotionResult) -> [String] { var availableEmojis = [String]() switch emotion.emotion { case .Anger: availableEmojis.append("😡") availableEmojis.append("😠") case .Contempt: availableEmojis.append("😤") case .Disgust: availableEmojis.append("😷") availableEmojis.append("🤐") case .Fear: availableEmojis.append("😱") case .Happiness: availableEmojis.append("😝") availableEmojis.append("😀") availableEmojis.append("😃") availableEmojis.append("😄") availableEmojis.append("😆") availableEmojis.append("😊") availableEmojis.append("🙂") availableEmojis.append("☺️") case .Neutral: availableEmojis.append("😶") availableEmojis.append("😐") availableEmojis.append("😑") case .Sadness: availableEmojis.append("🙁") availableEmojis.append("😞") availableEmojis.append("😟") availableEmojis.append("😔") availableEmojis.append("😢") availableEmojis.append("😭") case .Surprise: availableEmojis.append("😳") availableEmojis.append("😮") availableEmojis.append("😲") } return availableEmojis } public func drawEmojisFor (emotions: [CognitiveServicesEmotionResult]?, withFaceRect: Bool, image: UIImage) -> UIImage { var returnImage : UIImage! if let results = emotions { UIGraphicsBeginImageContext(image.size) image.draw(in: CGRect(origin: CGPoint.zero, size: image.size)) for result in results { let availableEmojis = emojisFor(emotion: result) let emoji = availableEmojis.randomElement() let maximumSize = result.frame.size let string = emoji as NSString let startingFontSize = 8192.0 var actualFontSize = startingFontSize var stepping = actualFontSize repeat { stepping /= 2.0 if stepping < 1.0 { break } let font = UIFont.systemFont(ofSize: CGFloat(actualFontSize)) let calculatedSize = string.size(withAttributes: [NSAttributedStringKey.font: font]) if calculatedSize.width > maximumSize.width { actualFontSize -= stepping } else { actualFontSize += stepping } } while true let font = UIFont.systemFont(ofSize: CGFloat(actualFontSize)) string.draw(in: result.frame, withAttributes: [NSAttributedStringKey.font: font]) if withFaceRect { let context = UIGraphicsGetCurrentContext() let frame = result.frame context!.setLineWidth(5) context!.addRect(frame) context!.drawPath(using: .stroke) } } returnImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } return returnImage } }
mit
da47b6835337316834e59a12f6fe29c5
36.006993
201
0.519085
5.641791
false
false
false
false
lorentey/swift
test/decl/var/static_var.swift
3
14951
// RUN: %target-typecheck-verify-swift -parse-as-library // See also rdar://15626843. static var gvu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} class var gvu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} override static var gvu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} override class var gvu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} static override var gvu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} class override var gvu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} // expected-error@-2 {{global 'var' declaration requires an initializer expression or getter/setter specifier}} static var gvu7: Int { // expected-error {{static properties may only be declared on a type}}{{1-8=}} return 42 } class var gvu8: Int { // expected-error {{class properties may only be declared on a type}}{{1-7=}} return 42 } static let glu1: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{global 'let' declaration requires an initializer expression}} class let glu2: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{global 'let' declaration requires an initializer expression}} override static let glu3: Int // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} override class let glu4: Int // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} static override let glu5: Int // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} class override let glu6: Int // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} // expected-error@-2 {{global 'let' declaration requires an initializer expression}} static var gvi1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} class var gvi2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} override static var gvi3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} override class var gvi4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} static override var gvi5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} class override var gvi6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} static let gli1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} class let gli2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} override static let gli3: Int = 0 // expected-error {{static properties may only be declared on a type}}{{10-17=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} override class let gli4: Int = 0 // expected-error {{class properties may only be declared on a type}}{{10-16=}} // expected-error@-1 {{'override' can only be specified on class members}}{{1-10=}} static override let gli5: Int = 0 // expected-error {{static properties may only be declared on a type}}{{1-8=}} // expected-error@-1 {{'override' can only be specified on class members}}{{8-17=}} class override let gli6: Int = 0 // expected-error {{class properties may only be declared on a type}}{{1-7=}} // expected-error@-1 {{'override' can only be specified on class members}}{{7-16=}} func inGlobalFunc() { static var v1: Int // expected-error {{static properties may only be declared on a type}}{{3-10=}} class var v2: Int // expected-error {{class properties may only be declared on a type}}{{3-9=}} static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{3-10=}} class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{3-9=}} v1 = 1; v2 = 1 _ = v1+v2+l1+l2 } struct InMemberFunc { func member() { static var v1: Int // expected-error {{static properties may only be declared on a type}}{{5-12=}} class var v2: Int // expected-error {{class properties may only be declared on a type}}{{5-11=}} static let l1: Int = 0 // expected-error {{static properties may only be declared on a type}}{{5-12=}} class let l2: Int = 0 // expected-error {{class properties may only be declared on a type}}{{5-11=}} v1 = 1; v2 = 1 _ = v1+v2+l1+l2 } } struct S { // expected-note 3{{extended type declared here}} static var v1: Int = 0 class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var v3: Int { return 0 } class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}} } extension S { static var ev1: Int = 0 class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var ev3: Int { return 0 } class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} } enum E { // expected-note 3{{extended type declared here}} static var v1: Int = 0 class var v2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var v3: Int { return 0 } class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final var v5 = 1 // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static final let l3 = 1 // expected-error {{only classes and class members may be marked with 'final'}} } extension E { static var ev1: Int = 0 class var ev2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static var ev3: Int { return 0 } class var ev4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} } class C { static var v1: Int = 0 class final var v3: Int = 0 // expected-error {{class stored properties not supported}} class var v4: Int = 0 // expected-error {{class stored properties not supported}} static var v5: Int { return 0 } class var v6: Int { return 0 } static final var v7: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} static let l1: Int = 0 class let l2: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} class final let l3: Int = 0 // expected-error {{class stored properties not supported}} static final let l4 = 2 // expected-error {{static declarations are already final}} {{10-16=}} } extension C { static var ev1: Int = 0 class final var ev2: Int = 0 // expected-error {{class stored properties not supported}} class var ev3: Int = 0 // expected-error {{class stored properties not supported}} static var ev4: Int { return 0 } class var ev5: Int { return 0 } static final var ev6: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} static let el1: Int = 0 class let el2: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} class final let el3: Int = 0 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} static final let el4: Int = 0 // expected-error {{static declarations are already final}} {{10-16=}} } protocol P { // expected-note{{extended type declared here}} // Both `static` and `class` property requirements are equivalent in protocols rdar://problem/17198298 static var v1: Int { get } class var v2: Int { get } // expected-error {{class properties are only allowed within classes; use 'static' to declare a requirement fulfilled by either a static or class property}} {{3-8=static}} static final var v3: Int { get } // expected-error {{only classes and class members may be marked with 'final'}} static let l1: Int // expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} class let l2: Int // expected-error {{class properties are only allowed within classes; use 'static' to declare a requirement fulfilled by either a static or class property}} {{3-8=static}} expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} } extension P { class var v4: Int { return 0 } // expected-error {{class properties are only allowed within classes; use 'static' to declare a static property}} {{3-8=static}} } struct S1 { // rdar://15626843 static var x: Int // expected-error {{'static var' declaration requires an initializer expression or getter/setter specifier}} var y = 1 static var z = 5 } extension S1 { static var zz = 42 static var xy: Int { return 5 } } enum E1 { static var y: Int { get {} } } class C1 { class var x: Int // expected-error {{class stored properties not supported}} expected-error {{'class var' declaration requires an initializer expression or getter/setter specifier}} } class C2 { var x: Int = 19 class var x: Int = 17 // expected-error{{class stored properties not supported}} func xx() -> Int { return self.x + C2.x } } class ClassHasVars { static var computedStatic: Int { return 0 } // expected-note 3{{overridden declaration is here}} final class var computedFinalClass: Int { return 0 } // expected-note 3{{overridden declaration is here}} class var computedClass: Int { return 0 } var computedInstance: Int { return 0 } } class ClassOverridesVars : ClassHasVars { override static var computedStatic: Int { return 1 } // expected-error {{cannot override static property}} override static var computedFinalClass: Int { return 1 } // expected-error {{static property overrides a 'final' class property}} override class var computedClass: Int { return 1 } override var computedInstance: Int { return 1 } } class ClassOverridesVars2 : ClassHasVars { override final class var computedStatic: Int { return 1 } // expected-error {{cannot override static property}} override final class var computedFinalClass: Int { return 1 } // expected-error {{class property overrides a 'final' class property}} } class ClassOverridesVars3 : ClassHasVars { override class var computedStatic: Int { return 1 } // expected-error {{cannot override static property}} override class var computedFinalClass: Int { return 1 } // expected-error {{class property overrides a 'final' class property}} } struct S2 { var x: Int = 19 static var x: Int = 17 func xx() -> Int { return self.x + C2.x } } // Mutating vs non-mutating conflict with static stored property witness - rdar://problem/19887250 protocol Proto { static var name: String {get set} } struct ProtoAdopter : Proto { static var name: String = "name" // no error, even though static setters aren't mutating } // Make sure the logic remains correct if we synthesized accessors for our stored property protocol ProtosEvilTwin { static var name: String {get set} } extension ProtoAdopter : ProtosEvilTwin {} // rdar://18990358 public struct Foo { // expected-note {{to match this opening '{'}}} public static let S { _ = 0; a // expected-error{{computed property must have an explicit type}} {{22-22=: <# Type #>}} // expected-error@-1{{type annotation missing in pattern}} // expected-error@-2{{'let' declarations cannot be computed properties}} {{17-20=var}} // expected-error@-3{{use of unresolved identifier 'a'}} } // expected-error@+1 {{expected '}' in struct}}
apache-2.0
1862ef04b342ac7dec422ae83dd08173
54.374074
294
0.699284
3.902636
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Apps/Printers/controller/PrintersMapViewController.swift
1
1655
// // PrintersMapViewController.swift // byuSuite // // Created by Alex Boswell on 5/4/18. // Copyright © 2018 Brigham Young University. All rights reserved. // import UIKit class PrintersMapViewController: ByuMapViewController2 { //MARK: Viewcontroller lifecycle override func viewDidLoad() { super.viewDidLoad() if let tabVC = self.tabBarController as? PrintersTabBarViewController, let printers = tabVC.printers { updatePrinters(printers) } } //MARK: MKMapViewDelegate Methods func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { if let printer = view.annotation as? Printer { self.displayAlert(title: "Restrictions", message: printer.restrictions, alertHandler: nil) } } func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { if let printer = annotation as? Printer { let pinView = mapView.dequeueDefaultReusablePin(annotation: annotation) pinView.canShowCallout = true if printer.isRestricted { pinView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) } else { pinView.rightCalloutAccessoryView = nil } return pinView } return nil } //MARK: Custom Methods func updatePrinters(_ printers: [Printer]) { if mapView != nil { spinner?.stopAnimating() self.mapView.removeAnnotations(mapView.annotations) self.mapView.addAnnotations(printers) zoomToFitMapAnnotations(includeUserLocation: true, keepByuInFrame: true) } } }
apache-2.0
a45e00b1aa59917f1365da76c24e3d79
28.535714
126
0.695284
4.633053
false
false
false
false
team-pie/DDDKit
DDDKit/Classes/DDDCube.swift
1
4141
// // DDDCube.swift // Pods // // Created by Guillaume Sabran on 10/02/2016. // Copyright (c) 2016 Guillaume Sabran. All rights reserved. // import Foundation import GLKit extension DDDGeometry { /// Represents a cube face private struct Face { let verticeRef: GLKVector3 let verticeX: GLKVector3 let verticeY: GLKVector3 let textureMappingRef: GLKVector2 } /// map a position on a cube to a position on a sphere private static func projectionOnSphere(point: GLKVector3, radius: Float) -> GLKVector3 { let r = sqrt(point.x * point.x + point.y * point.y + point.z * point.z) let theta = acos(-point.y / r) let phi = atan2(-point.x, point.z) return GLKVector3(v: ( radius * sin(theta) * cos(phi), radius * sin(theta) * sin(phi), radius * cos(theta) )) } /** Create a spherical geometry that uses a cubic texture mapping (see https://github.com/facebook/transform for instance) - Parameter radius: the radius of the sphere - Parameter strides: the number of subdivisions */ static func Cube(radius: GLfloat = 1.0, strides: Int = 20) -> DDDGeometry { // The cube vertices // // 5---------4 // /. /| // / . / | // 7---------6 | Y // | . | | / // | . | | / // | 1......|..0 0----Z // | . | / | // |. |/ | // 3---------2 X var vertices = [GLKVector3]() var texCoords = [GLKVector2]() var indices = [UInt16]() let fStride = Float(strides) let padding = Float(0.003) let faces = [ // front Face(verticeRef: GLKVector3(v: (1, 1, -1)), verticeX: GLKVector3(v: (0, 0, 2)), verticeY: GLKVector3(v: (-2, 0, 0)), textureMappingRef: GLKVector2(v: (1.0 / 3.0, 0))), // right Face(verticeRef: GLKVector3(v: (1, 1, 1)), verticeX: GLKVector3(v: (0, -2, 0)), verticeY: GLKVector3(v: (-2, 0, 0)), textureMappingRef: GLKVector2(v: (0, 0.5))), // left Face(verticeRef: GLKVector3(v: (1, -1, -1)), verticeX: GLKVector3(v: (0, 2, 0)), verticeY: GLKVector3(v: (-2, 0, 0)), textureMappingRef: GLKVector2(v: (1.0 / 3.0, 0.5))), // back Face(verticeRef: GLKVector3(v: (1, -1, 1)), verticeX: GLKVector3(v: (0, 0, -2)), verticeY: GLKVector3(v: (-2, 0, 0)), textureMappingRef: GLKVector2(v: (2.0 / 3.0, 0))), // top Face(verticeRef: GLKVector3(v: (-1, 1, -1)), verticeX: GLKVector3(v: (0, 0, 2)), verticeY: GLKVector3(v: (0, -2, 0)), textureMappingRef: GLKVector2(v: (2.0 / 3.0, 0.5))), // bottom Face(verticeRef: GLKVector3(v: (1, -1, -1)), verticeX: GLKVector3(v: (0, 0, 2)), verticeY: GLKVector3(v: (0, 2, 0)), textureMappingRef: GLKVector2(v: (0, 0))), ] faces.forEach { face in let indicesOffset = vertices.count for i in 0 ... strides { let k = Float(i) for j in 0 ... strides { let l = Float(j) let x0 = face.verticeRef let a = face.verticeX let b = face.verticeY let t = face.textureMappingRef let point = projectionOnSphere( point: GLKVector3(v: ( x0.x + a.x * k / fStride + b.x * l / fStride, x0.y + a.y * k / fStride + b.y * l / fStride, x0.z + a.z * k / fStride + b.z * l / fStride )), radius: radius ) let tex = GLKVector2(v: ( t.x + 1.0 / 3.0 * (k / fStride * (1 - 2 * padding) + padding), t.y + 0.5 * (l / fStride * (1 - 2 * padding) + padding) )) vertices.append(point) texCoords.append(GLKVector2(v: (1.0 - tex.y, tex.x))) } } for i in 0 ..< strides { for j in 0 ..< strides { let p = indicesOffset + j + i * (strides + 1) indices.append(UInt16(p)) indices.append(UInt16(p + strides + 1)) indices.append(UInt16(p + 1)) indices.append(UInt16(p + strides + 1)) indices.append(UInt16(p + strides + 2)) indices.append(UInt16(p + 1)) } } } return DDDGeometry(indices: indices, vertices: vertices, texCoords: texCoords) } }
mit
443ebe61b70cfb2b5e2e63aa125d8cc1
27.363014
119
0.541657
2.824693
false
false
false
false
kosua20/PtahRenderer
PtahRendererDemo/Renderer.swift
1
7563
// // Renderer.swift // PtahRenderer // // Created by Simon Rodriguez on 29/12/2016. // Copyright © 2016 Simon Rodriguez. All rights reserved. // import Foundation import PtahRenderer #if os(macOS) import Cocoa import simd #endif #if os(macOS) let imageExt = ".png" #else let imageExt = ".tga" #endif struct Camera { var position: Vertex var center: Vertex var up: Vertex var view: Matrix4 let projection: Matrix4 init(position: Vertex, center: Vertex, up: Vertex, projection: Matrix4) { self.position = position self.center = center self.up = up self.view = Matrix4.lookAtMatrix(eye: position, target: center, up: up) self.projection = projection } mutating func update() { view = Matrix4.lookAtMatrix(eye: position, target: center, up: up) } } public final class Renderer { private var internalRenderer: InternalRenderer private var time: Scalar = 0.0 private var camera: Camera public var horizontalAngle: Scalar = 0.0 public var verticalAngle: Scalar = 0.75 public var distance: Scalar = 2.0 private let lightDir: Point4 private let vpLight: Matrix4 private let dragon: Object private let floor: Object private let monkey: Object private let cubemap: Object public init(width: Int, height: Int, rootDir: String){ internalRenderer = InternalRenderer(width: width, height: height) //internalRenderer.mode = .wireframe // Add framebuffer for shadow mapping. internalRenderer.addFramebuffer(width: 128, height: 128) // Load models. var baseName = "dragon" dragon = Object(meshPath: rootDir + "models/" + baseName + "4k.obj", program: ObjectProgram(), textureNames: ["texture"], texturePaths: [rootDir + "textures/" + baseName + imageExt]) baseName = "floor" floor = Object(meshPath: rootDir + "models/" + baseName + ".obj", program: ObjectProgram(), textureNames: ["texture"], texturePaths: [rootDir + "textures/" + baseName + imageExt]) baseName = "monkey" monkey = Object(meshPath: rootDir + "models/" + baseName + "2k.obj", program: ObjectProgram(), textureNames: ["texture"], texturePaths: [rootDir + "textures/" + baseName + imageExt]) baseName = "cubemap" cubemap = Object(meshPath: rootDir + "models/" + baseName + ".obj", program: SkyboxProgram(), textureNames: ["texture"], texturePaths: [rootDir + "textures/" + baseName + imageExt]) // Define initial model matrices. dragon.model = Matrix4.translationMatrix(Point3(-0.25,0.0,-0.25)) * Matrix4.scaleMatrix(0.75) floor.model = Matrix4.translationMatrix(Point3(0.0,-0.5,0.0)) * Matrix4.scaleMatrix(2.0) monkey.model = Matrix4.translationMatrix(Point3(0.5,0.0,0.5)) * Matrix4.scaleMatrix(0.5) cubemap.model = Matrix4.scaleMatrix(5.0) // Projection matrix and camera setting. let proj = Matrix4.perspectiveMatrix(fov:70.0, aspect: Scalar(width)/Scalar(height), near: 0.1, far: 15.0) let initialPos = distance*normalize(Point3(1.0, 0.5, 0.0)) camera = Camera(position: initialPos, center: Point3(0.0, 0.0, 0.0), up: Point3(0.0, 1.0, 0.0), projection: proj) // Light settings: direction and view-projection matrix. lightDir = Point4(-0.57735, -0.57735, -0.57735, 0.0) vpLight = Matrix4.orthographicMatrix(right: 2.0, top: 2.0, near: 0.1, far: 100.0) * Matrix4.lookAtMatrix(eye: -Point3(lightDir), target: Point3(0.0,0.0,0.0), up: Point3(0.0,1.0,0.0)) } func update(elapsed: Scalar){ // Update camera position and matrix. camera.position = distance*Point3(cos(horizontalAngle)*cos(verticalAngle), sin(verticalAngle), sin(horizontalAngle)*cos(verticalAngle)) camera.update() // Update light direction in view space. let lightViewDir4 = camera.view * lightDir let lightViewDir = normalize(Point3(lightViewDir4)) // Dragon matrices. let mvDragon = camera.view*dragon.model let mvpDragon = camera.projection*mvDragon let invMVDragon = mvDragon.transpose.inverse let mvpLightDragon = vpLight*dragon.model dragon.program.register(index: 0, value: mvDragon) dragon.program.register(index: 1, value: mvpDragon) dragon.program.register(index: 2, value: invMVDragon) dragon.program.register(index: 0, value: lightViewDir) dragon.program.register(index: 3, value: mvpLightDragon) dragon.depthProgram.register(index: 0, value: mvpLightDragon) // Floor matrices. let mvFloor = camera.view*floor.model let mvpFloor = camera.projection*mvFloor let invMVFloor = mvFloor.transpose.inverse let mvpLightFloor = vpLight*floor.model floor.program.register(index: 0, value: mvFloor) floor.program.register(index: 1, value: mvpFloor) floor.program.register(index: 2, value: invMVFloor) floor.program.register(index: 0, value: lightViewDir) floor.program.register(index: 3, value: mvpLightFloor) floor.depthProgram.register(index: 0, value: mvpLightFloor) // Monkey matrices (only animated object). monkey.model = Matrix4.translationMatrix(Point3(0.5,0.0,0.5)) * Matrix4.scaleMatrix(0.4) * Matrix4.rotationMatrix(angle: time, axis: Point3(0.0,1.0,0.0)) let mvMonkey = camera.view*monkey.model let mvpMonkey = camera.projection*mvMonkey let invMVMonkey = mvMonkey.transpose.inverse let mvpLightMonkey = vpLight*monkey.model monkey.program.register(index: 0, value: mvMonkey) monkey.program.register(index: 1, value: mvpMonkey) monkey.program.register(index: 2, value: invMVMonkey) monkey.program.register(index: 0, value: lightViewDir) monkey.program.register(index: 3, value: mvpLightMonkey) monkey.depthProgram.register(index: 0, value: mvpLightMonkey) // Cubemap matrix. let mvpCubemap = camera.projection*camera.view*cubemap.model cubemap.program.register(index: 0, value: mvpCubemap) } public func render(elapsed: Scalar){ // Animation update. time += elapsed update(elapsed:elapsed) // First pass: draw depth only from light point of view, for shadow mapping. internalRenderer.bindFramebuffer(i: 1) internalRenderer.clear(color: false, depth: true) internalRenderer.drawMesh(mesh: monkey.mesh, program: monkey.depthProgram, depthOnly: true) internalRenderer.drawMesh(mesh: dragon.mesh, program: dragon.depthProgram, depthOnly: true) internalRenderer.drawMesh(mesh: floor.mesh, program: floor.depthProgram, depthOnly: true) // Transfer the resulting depth map to the objects for the second pass. let depthMap = ScalarTexture(buffer: internalRenderer.flushDepthBuffer(), width: internalRenderer.width, height: internalRenderer.height) floor.program.register(index: 0, value: depthMap) monkey.program.register(index: 0, value: depthMap) dragon.program.register(index: 0, value: depthMap) // Second pass: draw objects with lighting and shadows. // We avoid clearing the color as the skybox will cover the whole screen. internalRenderer.bindFramebuffer(i: 0) internalRenderer.clear(color: false, depth: true) internalRenderer.drawMesh(mesh: monkey.mesh, program: monkey.program) internalRenderer.drawMesh(mesh: dragon.mesh, program: dragon.program) internalRenderer.drawMesh(mesh: floor.mesh, program: floor.program) internalRenderer.drawMesh(mesh: cubemap.mesh, program: cubemap.program) } #if os(macOS) public func flush() -> CGImage { return internalRenderer.flushImage()! } #else public func flush() -> [Pixel] { return flushBuffer() } #endif public func flushBuffer() -> [Pixel] { return internalRenderer.flushBuffer() } }
mit
1ce92f30764ed07b7cfc442b5e88b0e2
33.688073
185
0.715816
3.27785
false
false
false
false
Rapid-SDK/ios
Examples/RapiDO - ToDo list/RapiDO macOS/ListViewController.swift
1
9656
// // ViewController.swift // ExampleMacOSApp // // Created by Jan on 15/05/2017. // Copyright © 2017 Rapid. All rights reserved. // import Cocoa import Rapid class ListViewController: NSViewController { @IBOutlet weak var tableView: NSTableView! @IBOutlet weak var completionPopUp: NSPopUpButton! @IBOutlet weak var homeCheckBox: NSButton! @IBOutlet weak var homeBackgroundView: NSView! @IBOutlet weak var workCheckBox: NSButton! @IBOutlet weak var workBackgroundView: NSView! @IBOutlet weak var otherCheckBox: NSButton! @IBOutlet weak var otherBackgroundView: NSView! var tasks: [Task] = [] fileprivate var subscription: RapidSubscription? fileprivate var ordering: RapidOrdering? fileprivate var filter: RapidFilter? lazy var dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.timeStyle = .medium formatter.dateStyle = .medium return formatter }() override func viewDidLoad() { super.viewDidLoad() setupRapid() setupUI() subscribe() } override func viewWillAppear() { super.viewWillAppear() homeBackgroundView.wantsLayer = true homeBackgroundView.layer?.backgroundColor = Tag.home.color.cgColor homeBackgroundView.layer?.cornerRadius = homeBackgroundView.frame.height/2 workBackgroundView.wantsLayer = true workBackgroundView.layer?.backgroundColor = Tag.work.color.cgColor workBackgroundView.layer?.cornerRadius = workBackgroundView.frame.height/2 otherBackgroundView.wantsLayer = true otherBackgroundView.layer?.backgroundColor = Tag.other.color.cgColor otherBackgroundView.layer?.cornerRadius = otherBackgroundView.frame.height/2 } @IBAction func filter(_ sender: AnyObject) { var operands = [RapidFilter]() if let item = completionPopUp.selectedItem { let index = completionPopUp.index(of: item) // Popup selected index equal to 0 means "show all tasks regardless completion state", so no filter is needed // Otherwise, create filter for either completed or incompleted tasks if index > 0 { let completed = index == 2 operands.append(RapidFilter.equal(keyPath: Task.completedAttributeName, value: completed)) } } // Create filter for selected tags var tags = [RapidFilter]() if homeCheckBox.state.rawValue > 0 { tags.append(RapidFilter.arrayContains(keyPath: Task.tagsAttributeName, value: Tag.home.rawValue)) } if workCheckBox.state.rawValue > 0 { tags.append(RapidFilter.arrayContains(keyPath: Task.tagsAttributeName, value: Tag.work.rawValue)) } if otherCheckBox.state.rawValue > 0 { tags.append(RapidFilter.arrayContains(keyPath: Task.tagsAttributeName, value: Tag.other.rawValue)) } // Combine single tag filters with logical "OR" operator if !tags.isEmpty { operands.append(RapidFilter.or(tags)) } // If there are any filters combine them with logical "AND" if operands.isEmpty { filter = nil } else { filter = RapidFilter.and(operands) } subscribe() } } fileprivate extension ListViewController { func setupUI() { tableView.dataSource = self tableView.delegate = self tableView.target = self tableView.doubleAction = #selector(self.tableViewDoubleClick(_:)) for column in tableView.tableColumns { let columnID = ColumnIdentifier(rawValue: column.identifier.rawValue) switch columnID { case .some(.priority), .some(.title), .some(.completed), .some(.created): column.sortDescriptorPrototype = NSSortDescriptor(key: columnID?.rawValue ?? "", ascending: true) default: break } } homeCheckBox.title = Tag.home.title workCheckBox.title = Tag.work.title otherCheckBox.title = Tag.other.title } func setupRapid() { // Set log level Rapid.logLevel = .info // Configure shared singleton with API key Rapid.configure(withApiKey: "<YOUR API KEY>") // Enable data cache Rapid.isCacheEnabled = true // Set timeout for requests Rapid.timeout = 10 } func subscribe() { // If there is a previous subscription then unsubscribe from it subscription?.unsubscribe() tasks.removeAll() tableView.reloadData() // Get Rapid collection reference with a given name var collection = Rapid.collection(named: Constants.collectionName) // If a filter is set, modify the collection reference with it if let filter = filter { collection.filtered(by: filter) } // If a ordering is set, modify the collection reference with it if let order = ordering { collection.ordered(by: order) } // Subscribe to the collection // Store a subscribtion reference to be able to unsubscribe from it subscription = collection.subscribe() { result in switch result { case .success(let documents): self.tasks = documents.flatMap({ Task(withSnapshot: $0) }) case .failure: self.tasks = [] } self.tableView.reloadData() } } } extension ListViewController: NSTableViewDataSource, NSTableViewDelegate { enum ColumnIdentifier: String { case completed = "Done" case title = "Title" case description = "Desc" case created = "Created" case priority = "Priority" case tags = "Tags" var cellIdentifier: String { return "\(self.rawValue)CellID" } } func numberOfRows(in tableView: NSTableView) -> Int { return tasks.count } func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let task = tasks[row] guard let id = tableColumn?.identifier, let column = ColumnIdentifier(rawValue: id.rawValue) else { return nil } let view = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: column.cellIdentifier), owner: nil) if let cell = view as? NSTableCellView { switch column { case .completed: if let cell = view as? CheckBoxCellView { cell.delegate = self cell.textField?.stringValue = "" cell.checkBox.state = NSControl.StateValue(rawValue: task.completed ? 1 : 0) } case .title: cell.textField?.stringValue = task.title case .description: cell.textField?.stringValue = task.description ?? "" case .created: cell.textField?.stringValue = dateFormatter.string(from: task.createdAt) case .priority: cell.textField?.stringValue = task.priority.title case .tags: if let cell = view as? TagsCellView { cell.configure(withTags: task.tags) } } } return view } @objc func tableViewDoubleClick(_ sender: AnyObject) { let row = tableView.selectedRow guard row >= 0 else { return } let task = tasks[row] let delegate = NSApplication.shared.delegate as? AppDelegate delegate?.updateTask(task) } func tableView(_ tableView: NSTableView, sortDescriptorsDidChange oldDescriptors: [NSSortDescriptor]) { // If there is no sort descriptor, remove current ordering guard let descriptor = tableView.sortDescriptors.first else { ordering = nil subscribe() return } guard let identifier = descriptor.key, let column = ColumnIdentifier(rawValue: identifier) else { return } // Get an ordering type let order = descriptor.ascending ? RapidOrdering.Ordering.ascending : .descending // Create an ordering switch column { case .completed: ordering = RapidOrdering(keyPath: Task.completedAttributeName, ordering: order) case .title: ordering = RapidOrdering(keyPath: Task.titleAttributeName, ordering: order) case .priority: ordering = RapidOrdering(keyPath: Task.priorityAttributeName, ordering: order) case .created: ordering = RapidOrdering(keyPath: Task.createdAttributeName, ordering: order) default: break } subscribe() } } extension ListViewController: CheckBoxCellViewDelegate { func checkBoxCellChangedValue(_ cellView: CheckBoxCellView, value: Bool) { let row = tableView.row(for: cellView) if row >= 0 { let task = tasks[row] task.updateCompleted(value) } } }
mit
8a2a7dab42068fc69028635845108b73
31.29097
129
0.589332
5.38483
false
false
false
false
whiteath/ReadFoundationSource
Foundation/Operation.swift
2
16977
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_ENABLE_LIBDISPATCH import Dispatch #endif import CoreFoundation open class Operation : NSObject { let lock = NSLock() internal weak var _queue: OperationQueue? internal var _cancelled = false internal var _executing = false internal var _finished = false internal var _ready = false internal var _dependencies = Set<Operation>() #if DEPLOYMENT_ENABLE_LIBDISPATCH internal var _group = DispatchGroup() internal var _depGroup = DispatchGroup() internal var _groups = [DispatchGroup]() #endif public override init() { super.init() #if DEPLOYMENT_ENABLE_LIBDISPATCH _group.enter() #endif } internal func _leaveGroups() { // assumes lock is taken #if DEPLOYMENT_ENABLE_LIBDISPATCH _groups.forEach() { $0.leave() } _groups.removeAll() _group.leave() #endif } open func start() { lock.lock() _executing = true lock.unlock() main() lock.lock() _executing = false lock.unlock() finish() } internal func finish() { lock.lock() _finished = true _leaveGroups() lock.unlock() if let queue = _queue { queue._operationFinished(self) } #if DEPLOYMENT_ENABLE_LIBDISPATCH // The completion block property is a bit cagey and can not be executed locally on the queue due to thread exhaust potentials. // This sets up for some strange behavior of finishing operations since the handler will be executed on a different queue if let completion = completionBlock { DispatchQueue.global(qos: .background).async { () -> Void in completion() } } #endif } open func main() { } open var isCancelled: Bool { return _cancelled } open func cancel() { lock.lock() _cancelled = true _leaveGroups() lock.unlock() } open var isExecuting: Bool { let wasExecuting: Bool lock.lock() wasExecuting = _executing lock.unlock() return wasExecuting } open var isFinished: Bool { return _finished } // - Note: This property is NEVER used in the objective-c implementation! open var isAsynchronous: Bool { return false } open var isReady: Bool { return _ready } open func addDependency(_ op: Operation) { lock.lock() _dependencies.insert(op) op.lock.lock() #if DEPLOYMENT_ENABLE_LIBDISPATCH _depGroup.enter() op._groups.append(_depGroup) #endif op.lock.unlock() lock.unlock() } open func removeDependency(_ op: Operation) { lock.lock() _dependencies.remove(op) op.lock.lock() #if DEPLOYMENT_ENABLE_LIBDISPATCH let groupIndex = op._groups.index(where: { $0 === self._depGroup }) if let idx = groupIndex { let group = op._groups.remove(at: idx) group.leave() } #endif op.lock.unlock() lock.unlock() } open var dependencies: [Operation] { lock.lock() let ops = _dependencies.map() { $0 } lock.unlock() return ops } open var queuePriority: QueuePriority = .normal public var completionBlock: (() -> Void)? open func waitUntilFinished() { #if DEPLOYMENT_ENABLE_LIBDISPATCH _group.wait() #endif } open var threadPriority: Double = 0.5 /// - Note: Quality of service is not directly supported here since there are not qos class promotions available outside of darwin targets. open var qualityOfService: QualityOfService = .default open var name: String? internal func _waitUntilReady() { #if DEPLOYMENT_ENABLE_LIBDISPATCH _depGroup.wait() #endif _ready = true } } /// The following two methods are added to provide support for Operations which /// are asynchronous from the execution of the operation queue itself. On Darwin, /// this is supported via KVO notifications. In the absence of KVO on non-Darwin /// platforms, these two methods (which are defined in NSObject on Darwin) are /// temporarily added here. They should be removed once a permanent solution is /// found. extension Operation { public func willChangeValue(forKey key: String) { // do nothing } public func didChangeValue(forKey key: String) { if key == "isFinished" && isFinished { finish() } } } extension Operation { public enum QueuePriority : Int { case veryLow case low case normal case high case veryHigh } } open class BlockOperation: Operation { typealias ExecutionBlock = () -> Void internal var _block: () -> Void internal var _executionBlocks = [ExecutionBlock]() public init(block: @escaping () -> Void) { _block = block } override open func main() { lock.lock() let block = _block let executionBlocks = _executionBlocks lock.unlock() block() executionBlocks.forEach { $0() } } open func addExecutionBlock(_ block: @escaping () -> Void) { lock.lock() _executionBlocks.append(block) lock.unlock() } open var executionBlocks: [() -> Void] { lock.lock() let blocks = _executionBlocks lock.unlock() return blocks } } public extension OperationQueue { public static let defaultMaxConcurrentOperationCount: Int = Int.max } internal struct _OperationList { var veryLow = [Operation]() var low = [Operation]() var normal = [Operation]() var high = [Operation]() var veryHigh = [Operation]() var all = [Operation]() mutating func insert(_ operation: Operation) { all.append(operation) switch operation.queuePriority { case .veryLow: veryLow.append(operation) case .low: low.append(operation) case .normal: normal.append(operation) case .high: high.append(operation) case .veryHigh: veryHigh.append(operation) } } mutating func remove(_ operation: Operation) { if let idx = all.index(of: operation) { all.remove(at: idx) } switch operation.queuePriority { case .veryLow: if let idx = veryLow.index(of: operation) { veryLow.remove(at: idx) } case .low: if let idx = low.index(of: operation) { low.remove(at: idx) } case .normal: if let idx = normal.index(of: operation) { normal.remove(at: idx) } case .high: if let idx = high.index(of: operation) { high.remove(at: idx) } case .veryHigh: if let idx = veryHigh.index(of: operation) { veryHigh.remove(at: idx) } } } mutating func dequeue() -> Operation? { if !veryHigh.isEmpty { return veryHigh.remove(at: 0) } if !high.isEmpty { return high.remove(at: 0) } if !normal.isEmpty { return normal.remove(at: 0) } if !low.isEmpty { return low.remove(at: 0) } if !veryLow.isEmpty { return veryLow.remove(at: 0) } return nil } var count: Int { return all.count } func map<T>(_ transform: (Operation) throws -> T) rethrows -> [T] { return try all.map(transform) } } open class OperationQueue: NSObject { let lock = NSLock() #if DEPLOYMENT_ENABLE_LIBDISPATCH var __concurrencyGate: DispatchSemaphore? var __underlyingQueue: DispatchQueue? { didSet { let key = OperationQueue.OperationQueueKey oldValue?.setSpecific(key: key, value: nil) __underlyingQueue?.setSpecific(key: key, value: Unmanaged.passUnretained(self)) } } let queueGroup = DispatchGroup() #endif var _operations = _OperationList() #if DEPLOYMENT_ENABLE_LIBDISPATCH internal var _concurrencyGate: DispatchSemaphore? { get { lock.lock() let val = __concurrencyGate lock.unlock() return val } } // This is NOT the behavior of the objective-c variant; it will never re-use a queue and instead for every operation it will create a new one. // However this is considerably faster and probably more effecient. internal var _underlyingQueue: DispatchQueue { lock.lock() if let queue = __underlyingQueue { lock.unlock() return queue } else { let effectiveName: String if let requestedName = _name { effectiveName = requestedName } else { effectiveName = "NSOperationQueue::\(Unmanaged.passUnretained(self).toOpaque())" } let attr: DispatchQueue.Attributes if maxConcurrentOperationCount == 1 { attr = [] __concurrencyGate = DispatchSemaphore(value: 1) } else { attr = .concurrent if maxConcurrentOperationCount != OperationQueue.defaultMaxConcurrentOperationCount { __concurrencyGate = DispatchSemaphore(value:maxConcurrentOperationCount) } } let queue = DispatchQueue(label: effectiveName, attributes: attr) if _suspended { queue.suspend() } __underlyingQueue = queue lock.unlock() return queue } } #endif public override init() { super.init() } #if DEPLOYMENT_ENABLE_LIBDISPATCH internal init(_queue queue: DispatchQueue, maxConcurrentOperations: Int = OperationQueue.defaultMaxConcurrentOperationCount) { __underlyingQueue = queue maxConcurrentOperationCount = maxConcurrentOperations super.init() queue.setSpecific(key: OperationQueue.OperationQueueKey, value: Unmanaged.passUnretained(self)) } #endif internal func _dequeueOperation() -> Operation? { lock.lock() let op = _operations.dequeue() lock.unlock() return op } open func addOperation(_ op: Operation) { addOperations([op], waitUntilFinished: false) } internal func _runOperation() { if let op = _dequeueOperation() { if !op.isCancelled { op._waitUntilReady() if !op.isCancelled { op.start() } } } } open func addOperations(_ ops: [Operation], waitUntilFinished wait: Bool) { #if DEPLOYMENT_ENABLE_LIBDISPATCH var waitGroup: DispatchGroup? if wait { waitGroup = DispatchGroup() } #endif /* If QueuePriority was not supported this could be much faster since it would not need to have the extra book-keeping for managing a priority queue. However this implementation attempts to be similar to the specification. As a concequence this means that the dequeue may NOT nessicarly be the same as the enqueued operation in this callout. So once the dispatch_block is created the operation must NOT be touched; since it has nothing to do with the actual execution. The only differential is that the block enqueued to dispatch_async is balanced with the number of Operations enqueued to the OperationQueue. */ lock.lock() ops.forEach { (operation: Operation) -> Void in operation._queue = self _operations.insert(operation) } lock.unlock() ops.forEach { (operation: Operation) -> Void in #if DEPLOYMENT_ENABLE_LIBDISPATCH if let group = waitGroup { group.enter() } let block = DispatchWorkItem(flags: .enforceQoS) { () -> Void in if let sema = self._concurrencyGate { sema.wait() self._runOperation() sema.signal() } else { self._runOperation() } if let group = waitGroup { group.leave() } } _underlyingQueue.async(group: queueGroup, execute: block) #endif } #if DEPLOYMENT_ENABLE_LIBDISPATCH if let group = waitGroup { group.wait() } #endif } internal func _operationFinished(_ operation: Operation) { lock.lock() _operations.remove(operation) operation._queue = nil lock.unlock() } open func addOperation(_ block: @escaping () -> Swift.Void) { let op = BlockOperation(block: block) op.qualityOfService = qualityOfService addOperation(op) } // WARNING: the return value of this property can never be used to reliably do anything sensible open var operations: [Operation] { lock.lock() let ops = _operations.map() { $0 } lock.unlock() return ops } // WARNING: the return value of this property can never be used to reliably do anything sensible open var operationCount: Int { lock.lock() let count = _operations.count lock.unlock() return count } open var maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount internal var _suspended = false open var isSuspended: Bool { get { return _suspended } set { lock.lock() if _suspended != newValue { _suspended = newValue #if DEPLOYMENT_ENABLE_LIBDISPATCH if let queue = __underlyingQueue { if newValue { queue.suspend() } else { queue.resume() } } #endif } lock.unlock() } } internal var _name: String? open var name: String? { get { lock.lock() let val = _name lock.unlock() return val } set { lock.lock() _name = newValue #if DEPLOYMENT_ENABLE_LIBDISPATCH __underlyingQueue = nil #endif lock.unlock() } } open var qualityOfService: QualityOfService = .default #if DEPLOYMENT_ENABLE_LIBDISPATCH // Note: this will return non nil whereas the objective-c version will only return non nil when it has been set. // it uses a target queue assignment instead of returning the actual underlying queue. open var underlyingQueue: DispatchQueue? { get { lock.lock() let queue = __underlyingQueue lock.unlock() return queue } set { lock.lock() __underlyingQueue = newValue lock.unlock() } } #endif open func cancelAllOperations() { lock.lock() let ops = _operations.map() { $0 } lock.unlock() ops.forEach() { $0.cancel() } } open func waitUntilAllOperationsAreFinished() { #if DEPLOYMENT_ENABLE_LIBDISPATCH queueGroup.wait() #endif } #if DEPLOYMENT_ENABLE_LIBDISPATCH static let OperationQueueKey = DispatchSpecificKey<Unmanaged<OperationQueue>>() #endif open class var current: OperationQueue? { #if DEPLOYMENT_ENABLE_LIBDISPATCH guard let specific = DispatchQueue.getSpecific(key: OperationQueue.OperationQueueKey) else { if _CFIsMainThread() { return OperationQueue.main } else { return nil } } return specific.takeUnretainedValue() #else return nil #endif } #if DEPLOYMENT_ENABLE_LIBDISPATCH private static let _main = OperationQueue(_queue: .main, maxConcurrentOperations: 1) #endif open class var main: OperationQueue { #if DEPLOYMENT_ENABLE_LIBDISPATCH return _main #else fatalError("OperationQueue requires libdispatch") #endif } }
apache-2.0
579998b363a659707eb536311b55d9d7
27.677365
146
0.574189
4.832622
false
false
false
false
csujedihy/Flicks
MoviesViewer/FullScreenPhotoViewController.swift
1
2084
// // FullScreenPhotoViewController.swift // MoviesViewer // // Created by YiHuang on 2/6/16. // Copyright © 2016 c2fun. All rights reserved. // import UIKit class FullScreenPhotoViewController: UIViewController, UIScrollViewDelegate { var photoUrl:String? var image:UIImage? @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var fullscreenImage: UIImageView! @IBAction func closeTap(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() scrollView.delegate = self fullscreenImage.image = self.image /* fetch image from Internet */ /* let posterBaseUrl = "http://image.tmdb.org/t/p/w500" if let url = self.photoUrl{ let posterUrl = NSURL(string: posterBaseUrl + url) let imageRequest = NSURLRequest(URL: posterUrl!) fullscreenImage.setImageWithURLRequest( imageRequest, placeholderImage: nil, success: { (imageRequest, imageResponse, image) -> Void in }, failure: { (imageRequest, imageResponse, error) -> Void in // do something for the failure condition }) } */ // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return fullscreenImage } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
f0b2f193144b868650f4290d8d4d2fd7
29.188406
106
0.620259
5.300254
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Home/RecentlySaved/RecentlySavedDataAdaptor.swift
1
4082
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation import Storage protocol RecentlySavedDataAdaptor { func getRecentlySavedData() -> [RecentlySavedItem] } protocol RecentlySavedDelegate: AnyObject { func didLoadNewData() } class RecentlySavedDataAdaptorImplementation: RecentlySavedDataAdaptor, Notifiable { var notificationCenter: NotificationProtocol private let bookmarkItemsLimit: UInt = 5 private let readingListItemsLimit: Int = 5 private let recentItemsHelper = RecentItemsHelper() private var readingList: ReadingList private var bookmarksHandler: BookmarksHandler private var recentBookmarks = [RecentlySavedBookmark]() private var readingListItems = [ReadingListItem]() weak var delegate: RecentlySavedDelegate? init(readingList: ReadingList, bookmarksHandler: BookmarksHandler, notificationCenter: NotificationProtocol = NotificationCenter.default) { self.notificationCenter = notificationCenter self.readingList = readingList self.bookmarksHandler = bookmarksHandler setupNotifications(forObserver: self, observing: [.ReadingListUpdated, .BookmarksUpdated, .RustPlacesOpened]) getRecentBookmarks() getReadingLists() } func getRecentlySavedData() -> [RecentlySavedItem] { var items = [RecentlySavedItem]() items.append(contentsOf: recentBookmarks) items.append(contentsOf: readingListItems) return items } // MARK: - Bookmarks private func getRecentBookmarks() { bookmarksHandler.getRecentBookmarks(limit: bookmarkItemsLimit) { bookmarks in let bookmarks = bookmarks.map { RecentlySavedBookmark(bookmark: $0) } self.updateRecentBookmarks(bookmarks: bookmarks) } } private func updateRecentBookmarks(bookmarks: [RecentlySavedBookmark]) { recentBookmarks = recentItemsHelper.filterStaleItems(recentItems: bookmarks) as? [RecentlySavedBookmark] ?? [] delegate?.didLoadNewData() // Send telemetry if bookmarks aren't empty if !recentBookmarks.isEmpty { TelemetryWrapper.recordEvent(category: .action, method: .view, object: .firefoxHomepage, value: .recentlySavedBookmarkItemView, extras: [TelemetryWrapper.EventObject.recentlySavedBookmarkImpressions.rawValue: "\(bookmarks.count)"]) } } // MARK: - Reading list private func getReadingLists() { let maxItems = readingListItemsLimit readingList.getAvailableRecords { readingList in let items = readingList.prefix(maxItems) self.updateReadingList(readingList: Array(items)) } } private func updateReadingList(readingList: [ReadingListItem]) { readingListItems = recentItemsHelper.filterStaleItems(recentItems: readingList) as? [ReadingListItem] ?? [] delegate?.didLoadNewData() let extra = [TelemetryWrapper.EventObject.recentlySavedReadingItemImpressions.rawValue: "\(readingListItems.count)"] TelemetryWrapper.recordEvent(category: .action, method: .view, object: .firefoxHomepage, value: .recentlySavedReadingListView, extras: extra) } // MARK: - Notifiable func handleNotifications(_ notification: Notification) { switch notification.name { case .ReadingListUpdated: getReadingLists() case .BookmarksUpdated, .RustPlacesOpened: getRecentBookmarks() default: break } } }
mpl-2.0
618aaeeb4000eae252b9a54f83b0484a
36.449541
144
0.641107
5.693166
false
false
false
false
iOSTestApps/firefox-ios
Providers/Profile.swift
1
25566
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Account import ReadingList import Shared import Storage import Sync import XCGLogger // TODO: same comment as for SyncAuthState.swift! private let log = XCGLogger.defaultInstance() public protocol SyncManager { func syncClients() -> SyncResult func syncClientsThenTabs() -> SyncResult func syncHistory() -> SyncResult func syncLogins() -> SyncResult // The simplest possible approach. func beginTimedSyncs() func endTimedSyncs() func onRemovedAccount(account: FirefoxAccount?) -> Success func onAddedAccount() -> Success } typealias EngineIdentifier = String typealias SyncFunction = (SyncDelegate, Prefs, Ready) -> SyncResult class ProfileFileAccessor: FileAccessor { init(profile: Profile) { let profileDirName = "profile.\(profile.localName())" // Bug 1147262: First option is for device, second is for simulator. var rootPath: String? if let sharedContainerIdentifier = ExtensionUtils.sharedContainerIdentifier(), url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(sharedContainerIdentifier), path = url.path { rootPath = path } else { log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.") rootPath = String(NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString) } super.init(rootPath: rootPath!.stringByAppendingPathComponent(profileDirName)) } } class CommandDiscardingSyncDelegate: SyncDelegate { func displaySentTabForURL(URL: NSURL, title: String) { // TODO: do something else. log.info("Discarding sent URL \(URL.absoluteString)") } } /** * This exists because the Sync code is extension-safe, and thus doesn't get * direct access to UIApplication.sharedApplication, which it would need to * display a notification. * This will also likely be the extension point for wipes, resets, and * getting access to data sources during a sync. */ let TabSendURLKey = "TabSendURL" let TabSendTitleKey = "TabSendTitle" let TabSendCategory = "TabSendCategory" enum SentTabAction: String { case View = "TabSendViewAction" case Bookmark = "TabSendBookmarkAction" case ReadingList = "TabSendReadingListAction" } class BrowserProfileSyncDelegate: SyncDelegate { let app: UIApplication init(app: UIApplication) { self.app = app } // SyncDelegate func displaySentTabForURL(URL: NSURL, title: String) { // check to see what the current notification settings are and only try and send a notification if // the user has agreed to them let currentSettings = app.currentUserNotificationSettings() if currentSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 { log.info("Displaying notification for URL \(URL.absoluteString)") let notification = UILocalNotification() notification.fireDate = NSDate() notification.timeZone = NSTimeZone.defaultTimeZone() notification.alertBody = String(format: NSLocalizedString("New tab: %@: %@", comment:"New tab [title] [url]"), title, URL.absoluteString!) notification.userInfo = [TabSendURLKey: URL.absoluteString!, TabSendTitleKey: title] notification.alertAction = nil notification.category = TabSendCategory app.presentLocalNotificationNow(notification) } } } /** * A Profile manages access to the user's data. */ protocol Profile: class { var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> { get } // var favicons: Favicons { get } var prefs: Prefs { get } var queue: TabQueue { get } var searchEngines: SearchEngines { get } var files: FileAccessor { get } var history: protocol<BrowserHistory, SyncableHistory> { get } var favicons: Favicons { get } var readingList: ReadingListService? { get } var logins: protocol<BrowserLogins, SyncableLogins> { get } var thumbnails: Thumbnails { get } func shutdown() // I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter. // Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>. func localName() -> String // URLs and account configuration. var accountConfiguration: FirefoxAccountConfiguration { get } func getAccount() -> FirefoxAccount? func removeAccount() func setAccount(account: FirefoxAccount) func getClients() -> Deferred<Result<[RemoteClient]>> func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> func getCachedClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> func storeTabs(tabs: [RemoteTab]) -> Deferred<Result<Int>> func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) var syncManager: SyncManager { get } } public class BrowserProfile: Profile { private let name: String weak private var app: UIApplication? init(localName: String, app: UIApplication?) { self.name = localName self.app = app let notificationCenter = NSNotificationCenter.defaultCenter() let mainQueue = NSOperationQueue.mainQueue() notificationCenter.addObserver(self, selector: Selector("onLocationChange:"), name: "LocationChange", object: nil) if let baseBundleIdentifier = ExtensionUtils.baseBundleIdentifier() { KeychainWrapper.serviceName = baseBundleIdentifier } else { log.error("Unable to get the base bundle identifier. Keychain data will not be shared.") } // If the profile dir doesn't exist yet, this is first run (for this profile). if !files.exists("") { log.info("New profile. Removing old account data.") removeAccount() prefs.clearAll() } } // Extensions don't have a UIApplication. convenience init(localName: String) { self.init(localName: localName, app: nil) } func shutdown() { if dbCreated { db.close() } if loginsDBCreated { loginsDB.close() } } @objc func onLocationChange(notification: NSNotification) { if let v = notification.userInfo!["visitType"] as? Int, let visitType = VisitType(rawValue: v), let url = notification.userInfo!["url"] as? NSURL, let title = notification.userInfo!["title"] as? NSString { // We don't record a visit if no type was specified -- that means "ignore me". let site = Site(url: url.absoluteString!, title: title as String) let visit = SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: visitType) log.debug("Recording visit for \(url) with type \(v).") history.addLocalVisit(visit) } else { let url = notification.userInfo!["url"] as? NSURL log.debug("Ignoring navigation for \(url).") } } deinit { self.syncManager.endTimedSyncs() NSNotificationCenter.defaultCenter().removeObserver(self) } func localName() -> String { return name } var files: FileAccessor { return ProfileFileAccessor(profile: self) } lazy var queue: TabQueue = { return SQLiteQueue(db: self.db) }() private var dbCreated = false lazy var db: BrowserDB = { self.dbCreated = true return BrowserDB(filename: "browser.db", files: self.files) }() /** * Favicons, history, and bookmarks are all stored in one intermeshed * collection of tables. */ private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory> = { return SQLiteHistory(db: self.db) }() var favicons: Favicons { return self.places } var history: protocol<BrowserHistory, SyncableHistory> { return self.places } lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = { return SQLiteBookmarks(db: self.db) }() lazy var searchEngines: SearchEngines = { return SearchEngines(prefs: self.prefs) }() func makePrefs() -> Prefs { return NSUserDefaultsPrefs(prefix: self.localName()) } lazy var prefs: Prefs = { return self.makePrefs() }() lazy var readingList: ReadingListService? = { return ReadingListService(profileStoragePath: self.files.rootPath) }() private lazy var remoteClientsAndTabs: RemoteClientsAndTabs = { return SQLiteRemoteClientsAndTabs(db: self.db) }() lazy var syncManager: SyncManager = { return BrowserSyncManager(profile: self) }() private func getSyncDelegate() -> SyncDelegate { if let app = self.app { return BrowserProfileSyncDelegate(app: app) } return CommandDiscardingSyncDelegate() } public func getClients() -> Deferred<Result<[RemoteClient]>> { return self.syncManager.syncClients() >>> { self.remoteClientsAndTabs.getClients() } } public func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> { return self.syncManager.syncClientsThenTabs() >>> { self.remoteClientsAndTabs.getClientsAndTabs() } } public func getCachedClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> { return self.remoteClientsAndTabs.getClientsAndTabs() } func storeTabs(tabs: [RemoteTab]) -> Deferred<Result<Int>> { return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs) } public func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) { let commands = items.map { item in SyncCommand.fromShareItem(item, withAction: "displayURI") } self.remoteClientsAndTabs.insertCommands(commands, forClients: clients) } lazy var logins: protocol<BrowserLogins, SyncableLogins> = { return SQLiteLogins(db: self.loginsDB) }() private lazy var loginsKey: String? = { let key = "sqlcipher.key.logins.db" if KeychainWrapper.hasValueForKey(key) { return KeychainWrapper.stringForKey(key) } let Length: UInt = 256 let secret = Bytes.generateRandomBytes(Length).base64EncodedString KeychainWrapper.setString(secret, forKey: key) return secret }() private var loginsDBCreated = false private lazy var loginsDB: BrowserDB = { self.loginsDBCreated = true return BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files) }() lazy var thumbnails: Thumbnails = { return SDWebThumbnails(files: self.files) }() let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration() private lazy var account: FirefoxAccount? = { if let dictionary = KeychainWrapper.objectForKey(self.name + ".account") as? [String: AnyObject] { return FirefoxAccount.fromDictionary(dictionary) } return nil }() func getAccount() -> FirefoxAccount? { return account } func removeAccount() { let old = self.account prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime) KeychainWrapper.removeObjectForKey(name + ".account") self.account = nil // tell any observers that our account has changed NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil) // Trigger cleanup. Pass in the account in case we want to try to remove // client-specific data from the server. self.syncManager.onRemovedAccount(old) // deregister for remote notifications app?.unregisterForRemoteNotifications() } func setAccount(account: FirefoxAccount) { KeychainWrapper.setObject(account.asDictionary(), forKey: name + ".account") self.account = account // register for notifications for the account registerForNotifications() // tell any observers that our account has changed NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil) self.syncManager.onAddedAccount() } func registerForNotifications() { let viewAction = UIMutableUserNotificationAction() viewAction.identifier = SentTabAction.View.rawValue viewAction.title = NSLocalizedString("View", comment: "View a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") viewAction.activationMode = UIUserNotificationActivationMode.Foreground viewAction.destructive = false viewAction.authenticationRequired = false let bookmarkAction = UIMutableUserNotificationAction() bookmarkAction.identifier = SentTabAction.Bookmark.rawValue bookmarkAction.title = NSLocalizedString("Bookmark", comment: "Bookmark a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") bookmarkAction.activationMode = UIUserNotificationActivationMode.Foreground bookmarkAction.destructive = false bookmarkAction.authenticationRequired = false let readingListAction = UIMutableUserNotificationAction() readingListAction.identifier = SentTabAction.ReadingList.rawValue readingListAction.title = NSLocalizedString("Add to Reading List", comment: "Add URL to the reading list - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440") readingListAction.activationMode = UIUserNotificationActivationMode.Foreground readingListAction.destructive = false readingListAction.authenticationRequired = false let sentTabsCategory = UIMutableUserNotificationCategory() sentTabsCategory.identifier = TabSendCategory sentTabsCategory.setActions([readingListAction, bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Default) sentTabsCategory.setActions([bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Minimal) app?.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: [sentTabsCategory])) app?.registerForRemoteNotifications() } // Extends NSObject so we can use timers. class BrowserSyncManager: NSObject, SyncManager { unowned private let profile: BrowserProfile let FifteenMinutes = NSTimeInterval(60 * 15) let OneMinute = NSTimeInterval(60) private var syncTimer: NSTimer? = nil /** * Locking is managed by withSyncInputs. Make sure you take and release these * whenever you do anything Sync-ey. */ var syncLock = OSSpinLock() private func beginSyncing() -> Bool { return OSSpinLockTry(&syncLock) } private func endSyncing() { return OSSpinLockUnlock(&syncLock) } init(profile: BrowserProfile) { self.profile = profile super.init() let center = NSNotificationCenter.defaultCenter() center.addObserver(self, selector: "onLoginDidChange:", name: NotificationDataLoginDidChange, object: nil) } deinit { // Remove 'em all. NSNotificationCenter.defaultCenter().removeObserver(self) } // Simple in-memory rate limiting. var lastTriggeredLoginSync: Timestamp = 0 @objc func onLoginDidChange(notification: NSNotification) { log.debug("Login did change.") if (NSDate.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds { lastTriggeredLoginSync = NSDate.now() // Give it a few seconds. let when: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, SyncConstants.SyncDelayTriggered) // Trigger on the main queue. The bulk of the sync work runs in the background. dispatch_after(when, dispatch_get_main_queue()) { self.syncLogins() } } } var prefsForSync: Prefs { return self.profile.prefs.branch("sync") } func onAddedAccount() -> Success { return self.syncEverything() } func onRemovedAccount(account: FirefoxAccount?) -> Success { let h: SyncableHistory = self.profile.history let flagHistory = h.onRemovedAccount() let clearTabs = self.profile.remoteClientsAndTabs.onRemovedAccount() let done = allSucceed(flagHistory, clearTabs) // Clear prefs after we're done clearing everything else -- just in case // one of them needs the prefs and we race. Clear regardless of success // or failure. done.upon { result in // This will remove keys from the Keychain if they exist, as well // as wiping the Sync prefs. SyncStateMachine.clearStateFromPrefs(self.prefsForSync) } return done } private func repeatingTimerAtInterval(interval: NSTimeInterval, selector: Selector) -> NSTimer { return NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: selector, userInfo: nil, repeats: true) } func beginTimedSyncs() { if self.syncTimer != nil { log.debug("Already running sync timer.") return } let interval = FifteenMinutes let selector = Selector("syncOnTimer") log.debug("Starting sync timer.") self.syncTimer = repeatingTimerAtInterval(interval, selector: selector) } /** * The caller is responsible for calling this on the same thread on which it called * beginTimedSyncs. */ func endTimedSyncs() { if let t = self.syncTimer { log.debug("Stopping history sync timer.") self.syncTimer = nil t.invalidate() } } private func syncClientsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing clients to storage.") let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs) return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info) } private func syncTabsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { let storage = self.profile.remoteClientsAndTabs let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs) return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info) } private func syncHistoryWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing history to storage.") let historySynchronizer = ready.synchronizer(HistorySynchronizer.self, delegate: delegate, prefs: prefs) return historySynchronizer.synchronizeLocalHistory(self.profile.history, withServer: ready.client, info: ready.info) } private func syncLoginsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult { log.debug("Syncing logins to storage.") let loginsSynchronizer = ready.synchronizer(LoginsSynchronizer.self, delegate: delegate, prefs: prefs) return loginsSynchronizer.synchronizeLocalLogins(self.profile.logins, withServer: ready.client, info: ready.info) } /** * Returns nil if there's no account. */ private func withSyncInputs<T>(label: EngineIdentifier? = nil, function: (SyncDelegate, Prefs, Ready) -> Deferred<Result<T>>) -> Deferred<Result<T>>? { if let account = profile.account { if !beginSyncing() { log.info("Not syncing \(label); already syncing something.") return deferResult(AlreadySyncingError()) } if let label = label { log.info("Syncing \(label).") } let authState = account.syncAuthState let syncPrefs = profile.prefs.branch("sync") let readyDeferred = SyncStateMachine.toReady(authState, prefs: syncPrefs) let delegate = profile.getSyncDelegate() let go = readyDeferred >>== { ready in function(delegate, syncPrefs, ready) } // Always unlock when we're done. go.upon({ res in self.endSyncing() }) return go } log.warning("No account; can't sync.") return nil } /** * Runs the single provided synchronization function and returns its status. */ private func sync(label: EngineIdentifier, function: (SyncDelegate, Prefs, Ready) -> SyncResult) -> SyncResult { return self.withSyncInputs(label: label, function: function) ?? deferResult(.NotStarted(.NoAccount)) } /** * Runs each of the provided synchronization functions with the same inputs. * Returns an array of IDs and SyncStatuses the same length as the input. */ private func syncSeveral(synchronizers: (EngineIdentifier, SyncFunction)...) -> Deferred<Result<[(EngineIdentifier, SyncStatus)]>> { typealias Pair = (EngineIdentifier, SyncStatus) let combined: (SyncDelegate, Prefs, Ready) -> Deferred<Result<[Pair]>> = { delegate, syncPrefs, ready in let thunks = synchronizers.map { (i, f) in return { () -> Deferred<Result<Pair>> in log.debug("Syncing \(i)…") return f(delegate, syncPrefs, ready) >>== { deferResult((i, $0)) } } } return accumulate(thunks) } return self.withSyncInputs(label: nil, function: combined) ?? deferResult(synchronizers.map { ($0.0, .NotStarted(.NoAccount)) }) } func syncEverything() -> Success { return self.syncSeveral( ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate), ("history", self.syncHistoryWithDelegate) ) >>> succeed } @objc func syncOnTimer() { log.debug("Running timed logins sync.") // Note that we use .upon here rather than chaining with >>> precisely // to allow us to sync subsequent engines regardless of earlier failures. // We don't fork them in parallel because we want to limit perf impact // due to background syncs, and because we're cautious about correctness. self.syncLogins().upon { result in if let success = result.successValue { log.debug("Timed logins sync succeeded. Status: \(success.description).") } else { let reason = result.failureValue?.description ?? "none" log.debug("Timed logins sync failed. Reason: \(reason).") } log.debug("Running timed history sync.") self.syncHistory().upon { result in if let success = result.successValue { log.debug("Timed history sync succeeded. Status: \(success.description).") } else { let reason = result.failureValue?.description ?? "none" log.debug("Timed history sync failed. Reason: \(reason).") } } } } func syncClients() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("clients", function: syncClientsWithDelegate) } func syncClientsThenTabs() -> SyncResult { return self.syncSeveral( ("clients", self.syncClientsWithDelegate), ("tabs", self.syncTabsWithDelegate) ) >>== { statuses in let tabsStatus = statuses[1].1 return deferResult(tabsStatus) } } func syncLogins() -> SyncResult { return self.sync("logins", function: syncLoginsWithDelegate) } func syncHistory() -> SyncResult { // TODO: recognize .NotStarted. return self.sync("history", function: syncHistoryWithDelegate) } } } class AlreadySyncingError: ErrorType { var description: String { return "Already syncing." } }
mpl-2.0
11c650999e3d7e09e28eff232c8b0659
37.674735
238
0.642466
5.280727
false
false
false
false
JaSpa/swift
test/Serialization/objc.swift
4
1731
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_objc.swift -disable-objc-attr-requires-foundation-module // RUN: llvm-bcanalyzer %t/def_objc.swiftmodule | %FileCheck %s // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen -I %t %s -o - | %FileCheck %s -check-prefix=SIL // CHECK-NOT: UnknownCode import def_objc // SIL: sil hidden @_T04objc9testProtoy04def_A09ObjCProto_p3obj_tF : $@convention(thin) (@owned ObjCProto) -> () { func testProto(obj obj: ObjCProto) { // SIL: = witness_method [volatile] $@opened({{.*}}) ObjCProto, #ObjCProto.doSomething!1.foreign obj.doSomething() } // SIL: sil hidden @_T04objc9testClassy04def_A09ObjCClassC3obj_tF : $@convention(thin) (@owned ObjCClass) -> () { func testClass(obj obj: ObjCClass) { // SIL: = class_method [volatile] %{{.+}} : $ObjCClass, #ObjCClass.implicitlyObjC!1.foreign obj.implicitlyObjC() // SIL: = class_method [volatile] %{{.+}} : $@thick ObjCClass.Type, #ObjCClass.classMethod!1.foreign ObjCClass.classMethod() } // SIL: sil hidden @_T04objc15testNativeClassy04def_A012NonObjCClassC3obj_tF : $@convention(thin) (@owned NonObjCClass) -> () { func testNativeClass(obj obj: NonObjCClass) { // SIL: = class_method [volatile] %{{.+}} : $NonObjCClass, #NonObjCClass.doSomething!1.foreign // SIL: = class_method [volatile] %{{.+}} : $NonObjCClass, #NonObjCClass.objcMethod!1.foreign obj.doSomething() obj.objcMethod() // SIL: class_method [volatile] [[OBJ:%[0-9]+]] : $NonObjCClass, #NonObjCClass.objcProp!getter.1.foreign var x = obj.objcProp // SIL: class_method [volatile] [[OBJ:%[0-9]+]] : $NonObjCClass, #NonObjCClass.subscript!getter.1.foreign _ = obj[42] }
apache-2.0
8c08864c74c24ac46cb42a09468c0660
43.384615
127
0.69093
3.297143
false
true
false
false
a736220388/TestKitchen_1606
TestKitchen/TestKitchen/classes/common/UILabel+Util.swift
1
715
// // UILabel+Util.swift // TestKitchen // // Created by qianfeng on 16/8/15. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit extension UILabel{ class func createLabel(text:String?,font:UIFont?,textAlignment:NSTextAlignment?,textColor:UIColor?)->UILabel{ let label = UILabel() if let labelText = text { label.text = labelText } if let labelFont = font{ label.font = labelFont } if let labelTextAlignment = textAlignment{ label.textAlignment = labelTextAlignment } if let labelTextColor = textColor{ label.textColor = labelTextColor } return label } }
mit
69c062419fcfd7e641824218fdffc577
25.37037
113
0.609551
4.746667
false
false
false
false
GiorgioNatili/CryptoMessages
CryptoMessages/messages/view/MessagesViewController+Extension.swift
1
1227
// // MessagesViewController+Extension.swift // CryptoMessages // // Created by Giorgio Natili on 5/9/17. // Copyright © 2017 Giorgio Natili. All rights reserved. // import Foundation import UIKit extension MessagesViewController: UITableViewDataSource, UITableViewDelegate { // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return allMessages.count } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let message = allMessages[indexPath.row] selectedMessage = message prepareForDecryption() tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let message = allMessages[indexPath.row] let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "MessageCell") cell.textLabel?.text = message.id.description return cell } }
unlicense
e9bb0e3ec2e433dd5e9c09cef49b6595
27.511628
103
0.663132
5.424779
false
false
false
false
austinzheng/swift
test/NameBinding/Inputs/overload_vars.swift
37
557
public var something : Int = 1 public var ambiguousWithVar : Int = 2 public var scopedVar : Int = 3 public var localVar : Int = 4 public var scopedFunction : Int = 5 public var typeNameWins : Int = 6 public protocol HasFoo { var foo: Int { get } } public protocol HasBar { var bar: Int { get } } public class HasFooGeneric<T> { public var foo: Int = 0 } extension HasFooGeneric { public var bar: Int { return 0 } } public class HasFooNonGeneric { public var foo: Int = 0 } extension HasFooNonGeneric { public var bar: Int { return 0 } }
apache-2.0
0a6be5de04c625b7b09bfd066fb762fc
16.40625
37
0.691203
3.355422
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/Platform/BRAPIClient+Currencies.swift
1
9035
// // BRAPIClient+Currencies.swift // breadwallet // // Created by Ehsan Rezaie on 2018-03-12. // Copyright © 2018-2019 Breadwinner AG. All rights reserved. // import Foundation import UIKit public enum APIResult<ResultType: Codable> { case success(ResultType) case error(Error) } public struct HTTPError: Error { let code: Int } struct FiatCurrency: Decodable { var name: String var code: String static var availableCurrencies: [FiatCurrency] = { guard let path = Bundle.main.path(forResource: "fiatcurrencies", ofType: "json") else { print("unable to locate currencies file") return [] } var currencies: [FiatCurrency]? do { let data = try Data(contentsOf: URL(fileURLWithPath: path)) let decoder = JSONDecoder() currencies = try decoder.decode([FiatCurrency].self, from: data) } catch let e { print("error parsing fiat currency data: \(e)") } return currencies ?? [] }() // case of code doesn't matter static func isCodeAvailable(_ code: String) -> Bool { let available = FiatCurrency.availableCurrencies.map { $0.code.lowercased() } return available.contains(code.lowercased()) } } extension BRAPIClient { // MARK: Currency List /// Get the list of supported currencies and their metadata from the backend or local cache func getCurrencyMetaData(completion: @escaping ([CurrencyId: CurrencyMetaData]) -> Void) { let fm = FileManager.default guard let documentsDir = try? fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) else { return assertionFailure() } let cachedFilePath = documentsDir.appendingPathComponent("currencies.json").path var shouldProcess = true // If cache isn't expired, use cached data and return before the network call if !isCacheExpired(path: cachedFilePath, timeout: C.secondsInMinute*60*24) && processCurrenciesCache(path: cachedFilePath, completion: completion) { //Even if cache is used, we still want to update the local version shouldProcess = false } var req = URLRequest(url: url("/currencies")) req.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData send(request: req, handler: { (result: APIResult<[CurrencyMetaData]>) in switch result { case .success(let currencies): // update cache do { let data = try JSONEncoder().encode(currencies) try data.write(to: URL(fileURLWithPath: cachedFilePath)) } catch let e { print("[CurrencyList] failed to write to cache: \(e.localizedDescription)") } if shouldProcess { processCurrencies(currencies, completion: completion) } case .error(let error): print("[CurrencyList] error fetching tokens: \(error)") copyEmbeddedCurrencies(path: cachedFilePath, fileManager: fm) if shouldProcess { let result = processCurrenciesCache(path: cachedFilePath, completion: completion) assert(result, "failed to get currency list from backend or cache") } } }) cleanupOldTokensFile() } private func send<ResultType>(request: URLRequest, handler: @escaping (APIResult<ResultType>) -> Void) { dataTaskWithRequest(request, authenticated: true, retryCount: 0, handler: { data, response, error in guard error == nil, let data = data else { print("[API] HTTP error: \(error!)") return handler(APIResult<ResultType>.error(error!)) } guard let statusCode = response?.statusCode, statusCode >= 200 && statusCode < 300 else { return handler(APIResult<ResultType>.error(HTTPError(code: response?.statusCode ?? 0))) } do { let result = try JSONDecoder().decode(ResultType.self, from: data) handler(APIResult<ResultType>.success(result)) } catch let jsonError { print("[API] JSON error: \(jsonError)") handler(APIResult<ResultType>.error(jsonError)) } }).resume() } private func cleanupOldTokensFile() { DispatchQueue.global(qos: .utility).async { let fm = FileManager.default guard let documentsDir = try? fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) else { return assertionFailure() } let oldTokensFile = documentsDir.appendingPathComponent("tokens.json").path if fm.fileExists(atPath: oldTokensFile) { try? fm.removeItem(atPath: oldTokensFile) } } } } // MARK: - File Manager Helpers // Converts an array of CurrencyMetaData to a dictionary keyed on uid private func processCurrencies(_ currencies: [CurrencyMetaData], completion: ([CurrencyId: CurrencyMetaData]) -> Void) { let currencyMetaData = currencies.reduce(into: [CurrencyId: CurrencyMetaData](), { (dict, token) in dict[token.uid] = token }) //Change currencyMetaData to var and uncomment the currencies below for testing // let tst = CurrencyMetaData(uid: "ethereum-testnet:0x722dd3f80bac40c951b51bdd28dd19d435762180", // code: "TST", // isSupported: true, // colors: (.blue, .blue), // name: "Test Standard Token", // tokenAddress: "0x722dd3f80bac40c951b51bdd28dd19d435762180", // decimals: 18, // alternateCode: nil, // coinGeckoId: nil) // // let bsv = CurrencyMetaData(uid: "bitcoinsv-mainnet:__native__", // code: "BSV", // isSupported: true, // colors: (.yellow, .blue), // name: "BSV", // tokenAddress: nil, // decimals: 8, // alternateCode: nil, // coinGeckoId: nil) // let xtz = CurrencyMetaData(uid: "tezos-mainnet:__native__", // code: "XTZ", // isSupported: true, // colors: (.blue, .blue), // name: "Tezos", // tokenAddress: nil, // decimals: 8, // alternateCode: nil, // coinGeckoId: "tezos") // currencyMetaData[tst.uid] = tst // currencyMetaData[bsv.uid] = bsv // currencyMetaData[xtz.uid] = xtz print("[CurrencyList] tokens updated: \(currencies.count) tokens") completion(currencyMetaData) } // Loads and processes cached currencies private func processCurrenciesCache(path: String, completion: ([CurrencyId: CurrencyMetaData]) -> Void) -> Bool { guard FileManager.default.fileExists(atPath: path) else { return false } do { print("[CurrencyList] using cached token list") let cachedData = try Data(contentsOf: URL(fileURLWithPath: path)) let currencies = try JSONDecoder().decode([CurrencyMetaData].self, from: cachedData) processCurrencies(currencies, completion: completion) return true } catch let e { print("[CurrencyList] error reading from cache: \(e)") // remove the invalid cached data try? FileManager.default.removeItem(at: URL(fileURLWithPath: path)) return false } } // Copies currencies embedded in bundle if cached file doesn't exist private func copyEmbeddedCurrencies(path: String, fileManager fm: FileManager) { if let embeddedFilePath = Bundle.main.path(forResource: "currencies", ofType: "json"), !fm.fileExists(atPath: path) { do { try fm.copyItem(atPath: embeddedFilePath, toPath: path) print("[CurrencyList] copied bundle tokens list to cache") } catch let e { print("[CurrencyList] unable to copy bundled \(embeddedFilePath) -> \(path): \(e)") } } } // Checks if file modification time has happened within a timeout private func isCacheExpired(path: String, timeout: TimeInterval) -> Bool { guard let attr = try? FileManager.default.attributesOfItem(atPath: path) else { return true } guard let modificationDate = attr[FileAttributeKey.modificationDate] as? Date else { return true } let difference = Date().timeIntervalSince(modificationDate) return difference > timeout }
mit
ac7b52a7c870c19a6bbd34272405e090
42.432692
165
0.584901
4.823278
false
false
false
false
dreymonde/SwiftyNURE
Sources/SwiftyNURE/Model/Group.swift
1
522
// // Group.swift // NUREAPI // // Created by Oleg Dreyman on 18.02.16. // Copyright © 2016 Oleg Dreyman. All rights reserved. // import Foundation public struct Group { public let id: Int public let name: String public init(name: String, id: Int) { self.id = id self.name = name } } extension Group: Hashable { public var hashValue: Int { return self.id } } public func == (lhs: Group, rhs: Group) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name }
mit
b885fabdbf51cce75f8d87323b1794ad
15.83871
55
0.598848
3.36129
false
false
false
false
LuAndreCast/iOS_WatchProjects
watchOS2/timesTables/timesTables WatchKit Extension/InterfaceController.swift
1
1927
// // InterfaceController.swift // timesTables WatchKit Extension // // Created by Luis Castillo on 1/6/16. // Copyright © 2016 Luis Castillo. All rights reserved. // import WatchKit import Foundation class InterfaceController: WKInterfaceController { @IBOutlet var timesSlider: WKInterfaceSlider! @IBOutlet var timesTable: WKInterfaceTable! //row info let timesRowName:String = "timesRow" let numberOfRow:Int = 10 //table info let startingValue = 10 override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) //setting up rows in table self.timesTable.setNumberOfRows(numberOfRow, withRowType: timesRowName) //setting value self.timesSlider.setValue( Float(startingValue) ) //updating rows self.updateTableRow(startingValue) }//eom override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() }//eom override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() }//eom //MARK: func updateTableRow(newTableValue:Int) { for(var iter = 0 ; iter < numberOfRow; iter++) { let currRowValue = newTableValue * iter //current row let currRow = timesTable.rowControllerAtIndex(iter) as? timesTableRowController currRow?.timesLabel.setText("\(newTableValue) X \(iter) = \(currRowValue)") }//eofl }//eom @IBAction func timesValueChanged(value: Float) { let numberChanged:Int = Int(value) self.updateTableRow(numberChanged) }//eo-a }//eoc
mit
c2d1637762c5d75a401e73ccde8b14bc
22.777778
91
0.604361
4.989637
false
false
false
false
mattiabugossi/Swifter
Swifter/Swifter.swift
1
8254
// // Swifter.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import Accounts public class Swifter { // MARK: - Types public typealias JSONSuccessHandler = (json: JSON, response: NSHTTPURLResponse) -> Void public typealias FailureHandler = (error: NSError) -> Void internal struct CallbackNotification { static let notificationName = "SwifterCallbackNotificationName" static let optionsURLKey = "SwifterCallbackNotificationOptionsURLKey" } internal struct SwifterError { static let domain = "SwifterErrorDomain" static let appOnlyAuthenticationErrorCode = 1 } internal struct DataParameters { static let dataKey = "SwifterDataParameterKey" static let fileNameKey = "SwifterDataParameterFilename" } // MARK: - Properties internal(set) var apiURL: NSURL internal(set) var uploadURL: NSURL internal(set) var streamURL: NSURL internal(set) var userStreamURL: NSURL internal(set) var siteStreamURL: NSURL public var client: SwifterClientProtocol // MARK: - Initializers public convenience init(consumerKey: String, consumerSecret: String) { self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, appOnly: false) } public init(consumerKey: String, consumerSecret: String, appOnly: Bool) { if appOnly { self.client = SwifterAppOnlyClient(consumerKey: consumerKey, consumerSecret: consumerSecret) } else { self.client = SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret) } self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")! self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")! self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")! self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")! self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")! } public init(consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String) { self.client = SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret , accessToken: oauthToken, accessTokenSecret: oauthTokenSecret) self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")! self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")! self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")! self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")! self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")! } public init(account: ACAccount) { self.client = SwifterAccountsClient(account: account) self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")! self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")! self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")! self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")! self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")! } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: - JSON Requests internal func jsonRequestWithPath(path: String, baseURL: NSURL, method: String, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler? = nil, downloadProgress: JSONSuccessHandler? = nil, success: JSONSuccessHandler? = nil, failure: SwifterHTTPRequest.FailureHandler? = nil) -> SwifterHTTPRequest { let jsonDownloadProgressHandler: SwifterHTTPRequest.DownloadProgressHandler = { data, _, _, response in if downloadProgress == nil { return } var error: NSError? if let jsonResult = JSON.parseJSONData(data, error: &error) { downloadProgress?(json: jsonResult, response: response) } else { let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding) let jsonChunks = jsonString!.componentsSeparatedByString("\r\n") for chunk in jsonChunks { chunk.utf16 if chunk.characters.count == 0 { continue } _ = chunk.dataUsingEncoding(NSUTF8StringEncoding) if let jsonResult = JSON.parseJSONData(data, error: &error) { if let downloadProgress = downloadProgress { downloadProgress(json: jsonResult, response: response) } } } } } let jsonSuccessHandler: SwifterHTTPRequest.SuccessHandler = { data, response in dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) { var error: NSError? if let jsonResult = JSON.parseJSONData(data, error: &error) { dispatch_async(dispatch_get_main_queue()) { if let success = success { success(json: jsonResult, response: response) } } } else { dispatch_async(dispatch_get_main_queue()) { if let failure = failure { failure(error: error!) } } } } } if method == "GET" { return self.client.get(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure) } else { return self.client.post(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure) } } internal func getJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: JSONSuccessHandler?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest { return self.jsonRequestWithPath(path, baseURL: baseURL, method: "GET", parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure) } internal func postJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: JSONSuccessHandler?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest { return self.jsonRequestWithPath(path, baseURL: baseURL, method: "POST", parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure) } }
mit
8549f84ab873773a90247413e6ff456a
45.111732
341
0.657499
4.954382
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationSettingDetailsViewController.swift
1
13643
import Foundation import WordPressShared import UserNotifications /// The purpose of this class is to render a collection of NotificationSettings for a given Stream, /// encapsulated in the class NotificationSettings.Stream, and to provide the user a simple interface /// to update those settings, as needed. /// class NotificationSettingDetailsViewController: UITableViewController { /// Index of the very first tableVIew Section /// private let firstSectionIndex = 0 /// NotificationSettings being rendered /// private var settings: NotificationSettings? /// Notification Stream to be displayed /// private var stream: NotificationSettings.Stream? /// TableView Sections to be rendered /// private var sections = [Section]() /// Contains all of the updated Stream Settings /// private var newValues = [String: Bool]() /// Indicates whether push notifications have been disabled, in the device, or not. /// private var pushNotificationsAuthorized: UNAuthorizationStatus = .notDetermined { didSet { reloadTable() } } /// Returns the name of the current site, if any /// private var siteName: String { switch settings!.channel { case .wordPressCom: return NSLocalizedString("WordPress.com Updates", comment: "WordPress.com Notification Settings Title") case .other: return NSLocalizedString("Other Sites", comment: "Other Sites Notification Settings Title") default: return settings?.blog?.settings?.name ?? NSLocalizedString("Unnamed Site", comment: "Displayed when a site has no name") } } convenience init(settings: NotificationSettings) { self.init(settings: settings, stream: settings.streams.first!) } convenience init(settings: NotificationSettings, stream: NotificationSettings.Stream) { self.init(style: .grouped) self.settings = settings self.stream = stream } override func viewDidLoad() { super.viewDidLoad() setupTitle() setupTableView() reloadTable() startListeningToNotifications() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshPushAuthorizationStatus() WPAnalytics.track(.openedNotificationSettingDetails) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) saveSettingsIfNeeded() } // MARK: - Setup Helpers private func startListeningToNotifications() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(refreshPushAuthorizationStatus), name: UIApplication.didBecomeActiveNotification, object: nil) } private func setupTitle() { title = stream?.kind.description() } private func setupTableView() { // Register the cells tableView.register(SwitchTableViewCell.self, forCellReuseIdentifier: Row.Kind.Setting.rawValue) tableView.register(WPTableViewCell.self, forCellReuseIdentifier: Row.Kind.Text.rawValue) // Hide the separators, whenever the table is empty tableView.tableFooterView = UIView() // Style! WPStyleGuide.configureColors(view: view, tableView: tableView) WPStyleGuide.configureAutomaticHeightRows(for: tableView) } @IBAction func reloadTable() { if isDeviceStreamDisabled() { sections = sectionsForDisabledDeviceStream() } else if isDeviceStreamUnknown() { sections = sectionsForUnknownDeviceStream() } else if let settings = settings, let stream = stream { sections = sectionsForSettings(settings, stream: stream) } tableView.reloadData() } // MARK: - Private Helpers private func sectionsForSettings(_ settings: NotificationSettings, stream: NotificationSettings.Stream) -> [Section] { // WordPress.com Channel requires a brief description per row. // For that reason, we'll render each row in its own section, with it's very own footer let singleSectionMode = settings.channel != .wordPressCom // Parse the Rows var rows = [Row]() for key in settings.sortedPreferenceKeys(stream) { let description = settings.localizedDescription(key) let value = stream.preferences?[key] ?? true let row = Row(kind: .Setting, description: description, key: key, value: value) rows.append(row) } // Single Section Mode: A single section will contain all of the rows if singleSectionMode { // Switch on stream type to provide descriptive text in footer for more context switch stream.kind { case .Device: return [Section(rows: rows, footerText: NSLocalizedString("Settings for push notifications that appear on your mobile device.", comment: "Descriptive text for the Push Notifications Settings"))] case .Email: return [Section(rows: rows, footerText: NSLocalizedString("Settings for notifications that are sent to the email tied to your account.", comment: "Descriptive text for the Email Notifications Settings"))] case .Timeline: return [Section(rows: rows, footerText: NSLocalizedString("Settings for notifications that appear in the Notifications tab.", comment: "Descriptive text for the Notifications Tab Settings"))] } } // Multi Section Mode: We'll have one Section per Row var sections = [Section]() for row in rows { let unwrappedKey = row.key ?? String() let footerText = settings.localizedDetails(unwrappedKey) let section = Section(rows: [row], footerText: footerText) sections.append(section) } return sections } private func sectionsForDisabledDeviceStream() -> [Section] { let description = NSLocalizedString("Go to iOS Settings", comment: "Opens WPiOS Settings.app Section") let row = Row(kind: .Text, description: description, key: nil, value: nil) let footerText = NSLocalizedString("Push Notifications have been turned off in iOS Settings App. " + "Toggle \"Allow Notifications\" to turn them back on.", comment: "Suggests to enable Push Notification Settings in Settings.app") let section = Section(rows: [row], footerText: footerText) return [section] } private func sectionsForUnknownDeviceStream() -> [Section] { defer { WPAnalytics.track(.pushNotificationPrimerSeen, withProperties: [Analytics.locationKey: Analytics.alertKey]) } let description = NSLocalizedString("Allow push notifications", comment: "Shown to the user in settings when they haven't yet allowed or denied push notifications") let row = Row(kind: .Text, description: description, key: nil, value: nil) let footerText = NSLocalizedString("Allow WordPress to send you push notifications", comment: "Suggests the user allow push notifications. Appears within app settings.") let section = Section(rows: [row], footerText: footerText) return [section] } // MARK: - UITableView Delegate Methods override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].rows.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let section = sections[indexPath.section] let row = section.rows[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: row.kind.rawValue) switch row.kind { case .Text: configureTextCell(cell as! WPTableViewCell, row: row) case .Setting: configureSwitchCell(cell as! SwitchTableViewCell, row: row) } return cell! } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard section == firstSectionIndex else { return nil } return siteName } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return sections[section].footerText } override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { WPStyleGuide.configureTableViewSectionFooter(view) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectSelectedRowWithAnimation(true) if isDeviceStreamDisabled() { openApplicationSettings() } else if isDeviceStreamUnknown() { requestNotificationAuthorization() } } // MARK: - UITableView Helpers private func configureTextCell(_ cell: WPTableViewCell, row: Row) { cell.textLabel?.text = row.description WPStyleGuide.configureTableViewCell(cell) } private func configureSwitchCell(_ cell: SwitchTableViewCell, row: Row) { let settingKey = row.key ?? String() cell.name = row.description cell.on = newValues[settingKey] ?? (row.value ?? true) cell.onChange = { [weak self] (newValue: Bool) in self?.newValues[settingKey] = newValue } } // MARK: - Disabled Push Notifications Handling private func isDeviceStreamDisabled() -> Bool { return stream?.kind == .Device && pushNotificationsAuthorized == .denied } private func isDeviceStreamUnknown() -> Bool { return stream?.kind == .Device && pushNotificationsAuthorized == .notDetermined } private func openApplicationSettings() { let targetURL = URL(string: UIApplication.openSettingsURLString) UIApplication.shared.open(targetURL!) } private func requestNotificationAuthorization() { defer { WPAnalytics.track(.pushNotificationPrimerAllowTapped, withProperties: [Analytics.locationKey: Analytics.alertKey]) } InteractiveNotificationsManager.shared.requestAuthorization { [weak self] _ in self?.refreshPushAuthorizationStatus() } } @objc func refreshPushAuthorizationStatus() { PushNotificationsManager.shared.loadAuthorizationStatus { status in self.pushNotificationsAuthorized = status } } // MARK: - Service Helpers private func saveSettingsIfNeeded() { if newValues.count == 0 || settings == nil { return } let context = ContextManager.sharedInstance().mainContext let service = NotificationSettingsService(managedObjectContext: context) service.updateSettings(settings!, stream: stream!, newValues: newValues, success: { WPAnalytics.track(.notificationsSettingsUpdated, withProperties: ["success": true]) }, failure: { (error: Error?) in WPAnalytics.track(.notificationsSettingsUpdated, withProperties: ["success": false]) self.handleUpdateError() }) } private func handleUpdateError() { let title = NSLocalizedString("Oops!", comment: "An informal exclaimation meaning `something went wrong`.") let message = NSLocalizedString("There has been an unexpected error while updating your Notification Settings", comment: "Displayed after a failed Notification Settings call") let cancelText = NSLocalizedString("Cancel", comment: "Cancel. Action.") let retryText = NSLocalizedString("Retry", comment: "Retry. Action") let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addCancelActionWithTitle(cancelText, handler: nil) alertController.addDefaultActionWithTitle(retryText) { (action: UIAlertAction) in self.saveSettingsIfNeeded() } alertController.presentFromRootViewController() } // MARK: - Private Nested Class'ess private class Section { var rows: [Row] var footerText: String? init(rows: [Row], footerText: String? = nil) { self.rows = rows self.footerText = footerText } } private class Row { let description: String let kind: Kind let key: String? let value: Bool? init(kind: Kind, description: String, key: String? = nil, value: Bool? = nil) { self.description = description self.kind = kind self.key = key self.value = value } enum Kind: String { case Setting = "SwitchCell" case Text = "TextCell" } } private struct Analytics { static let locationKey = "location" static let alertKey = "settings" } }
gpl-2.0
fb6ab92fd6e3f1ec4e9542da9212071a
36.275956
220
0.640915
5.50121
false
false
false
false
powerytg/PearlCam
PearlCam/PearlCam/Components/MeterView.swift
2
2648
// // MeterView.swift // PearlCam // // MeterView is a slider that allows users to swipe through the specified range of values // // Created by Tiangong You on 6/11/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit import CRRulerControl enum MeterType { case exposureCompensation case iso case shutterSpeed } protocol MeterViewDelegate : NSObjectProtocol { func meterValueDidChange(_ value : Float) } class MeterView: UIView { private var backgroundView = UIImageView(image: UIImage(named: "SliderBackground")) var rulerView = CRRulerControl() weak var delegate : MeterViewDelegate? private var meterType : MeterType private var minValue : CGFloat private var maxValue : CGFloat private var value : CGFloat init(meterType : MeterType, minValue : Float, maxValue : Float, currentValue : Float, frame : CGRect) { self.meterType = meterType self.minValue = CGFloat(minValue) self.maxValue = CGFloat(maxValue) self.value = CGFloat(currentValue) super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func initialize() { rulerView.frame = self.bounds.insetBy(dx: 8, dy: 3) addSubview(backgroundView) addSubview(rulerView) rulerView.setColor(UIColor.white, for: .all) rulerView.setTextColor(UIColor.white, for: .all) rulerView.rangeFrom = minValue rulerView.rangeLength = maxValue - minValue rulerView.setValue(value, animated: false) switch meterType { case .exposureCompensation: rulerView.rulerWidth = self.bounds.width * 1.4 rulerView.spacingBetweenMarks = 30 case .iso: rulerView.setFrequency(50, for: .all) rulerView.rulerWidth = self.bounds.width * 2.0 rulerView.spacingBetweenMarks = 60 case .shutterSpeed: rulerView.setFrequency(50, for: .all) rulerView.rulerWidth = self.bounds.width * 2.4 rulerView.spacingBetweenMarks = 60 } rulerView.setNeedsLayout() rulerView.addTarget(self, action: #selector(rulerValueDidChange(_:)), for: .valueChanged) } override func layoutSubviews() { super.layoutSubviews() backgroundView.frame = self.bounds } @objc private func rulerValueDidChange(_ sender : CRRulerControl) { delegate?.meterValueDidChange(Float(rulerView.value)) } }
bsd-3-clause
073dfd21a34461a2975a48a923f13ebe
29.77907
107
0.646392
4.339344
false
false
false
false
BlueCocoa/Maria
Maria/SettingsAria2ConfigViewController.swift
1
6141
// // SettingsAria2ViewController.swift // Maria // // Created by ShinCurry on 16/4/23. // Copyright © 2016年 ShinCurry. All rights reserved. // import Cocoa class SettingsAria2ConfigViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. userDefaultsInit() } let defaults = MariaUserDefault.auto var config: AriaConfig! @IBOutlet weak var enableAria2AutoLaunch: NSButton! @IBOutlet weak var aria2ConfPath: NSTextField! @IBOutlet weak var aria2ConfPathButton: NSPopUpButton! @IBOutlet weak var aria2ConfTableView: NSTableView! @IBOutlet var confArrayController: NSArrayController! @IBAction func selectFilePath(_ sender: NSMenuItem) { aria2ConfPathButton.selectItem(at: 0) let openPanel = NSOpenPanel() openPanel.title = NSLocalizedString("selectConfPath.title", comment: "") openPanel.canChooseDirectories = false openPanel.canCreateDirectories = false openPanel.showsHiddenFiles = true openPanel.beginSheetModal(for: self.view.window!, completionHandler: { key in if key == 1, let url = openPanel.url?.relativePath { self.defaults[.aria2ConfPath] = url self.aria2ConfPathButton.item(at: 0)!.title = url self.config.reload() self.aria2ConfTableView.reloadData() } }) } @IBAction func switchOptions(_ sender: NSButton) { let boolValue = sender.state == 1 ? true : false switch sender { case enableAria2AutoLaunch: defaults[.enableAria2AutoLaunch] = boolValue default: break } } @IBAction func confControl(_ sender: NSSegmentedControl) { switch sender.selectedSegment { case 0: addConf() case 1: removeConf() default: break } } func addConf() { aria2ConfTableView.deselectAll(nil) aria2ConfTableView.becomeFirstResponder() config.data.append(("newKey", "")) aria2ConfTableView.reloadData() aria2ConfTableView.scrollRowToVisible(config.data.count-1) aria2ConfTableView.selectRowIndexes(IndexSet(integer: config.data.count-1), byExtendingSelection: false) } func removeConf() { aria2ConfTableView.selectedRowIndexes.reversed().forEach { index in config.data.remove(at: index) } aria2ConfTableView.reloadData() config.save() } @IBAction func resetConfig(_ sender: NSButton) { let alert = NSAlert() alert.messageText = NSLocalizedString("resetConfig.alert.messageText", comment: "") alert.informativeText = NSLocalizedString("resetConfig.alert.informativeText", comment: "") alert.addButton(withTitle: NSLocalizedString("button.sure", comment: "")) alert.addButton(withTitle: NSLocalizedString("button.cancel", comment: "")) alert.beginSheetModal(for: self.view.window!, completionHandler: { response in if response == NSAlertFirstButtonReturn { self.config.reset() self.aria2ConfTableView.reloadData() } }) } @IBAction func restartAria2(_ sender: NSButton) { let alert = NSAlert() alert.messageText = NSLocalizedString("restartAria2.alert.messageText", comment: "") alert.informativeText = NSLocalizedString("restartAria2.alert.informativeText", comment: "") alert.addButton(withTitle: NSLocalizedString("button.sure", comment: "")) alert.addButton(withTitle: NSLocalizedString("button.cancel", comment: "")) alert.beginSheetModal(for: self.view.window!, completionHandler: { response in if response == NSAlertFirstButtonReturn { let shutdown = Process() let shutdownSH = Bundle.main.path(forResource: "shutdownAria2c", ofType: "sh") shutdown.launchPath = shutdownSH shutdown.launch() shutdown.waitUntilExit() let when = DispatchTime.now() + 1 DispatchQueue.main.asyncAfter(deadline: when) { let run = Process() let confPath = self.defaults[.aria2ConfPath]! let runSH = Bundle.main .path(forResource: "runAria2c", ofType: "sh") run.launchPath = runSH run.arguments = [confPath] run.launch() run.waitUntilExit() let appDelegate = NSApplication.shared().delegate as! AppDelegate appDelegate.aria2open() } } }) } } extension SettingsAria2ConfigViewController: NSTableViewDelegate, NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { return config.data.count } func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? { let item = config.data[row] switch tableColumn!.title { case "Key": return item.key case "Value": return item.value default: return "" } } func tableView(_ tableView: NSTableView, setObjectValue object: Any?, for tableColumn: NSTableColumn?, row: Int) { switch tableColumn!.title { case "Key": config.data[row].key = object as! String case "Value": config.data[row].value = object as! String default: break } config.save() } } extension SettingsAria2ConfigViewController { func userDefaultsInit() { enableAria2AutoLaunch.state = defaults[.enableAria2AutoLaunch] ? 1 : 0 if let value = defaults[.aria2ConfPath] { aria2ConfPathButton.item(at: 0)!.title = value config = AriaConfig(filePath: value) config.load() } } }
gpl-3.0
d492314086120fa3a5b48f3ae631afa0
35.105882
118
0.605083
4.886943
false
true
false
false
apple/swift
test/Generics/rdar28544316.swift
6
1661
// RUN: %target-swift-frontend %s -emit-ir -debug-generic-signatures 2>&1 | %FileCheck %s // REQUIRES: asserts class PropertyDataSource<O: PropertyHosting> { } protocol TableViewCellFactoryType { associatedtype Item } public protocol PropertyHosting { associatedtype PType: Hashable, EntityOwned } public protocol EntityOwned: class { associatedtype Owner } public protocol PropertyType: class { } func useType<T>(cellType: T.Type) { } // The GSB would reject this declaration because it was "too minimal", // missing the Factory.Item : EntityOwned requirement that is // required to get a conformance-valid rewrite system. // // The Requirement Machine correctly infers this requirement and adds // it during minimization. // CHECK-LABEL: rdar28544316.(file).PropertyTableViewAdapter@ // CHECK-NEXT: Generic signature: <Factory where Factory : TableViewCellFactoryType, Factory.[TableViewCellFactoryType]Item : EntityOwned, Factory.[TableViewCellFactoryType]Item : PropertyType, Factory.[TableViewCellFactoryType]Item == Factory.[TableViewCellFactoryType]Item.[EntityOwned]Owner.[PropertyHosting]PType, Factory.[TableViewCellFactoryType]Item.[EntityOwned]Owner : PropertyHosting> final class PropertyTableViewAdapter<Factory: TableViewCellFactoryType> where Factory.Item: PropertyType, Factory.Item.Owner: PropertyHosting, Factory.Item.Owner.PType == Factory.Item { typealias Item = Factory.Item let dataManager: PropertyDataSource<Factory.Item.Owner> init(dataManager: PropertyDataSource<Factory.Item.Owner>) { useType(cellType: Factory.Item.Owner.self) self.dataManager = dataManager } }
apache-2.0
3ec1329e5fb4a48ef0fb62f531ecb19d
33.604167
394
0.773028
4.29199
false
false
false
false
wbaumann/SmartReceiptsiOS
SmartReceipts/Services/Local/MigrationService.swift
2
1873
// // MigrationService.swift // SmartReceipts // // Created by Bogdan Evsenev on 30/12/2017. // Copyright © 2017 Will Baumann. All rights reserved. // import Foundation import FMDB fileprivate let migrationKey = "migration_version_key" class MigrationService { // MARK: - Public Interface func migrate() { //MARK: Migration 0 -> 1 migrate(to: 1, { migrateIlligalTripNames() }) migrate(to: 2, { migrateCustomOrderIds() }) // Commit Migration Version UserDefaults.standard.set(MIGRATION_VERSION, forKey: migrationKey) } private func migrate(to: Int, _ migrationBlock: MigrationBlock) { let currentVersion = UserDefaults.standard.integer(forKey: migrationKey) if currentVersion < MIGRATION_VERSION && currentVersion < to { migrationBlock() } } // MARK: - Private Interface func migrateIlligalTripNames() { for trip in Database.sharedInstance().allTrips() as! [WBTrip] { trip.name = WBTextUtils.omitIllegalCharacters(trip.name) Database.sharedInstance().update(trip) } } func migrateCustomOrderIds() { for trip in Database.sharedInstance().allTrips() as! [WBTrip] { let receipts = Array(Database.sharedInstance().allReceipts(for: trip).reversed()) as! [WBReceipt] for receipt in receipts { let idGroup = (receipt.date as NSDate).days() let receiptsCount = Database.sharedInstance().receiptsCount(inOrderIdGroup: idGroup) let newOrderId = idGroup * kDaysToOrderFactor + receiptsCount + 1 receipt.customOrderId = newOrderId Database.sharedInstance().save(receipt) } } } }
agpl-3.0
ec71a10a499fd58989541666d6d1a10b
28.714286
109
0.599893
4.633663
false
false
false
false
manfengjun/KYMart
Section/Product/Detail/View/KYPropertyFootView.swift
1
1528
// // KYPropertyFootView.swift // KYMart // // Created by jun on 2017/6/8. // Copyright © 2017年 JUN. All rights reserved. // import UIKit import PPNumberButtonSwift class KYPropertyFootView: UIView { @IBOutlet var contentView: UIView! @IBOutlet weak var numberButton: PPNumberButton! var CountResultClosure: ResultClosure? // 闭包 override init(frame: CGRect) { super.init(frame: frame) contentView = Bundle.main.loadNibNamed("KYPropertyFootView", owner: self, options: nil)?.first as! UIView contentView.frame = self.bounds addSubview(contentView) awakeFromNib() } func reloadMaxValue(){ numberButton.maxValue = (SingleManager.instance.productBuyInfoModel?.good_buy_store_count)! } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() numberButton.shakeAnimation = true numberButton.minValue = 1 numberButton.maxValue = (SingleManager.instance.productBuyInfoModel?.good_buy_store_count)! numberButton.borderColor(UIColor.hexStringColor(hex: "#666666")) numberButton.numberResult { (number) in if let count = Int(number){ self.CountResultClosure?(count) } } } /** 加减按钮的响应闭包回调 */ func countResult(_ finished: @escaping ResultClosure) { CountResultClosure = finished } }
mit
234289398882af99970474a4d288690c
30.229167
113
0.657105
4.370262
false
false
false
false