Best JavaScript code snippet using mocha
jquery.flot.touch.js
Source:jquery.flot.touch.js
1/* global jQuery */2(function($) {3 'use strict';4 var options = {5 propagateSupportedGesture: false6 };7 function init(plot) {8 plot.hooks.processOptions.push(initTouchNavigation);9 }10 function initTouchNavigation(plot, options) {11 var gestureState = {12 twoTouches: false,13 currentTapStart: { x: 0, y: 0 },14 currentTapEnd: { x: 0, y: 0 },15 prevTap: { x: 0, y: 0 },16 currentTap: { x: 0, y: 0 },17 interceptedLongTap: false,18 isUnsupportedGesture: false,19 prevTapTime: null,20 tapStartTime: null,21 longTapTriggerId: null22 },23 maxDistanceBetweenTaps = 20,24 maxIntervalBetweenTaps = 500,25 maxLongTapDistance = 20,26 minLongTapDuration = 1500,27 pressedTapDuration = 125,28 mainEventHolder;29 function interpretGestures(e) {30 var o = plot.getOptions();31 if (!o.pan.active && !o.zoom.active) {32 return;33 }34 updateOnMultipleTouches(e);35 mainEventHolder.dispatchEvent(new CustomEvent('touchevent', { detail: e }));36 if (isPinchEvent(e)) {37 executeAction(e, 'pinch');38 } else {39 executeAction(e, 'pan');40 if (!wasPinchEvent(e)) {41 if (isDoubleTap(e)) {42 executeAction(e, 'doubleTap');43 }44 executeAction(e, 'tap');45 executeAction(e, 'longTap');46 }47 }48 }49 function executeAction(e, gesture) {50 switch (gesture) {51 case 'pan':52 pan[e.type](e);53 break;54 case 'pinch':55 pinch[e.type](e);56 break;57 case 'doubleTap':58 doubleTap.onDoubleTap(e);59 break;60 case 'longTap':61 longTap[e.type](e);62 break;63 case 'tap':64 tap[e.type](e);65 break;66 }67 }68 function bindEvents(plot, eventHolder) {69 mainEventHolder = eventHolder[0];70 eventHolder[0].addEventListener('touchstart', interpretGestures, false);71 eventHolder[0].addEventListener('touchmove', interpretGestures, false);72 eventHolder[0].addEventListener('touchend', interpretGestures, false);73 }74 function shutdown(plot, eventHolder) {75 eventHolder[0].removeEventListener('touchstart', interpretGestures);76 eventHolder[0].removeEventListener('touchmove', interpretGestures);77 eventHolder[0].removeEventListener('touchend', interpretGestures);78 if (gestureState.longTapTriggerId) {79 clearTimeout(gestureState.longTapTriggerId);80 gestureState.longTapTriggerId = null;81 }82 }83 var pan = {84 touchstart: function(e) {85 updatePrevForDoubleTap();86 updateCurrentForDoubleTap(e);87 updateStateForLongTapStart(e);88 mainEventHolder.dispatchEvent(new CustomEvent('panstart', { detail: e }));89 },90 touchmove: function(e) {91 preventEventBehaviors(e);92 updateCurrentForDoubleTap(e);93 updateStateForLongTapEnd(e);94 if (!gestureState.isUnsupportedGesture) {95 mainEventHolder.dispatchEvent(new CustomEvent('pandrag', { detail: e }));96 }97 },98 touchend: function(e) {99 preventEventBehaviors(e);100 if (wasPinchEvent(e)) {101 mainEventHolder.dispatchEvent(new CustomEvent('pinchend', { detail: e }));102 mainEventHolder.dispatchEvent(new CustomEvent('panstart', { detail: e }));103 } else if (noTouchActive(e)) {104 mainEventHolder.dispatchEvent(new CustomEvent('panend', { detail: e }));105 }106 }107 };108 var pinch = {109 touchstart: function(e) {110 mainEventHolder.dispatchEvent(new CustomEvent('pinchstart', { detail: e }));111 },112 touchmove: function(e) {113 preventEventBehaviors(e);114 gestureState.twoTouches = isPinchEvent(e);115 if (!gestureState.isUnsupportedGesture) {116 mainEventHolder.dispatchEvent(new CustomEvent('pinchdrag', { detail: e }));117 }118 },119 touchend: function(e) {120 preventEventBehaviors(e);121 }122 };123 var doubleTap = {124 onDoubleTap: function(e) {125 preventEventBehaviors(e);126 mainEventHolder.dispatchEvent(new CustomEvent('doubletap', { detail: e }));127 }128 };129 var longTap = {130 touchstart: function(e) {131 longTap.waitForLongTap(e);132 },133 touchmove: function(e) {134 },135 touchend: function(e) {136 if (gestureState.longTapTriggerId) {137 clearTimeout(gestureState.longTapTriggerId);138 gestureState.longTapTriggerId = null;139 }140 },141 isLongTap: function(e) {142 var currentTime = new Date().getTime(),143 tapDuration = currentTime - gestureState.tapStartTime;144 if (tapDuration >= minLongTapDuration && !gestureState.interceptedLongTap) {145 if (distance(gestureState.currentTapStart.x, gestureState.currentTapStart.y, gestureState.currentTapEnd.x, gestureState.currentTapEnd.y) < maxLongTapDistance) {146 gestureState.interceptedLongTap = true;147 return true;148 }149 }150 return false;151 },152 waitForLongTap: function(e) {153 var longTapTrigger = function() {154 if (longTap.isLongTap(e)) {155 mainEventHolder.dispatchEvent(new CustomEvent('longtap', { detail: e }));156 }157 gestureState.longTapTriggerId = null;158 };159 if (!gestureState.longTapTriggerId) {160 gestureState.longTapTriggerId = setTimeout(longTapTrigger, minLongTapDuration);161 }162 }163 };164 var tap = {165 touchstart: function(e) {166 gestureState.tapStartTime = new Date().getTime();167 },168 touchmove: function(e) {169 },170 touchend: function(e) {171 if (tap.isTap(e)) {172 mainEventHolder.dispatchEvent(new CustomEvent('tap', { detail: e }));173 preventEventBehaviors(e);174 }175 },176 isTap: function(e) {177 var currentTime = new Date().getTime(),178 tapDuration = currentTime - gestureState.tapStartTime;179 if (tapDuration <= pressedTapDuration) {180 if (distance(gestureState.currentTapStart.x, gestureState.currentTapStart.y, gestureState.currentTapEnd.x, gestureState.currentTapEnd.y) < maxLongTapDistance) {181 return true;182 }183 }184 return false;185 }186 };187 if (options.pan.enableTouch === true || options.zoom.enableTouch) {188 plot.hooks.bindEvents.push(bindEvents);189 plot.hooks.shutdown.push(shutdown);190 };191 function updatePrevForDoubleTap() {192 gestureState.prevTap = {193 x: gestureState.currentTap.x,194 y: gestureState.currentTap.y195 };196 };197 function updateCurrentForDoubleTap(e) {198 gestureState.currentTap = {199 x: e.touches[0].pageX,200 y: e.touches[0].pageY201 };202 }203 function updateStateForLongTapStart(e) {204 gestureState.tapStartTime = new Date().getTime();205 gestureState.interceptedLongTap = false;206 gestureState.currentTapStart = {207 x: e.touches[0].pageX,208 y: e.touches[0].pageY209 };210 gestureState.currentTapEnd = {211 x: e.touches[0].pageX,212 y: e.touches[0].pageY213 };214 };215 function updateStateForLongTapEnd(e) {216 gestureState.currentTapEnd = {217 x: e.touches[0].pageX,218 y: e.touches[0].pageY219 };220 };221 function isDoubleTap(e) {222 var currentTime = new Date().getTime(),223 intervalBetweenTaps = currentTime - gestureState.prevTapTime;224 if (intervalBetweenTaps >= 0 && intervalBetweenTaps < maxIntervalBetweenTaps) {225 if (distance(gestureState.prevTap.x, gestureState.prevTap.y, gestureState.currentTap.x, gestureState.currentTap.y) < maxDistanceBetweenTaps) {226 e.firstTouch = gestureState.prevTap;227 e.secondTouch = gestureState.currentTap;228 return true;229 }230 }231 gestureState.prevTapTime = currentTime;232 return false;233 }234 function preventEventBehaviors(e) {235 if (!gestureState.isUnsupportedGesture) {236 e.preventDefault();237 if (!plot.getOptions().propagateSupportedGesture) {238 e.stopPropagation();239 }240 }241 }242 function distance(x1, y1, x2, y2) {243 return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));244 }245 function noTouchActive(e) {246 return (e.touches && e.touches.length === 0);247 }248 function wasPinchEvent(e) {249 return (gestureState.twoTouches && e.touches.length === 1);250 }251 function updateOnMultipleTouches(e) {252 if (e.touches.length >= 3) {253 gestureState.isUnsupportedGesture = true;254 } else {255 gestureState.isUnsupportedGesture = false;256 }257 }258 function isPinchEvent(e) {259 if (e.touches && e.touches.length >= 2) {260 if (e.touches[0].target === plot.getEventHolder() &&261 e.touches[1].target === plot.getEventHolder()) {262 return true;263 }264 }265 return false;266 }267 }268 $.plot.plugins.push({269 init: init,270 options: options,271 name: 'navigateTouch',272 version: '0.3'273 });...
tapTarget.js
Source:tapTarget.js
1(function ($) {2 var methods = {3 init: function (options) {4 return this.each(function() {5 var origin = $('#'+$(this).attr('data-activates'));6 var screen = $('body');7 // Creating tap target8 var tapTargetEl = $(this);9 var tapTargetWrapper = tapTargetEl.parent('.tap-target-wrapper');10 var tapTargetWave = tapTargetWrapper.find('.tap-target-wave');11 var tapTargetOriginEl = tapTargetWrapper.find('.tap-target-origin');12 var tapTargetContentEl = tapTargetEl.find('.tap-target-content');13 // Creating wrapper14 if (!tapTargetWrapper.length) {15 tapTargetWrapper = tapTargetEl.wrap($('<div class="tap-target-wrapper"></div>')).parent();16 }17 // Creating content18 if (!tapTargetContentEl.length) {19 tapTargetContentEl = $('<div class="tap-target-content"></div>');20 tapTargetEl.append(tapTargetContentEl);21 }22 // Creating foreground wave23 if (!tapTargetWave.length) {24 tapTargetWave = $('<div class="tap-target-wave"></div>');25 // Creating origin26 if (!tapTargetOriginEl.length) {27 tapTargetOriginEl = origin.clone(true, true);28 tapTargetOriginEl.addClass('tap-target-origin');29 tapTargetOriginEl.removeAttr('id');30 tapTargetOriginEl.removeAttr('style');31 tapTargetWave.append(tapTargetOriginEl);32 }33 tapTargetWrapper.append(tapTargetWave);34 }35 // Open36 var openTapTarget = function() {37 if (tapTargetWrapper.is('.open')) {38 return;39 }40 // Adding open class41 tapTargetWrapper.addClass('open');42 setTimeout(function() {43 tapTargetOriginEl.off('click.tapTarget').on('click.tapTarget', function(e) {44 closeTapTarget();45 tapTargetOriginEl.off('click.tapTarget');46 });47 $(document).off('click.tapTarget').on('click.tapTarget', function(e) {48 closeTapTarget();49 $(document).off('click.tapTarget');50 });51 var throttledCalc = Materialize.throttle(function() {52 calculateTapTarget();53 }, 200);54 $(window).off('resize.tapTarget').on('resize.tapTarget', throttledCalc);55 }, 0);56 };57 // Close58 var closeTapTarget = function(){59 if (!tapTargetWrapper.is('.open')) {60 return;61 }62 tapTargetWrapper.removeClass('open');63 tapTargetOriginEl.off('click.tapTarget')64 $(document).off('click.tapTarget');65 $(window).off('resize.tapTarget');66 };67 // Pre calculate68 var calculateTapTarget = function() {69 // Element or parent is fixed position?70 var isFixed = origin.css('position') === 'fixed';71 if (!isFixed) {72 var parents = origin.parents();73 for(var i = 0; i < parents.length; i++) {74 isFixed = $(parents[i]).css('position') == 'fixed';75 if (isFixed) {76 break;77 }78 }79 }80 // Calculating origin81 var originWidth = origin.outerWidth();82 var originHeight = origin.outerHeight();83 var originTop = isFixed ? origin.offset().top - $(document).scrollTop() : origin.offset().top;84 var originLeft = isFixed ? origin.offset().left - $(document).scrollLeft() : origin.offset().left;85 // Calculating screen86 var windowWidth = $(window).width();87 var windowHeight = $(window).height();88 var centerX = windowWidth / 2;89 var centerY = windowHeight / 2;90 var isLeft = originLeft <= centerX;91 var isRight = originLeft > centerX;92 var isTop = originTop <= centerY;93 var isBottom = originTop > centerY;94 var isCenterX = originLeft >= windowWidth*0.25 && originLeft <= windowWidth*0.75;95 var isCenterY = originTop >= windowHeight*0.25 && originTop <= windowHeight*0.75;96 // Calculating tap target97 var tapTargetWidth = tapTargetEl.outerWidth();98 var tapTargetHeight = tapTargetEl.outerHeight();99 var tapTargetTop = originTop + originHeight/2 - tapTargetHeight/2;100 var tapTargetLeft = originLeft + originWidth/2 - tapTargetWidth/2;101 var tapTargetPosition = isFixed ? 'fixed' : 'absolute';102 // Calculating content103 var tapTargetTextWidth = isCenterX ? tapTargetWidth : tapTargetWidth/2 + originWidth;104 var tapTargetTextHeight = tapTargetHeight/2;105 var tapTargetTextTop = isTop ? tapTargetHeight/2 : 0;106 var tapTargetTextBottom = 0;107 var tapTargetTextLeft = isLeft && !isCenterX ? tapTargetWidth/2 - originWidth : 0;108 var tapTargetTextRight = 0;109 var tapTargetTextPadding = originWidth;110 var tapTargetTextAlign = isBottom ? 'bottom' : 'top';111 // Calculating wave112 var tapTargetWaveWidth = originWidth > originHeight ? originWidth*2 : originWidth*2;113 var tapTargetWaveHeight = tapTargetWaveWidth;114 var tapTargetWaveTop = tapTargetHeight/2 - tapTargetWaveHeight/2;115 var tapTargetWaveLeft = tapTargetWidth/2 - tapTargetWaveWidth/2;116 // Setting tap target117 var tapTargetWrapperCssObj = {};118 tapTargetWrapperCssObj.top = isTop ? tapTargetTop : '';119 tapTargetWrapperCssObj.right = isRight ? windowWidth - tapTargetLeft - tapTargetWidth : '';120 tapTargetWrapperCssObj.bottom = isBottom ? windowHeight - tapTargetTop - tapTargetHeight : '';121 tapTargetWrapperCssObj.left = isLeft ? tapTargetLeft : '';122 tapTargetWrapperCssObj.position = tapTargetPosition;123 tapTargetWrapper.css(tapTargetWrapperCssObj);124 // Setting content125 tapTargetContentEl.css({126 width: tapTargetTextWidth,127 height: tapTargetTextHeight,128 top: tapTargetTextTop,129 right: tapTargetTextRight,130 bottom: tapTargetTextBottom,131 left: tapTargetTextLeft,132 padding: tapTargetTextPadding,133 verticalAlign: tapTargetTextAlign134 });135 // Setting wave136 tapTargetWave.css({137 top: tapTargetWaveTop,138 left: tapTargetWaveLeft,139 width: tapTargetWaveWidth,140 height: tapTargetWaveHeight141 });142 }143 if (options == 'open') {144 calculateTapTarget();145 openTapTarget();146 }147 if (options == 'close')148 closeTapTarget();149 });150 },151 open: function() {},152 close: function() {}153 };154 $.fn.tapTarget = function(methodOrOptions) {155 if (methods[methodOrOptions] || typeof methodOrOptions === 'object')156 return methods.init.apply( this, arguments );157 $.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tap-target' );158 };...
tap.js.uncompressed.js
Source:tap.js.uncompressed.js
1define("dojox/gesture/tap", [2 "dojo/_base/kernel",3 "dojo/_base/declare",4 "dojo/_base/lang",5 "./Base",6 "../main"7], function(kernel, declare, lang, Base, dojox){8// module:9// dojox/gesture/tap10 11/*=====12 dojox.gesture.tap = {13 // summary:14 // This module provides tap gesture event handlers:15 //16 // 1. dojox.gesture.tap: 'tap' event17 //18 // 2. dojox.gesture.tap.hold: 'tap.hold' event19 //20 // 3. dojox.gesture.tap.doubletap: 'tap.doubletap' event21 //22 // example:23 // A. Used with dojo.connect()24 // | dojo.connect(node, dojox.gesture.tap, function(e){});25 // | dojo.connect(node, dojox.gesture.tap.hold, function(e){});26 // | dojo.connect(node, dojox.gesture.tap.doubletap, function(e){});27 //28 // B. Used with dojo.on29 // | define(['dojo/on', 'dojox/gesture/tap'], function(on, tap){30 // | on(node, tap, function(e){});31 // | on(node, tap.hold, function(e){});32 // | on(node, tap.doubletap, function(e){});33 //34 // C. Used with dojox.gesture.tap.* directly35 // | dojox.gesture.tap(node, function(e){});36 // | dojox.gesture.tap.hold(node, function(e){});37 // | dojox.gesture.tap.doubletap(node, function(e){});38 //39 // Though there is always a default gesture instance after being required, e.g40 // | require(['dojox/gesture/tap'], function(){...});41 //42 // It's possible to create a new one with different parameter setting:43 // | var myTap = new dojox.gesture.tap.Tap({holdThreshold: 300});44 // | dojo.connect(node, myTap, function(e){});45 // | dojo.connect(node, myTap.hold, function(e){});46 // | dojo.connect(node, myTap.doubletap, function(e){});47 };48=====*/49kernel.experimental("dojox.gesture.tap");50// Declare an internal anonymous class which will only be exported51// by module return value e.g. dojox.gesture.tap.Tap52var clz = declare(/*===== "dojox.gesture.tap", =====*/Base, {53 // defaultEvent: [readonly] String54 // Default event - 'tap'55 defaultEvent: "tap",56 // subEvents: [readonly] Array57 // List of sub events, used by being58 // combined with defaultEvent as 'tap.hold', 'tap.doubletap'.59 subEvents: ["hold", "doubletap"],60 // holdThreshold: Integer61 // Threshold(in milliseconds) for 'tap.hold'62 holdThreshold: 500,63 // holdThreshold: Integer64 // Timeout (in milliseconds) for 'tap.doubletap'65 doubleTapTimeout: 250,66 // tapRadius: Integer67 // Valid tap radius from previous touch point68 tapRadius: 10,69 press: function(/*Object*/data, /*Event*/e){70 // summary:71 // Overwritten, record initial tap info and register a timeout checker for 'tap.hold'72 if(e.touches && e.touches.length >= 2){73 //tap gesture is only for single touch74 clearTimeout(data.tapTimeOut); 75 delete data.context;76 return;77 }78 var target = e.target;79 this._initTap(data, e);80 data.tapTimeOut = setTimeout(lang.hitch(this, function(){81 if(this._isTap(data, e)){82 this.fire(target, {type: "tap.hold"});83 }84 delete data.context;85 }), this.holdThreshold);86 },87 release: function(/*Object*/data, /*Event*/e){88 // summary:89 // Overwritten, fire matched 'tap' or 'tap.doubletap' during touchend90 if(!data.context){91 clearTimeout(data.tapTimeOut);92 return;93 }94 if(this._isTap(data, e)){95 switch(data.context.c){96 case 1: 97 this.fire(e.target, {type: "tap"});98 break;99 case 2:100 this.fire(e.target, {type: "tap.doubletap"});101 break;102 }103 }104 clearTimeout(data.tapTimeOut);105 },106 _initTap: function(/*Object*/data, /*Event*/e){107 // summary:108 // Update the gesture data with new tap info 109 if(!data.context){110 data.context = {x: 0, y: 0, t: 0, c: 0};111 }112 var ct = new Date().getTime();113 if(ct - data.context.t <= this.doubleTapTimeout){114 data.context.c++;115 }else{116 data.context.c = 1;117 data.context.x = e.screenX;118 data.context.y = e.screenY;119 }120 data.context.t = ct;121 },122 _isTap: function(/*Object*/data, /*Event*/e){123 // summary:124 // Check whether it's an valid tap125 if (!data.context) {126 return false;127 }128 var dx = Math.abs(data.context.x - e.screenX);129 var dy = Math.abs(data.context.y - e.screenY);130 return dx <= this.tapRadius && dy <= this.tapRadius;131 }132});133// the default tap instance for handy use134dojox.gesture.tap = new clz();135// Class for creating a new Tap instance136dojox.gesture.tap.Tap = clz;137return dojox.gesture.tap;...
tap.js
Source:tap.js
1define([2 "dojo/_base/kernel",3 "dojo/_base/declare",4 "dojo/_base/lang",5 "./Base",6 "../main"7], function(kernel, declare, lang, Base, dojox){8// module:9// dojox/gesture/tap10 11/*=====12 dojox.gesture.tap = {13 // summary:14 // This module provides tap gesture event handlers:15 //16 // 1. dojox.gesture.tap: 'tap' event17 //18 // 2. dojox.gesture.tap.hold: 'tap.hold' event19 //20 // 3. dojox.gesture.tap.doubletap: 'tap.doubletap' event21 //22 // example:23 // A. Used with dojo.connect()24 // | dojo.connect(node, dojox.gesture.tap, function(e){});25 // | dojo.connect(node, dojox.gesture.tap.hold, function(e){});26 // | dojo.connect(node, dojox.gesture.tap.doubletap, function(e){});27 //28 // B. Used with dojo.on29 // | define(['dojo/on', 'dojox/gesture/tap'], function(on, tap){30 // | on(node, tap, function(e){});31 // | on(node, tap.hold, function(e){});32 // | on(node, tap.doubletap, function(e){});33 //34 // C. Used with dojox.gesture.tap.* directly35 // | dojox.gesture.tap(node, function(e){});36 // | dojox.gesture.tap.hold(node, function(e){});37 // | dojox.gesture.tap.doubletap(node, function(e){});38 //39 // Though there is always a default gesture instance after being required, e.g40 // | require(['dojox/gesture/tap'], function(){...});41 //42 // It's possible to create a new one with different parameter setting:43 // | var myTap = new dojox.gesture.tap.Tap({holdThreshold: 300});44 // | dojo.connect(node, myTap, function(e){});45 // | dojo.connect(node, myTap.hold, function(e){});46 // | dojo.connect(node, myTap.doubletap, function(e){});47 };48=====*/49kernel.experimental("dojox.gesture.tap");50// Declare an internal anonymous class which will only be exported51// by module return value e.g. dojox.gesture.tap.Tap52var clz = declare(/*===== "dojox.gesture.tap", =====*/Base, {53 // defaultEvent: [readonly] String54 // Default event - 'tap'55 defaultEvent: "tap",56 // subEvents: [readonly] Array57 // List of sub events, used by being58 // combined with defaultEvent as 'tap.hold', 'tap.doubletap'.59 subEvents: ["hold", "doubletap"],60 // holdThreshold: Integer61 // Threshold(in milliseconds) for 'tap.hold'62 holdThreshold: 500,63 // holdThreshold: Integer64 // Timeout (in milliseconds) for 'tap.doubletap'65 doubleTapTimeout: 250,66 // tapRadius: Integer67 // Valid tap radius from previous touch point68 tapRadius: 10,69 press: function(/*Object*/data, /*Event*/e){70 // summary:71 // Overwritten, record initial tap info and register a timeout checker for 'tap.hold'72 if(e.touches && e.touches.length >= 2){73 //tap gesture is only for single touch74 clearTimeout(data.tapTimeOut); 75 delete data.context;76 return;77 }78 var target = e.target;79 this._initTap(data, e);80 data.tapTimeOut = setTimeout(lang.hitch(this, function(){81 if(this._isTap(data, e)){82 this.fire(target, {type: "tap.hold"});83 }84 delete data.context;85 }), this.holdThreshold);86 },87 release: function(/*Object*/data, /*Event*/e){88 // summary:89 // Overwritten, fire matched 'tap' or 'tap.doubletap' during touchend90 if(!data.context){91 clearTimeout(data.tapTimeOut);92 return;93 }94 if(this._isTap(data, e)){95 switch(data.context.c){96 case 1: 97 this.fire(e.target, {type: "tap"});98 break;99 case 2:100 this.fire(e.target, {type: "tap.doubletap"});101 break;102 }103 }104 clearTimeout(data.tapTimeOut);105 },106 _initTap: function(/*Object*/data, /*Event*/e){107 // summary:108 // Update the gesture data with new tap info 109 if(!data.context){110 data.context = {x: 0, y: 0, t: 0, c: 0};111 }112 var ct = new Date().getTime();113 if(ct - data.context.t <= this.doubleTapTimeout){114 data.context.c++;115 }else{116 data.context.c = 1;117 data.context.x = e.screenX;118 data.context.y = e.screenY;119 }120 data.context.t = ct;121 },122 _isTap: function(/*Object*/data, /*Event*/e){123 // summary:124 // Check whether it's an valid tap125 var dx = Math.abs(data.context.x - e.screenX);126 var dy = Math.abs(data.context.y - e.screenY);127 return dx <= this.tapRadius && dy <= this.tapRadius;128 }129});130// the default tap instance for handy use131dojox.gesture.tap = new clz();132// Class for creating a new Tap instance133dojox.gesture.tap.Tap = clz;134return dojox.gesture.tap;...
tripletap.py
Source:tripletap.py
1'''2Triple Tap3==========4.. versionadded:: 1.7.05Search touch for a triple tap6'''7__all__ = ('InputPostprocTripleTap', )8from time import time9from kivy.config import Config10from kivy.vector import Vector11class InputPostprocTripleTap(object):12 '''13 InputPostProcTripleTap is a post-processor to check if14 a touch is a triple tap or not.15 Triple tap can be configured in the Kivy config file::16 [postproc]17 triple_tap_time = 25018 triple_tap_distance = 2019 The distance parameter is in the range 0-1000 and time is in milliseconds.20 '''21 def __init__(self):22 dist = Config.getint('postproc', 'triple_tap_distance')23 self.triple_tap_distance = dist / 1000.024 time = Config.getint('postproc', 'triple_tap_time')25 self.triple_tap_time = time / 1000.026 self.touches = {}27 def find_triple_tap(self, ref):28 '''Find a triple tap touch within *self.touches*.29 The touch must be not be a previous triple tap and the distance30 must be be within the bounds specified. Additionally, the touch profile31 must be the same kind of touch.32 '''33 ref_button = None34 if 'button' in ref.profile:35 ref_button = ref.button36 for touchid in self.touches:37 if ref.uid == touchid:38 continue39 etype, touch = self.touches[touchid]40 if not touch.is_double_tap:41 continue42 if etype != 'end':43 continue44 if touch.is_triple_tap:45 continue46 distance = Vector.distance(47 Vector(ref.sx, ref.sy),48 Vector(touch.osx, touch.osy))49 if distance > self.triple_tap_distance:50 continue51 if touch.is_mouse_scrolling or ref.is_mouse_scrolling:52 continue53 touch_button = None54 if 'button' in touch.profile:55 touch_button = touch.button56 if touch_button != ref_button:57 continue58 touch.triple_tap_distance = distance59 return touch60 def process(self, events):61 if self.triple_tap_distance == 0 or self.triple_tap_time == 0:62 return events63 # first, check if a touch down have a triple tap64 for etype, touch in events:65 if not touch.is_touch:66 continue67 if etype == 'begin':68 triple_tap = self.find_triple_tap(touch)69 if triple_tap:70 touch.is_double_tap = False71 touch.is_triple_tap = True72 tap_time = touch.time_start - triple_tap.time_start73 touch.triple_tap_time = tap_time74 distance = triple_tap.triple_tap_distance75 touch.triple_tap_distance = distance76 # add the touch internally77 self.touches[touch.uid] = (etype, touch)78 # second, check if up-touch is timeout for triple tap79 time_current = time()80 to_delete = []81 for touchid in self.touches.keys():82 etype, touch = self.touches[touchid]83 if etype != 'end':84 continue85 if time_current - touch.time_start < self.triple_tap_time:86 continue87 to_delete.append(touchid)88 for touchid in to_delete:89 del self.touches[touchid]...
doubletap.py
Source:doubletap.py
1'''2Double Tap3==========4Search touch for a double tap5'''6__all__ = ('InputPostprocDoubleTap', )7from time import time8from kivy.config import Config9from kivy.vector import Vector10class InputPostprocDoubleTap(object):11 '''12 InputPostProcDoubleTap is a post-processor to check if13 a touch is a double tap or not.14 Double tap can be configured in the Kivy config file::15 [postproc]16 double_tap_time = 25017 double_tap_distance = 2018 Distance parameter is in the range 0-1000 and time is in milliseconds.19 '''20 def __init__(self):21 dist = Config.getint('postproc', 'double_tap_distance')22 self.double_tap_distance = dist / 1000.023 tap_time = Config.getint('postproc', 'double_tap_time')24 self.double_tap_time = tap_time / 1000.025 self.touches = {}26 def find_double_tap(self, ref):27 '''Find a double tap touch within self.touches.28 The touch must be not a previous double tap and the distance must be29 within the specified threshold. Additionally, the touch profiles30 must be the same kind of touch.31 '''32 ref_button = None33 if 'button' in ref.profile:34 ref_button = ref.button35 for touchid in self.touches:36 if ref.uid == touchid:37 continue38 etype, touch = self.touches[touchid]39 if etype != 'end':40 continue41 if touch.is_double_tap:42 continue43 distance = Vector.distance(44 Vector(ref.sx, ref.sy),45 Vector(touch.osx, touch.osy))46 if distance > self.double_tap_distance:47 continue48 if touch.is_mouse_scrolling or ref.is_mouse_scrolling:49 continue50 touch_button = None51 if 'button' in touch.profile:52 touch_button = touch.button53 if touch_button != ref_button:54 continue55 touch.double_tap_distance = distance56 return touch57 def process(self, events):58 if self.double_tap_distance == 0 or self.double_tap_time == 0:59 return events60 # first, check if a touch down have a double tap61 for etype, touch in events:62 if not touch.is_touch:63 continue64 if etype == 'begin':65 double_tap = self.find_double_tap(touch)66 if double_tap:67 touch.is_double_tap = True68 tap_time = touch.time_start - double_tap.time_start69 touch.double_tap_time = tap_time70 distance = double_tap.double_tap_distance71 touch.double_tap_distance = distance72 # add the touch internally73 self.touches[touch.uid] = (etype, touch)74 # second, check if up-touch is timeout for double tap75 time_current = time()76 to_delete = []77 for touchid in self.touches.keys():78 etype, touch = self.touches[touchid]79 if etype != 'end':80 continue81 if time_current - touch.time_start < self.double_tap_time:82 continue83 to_delete.append(touchid)84 for touchid in to_delete:85 del self.touches[touchid]...
tuntap_unittest.py
Source:tuntap_unittest.py
1# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.2# Use of this source code is governed by a BSD-style license that can be3# found in the LICENSE file.4import unittest5from lansim import tuntap6class TunTapTest(unittest.TestCase):7 """Unit tests for the TunTap class."""8 def testCreateTapDevice(self):9 """Tests creation of a TAP device and its attributes."""10 tap = tuntap.TunTap(tuntap.IFF_TAP, name="faketap%d")11 self.assertEqual(tap.mode, tuntap.IFF_TAP)12 # Interface name respects the provided format.13 self.assertTrue(hasattr(tap, 'name'))14 self.assertTrue(tap.name.startswith('faketap'))15 # MTU is set for the interface.16 self.assertTrue(hasattr(tap, 'mtu'))17 self.assertTrue(tap.mtu)18 def testCreateTunDevice(self):19 """Tests creation of a TAP device and its attributes."""20 tun = tuntap.TunTap(tuntap.IFF_TUN, name="faketun%d")21 self.assertEqual(tun.mode, tuntap.IFF_TUN)22 def testTapDeviceHWAddr(self):23 """Tests that we can get and set the HW address of a TAP device."""24 tap = tuntap.TunTap(tuntap.IFF_TAP, name="faketap%d")25 family, addr = tap.get_hwaddr()26 self.assertEqual(family, 1) # Ethernet address27 # Select a different hwaddr.28 addr = addr[:-2] + ('11' if addr[-2:] != '11' else '22')29 new_family, new_addr = tap.set_hwaddr(addr)30 self.assertEqual(new_family, 1)31 self.assertEqual(new_addr, addr)32 new_family, new_addr = tap.get_hwaddr()33 self.assertEqual(new_family, 1)34 self.assertEqual(new_addr, addr)35 def testTapDeviceUpDown(self):36 """Tests if it is possible to bring up and down the interface."""37 tap = tuntap.TunTap(tuntap.IFF_TAP, name="faketap%d")38 # Set the IP address to a safe value:39 tap.set_addr('169.254.10.1')40 self.assertEqual(tap.addr, '169.254.10.1')41 tap.set_addr('0.0.0.0')42 self.assertFalse(tap.is_up())43 tap.up()44 self.assertTrue(tap.is_up())45 # Checks that calling up() twice is harmless.46 tap.up()47 self.assertTrue(tap.is_up())48 tap.down()49 self.assertFalse(tap.is_up())50if __name__ == '__main__':...
wscript
Source:wscript
1## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-2import os.path3def configure(conf):4 if conf.env['ENABLE_THREADING']:5 conf.env['ENABLE_TAP'] = conf.check_nonfatal(header_name='linux/if_tun.h',6 define_name='HAVE_IF_TUN_H')7 conf.report_optional_feature("TapBridge", "Tap Bridge",8 conf.env['ENABLE_TAP'],9 "<linux/if_tun.h> include not detected")10 else:11 conf.report_optional_feature("TapBridge", "Tap Bridge",12 False,13 "needs threading support which is not available")14 if conf.env['ENABLE_TAP']:15 blddir = os.path.abspath(os.path.join(conf.bldnode.abspath(), conf.variant))16 tapcreatordir = os.path.abspath(os.path.join(blddir, "src/tap-bridge"))17 conf.env.append_value('NS3_EXECUTABLE_PATH', tapcreatordir)18 else:19 # Add this module to the list of modules that won't be built20 # if they are enabled.21 conf.env['MODULES_NOT_BUILT'].append('tap-bridge')22def build(bld):23 # Don't do anything for this module if tap-bridge's not enabled.24 if not bld.env['ENABLE_TAP']:25 return26 module = bld.create_ns3_module('tap-bridge', ['internet', 'network', 'core'])27 module.source = [28 'model/tap-bridge.cc',29 'model/tap-encode-decode.cc',30 'helper/tap-bridge-helper.cc',31 ]32 headers = bld(features='ns3header')33 headers.module = 'tap-bridge'34 headers.source = [35 'model/tap-bridge.h',36 'helper/tap-bridge-helper.h',37 'doc/tap.h',38 ]39 if not bld.env['PLATFORM'].startswith('freebsd'):40 tap_creator = bld.create_suid_program('tap-creator')41 tap_creator.source = [42 'model/tap-creator.cc',43 'model/tap-encode-decode.cc',44 ]45 module.env.append_value("DEFINES", "TAP_CREATOR=\"%s\"" % (tap_creator.target,))46 if bld.env['ENABLE_EXAMPLES']:47 bld.recurse('examples')...
Using AI Code Generation
1var assert = require('assert');2var expect = require('chai').expect;3var should = require('chai').should();4var myApp = require('../app');5describe('App', function(){6 it('app should return hello', function(){7 var result = myApp.sayHello();8 assert.equal(result, 'hello');9 });10 it('app should return type string', function(){11 var result = myApp.sayHello();12 assert.typeOf(result, 'string');13 });14 it('app should return number', function(){15 var result = myApp.addNumbers(5,5);16 assert.typeOf(result, 'number');17 });18 it('app should return value of 10', function(){19 var result = myApp.addNumbers(5,5);20 assert.equal(result, 10);21 });22 it('app should return value of 10 using expect', function(){23 var result = myApp.addNumbers(5,5);24 expect(result).to.equal(10);25 });26 it('app should return value of 10 using should', function(){27 var result = myApp.addNumbers(5,5);28 result.should.equal(10);29 });30 it('app should be above 5', function(){31 var result = myApp.addNumbers(5,5);32 result.should.be.above(5);33 });34 it('app should return value of 10 using should', function(){35 var result = myApp.addNumbers(5,5);36 result.should.equal(10);37 });38 it('app should return value of 10 using should', function(){39 var result = myApp.addNumbers(5,5);40 result.should.equal(10);41 });42 it('app should return value of 10 using should', function(){43 var result = myApp.addNumbers(5,5);44 result.should.equal(10);45 });46 it('app should return value of 10 using should', function(){47 var result = myApp.addNumbers(5,5);48 result.should.equal(10);49 });50});
Using AI Code Generation
1var assert = require('assert');2var should = require('should');3var supertest = require('supertest');4describe('User', function () {5 describe('create', function () {6 it('should create a new user', function (done) {7 api.post('/user')8 .set('Accept', 'application/json')9 .send({10 })11 .expect(200)12 .end(function (err, res) {13 if (err) {14 throw err;15 }16 res.body.should.have.property('message', 'User created!');17 done();18 });19 });20 });21});
Using AI Code Generation
1var assert = require('assert');2var mocha = require('mocha');3var describe = mocha.describe;4var it = mocha.it;5describe('test', function () {6 it('should return 4', function () {7 assert.equal(4, 4);8 });9});
Using AI Code Generation
1var assert = require('assert');2var tap = require('tap');3var test = tap.test;4var myApp = require('../app.js');5var myApp2 = require('../app2.js');6var myApp3 = require('../app3.js');7var myApp4 = require('../app4.js');8test('Test 1: Testing app.js for a valid email address', function (t) {9 t.ok(myApp.validateEmail("
Using AI Code Generation
1var tap = require('tap');2var test = tap.test;3var add = require('../index.js');4test('add', function (t) {5 t.equal(add(2, 3), 5, '2 plus 3 is 5');6 t.end();7});8var mocha = new Mocha({9});10mocha.addFile('./test/test.js');11mocha.run(function(failures){12 process.on('exit', function () {13 });14});
Using AI Code Generation
1var assert = require('assert');2var tap = require('tap');3var test = tap.test;4var add = require('../add.js');5test('add', function(t) {6 t.plan(2);7 t.equal(add(1,2), 3);8 t.equal(add(5,5), 10);9 t.end();10});11module.exports = function(a, b) {12 return a + b;13};14var should = require('should');15var add = require('../add.js');16describe('add', function() {17 it('should add two numbers', function() {18 add(1,2).should.equal(3);19 });20 it('should add two numbers', function() {21 add(5,5).should.equal(10);22 });23});24module.exports = function(a, b) {25 return a + b;26};272 passing (9ms)28var expect = require('expect.js');29var add = require('../add.js');30describe('add', function() {31 it('should add two numbers', function() {32 expect(add(1,2)).to.be(3);33 });34 it('should add two numbers', function() {35 expect(add(5,5)).to.be(10);36 });37});38module.exports = function(a, b) {39 return a + b;40};412 passing (8ms)42var chai = require('chai');43var add = require('../add.js');
Using AI Code Generation
1const assert = require('assert')2const math = require('./math')3describe('math', function() {4 it('should return sum of two numbers', function() {5 assert.equal(math.sum(1, 2), 3)6 })7 it('should return product of two numbers', function() {8 assert.equal(math.product(2, 3), 6)9 })10 it('should return square of a number', function() {11 assert.equal(math.square(3), 9)12 })13})14const sum = (a, b) => a + b15const product = (a, b) => a * b16module.exports = {17}18{19 "scripts": {20 },21 "devDependencies": {22 }23}24const assert = require('assert')25const math = require('./math')26describe('math', function() {27 it('should return sum of two numbers', function() {28 assert.equal(math.sum(1, 2), 3)29 })30 it('should return product of two numbers', function() {31 assert.equal(math.product(2, 3), 6)32 })33 it('should return square of a number', function() {34 assert.equal(math.square(3), 9)35 })36})37const sum = (a, b) => a + b38const product = (a, b) => a * b39module.exports = {40}
Using AI Code Generation
1var assert = require('assert');2var tap = require('tap');3var request = require('request');4var server = require('../server.js');5var superagent = require('superagent');6tap.test("Testing the server", function(t) {7 t.test("Testing the index route", function(t) {8 t.equal(res.statusCode, 200, "Status code is 200");9 t.end();10 });11 });12 t.test("Testing the hello route", function(t) {13 t.equal(res.statusCode, 200, "Status code is 200");14 t.end();15 });16 });17 t.test("Testing the hello route with name", function(t) {18 t.equal(res.statusCode, 200, "Status code is 200");19 t.end();20 });21 });22 t.test("Testing the hello route with name", function(t) {23 t.equal(body, "Hello Jen", "Body is Hello Jen");24 t.end();25 });26 });27 t.test("Testing the hello route with no name", function(t) {28 t.equal(body, "Hello World", "Body is Hello World");29 t.end();30 });31 });32 t.test("Testing the hello route with no name", function(t) {33 t.equal(body, "Hello World", "Body is Hello World");34 t.end();35 });36 });37 t.test("Testing the hello route with no name", function(t) {38 t.equal(body, "Hello World", "Body is Hello World");39 t.end();40 });41 });42 t.test("Testing the hello route with no name", function(t) {
Using AI Code Generation
1var test = require('tap').test;2var expect = require('chai').expect;3var should = require('chai').should();4var browserify = require('browserify');5var vm = require('vm');6var jsdom = require('jsdom');7var window = jsdom.jsdom().defaultView;8var $ = require('jquery')(window);9var jsdom = require('jsdom');10var document = jsdom.jsdom('<html><body></body></html>');11var window = document.parentWindow;12var $ = require('jquery')(window);13var jsdom = require('jsdom');14var document = jsdom.jsdom('<html><body></body></html>');15var window = document.parentWindow;16var $ = require('jquery')(window);17var jsdom = require('jsdom');18var document = jsdom.jsdom('<html><body></body></html>');19var window = document.parentWindow;20var $ = require('jquery')(window);21var browserify = require('browserify');22var vm = require('vm');23var jsdom = require('jsdom');24var document = jsdom.jsdom('<html><body></body></html>');25var window = document.parentWindow;26var $ = require('jquery')(window);27var browserify = require('browserify');28var vm = require('vm');29var jsdom = require('jsdom');30var document = jsdom.jsdom('<html><body></body></html>');31var window = document.parentWindow;32var $ = require('jquery')(window);33var browserify = require('browserify');34var vm = require('vm');35var browserify = require('browserify');36var vm = require('vm');37var jsdom = require('jsdom');38var document = jsdom.jsdom('<html><body></body></html>');39var window = document.parentWindow;40var $ = require('jquery')(window);41var jsdom = require('jsdom');42var document = jsdom.jsdom('<html><body></body></
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!