Best JavaScript code snippet using root
webgazerExtractClient.js
Source:webgazerExtractClient.js  
1// Initialize variables2var overlay;3var width = 640;4var height = 480;5var topDist = '0px';6var leftDist = '0px';7var logs = "";8var logsCount = 0;9var videoFilename = "";10var frameNum = -1;11var frameTimeEpoch = -1;12var frameTimeIntoVideoMS = -1;13var tobiiX, tobiiY;14// Screen space size (received from server)15var screenWidthPixels, screenHeightPixels;16// Where the document starts in screen space (e.g., where clientX,clientY 0,0 is in screen space)17var docStartX, docStartY;18// Whether the participant is a touch typist or not19var touchTypist;20var processTimePrev = 0;21// WebSocket for sending image data22var ws;23// CLM tracker24var fm;25// TODO magic numbers26var fmPosFeaturesSize = 468;27var eyeFeaturesSize = 120;28// Screencap video29var screencapVideo;30var showScreenCap = false;31var screencapStartTime = 0;32var screencapTimeOffsetMS = 0;33var participant_id = "";34var total_participants = 64;35var video_number = 1;36var total_videos = 6;37function toggleScreenCap()38{39    showScreenCap = !showScreenCap;40    if( !showScreenCap )41        screencapVideo.style.visibility="hidden"42    else43        screencapVideo.style.visibility="visible"44}45function setScreenCapTimeOffset()46{47    screencapTimeOffsetMS = parseInt( parseFloat(document.getElementById('scTimeOffset').value) * 1000 )48    console.log( screencapTimeOffsetMS )49}50function onLoad() 51{52    // Init webgazer and set parameters53    webgazer.setRegression('ridge').setTracker('TFFacemesh');54    // Drawing overlay55    var c = document.getElementById('wsCanvas')56    c.style.position = 'absolute';57    c.width = width;58    c.height = height;59    c.style.top = topDist;60    c.style.left = leftDist;61    c.style.margin = '0px';62    // Set our canvas to be the one that webgazer uses63    webgazer.setVideoElementCanvas(c);64    webgazer.params.videoElementCanvasId = 'wsCanvas';65    webgazer.getVideoElementCanvas().id = webgazer.params.videoElementCanvasId;66    67    screencapVideo = document.getElementById('screencap')68    screencapVideo.style.position = 'absolute';69    screencapVideo.style.top = topDist;70    screencapVideo.style.left = '640px';71    screencapVideo.style.margin = '0px'72    screencapVideo.style.visibility="hidden"73    // Overlay for fm tracker74    overlay = document.createElement('canvas');75    overlay.id = 'overlay';76    overlay.style.position = 'absolute';77    overlay.width = width;78    overlay.height = height;79    overlay.style.top = topDist;80    overlay.style.left = leftDist;81    overlay.style.margin = '0px';82    document.body.appendChild(overlay);83    fm = webgazer.getTracker();84    // Start WebSocket85    ws = new WebSocket("ws://localhost:8000/websocket");86    ws.binaryType = "blob"87    ws.onopen = function(e) 88    {};89    ws.onmessage = async function(e) 90    {91        // Received image data92        if( e.data instanceof Blob )93        {94            var c = document.getElementById('wsCanvas')95            ctx = c.getContext('2d')96            var fr = new FileReader();97            fr.onload = async function (e) {98                var buffer = new Uint8ClampedArray(e.target.result);99                var imageData = new ImageData(buffer, width, height);100                ctx.putImageData( imageData, 0, 0 )101                runWebGazerSendResult();102            };103            fr.readAsArrayBuffer(e.data);104        }105        else106        {107            try108            {109                obj = JSON.parse( e.data );110            }111            catch( err )112            {113                console.log( err );114                return;115            }116            // Receiving participant info117            if( obj.msgID == "0" )118            {119                screencapStartTime = parseInt( obj.screencapStartTime );120                screenWidthPixels = parseInt( obj.screenWidthPixels );    121                screenHeightPixels = parseInt( obj.screenHeightPixels );122                docStartX = parseInt( obj.docStartX );123                docStartY = parseInt( obj.docStartY );124                touchTypist = obj.touchTypist;125                screencapVideo.src = obj.participantScreenCapFile;126                participant_id = obj.participantScreenCapFile.substring(2,4)127                video_number = 1;128                // Server has told us we are switching participants.129                // Let's load the input log for this participant from the server130                // TODO do this with websockets?!?!131                fetch(obj.participantInputLogFile)132                .then(function (response) {133                    return response.json();134                })135                .then(function (body) {136                    logs = body;137                });138                // Reset logs count as new participant139                logsCount = 0140                141                // Reset fm tracker as it's a new participant with new interactions/appearance142                fm.reset();143                var send = { msgID: "1" };144                sendMsg( JSON.stringify(send) );145            }146            // Receiving frame info147            else if( obj.msgID == "2" )148            {149                videoFilename = obj.videoFilename;150                frameNum = parseInt( obj.frameNum );151                frameNumTotal = parseInt( obj.frameNumTotal );152                tobiiX = parseFloat( obj.tobiiX );153                tobiiY = parseFloat( obj.tobiiY );154                frameTimeEpoch = parseInt( obj.frameTimeEpoch )155                frameTimeIntoVideoMS = parseInt( obj.frameTimeIntoVideoMS );156                // Update screen cap video157                seekTimeMS = frameTimeEpoch - screencapStartTime + screencapTimeOffsetMS;158                if( showScreenCap )159                    screencapVideo.currentTime = seekTimeMS / 1000.0160            }161            else if( obj.msgID == "4" )162            {163                // Video has ended; ask for a new video.164                var send = { msgID: "1" };165                sendMsg( JSON.stringify(send) );166                video_number++;167            }168        }169    };170}171async function sendMsg(msg) {172    ws.send(msg);173}174// Thanks to http://jsfiddle.net/d4rcuxw9/1/175// https://stackoverflow.com/questions/29573700/finding-the-difference-between-two-string-in-javascript-with-regex176function getStringDifference(a, b)177{178    var i = 0;179    var j = 0;180    var result = "";181    182    while (j < b.length)183    {184        if (a[i] != b[j] || i == a.length)185            result += b[j];186        else187            i++;188        j++;189    }190    return result;191}192async function runWebGazerSendResult()193{194    // Object to collect all the results195    var s = {};196    /////////////////////////////////////////////////////////197    // Interaction inputs (default values)198    s.mouseMoveX = [];199    s.mouseMoveY = [];200    s.mouseClickX = [];201    s.mouseClickY = [];202    s.keyPressed = [];203    s.keyPressedX = [];204    s.keyPressedY = [];205    //////////////////////////////////////////////////////////206    // Push mouse clicks and keyboard input from logs to WebGazer207    //208    var mouseImg = document.getElementById("myMouse");209    while (logsCount < logs.length && (logs[logsCount].epoch) < frameTimeEpoch) 210    {211        switch (logs[logsCount].type) 212        {213            case "mouseclick":214                // Ignore all interactions for the 'dot_test_final.' video215                if( !videoFilename.includes("dot_test_final.") )216                    webgazer.recordScreenPosition(logs[logsCount].clientX, logs[logsCount].clientY, "click");217                218                s.mouseClickX.push( (logs[logsCount].clientX + docStartX) / screenWidthPixels );219                s.mouseClickY.push( (logs[logsCount].clientY + docStartY) / screenHeightPixels );220                221                mouseImg.style.height = '20px';222                mouseImg.style.width = '20px';223                mouseImg.style.top = (s.mouseClickY * screencapVideo.height) -10 + 'px';224                mouseImg.style.left = width + (s.mouseClickX * screencapVideo.width) -10 + 'px';225                break;226            case "mousemove":227                // Ignore all interactions for the 'dot_test_final.' video228                if( !videoFilename.includes("dot_test_final.") )229                    webgazer.recordScreenPosition(logs[logsCount].clientX, logs[logsCount].clientY, "move");230                s.mouseMoveX.push( (logs[logsCount].clientX + docStartX) / screenWidthPixels );231                s.mouseMoveY.push( (logs[logsCount].clientY + docStartY) / screenHeightPixels );232                mouseImg.style.height = '10px';233                mouseImg.style.width = '10px';234                mouseImg.style.top = (s.mouseMoveY * screencapVideo.height) -5 + 'px';235                mouseImg.style.left = width + (s.mouseMoveX * screencapVideo.width) -5 + 'px';236                break;237            case "textInput":238                //IMPORTANT: CHANGE WEBGAZER.js CODE IF YOU WANT TO INCLUDE TYPING239                //if( !videoFilename.includes("dot_test_final.") && touchTypist === "Yes" )240                //    webgazer.recordScreenPosition( logs[logsCount].pos.left, logs[logsCount].pos.top, "click" );241                242                // There is a bug in the data collection here, where the value of .text is 'one event behind'243                // textTyped = logs[count].text;  <- BAD!244                // So, let's go get the next textTyped event.245                var localCount = logsCount+1;246                while( logs[localCount] && logs[localCount].type !== "textInput" )247                    localCount++;248                if( !logs[localCount] )249                {250                    // We've run out of events and not found a next textInput event.251                    keyPressed = "Unknown";252                }253                else if( logs[localCount.text] === "" )254                {255                    // We've started a new text field with this event, or some other weird thing happened, which means the last character has been lost forever : (256                    keyPressed = "Unknown";257                }258                else259                {   260                    // We've found a textInput event and it's not empty.261                    // Now let's check for the difference between these two strings262                    // Note that we can't just look at the last character in logs[localCount].text, because the user could have inserted text anywhere.263                    if( logs[localCount].text.length > logs[logsCount].text.length )264                        keyPressed = getStringDifference( logs[logsCount].text, logs[localCount].text );265                    else266                        // The new text is _shorter_ than the old text, which means the user must have pressed backspace at some point _after_ this.267                        // However, 'Backspace' as a key isn't logged.268                        // A key was pressed at this time instance, but it wasn't 'Backspace' yet, because those events aren't logged.269                        // So, it is 'Unknown'270                        keyPressed = "Unknown";271                        //272                        // After this event there is some unknown event where backspace is pressed, but it isn't logged.273                }274                // Escape an escape key so that we transmit it whole275                // keyPressed will not send correctly if the keystroke is ", because276                // the " is considered to be part of the url.277                // So, let's wrap it up.278                // if( keyPressed === ';' )279                //     keyPressed = 'semicolon';280                // if( keyPressed === '&' )281                //     keyPressed = 'ampersand';282                // if( keyPressed === '=' )283                //     keyPressed = 'equals';284                console.log( "Key pressed: " + keyPressed );285                s.keyPressed.push( keyPressed );286                s.keyPressedX.push( (logs[logsCount].pos.left + docStartX) / screenWidthPixels );287                s.keyPressedY.push( (logs[logsCount].pos.top  + docStartY) / screenHeightPixels );288                mouseImg.style.height = '10px';289                mouseImg.style.width = '3px';290                mouseImg.style.top = (s.keyPressedY * screencapVideo.height) + 'px';291                mouseImg.style.left = width + (s.keyPressedX * screencapVideo.width) + 'px';292                293                break;294        }295        logsCount++;296    }297    // Update tobii visualization298    var wgv = document.getElementById('tobiiGP');299    wgv.style.height = '10px';300    wgv.style.width = '10px';301    wgv.style.top = (tobiiY * screencapVideo.height - 5) + 'px'; // half height302    wgv.style.left = width + (tobiiX * screencapVideo.width - 5) + 'px';303    //////////////////////////////////////////////////////////304    // Run WebGazer305    //306    var webGazerX = "-1"307    var webGazerY = "-1"308    // TODO magic numbers309    var eyeFeatures = Array(eyeFeaturesSize).fill(-1)310    var gazeData = await webgazer.getCurrentPrediction();311    if ( gazeData )312    {313        // Gaze in [0,1] coordinates314        webGazerX = ( gazeData.x + docStartX ) / screenWidthPixels315        webGazerY = ( gazeData.y + docStartY ) / screenHeightPixels316        // Grab eye features317        318        eyeFeatures = webgazer.util.getEyeFeats(gazeData.eyeFeatures)319        // Update position of output visualizer320        //321        var wgv = document.getElementById('wgGP');322        wgv.style.height = '10px';323        wgv.style.width = '10px';324        wgv.style.top = (webGazerY * screencapVideo.height - 5) + 'px'; // half height325        wgv.style.left = width + (webGazerX * screencapVideo.width - 5) + 'px';326    }327    328    // Also collect the CLMTracker positions329    // 330    //var clmPos = cl.getCurrentPosition();331    var fmPos = fm.getPositions();332    if ( fmPos ) 333    {334        overlay.getContext('2d').clearRect(0, 0, width, height);335        fm.drawFaceOverlay(overlay.getContext('2d'),fmPos);336    }337    else338    {   // Reproduce necessary structure339        fmPos = Array(fmPosFeaturesSize/2).fill(Array(-1,-1))340    }341    // Update display342    var pDiag = document.getElementById("partvidframe")343    pDiag.innerHTML  = "Video: " + videoFilename + "<br> Frame num: " + frameNum + "/" + frameNumTotal + " Video current time (MS): " + frameTimeIntoVideoMS;344    //console.log( "Frame num: " + frameNum + "    Video current time: " + frameTimeIntoVideoMS );345    var eDiag = document.getElementById("wgError")346    var xdiff = tobiiX - webGazerX;347    var ydiff = tobiiY - webGazerY;348    var xdiffPix = xdiff * screenWidthPixels;349    var ydiffPix = ydiff * screenHeightPixels;350    var error = Math.sqrt( xdiff*xdiff + ydiff*ydiff )351    var errorPix = Math.sqrt( xdiffPix*xdiffPix + ydiffPix*ydiffPix )352    eDiag.innerHTML  = "Error: " + error.toFixed(4) + " (pixels: " + errorPix.toFixed(4) + ")";353    var fpsDiag = document.getElementById("procFPS")354    var tdiff = performance.now() - processTimePrev;355    processTimePrev = performance.now();356    fpsDiag.innerHTML  = "Processing FPS: " + (1000 / tdiff).toFixed(2)357    var parcipants_status = document.getElementById("parcipants_status");358    parcipants_status.innerHTML = "Participant " + participant_id + "/" + String(total_participants);359    var videos_status = document.getElementById("videos_status");360    videos_status.innerHTML = "Video " + String(video_number) + "/" + String(total_videos);361    // Send a msg to the server, which can write out the file + metadata362    s.msgID = "3"363    s.frameNum = frameNum; // Sanity364    s.frameTimeEpoch = frameTimeEpoch;365    s.webGazerX = webGazerX;366    s.webGazerY = webGazerY;367    s.fmPos = fmPos;368    s.eyeFeatures = eyeFeatures;369    s.error = error;370    s.errorPix = errorPix;371    sendMsg( JSON.stringify(s) )            ...screencap.js
Source:screencap.js  
1var Command, LineTransform, Parser, Promise, Protocol, ScreencapCommand,2  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },3  hasProp = {}.hasOwnProperty;4Promise = require('bluebird');5Command = require('../../command');6Protocol = require('../../protocol');7Parser = require('../../parser');8LineTransform = require('../../linetransform');9ScreencapCommand = (function(superClass) {10  extend(ScreencapCommand, superClass);11  function ScreencapCommand() {12    return ScreencapCommand.__super__.constructor.apply(this, arguments);13  }14  ScreencapCommand.prototype.execute = function() {15    this._send('shell:echo && screencap -p 2>/dev/null');16    return this.parser.readAscii(4).then((function(_this) {17      return function(reply) {18        var transform;19        switch (reply) {20          case Protocol.OKAY:21            transform = new LineTransform;22            return _this.parser.readBytes(1).then(function(chunk) {23              transform = new LineTransform({24                autoDetect: true25              });26              transform.write(chunk);27              return _this.parser.raw().pipe(transform);28            })["catch"](Parser.PrematureEOFError, function() {29              throw new Error('No support for the screencap command');30            });31          case Protocol.FAIL:32            return _this.parser.readError();33          default:34            return _this.parser.unexpected(reply, 'OKAY or FAIL');35        }36      };37    })(this));38  };39  return ScreencapCommand;40})(Command);...shouldScreencapUrl.test.js
Source:shouldScreencapUrl.test.js  
1const shouldScreencapUrl = require('./shouldScreencapUrl');2test('only allow urls of packages to return true', () => {3  expect(shouldScreencapUrl('https://npmcharts.com/compare/glamor')).toBe(true);4  expect(shouldScreencapUrl('http://localhost/compare/glamor')).toBe(true);5  expect(6    shouldScreencapUrl('https://npmcharts.com/compare/glamor,emotion'),7  ).toBe(true);8  expect(shouldScreencapUrl('https://npmcharts.com/compare/')).toBe(false);9  expect(shouldScreencapUrl('https://npmcharts.com/')).toBe(false);10  expect(shouldScreencapUrl('https://google.com/')).toBe(false);11  expect(shouldScreencapUrl('https://google.com/compare/glamor')).toBe(false);12  expect(shouldScreencapUrl('google.com/compare/glamor')).toBe(false);13  expect(shouldScreencapUrl('googlecom/compare/glamor')).toBe(false);...Using AI Code Generation
1var root = require('root');2var screenCap = root.screencap();3screenCap.on('data', function(data) {4    console.log('got data');5});6screenCap.on('error', function(error) {7    console.log('error: ', error);8});9var root = require('root');10var screenCap = root.screencap();11screenCap.on('data', function(data) {12    console.log('got data');13});14screenCap.on('error', function(error) {15    console.log('error: ', error);16});17var fs = require('fs');18var root = require('root');19var screenCap = root.screencap();20screenCap.pipe(fs.createWriteStream('screencap.png'));21var root = require('root');22var screenCap = root.screencap();23screenCap.on('data', function(data) {24    console.log('got data');25});26screenCap.on('error', function(error) {27    console.log('error: ', error);28});29var fs = require('fs');30var root = require('root');31var screenCap = root.screencap();32screenCap.pipe(fs.createWriteStream('screencap.png'));Using AI Code Generation
1var sc = new Screencap();2var file = new java.io.File("/sdcard/screenshot.png");3var out = new java.io.FileOutputStream(file);4sc.capture().compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out);5out.close();6var sc = new Screencap();7var file = new java.io.File("/sdcard/screenshot.png");8var out = new java.io.FileOutputStream(file);9sc.capture().compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out);10out.close();11var sc = new Screencap();12var file = new java.io.File("/sdcard/screenshot.png");13var out = new java.io.FileOutputStream(file);14sc.capture().compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out);15out.close();16var sc = new Screencap();17var file = new java.io.File("/sdcard/screenshot.png");18var out = new java.io.FileOutputStream(file);19sc.capture().compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out);20out.close();21var sc = new Screencap();22var file = new java.io.File("/sdcard/screenshot.png");23var out = new java.io.FileOutputStream(file);24sc.capture().compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out);25out.close();26var sc = new Screencap();27var file = new java.io.File("/sdcard/screenshot.png");28var out = new java.io.FileOutputStream(file);29sc.capture().compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out);30out.close();31var sc = new Screencap();32var file = new java.io.File("/sdcard/screenshotUsing AI Code Generation
1var screencap = require('screencap');2screencap.screencap(function(err, data) {3    if(err) {4        console.log('screencap failed');5        return;6    }7    Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory, 'screenshot.jpg').write(data);8});Using AI Code Generation
1var root = require('./root.js');2var exec = require('child_process').exec;3var fs = require('fs');4var path = '/sdcard/screencap.png';5var cmd = 'screencap ' + path;6var savepath = '/home/rahul/Desktop/screencap.png';7var savecmd = 'adb pull ' + path + ' ' + savepath;8var callback = function (error, stdout, stderr) {9    if (error !== null) {10        console.log('exec error: ' + error);11    }12    else {13        var savecallback = function (error, stdout, stderr) {14            if (error !== null) {15                console.log('exec error: ' + error);16            }17            else {18                var removecallback = function (error, stdout, stderr) {19                    if (error !== null) {20                        console.log('exec error: ' + error);21                    }22                    else {23                        console.log('Screenshot Saved');24                    }25                }26                var removecmd = 'adb shell rm ' + path;27                root.execute(removecmd, removecallback);28            }29        }30        root.execute(savecmd, savecallback);31    }32}33root.execute(cmd, callback);34var root = require('./root.js');35var exec = require('child_process').exec;36var fs = require('fs');37var path = '/sdcard/screencap.png';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!!
