Best JavaScript code snippet using devicefarmer-stf
script.js
Source:script.js
1// Calculator object.2let Calculator = {3 add: (x, y) => { return x + y },4 subtract: (x, y) => { return x - y },5 multiply: (x, y) => { return x * y },6 divide: (x, y) => { return (y !== 0 ? x / y : alert("Can't divide by zero.")) },7 operate: (op, x, y) => { return Calculator[op](x, y); }8}9// All states in the calculator's finite state diagram.10let States = {11 start: 'S',12 firstNumInstance: 'N1',13 secondNumInstance: 'N2',14 firstOpInstance: 'O1',15 secondOpInstance: 'O2',16 evaluation: 'E',17 decPointStart: 'DP1',18 decPointFirstNumInstance: 'DP2',19 decPointFirstOpInstance: 'DP3',20 decPointSecondNumInstance: 'DP4',21 decPointSecondOpInstance: 'DP5',22 decPointEvaluation: 'DP6',23}24let screenVal = '', secondOperand = '', currOp = '', currState = States.start, canUseDecimalPoint = true;25const digitClass = 'digit', opClass = 'op', evalCalss = 'evaluation', decPointClass = 'dec-point',26 resetClass = 'reset', deleteClass = 'delete';27const gridContainer = document.querySelector('.container');28const screen = document.querySelector('.screen');29gridContainer.addEventListener('click', onClick, false);30// Handle UI clicks.31function onClick(event) {32 let shouldDisplay;33 switch (event.target.className) {34 case digitClass: shouldDisplay = handleDigitClick(event.target.textContent); break;35 case opClass: shouldDisplay = handleOpClick(event.target.id); break;36 case evalCalss: shouldDisplay = handleEvaluationClick(); break;37 case decPointClass: shouldDisplay = handleDecPointClick(); break;38 case resetClass: shouldDisplay = handleResetClick(); break;39 case deleteClass: shouldDisplay = handledeleteClick(); break;40 default: shouldDisplay = false;41 }42 // If the user clicked on a valid button in the current state of the computation then update the display.43 if (shouldDisplay)44 screen.textContent = screenVal;45}46/**47 * Handle the case where the user want to delete the last character in the display.48 * @returns true if the display will update, false otherwise .49 */50function handledeleteClick() {51 if (screenVal === '')52 return false;53 // If the last character is a decimal point then now the user can use decimal point again,54 // since we are deleting the current decimal point and there can be only one decimal point in the display.55 if (screenVal[screenVal.length - 1] === '.')56 canUseDecimalPoint = true;57 // Get al the display value except the last character. 58 screenVal = screenVal.slice(0, -1);59 // true if the current last character is a decimal point.60 isLastCharDecPoint = screenVal[screenVal.length - 1] === '.';61 // Act according to the current state.62 switch (currState) {63 case States.decPointStart:64 case States.decPointFirstNumInstance:65 case States.decPointEvaluation:66 currState = States.firstNumInstance;67 break;68 case States.decPointFirstOpInstance:69 case States.decPointSecondOpInstance:70 case States.decPointSecondNumInstance:71 currState = States.secondNumInstance;72 break;73 case States.firstNumInstance:74 if (isLastCharDecPoint)75 currState = States.decPointFirstNumInstance;76 break;77 case States.firstOpInstance:78 currState = States.firstNumInstance;79 if (screenVal.includes('.')) { 80 canUseDecimalPoint = false;81 if (isLastCharDecPoint)82 currState = States.decPointFirstNumInstance;83 }84 break;85 86 case States.secondNumInstance:87 if (isLastCharDecPoint)88 currState = States.decPointSecondNumInstance;89 break;90 91 case States.secondOpInstance:92 case States.evaluation:93 screenVal = '0';94 currState = States.start;95 break;96 }97 return true;98}99/**100 * Handle the case where the user clicks on a digit.101 * @returns true if the display will update, false otherwise.102 * @param {String} digitStr The digit that the user clicked on.103 */104function handleDigitClick(digitStr) {105 // You can't append digits with a leading zero.106 if (screenVal === '0' && (currState === States.firstNumInstance || currState === States.secondNumInstance)) 107 return false;108 109 // Append to the display the user's input.110 screenVal += digitStr;111 // true if the curren state is not representing a decimal point state, false otherwise.112 // If the currentState is not a decimal point state then handle this case.113 let wasInNonDecPointState = handleNonDecPointStates(digitStr);114 if (!wasInNonDecPointState)115 handleDecPointStates();116 return true;117}118/**119 * Handle the case where the user clicks on a digit and the current state is not a decimal point state.120 * @returns true if the current state represents a state that is not a decimal point state.121 * @param {String} digitStr The digit that the user clicked on.122 */123function handleNonDecPointStates(digitStr) {124 switch (currState) {125 case States.start:126 case States.evaluation:127 screenVal = digitStr;128 // Transition to next state.129 currState = States.firstNumInstance;130 break;131 case States.firstOpInstance:132 case States.secondOpInstance:133 // Because in the caller we updated screenVal. However, in this case the updated value is not suitable.134 secondOperand = screenVal.slice(0, -1);135 screenVal = digitStr;136 currState = States.secondNumInstance;137 break;138 case States.firstNumInstance:139 case States.secondNumInstance:140 break;141 default: return false;142 }143 return true;144}145/**146 * Handle the case where the user clicks on a digit and the current state represents a decimal point state.147 */148function handleDecPointStates() {149 switch (currState) {150 case States.decPointStart:151 case States.decPointFirstNumInstance:152 case States.decPointEvaluation:153 currState = States.firstNumInstance;154 break;155 case States.decPointFirstOpInstance:156 case States.decPointSecondOpInstance:157 case States.decPointSecondNumInstance:158 currState = States.secondNumInstance;159 break;160 }161}162/**163 * Handle the case where the user clicks on a an operation.164 * @returns true if the display will update, false otherwise.165 * @param {String} digitStr The digit that the user clicked on.166 */167function handleOpClick(opId) {168 if (isEmptyScreen())169 return false;170 let shouldUpdateScreen = false, isEvalSucceeded = true, prevDecPointUsedVal = canUseDecimalPoint;171 canUseDecimalPoint = true;172 // TODO - Highlight op button173 switch (currState) {174 case States.firstNumInstance:175 currOp = opId;176 currState = States.firstOpInstance;177 break;178 case (States.secondNumInstance):179 isEvalSucceeded = evaluate()180 shouldUpdateScreen = true;181 // No break182 case (States.evaluation):183 if (isEvalSucceeded) {184 currOp = opId;185 currState = States.secondOpInstance;186 }187 break;188 default: canUseDecimalPoint = prevDecPointUsedVal;189 }190 return shouldUpdateScreen;191}192/**193 * Handle the case where the user clicks on the equals button.194 * @returns true if the display will update, false otherwise.195 */196function handleEvaluationClick() {197 if (currState === States.secondNumInstance && !isEmptyScreen()) {198 currState = States.evaluation;199 evaluate();200 canUseDecimalPoint = true;201 return true;202 }203 return false;204}205/**206 * Handle the case where the user clicks on the reset button.207 * @returns true since we always need to the update the display if t he user pressed the reset button.208 */209function handleResetClick() {210 currState = States.start;211 screenVal = '0';212 canUseDecimalPoint = true;213 return true;214}215/**216 * Handle the case where the user clicks on a decimal point .217 * @returns true if the display will update, false otherwise.218 */219function handleDecPointClick() {220 if (!canUseDecimalPoint)221 return false;222 canUseDecimalPoint = !canUseDecimalPoint;223 let prevScreenVal = screenVal;224 screenVal = '0.';225 switch (currState) {226 case States.start:227 currState = States.decPointStart;228 break;229 case States.firstNumInstance:230 currState = States.decPointFirstNumInstance;231 screenVal = prevScreenVal + '.';232 break;233 case States.firstOpInstance:234 secondOperand = prevScreenVal;235 currState = States.decPointFirstOpInstance;236 break;237 case States.secondNumInstance:238 screenVal = prevScreenVal + '.';239 currState = States.decPointSecondNumInstance;240 break;241 case States.secondOpInstance:242 secondOperand = prevScreenVal;243 currState = States.decPointSecondOpInstance;244 break;245 case States.evaluation:246 currState = States.decPointEvaluation;247 break;248 default:249 screenVal = prevScreenVal;250 return false;251 }252 return true;253}254/**255 * Perform the current operation on the current operands.256 * @returns true if the display will update, false otherwise.257 */258function evaluate() {259 screenVal = Calculator.operate(currOp, parseFloat(secondOperand), parseFloat(screenVal));260 // If the current display is not a number.261 if (isNaN(screenVal)) {262 screenVal = '0';263 currState = States.start;264 return false;265 }266 screenVal = parseFloat(screenVal.toFixed(3)).toString();267 return true;268}269/**270 * @returns true if the display is empty, false otherwise.271 */272function isEmptyScreen() {273 return screenVal === '';...
display_socket.js
Source:display_socket.js
1/*2 * Copyright (C) 2015 Opersys inc.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16/*17 * This wraps the basic functionality of the display websocket.18 */19var signals = require("signals");20var RETRY_COUNT = 5;21var DisplaySocket = function () {22 this.onOpen = new signals.Signal();23 this.onClose = new signals.Signal();24 this.onFrame = new signals.Signal();25 this.onInfo = new signals.Signal();26 this._expectClose = false;27 this._retryCount = RETRY_COUNT;28 this._connect();29};30DisplaySocket.prototype._connect = function () {31 this._ws = new WebSocket("ws://" + window.location.host + "/display", "minicap");32 this._ws.binaryType = 'blob';33 this._expectClose = false;34 this._ws.onopen = this._onOpen.bind(this);35 this._ws.onclose = this._onClose.bind(this);36 this._ws.onerror = this._onError.bind(this);37};38DisplaySocket.prototype._onError = function (err) {39 console.error(err.message);40};41DisplaySocket.prototype._onMessage = function (msg) {42 if (msg.data instanceof Blob) {43 this.onFrame.dispatch(msg.data);44 } else {45 var eventData = JSON.parse(msg.data);46 switch (eventData.event) {47 case "info":48 this.onInfo.dispatch(eventData.data);49 break;50 default:51 console.log("Received unknown event: " + eventData.event);52 }53 }54};55DisplaySocket.prototype._onOpen = function () {56 this._retryCount = RETRY_COUNT;57 this._ws.onmessage = this._onMessage.bind(this);58 this.onOpen.dispatch();59};60DisplaySocket.prototype._onClose = function () {61 if (!this._expectClose || this._retryCount == 0) {62 this.onClose.dispatch();63 }64 this._retryCount--;65};66DisplaySocket.prototype.shouldUpdateScreen = function () {Â 67 return this._ws.readyState === WebSocket.OPEN;68};69/*70 * It is important to set a geometry because we can't start "minicap" until this is set.71 */72DisplaySocket.prototype.geom = function (w, h) {73 if (this._ws.readyState === WebSocket.OPEN) {74 this._expectClose = true;75 this._ws.send("size " + w + "x" + h);76 }77};...
TaskBar.jsx
Source:TaskBar.jsx
...7import './TaskBar.scss';8export default function TaskBar({ taskTitle, id, shouldUpdateScreen }) {9 const handleDeleteClick = async (_e) => {10 await deleteTask(id);11 shouldUpdateScreen(true);12 };13 const handleUpdateTask = async (_e) => {14 await updateCompletedTask(id);15 shouldUpdateScreen(true);16 };17 return (18 <Box className='taskbar-box'>19 <Typography className='taskbar-title' component='span' variant='body2'>20 {taskTitle}21 </Typography>22 <Box className='taskbar-icons'>23 <IconButton onClick={handleUpdateTask}>24 <CheckIcon sx={{ color: 'white' }} />25 </IconButton>26 <IconButton onClick={handleDeleteClick}>27 <DeleteIcon sx={{ color: 'white' }} />28 </IconButton>29 </Box>...
Using AI Code Generation
1var stf = require('stf-client');2var Promise = require('bluebird');3var _ = require('lodash');4var util = require('util');5var EventEmitter = require('events').EventEmitter;6var adbkit = require('adbkit');7var client = adbkit.createClient();8var adb = require('adbkit');9var client = adb.createClient();10var device = new stf.Device(client, 'emulator-5554');11device.shouldUpdateScreen().then(function(shouldUpdate) {12 console.log("should update: " + shouldUpdate);13});14Device.prototype.shouldUpdateScreen = function() {15 return this.getScreenInfo().then(function(info) {16 var result = true;17 if (this._screenInfo && info) {18 this._screenInfo.rotation !== info.rotation;19 }20 this._screenInfo = info;21 return result;22 }.bind(this));23};24Device.prototype.getScreenInfo = function() {25 return this.getProp('ro.sf.lcd_density').then(function(d
Using AI Code Generation
1var shouldUpdateScreen = require('./node_modules/devicefarmer-stf-client/lib/util/shouldUpdateScreen');2var device = {3 "screen": {4 },5 "plugins": {6 "touch": {7 },8 "openstf": {9 "display": {10 },11 "touch": {12 }13 }14 }15}16var previous = {17 "screen": {18 },19 "plugins": {20 "touch": {21 },22 "openstf": {23 "display": {
Using AI Code Generation
1var stf = require('devicefarmer-stf');2var device = client.getDevice('emulator-5554');3device.shouldUpdateScreen(function (err, shouldUpdateScreen) {4 if (err) throw err;5 console.log(shouldUpdateScreen);6});7 throw new Error('Device is not connected');8 at Device.shouldUpdateScreen (C:\Users\user\Desktop\stf\node_modules\devicefarmer-stf\lib\device.js:83:15)9 at Request._callback (C:\Users\user\Desktop\stf\node_modules\devicefarmer-stf\node_modules\request\request.js:186:22)10 at self.callback (C:\Users\user\Desktop\stf\node_modules\devicefarmer-stf\node_modules\request\request.js:371:22)11 at Request.EventEmitter.emit (events.js:98:17)12 at Request.onRequestError (C:\Users\user\Desktop\stf\node_modules\devicefarmer-stf\node_modules\request\request.js:965:8)13 at ClientRequest.EventEmitter.emit (events.js:117:20)14 at Socket.socketErrorListener (http.js:1541:9)
Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2var client = new stf.Client('localhost', 7100);3client.shouldUpdateScreen().then(function(shouldUpdateScreen) {4console.log('shouldUpdateScreen: ' + shouldUpdateScreen);5});6var stf = require('devicefarmer-stf-client');7var client = new stf.Client('localhost', 7100);8client.getDevices().then(function(devices) {9console.log('devices: ' + JSON.stringify(devices));10});11getDevices()12getDevice(serial)13getDeviceByOwner(owner)14getDeviceByGroup(group)15getDeviceByProvider(provider)16getDeviceByUser(user)17addDevice(serial)18removeDevice(serial)19getDeviceUsage(serial)20getDeviceConnectUrl(serial)21getDeviceConnectUrlWithParams(serial, params)22getDeviceConnectUrlWithToken(serial, token)23getDeviceConnectUrlWithTokenAndParams(serial, token, params)24getDeviceConnectUrlWithTokenAndParamsAndTimeout(serial, token, params, timeout)25getDeviceConnectUrlWithParamsAndTimeout(serial, params, timeout)26getDeviceDisconnectUrl(serial)
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!!