Best JavaScript code snippet using playwright-internal
light-viz-cli.js
Source:light-viz-cli.js
...6const path = require('path');7const program = require('commander');8let paraview = process.env.PARAVIEW_HOME;9require('shelljs/global');10function quotePath(str) {11 return '"' + str + '"';12}13program14 .version('1.0.0')15 .option('-p, --port [8080]', 'Start web server with given port', 8080)16 .option('-d, --data [directory]', 'Data directory to serve')17 .option('-s, --server-only', 'Do not open the web browser\n')18 .option('--paraview [path]', 'Provide the ParaView root path to use')19 .option('--data-analysis', 'Inspect data directory and compute metadata\n')20 .option('--config [path]', 'Provide a Lightviz config file to use')21 .option(22 '--profile [profile]',23 'Specify which profile from the config file to use\n'24 )25 .option(26 '--add-dataset [path]',27 'Specify a dataset to add to the given data directory. Requires the description and data flags'28 )29 .option(30 '--description [description]',31 'Specify the description for the dataset being added'32 )33 .option(34 '--autoApply',35 'Optional for use with --add-dataset. Specifies that apply/reset buttons are not needed with the dataset'36 )37 .option('--virtual-env [path]', 'Path to virtual environment to use')38 .option('--settings-lod-threshold [102400]', 'LOD Threshold in Megabytes\n')39 .parse(process.argv);40// Try to find a paraview directory inside /Applications or /opt41const pvPossibleBasePath = [];42['/Applications', '/opt', '/usr/local/opt/'].forEach(function(directoryPath) {43 shell.ls(directoryPath).forEach(function(fileName) {44 if (fileName.toLowerCase().indexOf('paraview') !== -1) {45 pvPossibleBasePath.push(path.join(directoryPath, fileName));46 }47 });48});49if (!paraview) {50 paraview = [];51 [program.paraview].concat(pvPossibleBasePath).forEach(function(directory) {52 try {53 if (fs.statSync(directory).isDirectory()) {54 paraview.push(directory);55 }56 } catch (err) {57 // skip58 }59 });60}61if (!process.argv.slice(2).length || !program.help || paraview.length === 0) {62 program.outputHelp();63 process.exit(0);64}65var pvPythonExecs = shell.find(paraview).filter(function(file) {66 return file.match(/pvpython$/) || file.match(/pvpython.exe$/);67});68if (pvPythonExecs.length < 1) {69 console.log(70 'Could not find pvpython in your ParaView HOME directory ($PARAVIEW_HOME)'71 );72 program.outputHelp();73} else {74 if (program.addDataset) {75 if (!program.data) {76 console.log(77 'Adding data requires specifying the data directory to use with -d or --data'78 );79 process.exit(1);80 }81 if (!program.description) {82 console.log(83 'Adding data requires specifying the description of the dataset with --description'84 );85 }86 const addDatasetCmdLine = [87 quotePath(pvPythonExecs[0]),88 '-dr',89 quotePath(90 path.normalize(path.join(__dirname, '../server/add_dataset.py'))91 ),92 '--data-dir',93 quotePath(program.data),94 '--file',95 quotePath(program.addDataset),96 '--description',97 quotePath(program.description),98 ];99 if (program.autoApply) {100 addDatasetCmdLine.push('--autoApply');101 }102 if (program.virtualEnv) {103 cmdLine.push('--virtual-env');104 cmdLine.push(program.virtualEnv);105 }106 console.log(107 '\n==============================================================================='108 );109 console.log('| Execute:');110 console.log('| $', addDatasetCmdLine.join('\n|\t'));111 console.log(112 '===============================================================================\n'113 );114 shell115 .exec(addDatasetCmdLine.join(' '), { async: true })116 .stdout.on('data', function(data) {117 if (data.indexOf('Starting factory') !== -1) {118 // Open browser if asked119 if (!program.serverOnly) {120 require('open')('http://localhost:' + program.port);121 }122 }123 });124 } else {125 const cmdLine = [126 quotePath(pvPythonExecs[0]),127 '-dr',128 '--force-offscreen-rendering',129 quotePath(130 path.normalize(path.join(__dirname, '../server/pvw-light-viz.py'))131 ),132 '--content',133 quotePath(path.normalize(path.join(__dirname, '../dist'))),134 '--port',135 program.port,136 ];137 if (program.data) {138 cmdLine.push('--data');139 cmdLine.push(quotePath(program.data));140 // cmdLine.push('--fs-endpoints');141 // cmdLine.push('ds:' + program.data);142 }143 if (program.config) {144 cmdLine.push('--config');145 cmdLine.push(quotePath(program.config));146 }147 if (program.profile) {148 cmdLine.push('--profile');149 cmdLine.push(quotePath(program.profile));150 }151 if (program.virtualEnv) {152 cmdLine.push('--virtual-env');153 cmdLine.push(program.virtualEnv);154 }155 if (program.settingsLodThreshold) {156 cmdLine.push('--settings-lod-threshold');157 cmdLine.push(program.settingsLodThreshold);158 }159 console.log(160 '\n==============================================================================='161 );162 console.log('| Execute:');163 console.log('| $', cmdLine.join('\n|\t'));...
bittrex.js
Source:bittrex.js
1'use strict';2/**3 * Copyright 2018 Universal Health Coin4 * 5 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), 6 * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,7 * 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:8 * 9 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.10 * 11 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 12 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 13 * 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 14 * IN THE SOFTWARE.15 * 16 * Developed on behalf of Universal Health Coin by the Mohawk mHealth & eHealth Development & Innovation Centre (MEDIC)17 */18 const request = require("request"),19 exception = require("../exception"),20 uhx = require("../uhx");21 module.exports = class BittrexClient {22 /**23 * 24 * @param {*} quoteRequest The quote request or array of requests25 * @param {string} quoteRequest.from The asset code which is the source 26 * @param {string} quoteRequest.to The asset code which is the target 27 * @param {Array} quoteRequest.via An array of codes to establish the from>to quote28 * @return {number} The identified / calculated exchange rate29 * @example Fetch USD<>XLM price via BTC30 * var client = new BittrexClient();31 * client.getExchange("XLM", "USD", ["BTC"]);32 */33 async getExchange(quoteRequest) {34 // Establish the quote path35 if(quoteRequest && !Array.isArray(quoteRequest))36 quoteRequest = [quoteRequest];37 // Promise 38 return new Promise((fulfill, reject) => {39 request("https://bittrex.com/api/v2.0/pub/markets/GetMarketSummaries",40 function(err, res, body) {41 if(err) {42 uhx.log.error(`HTTP ERR: ${err}`)43 reject(new exception.Exception("Error contacting BitTrex API", exception.ErrorCodes.COM_FAILURE, err));44 }45 else if(res.statusCode == 200) {46 var response = JSON.parse(body);47 48 var retVal = [];49 quoteRequest.forEach((quote) => {50 // From Code is USD or EUR we need to tether51 if(quote.from == "USD" || quote.from == "EUR")52 quote.from += "T";53 if(quote.to == "USD" || quote.to == "EUR")54 quote.to += "T";55 if(quote.via && !Array.isArray(quote.via))56 quote.via = [quote.via];57 58 // Quote path59 var quotePath = quote.via || [];60 quotePath.push(quote.from);61 quotePath.unshift(quote.to);62 // Calculate quote63 var currency = quotePath.shift();64 var quote = 1;65 while(quotePath.length > 0) {66 var base = quotePath.shift();67 if(base == currency) continue;68 var tradePair = response.result.find((o)=> o.Market.MarketCurrency == currency && o.Market.BaseCurrency == base );69 if(!tradePair)70 reject(new exception.NotFoundException(`Trade pair ${currency}>${base} not valid`, exception.ErrorCodes.NOT_FOUND));71 else 72 {73 quote *= tradePair.Summary.Bid;74 uhx.log.verbose(`${currency}>${base} = ${base.bid} ===> ${quote.from}>${base} = ${quote}`)75 }76 currency = base;77 }78 retVal.push(quote);79 });80 fulfill(retVal);81 }82 })83 });84 }...
platform.js
Source:platform.js
...78 }79 return path;80}81// Quote backslashes82function quotePath(path) {83 return path.replace(/\\/g, "\\\\");84}85// Return path with unix style separators86function unixPath(path) {87 return path.replace(/\\/g, "/");88}89// Return path with win style separators90function winPath(path) {91 return path.replace(/\//g, "\\");92}93/******************************** Initialize *********************************/94dojo.ready(function initialize() {95 mcc.util.dbg("Platform utilities module initialized");96});
pvw-divvy-cli.js
Source:pvw-divvy-cli.js
...5 program = require('commander'),6 paraview = process.env.PARAVIEW_HOME,7 pkg = require('../package.json'),8 version = /semantically-release/.test(pkg.version) ? 'development version' : pkg.version;9function quotePath(str) {10 return '"' + str + '"';11}12program13 .version(version)14 .option('-p, --port [8080]', 'Start web server with given port', 8080)15 .option('-d, --data [filePath]', 'Data to load')16 .option('-s, --server-only', 'Do not open the web browser\n')17 .option('--virtual-env [path]', 'Path to virtual environment to use\n')18 .option('--paraview [path]', 'Provide the ParaView root path to use\n')19 .parse(process.argv);20// Try to find a paraview directory inside /Applications or /opt21const pvPossibleBasePath = [];22['/Applications', '/opt', '/usr/local/opt/'].forEach(function (directoryPath) {23 shell.ls(directoryPath).forEach(function (fileName) {24 if (fileName.toLowerCase().indexOf('paraview') !== -1) {25 pvPossibleBasePath.push(path.join(directoryPath, fileName));26 }27 });28});29if(!paraview) {30 paraview = [];31 [program.paraview].concat(pvPossibleBasePath).forEach(function(directory){32 try {33 if(fs.statSync(directory).isDirectory()) {34 paraview.push(directory);35 }36 } catch(err) {37 // skip38 }39 });40}41if (!process.argv.slice(2).length || !program.help || paraview.length === 0) {42 program.outputHelp();43 process.exit(0);44}45var pvPythonExecs = shell.find(paraview).filter(function(file) { return file.match(/pvpython$/) || file.match(/pvpython.exe$/); });46if(pvPythonExecs.length < 1) {47 console.log('Could not find pvpython in your ParaView HOME directory ($PARAVIEW_HOME)');48 program.outputHelp();49} else {50 const cmdLine = [51 quotePath(pvPythonExecs[0]), '-dr',52 quotePath(path.normalize(path.join(__dirname, '../Server/pvw-divvy.py'))),53 '--content', quotePath(path.normalize(path.join(__dirname, '../dist'))),54 '--port', program.port,55 '--data', quotePath(program.data),56 ];57 if (program.virtualEnv) {58 cmdLine.push('--virtual-env');59 cmdLine.push(program.virtualEnv);60 }61 console.log('\n===============================================================================');62 console.log('| Execute:');63 console.log('| $', cmdLine.join('\n|\t'));64 console.log('===============================================================================\n');65 shell.exec(cmdLine.join(' '), { async: true }).stdout.on('data', function(data) {66 if (data.indexOf('Starting factory') !== -1) {67 // Open browser if asked68 if (!program.serverOnly) {69 require('open')('http://localhost:' + program.port);...
pathchooser.js
Source:pathchooser.js
1{% autoescape true %}2var submit = true;3{% if absolute %}4var cwd = "{{oldfile|default(cwd, True)|abspath|quotepath|replace('\\', '\\\\')}}";5var isabsolute = true;6{% else %}7var cwd = "{{oldfile|default(cwd, True)|relpath|quotepath|replace('\\', '\\\\')}}";8var isabsolute = false;9{% endif %}10{% if type == 'folder' %} {# browsing for folder #}11var abspath = "/pathchooser/{{cwd|abspath|quotepath|replace('\\', '\\\\')}}";12var relpath = "/pathchooser/{{cwd|relpath|quotepath|replace('\\', '\\\\')}}";13{% else %} {# browsing for file #}14var abspath = "/filechooser/{{oldfile|default(cwd, True)|abspath|quotepath|replace('\\', '\\\\')}}";15var relpath = "/filechooser/{{oldfile|default(cwd, True)|relpath|quotepath|replace('\\', '\\\\')}}";16{% endif %}17document.addEventListener("readystatechange", function(event) {18 if (this.readyState === "complete") {19 document.getElementById("tbody").style.height = (window.innerHeight - 25) + "px";20 window.onresize = function (event) {21 document.getElementById("tbody").style.height = (window.innerHeight - 25) + "px";22 };23 var clickables = document.getElementsByClassName("tr-clickable");24 for (var i = 0; i < clickables.length; i++) {25 clickables[i].onclick = (function () {26 var onclick = clickables[i].onclick;27 return function (e) {28 if (onclick != null && !onclick()) {29 return false30 }31 if (this.dataset.href !== undefined && this.dataset.href !== "#") {32 window.location.href = this.dataset.href;33 return false34 } else {35 return true;36 }37 }38 })();39 }40 }41});42function updateParent()43{44 if (window.top.SettingsUI != undefined) {45 window.top.SettingsUI.prototype.pathchooserChanged(this);46 }47}48function setInvalid() {49 submit = false;50 cwd = "";51 updateParent();52}53function setValid() {54 submit = true;55 updateParent();56}57function setFile(fullpath, name)58{59 cwd = fullpath;60 {% if type == "file" %} {# browsing for file #}61 abspath = "/filechooser/{{cwd|abspath|quotepath|replace('\\', '\\\\')}}" + name;62 relpath = "/filechooser/{{cwd|relpath|quotepath|replace('\\', '\\\\')}}" + name;63 {% endif %}64 setValid();65}66 ...
utils.js
Source:utils.js
1const chalk = require('chalk');2const infoLabel = chalk.inverse.green('INFO');3const warningLabel = chalk.inverse('WARN');4const errorLabel = chalk.inverse('ERROR');5const { exec } = require('child_process');6const utils = {};7utils.log = function (msg) {8 console.log(`${infoLabel} ${msg}`);9};10utils.warn = function (msg) {11 console.log(chalk.yellow(`${warningLabel} ${msg}`));12};13utils.error = function (msg) {14 console.log(chalk.red(`${errorLabel} ${msg}`));15 process.exit(1);16};17utils.isEmpty = function (obj) {18 if (typeof obj === 'undefined' || obj === null || obj === '') {19 return true;20 } else {21 return false;22 }23};24utils.parseGitCloneUrl = function (url, username, password) {25 // https://gitlab.bingosoft.net/linkide/source-template-hub.git26 if (/^https?:\/\//.test(url.toLowerCase())) {27 return url.replace(RegExp.lastMatch, `${RegExp.lastMatch}${username.replace(/@/g, '%40')}:${password.replace(/@/g, '%40')}@`);28 } else {29 return new Error('repository URL ä¸æ¯ HTTP/HTTPS æ ¼å¼');30 }31};32utils.getGitUrlName = function (url) {33 return url.substr(url.lastIndexOf('/') + 1).replace('.git', '');34};35utils.randomString = function (length) {36 const len = length || 32;37 const $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';38 const base = $chars.length;39 let result = '';40 for (let i = 0; i < len; i++) {41 const pos = Math.random() * base;42 result += $chars.charAt(~~pos);43 }44 return result.toLowerCase();45};46/**47 * åå§å Git configï¼é¿å
å
¶æ¬èº«åå¨çä¸äºé®é¢48 */49utils.initGitConfig = function () {50 exec('git config --global --list', (err, stdout, stderr) => {51 if (err) {52 console.error(err);53 } else {54 if (!stdout.includes('http.sslverify=false')) {55 console.info('Set git global config http.sslverify to false');56 exec('git config --global http.sslverify false');57 }58 if (!stdout.includes('core.quotepath=false')) {59 console.info('Set git global config core.quotepath to false');60 exec('git config --global core.quotepath false');61 }62 }63 });64};...
problem-8.test.js
Source:problem-8.test.js
1const { quotePath, quotePaths } = require('./solutions');2describe('Problem 8 - quotePath() and quotePaths() functions', function() {3 describe('quotePath()', function() {4 test('absolute Unix paths without spaces should be unchanged', function() {5 let path = '/a/b/c';6 expect(quotePath(path)).toBe(path);7 });8 test('absolute Unix paths with spaces should be quoted', function() {9 let path = '/a/b /c d';10 expect(quotePath(path)).toBe('"/a/b /c d"');11 });12 test('absolute Windows paths without spaces should be unchanged', function() {13 let path = 'C:\\a\\b\\c';14 expect(quotePath(path)).toBe(path);15 });16 test('absolute Windows paths with spaces should be quoted', function() {17 let path = 'C:\\a\\b \\c d';18 expect(quotePath(path)).toBe('"C:\\a\\b \\c d"');19 });20 test('relative paths without spaces should be unchanged', function() {21 let path = 'a';22 expect(quotePath(path)).toBe(path);23 });24 test('relative paths with spaces should be quoted', function() {25 let path = 'a b';26 expect(quotePath(path)).toBe('"a b"');27 });28 });29 describe('quotePaths()', function() {30 test('passing a single path should work the same as quotePath()', function() {31 expect(quotePaths('a b')).toBe('"a b"');32 expect(quotePaths('ab')).toBe('ab');33 expect(quotePaths('/a/b /c d')).toBe('"/a/b /c d"');34 expect(quotePaths('/a/b/cd')).toBe('/a/b/cd');35 expect(quotePaths('C:\\a\\b \\c d')).toBe('"C:\\a\\b \\c d"');36 expect(quotePaths('C:\\a\\b\\cd')).toBe('C:\\a\\b\\cd');37 });38 test('passing multiple paths should result in a space delimited list of paths', function() {39 expect(quotePaths('a', 'b')).toBe('a b');40 expect(quotePaths('a', 'b')).toBe('a b');41 expect(quotePaths('a', 'b', 'c')).toBe('a b c');42 expect(quotePaths('a', 'b', 'c', 'd')).toBe('a b c d');43 });44 test('passing paths with and without spaces works as expected', function() {...
task2.js
Source:task2.js
1var express = require('express');2var router =express.Router();3router.get('/',function(req,res){4 res.sendFile(__dirname + '/task2.htm')5})6router.get('/:emotion',function(req,res){7 8 emotion = req.params9 emotion= Object.values(emotion);10 var emotions = [11 {12 title: 'happy',13 imagePath: '/images/task2/happy.jpeg',14 quotePath: '/images/task2/happy/happy1.jpg'15 },16 {17 title: 'sad',18 imagePath: '/images/task2/sad.jpeg',19 quotePath: '/images/task2/sad/sad1.jpg'20 },21 {22 title: 'stress',23 imagePath: '/images/task2/stress.jpeg',24 quotePath: '/images/task2/stress/stress1.jpg'25 },26 {27 title: 'angry',28 imagePath: '/images/task2/angry.jpeg',29 quotePath: '/images/task2/angry/angry1.jpg'30 }31 ];32 const found = emotions.find(emoti => emoti.title == emotion)33 console.log(found)34 res.render('task2-hbs',found)35});...
Using AI Code Generation
1const { quotePath } = require('playwright-core/lib/utils/utils');2const path = require('path');3const fs = require('fs');4const os = require('os');5const dir = path.join(os.tmpdir(), 'playwright_tmp_dir');6fs.mkdirSync(dir, { recursive: true });7const filePath = path.join(dir, 'tmp_file.txt');8fs.writeFileSync(filePath, 'Hello world');9const quotedPath = quotePath(filePath);10console.log(quotedPath);11- [Playwright Internal API](
Using AI Code Generation
1const path = require("path");2const { quotePath } = require("playwright/lib/utils/utils");3const pathToTestFile = path.join(__dirname, "test.js");4const quotedPath = quotePath(pathToTestFile);5console.log(quotedPath);6Please read the [contribution guidelines](
Using AI Code Generation
1const { quotePath } = require('playwright/lib/utils/utils');2console.log(quotePath('c:\\test\\test.js'));3const { quotePath } = require('playwright/lib/utils/utils');4console.log(quotePath('c:\\test\\test.js'));5const { quotePath } = require('playwright/lib/utils/utils');6console.log(quotePath('c:\\test\\test.js'));7const { quotePath } = require('playwright/lib/utils/utils');8console.log(quotePath('c:\\test\\test.js'));9const { quotePath } = require('playwright/lib/utils/utils');10console.log(quotePath('c:\\test\\test.js'));11const { quotePath } = require('playwright/lib/utils/utils');12console.log(quotePath('c:\\test\\test.js'));13const { quotePath } = require('playwright/lib/utils/utils');14console.log(quotePath('c:\\test\\test.js'));15const { quotePath } = require('playwright/lib/utils/utils');16console.log(quotePath('c:\\test\\test.js'));
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!