Best JavaScript code snippet using playwright-internal
data_mnist.js
Source: data_mnist.js
1/**2 * @license3 * Copyright 2019 Google LLC. All Rights Reserved.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/**18 * Provides methods and classes that support loading data from19 * both MNIST and Fashion MNIST datasets.20 */21import * as tf from '@tensorflow/tfjs';22import * as fs from 'fs';23import * as http from 'http';24import * as https from 'https';25import * as path from 'path';26import * as util from 'util';27import * as zlib from 'zlib';28const exists = util.promisify(fs.exists);29const mkdir = util.promisify(fs.mkdir);30const readFile = util.promisify(fs.readFile);31const rename = util.promisify(fs.rename);32// Shared specs for the MNIST and Fashion MNIST datasets.33const IMAGE_HEADER_MAGIC_NUM = 2051;34const IMAGE_HEADER_BYTES = 16;35const IMAGE_HEIGHT = 28;36const IMAGE_WIDTH = 28;37const IMAGE_FLAT_SIZE = IMAGE_HEIGHT * IMAGE_WIDTH;38const LABEL_HEADER_MAGIC_NUM = 2049;39const LABEL_HEADER_BYTES = 8;40const LABEL_RECORD_BYTE = 1;41const LABEL_FLAT_SIZE = 10;42// Downloads a test file only once and returns the buffer for the file.43export async function fetchOnceAndSaveToDiskWithBuffer(44 baseURL, destDir, filename) {45 return new Promise(async (resolve, reject) => {46 const url = `${baseURL}${filename}.gz`;47 const localPath = path.join(destDir, filename);48 if (await exists(localPath)) {49 resolve(readFile(localPath));50 return;51 }52 const file = fs.createWriteStream(filename);53 console.log(` * Downloading from: ${url}`);54 let httpModule;55 if (url.indexOf('https://') === 0) {56 httpModule = https;57 } else if (url.indexOf('http://') === 0) {58 httpModule = http;59 } else {60 return reject(`Unrecognized protocol in URL: ${url}`);61 }62 httpModule.get(url, (response) => {63 const unzip = zlib.createGunzip();64 response.pipe(unzip).pipe(file);65 unzip.on('end', async () => {66 await rename(filename, localPath);67 resolve(readFile(localPath));68 });69 });70 });71}72function loadHeaderValues(buffer, headerLength) {73 const headerValues = [];74 for (let i = 0; i < headerLength / 4; i++) {75 // Header data is stored in-order (aka big-endian)76 headerValues[i] = buffer.readUInt32BE(i * 4);77 }78 return headerValues;79}80async function loadImages(baseURL, destDir, filename) {81 const buffer =82 await fetchOnceAndSaveToDiskWithBuffer(baseURL, destDir, filename);83 const headerBytes = IMAGE_HEADER_BYTES;84 const recordBytes = IMAGE_HEIGHT * IMAGE_WIDTH;85 const headerValues = loadHeaderValues(buffer, headerBytes);86 tf.util.assert(87 headerValues[0] === IMAGE_HEADER_MAGIC_NUM,88 () => `Image file header doesn't match expected magic num.`);89 tf.util.assert(90 headerValues[2] === IMAGE_HEIGHT,91 () => `Value in file header (${headerValues[2]}) doesn't ` +92 `match the expected image height ${IMAGE_HEIGHT}`);93 tf.util.assert(94 headerValues[3] === IMAGE_WIDTH,95 () => `Value in file header (${headerValues[3]}) doesn't ` +96 `match the expected image height ${IMAGE_WIDTH}`);97 const images = [];98 let index = headerBytes;99 while (index < buffer.byteLength) {100 const array = new Float32Array(recordBytes);101 for (let i = 0; i < recordBytes; i++) {102 // Normalize the pixel values into the 0-1 interval, from103 // the original 0-255 interval.104 array[i] = buffer.readUInt8(index++) / 255;105 }106 images.push(array);107 }108 tf.util.assert(109 images.length === headerValues[1],110 () => `Actual images length (${images.length} doesn't match ` +111 `value in header (${headerValues[1]})`);112 return images;113}114async function loadLabels(baseURL, destDir, filename) {115 const buffer =116 await fetchOnceAndSaveToDiskWithBuffer(baseURL, destDir, filename);117 const headerBytes = LABEL_HEADER_BYTES;118 const recordBytes = LABEL_RECORD_BYTE;119 const headerValues = loadHeaderValues(buffer, headerBytes);120 tf.util.assert(121 headerValues[0] === LABEL_HEADER_MAGIC_NUM,122 () => `Label file header doesn't match expected magic num.`);123 const labels = [];124 let index = headerBytes;125 while (index < buffer.byteLength) {126 const array = new Int32Array(recordBytes);127 for (let i = 0; i < recordBytes; i++) {128 array[i] = buffer.readUInt8(index++);129 }130 labels.push(array);131 }132 tf.util.assert(133 labels.length === headerValues[1],134 () => `Actual labels length (${images.length} doesn't match ` +135 `value in header (${headerValues[1]})`);136 return labels;137}138/** Helper class to handle loading training and test data. */139export class MnistDataset {140 // MNIST data constants:141 constructor() {142 this.dataset = null;143 this.trainSize = 0;144 this.testSize = 0;145 this.trainBatchIndex = 0;146 this.testBatchIndex = 0;147 }148 getBaseUrlAndFilePaths() {149 return {150 baseUrl: 'https://storage.googleapis.com/cvdf-datasets/mnist/',151 destDir: 'data-mnist',152 trainImages: 'train-images-idx3-ubyte',153 trainLabels: 'train-labels-idx1-ubyte',154 testImages: 't10k-images-idx3-ubyte',155 testLabels: 't10k-labels-idx1-ubyte'156 }157 }158 /** Loads training and test data. */159 async loadData() {160 const baseUrlAndFilePaths = this.getBaseUrlAndFilePaths();161 const baseUrl = baseUrlAndFilePaths.baseUrl;162 const destDir = baseUrlAndFilePaths.destDir;163 if (!(await exists(destDir))) {164 await mkdir(destDir);165 }166 this.dataset = await Promise.all([167 loadImages(baseUrl, destDir, baseUrlAndFilePaths.trainImages),168 loadLabels(baseUrl, destDir, baseUrlAndFilePaths.trainLabels),169 loadImages(baseUrl, destDir, baseUrlAndFilePaths.testImages),170 loadLabels(baseUrl, destDir, baseUrlAndFilePaths.testLabels)171 ]);172 this.trainSize = this.dataset[0].length;173 this.testSize = this.dataset[2].length;174 }175 getTrainData() {176 return this.getData_(true);177 }178 getTestData() {179 return this.getData_(false);180 }181 getData_(isTrainingData) {182 let imagesIndex;183 let labelsIndex;184 if (isTrainingData) {185 imagesIndex = 0;186 labelsIndex = 1;187 } else {188 imagesIndex = 2;189 labelsIndex = 3;190 }191 const size = this.dataset[imagesIndex].length;192 tf.util.assert(193 this.dataset[labelsIndex].length === size,194 `Mismatch in the number of images (${size}) and ` +195 `the number of labels (${this.dataset[labelsIndex].length})`);196 // Only create one big array to hold batch of images.197 const imagesShape = [size, IMAGE_HEIGHT, IMAGE_WIDTH, 1];198 const images = new Float32Array(tf.util.sizeFromShape(imagesShape));199 const labels = new Int32Array(tf.util.sizeFromShape([size, 1]));200 let imageOffset = 0;201 let labelOffset = 0;202 for (let i = 0; i < size; ++i) {203 images.set(this.dataset[imagesIndex][i], imageOffset);204 labels.set(this.dataset[labelsIndex][i], labelOffset);205 imageOffset += IMAGE_FLAT_SIZE;206 labelOffset += 1;207 }208 return {209 images: tf.tensor4d(images, imagesShape),210 labels: tf.oneHot(tf.tensor1d(labels, 'int32'), LABEL_FLAT_SIZE).toFloat()211 };212 }213}214export class FashionMnistDataset extends MnistDataset {215 getBaseUrlAndFilePaths() {216 return {217 baseUrl: 'http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/',218 destDir: 'data-fashion-mnist',219 trainImages: 'train-images-idx3-ubyte',220 trainLabels: 'train-labels-idx1-ubyte',221 testImages: 't10k-images-idx3-ubyte',222 testLabels: 't10k-labels-idx1-ubyte'223 }224 }...
FormOne.js
Source: FormOne.js
1import React from 'react';2export default class FormOne extends React.Component{3 constructor(props){4 super(props);5 }6 onTodoChange = (value) =>{7 this.setState({8 name: value9 });10 }11 render(){12 let { headervalues } = this.props;13 console.log(headervalues);14 let headerPrint = null;15 let setUI,leftCol1,midCol1, rightCol1, leftCol2, midCol2, rightCol2 = null;16 17 18 if(headervalues[0]['column_0'].length>0)19 {20 21 leftCol1 = headervalues[0]['column_0'].map((val,index)=>{ 22 let label, field = null;23 if(val.labelEdit==='N')24 {25 label = <label className="wid200">{val.label}:</label>26 }27 else28 {29 label = <div className="wid200"><input type="text" name={val.id+"_label"} defaultValue={val.label} onChange={e => this.onTodoChange(e.target.value)}/></div>30 }31 field = <input type="text" name={val.id}/> 32 33 return(34 <div key={val.id} className="setbox pad1">35 {label}36 {field}37 </div>38 )39 })40 }41 if(headervalues[1]['column_1'].length>0)42 {43 44 midCol1 = headervalues[1]['column_1'].map((val,index)=>{ 45 let label, field = null;46 if(val.labelEdit==='N')47 {48 label = <label className="wid200">{val.label}:</label>49 }50 else51 {52 label = <div className="wid200"><input type="text" name={val.id+"_label"} defaultValue={val.label} onChange={e => this.onTodoChange(e.target.value)}/></div>53 }54 field = <input type="text" name={val.id}/> 55 56 return(57 <div key={val.id} className="setbox pad1">58 {label}59 {field}60 </div>61 )62 })63 }64 if(headervalues[2]['column_2'].length>0)65 {66 67 rightCol1 = headervalues[2]['column_2'].map((val,index)=>{ 68 let label, field = null;69 if(val.labelEdit==='N')70 {71 label = <label className="wid200">{val.label}:</label>72 }73 else74 {75 label = <div className="wid200"><input type="text" name={val.id+"_label"} defaultValue={val.label} onChange={e => this.onTodoChange(e.target.value)}/></div>76 }77 field = <input type="text" name={val.id}/> 78 79 return(80 <div key={val.id} className="setbox pad1">81 {label}82 {field}83 </div>84 )85 })86 }87 if(headervalues[3]['column_3'].length>0)88 {89 90 leftCol2 = headervalues[3]['column_3'].map((val,index)=>{ 91 let label, field = null;92 if(val.labelEdit==='N')93 {94 label = <label className="wid200">{val.label}:</label>95 }96 else97 {98 label = <div className="wid200"><input type="text" name={val.id+"_label"} defaultValue={val.label} onChange={e => this.onTodoChange(e.target.value)}/></div>99 }100 field = <input type="text" name={val.id}/> 101 102 return(103 <div key={val.id} className="setbox pad1">104 {label}105 {field}106 </div>107 )108 })109 }110 if(headervalues[4]['column_4'].length>0)111 {112 113 midCol2 = headervalues[4]['column_4'].map((val,index)=>{ 114 let label, field = null;115 if(val.labelEdit==='N')116 {117 label = <label className="wid200">{val.label}:</label>118 }119 else120 {121 label = <div className="wid200"><input type="text" name={val.id+"_label"} defaultValue={val.label} onChange={e => this.onTodoChange(e.target.value)}/></div>122 }123 field = <input type="text" name={val.id}/> 124 125 return(126 <div key={val.id} className="setbox pad1">127 {label}128 {field}129 </div>130 )131 })132 }133 if(headervalues[5]['column_5'].length>0)134 {135 136 rightCol2 = headervalues[5]['column_5'].map((val,index)=>{ 137 let label, field = null;138 if(val.labelEdit==='N')139 {140 label = <label className="wid200">{val.label}:</label>141 }142 else143 {144 label = <div className="wid200"><input type="text" name={val.id+"_label"} defaultValue={val.label} onChange={e => this.onTodoChange(e.target.value)}/></div>145 }146 field = <input type="text" name={val.id}/> 147 148 return(149 <div key={val.id} className="setbox pad1">150 {label}151 {field}152 </div>153 )154 })155 }156 157 158 159 160 161 return(162 <div className="fullw">163 <div className="txtc sethead">Tax Invoice</div>164 <div id="SenderDetails" className="mt5 bg1 dispt fullw setequal"> 165 <div id="header_col_0" className="disptc vmid">{leftCol1}</div>166 <div id="header_col_1" className="disptc vmid">{midCol1}</div>167 <div id="header_col_2" className="disptc vmid">{rightCol1}</div> 168 </div>169 <div id="RecieverDetails" className="mt5 bg1 dispt fullw setequal">170 <div id="header_col_3" className="disptc vmid">{leftCol2}</div>171 <div id="header_col_4" className="disptc vmid">{midCol2}</div>172 <div id="header_col_5" className="disptc vmid">{rightCol2}</div> 173 </div>174 </div>175 );176 }...
data.js
Source: data.js
1const tf = require("@tensorflow/tfjs");2const assert = require("assert");3const fs = require("fs");4const https = require("https");5const util = require("util");6const zlib = require("zlib");7const readFile = util.promisify(fs.readFile);8// MNIST data constants:9const BASE_URL = "https://storage.googleapis.com/cvdf-datasets/mnist/";10const TRAIN_IMAGES_FILE = "train-images-idx3-ubyte";11const TRAIN_LABELS_FILE = "train-labels-idx1-ubyte";12const TEST_IMAGES_FILE = "t10k-images-idx3-ubyte";13const TEST_LABELS_FILE = "t10k-labels-idx1-ubyte";14const IMAGE_HEADER_MAGIC_NUM = 2051;15const IMAGE_HEADER_BYTES = 16;16const IMAGE_HEIGHT = 28;17const IMAGE_WIDTH = 28;18const IMAGE_FLAT_SIZE = IMAGE_HEIGHT * IMAGE_WIDTH;19const LABEL_HEADER_MAGIC_NUM = 2049;20const LABEL_HEADER_BYTES = 8;21const LABEL_RECORD_BYTE = 1;22const LABEL_FLAT_SIZE = 10;23// Downloads a test file only once and returns the buffer for the file.24async function fetchOnceAndSaveToDiskWithBuffer(filename) {25 return new Promise(resolve => {26 const url = `${BASE_URL}${filename}.gz`;27 if (fs.existsSync(filename)) {28 resolve(readFile(filename));29 return;30 }31 const file = fs.createWriteStream(filename);32 console.log(` * Downloading from: ${url}`);33 https.get(url, response => {34 const unzip = zlib.createGunzip();35 response.pipe(unzip).pipe(file);36 unzip.on("end", () => {37 resolve(readFile(filename));38 });39 });40 });41}42function loadHeaderValues(buffer, headerLength) {43 const headerValues = [];44 for (let i = 0; i < headerLength / 4; i++) {45 // Header data is stored in-order (aka big-endian)46 headerValues[i] = buffer.readUInt32BE(i * 4);47 }48 return headerValues;49}50async function loadImages(filename) {51 const buffer = await fetchOnceAndSaveToDiskWithBuffer(filename);52 const headerBytes = IMAGE_HEADER_BYTES;53 const recordBytes = IMAGE_HEIGHT * IMAGE_WIDTH;54 const headerValues = loadHeaderValues(buffer, headerBytes);55 assert.equal(headerValues[0], IMAGE_HEADER_MAGIC_NUM);56 assert.equal(headerValues[2], IMAGE_HEIGHT);57 assert.equal(headerValues[3], IMAGE_WIDTH);58 const images = [];59 let index = headerBytes;60 while (index < buffer.byteLength) {61 const array = new Float32Array(recordBytes);62 for (let i = 0; i < recordBytes; i++) {63 // Normalize the pixel values into the 0-1 interval, from64 // the original 0-255 interval.65 array[i] = buffer.readUInt8(index++) / 255;66 }67 images.push(array);68 }69 assert.equal(images.length, headerValues[1]);70 return images;71}72async function loadLabels(filename) {73 const buffer = await fetchOnceAndSaveToDiskWithBuffer(filename);74 const headerBytes = LABEL_HEADER_BYTES;75 const recordBytes = LABEL_RECORD_BYTE;76 const headerValues = loadHeaderValues(buffer, headerBytes);77 assert.equal(headerValues[0], LABEL_HEADER_MAGIC_NUM);78 const labels = [];79 let index = headerBytes;80 while (index < buffer.byteLength) {81 const array = new Int32Array(recordBytes);82 for (let i = 0; i < recordBytes; i++) {83 array[i] = buffer.readUInt8(index++);84 }85 labels.push(array);86 }87 assert.equal(labels.length, headerValues[1]);88 return labels;89}90/** Helper class to handle loading training and test data. */91class MnistDataset {92 constructor() {93 this.dataset = null;94 this.trainSize = 0;95 this.testSize = 0;96 this.trainBatchIndex = 0;97 this.testBatchIndex = 0;98 }99 /** Loads training and test data. */100 async loadData() {101 this.dataset = await Promise.all([102 loadImages(TRAIN_IMAGES_FILE),103 loadLabels(TRAIN_LABELS_FILE),104 loadImages(TEST_IMAGES_FILE),105 loadLabels(TEST_LABELS_FILE)106 ]);107 this.trainSize = this.dataset[0].length;108 this.testSize = this.dataset[2].length;109 }110 getTrainData() {111 return this.getData_(true);112 }113 getTestData() {114 return this.getData_(false);115 }116 getData_(isTrainingData) {117 let imagesIndex;118 let labelsIndex;119 if (isTrainingData) {120 imagesIndex = 0;121 labelsIndex = 1;122 } else {123 imagesIndex = 2;124 labelsIndex = 3;125 }126 const size = this.dataset[imagesIndex].length;127 tf.util.assert(128 this.dataset[labelsIndex].length === size,129 `Mismatch in the number of images (${size}) and ` +130 `the number of labels (${this.dataset[labelsIndex].length})`131 );132 // Only create one big array to hold batch of images.133 const imagesShape = [size, IMAGE_HEIGHT, IMAGE_WIDTH, 1];134 const images = new Float32Array(tf.util.sizeFromShape(imagesShape));135 const labels = new Int32Array(tf.util.sizeFromShape([size, 1]));136 let imageOffset = 0;137 let labelOffset = 0;138 for (let i = 0; i < size; ++i) {139 images.set(this.dataset[imagesIndex][i], imageOffset);140 labels.set(this.dataset[labelsIndex][i], labelOffset);141 imageOffset += IMAGE_FLAT_SIZE;142 labelOffset += 1;143 }144 return {145 images: tf.tensor4d(images, imagesShape),146 labels: tf.oneHot(tf.tensor1d(labels, "int32"), LABEL_FLAT_SIZE).toFloat()147 };148 }149}...
common.gs
Source: common.gs
1/*2 * Copyright (c) 2020, salesforce.com, inc.3 * All rights reserved.4 * SPDX-License-Identifier: BSD-3-Clause5 * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause6 */7var residualRiskSheet = "Residual Risk"8var residualDataSheet = "Raw Residual Data"9var residualRiskFactorSheet = "ResidualRiskFactors"10var inherentRiskSheet = "Inherent Risk";11function mapRowToSystem(rowValues, headerValues) {12 var ret = {};13 for(var i = 0; i < headerValues.length; i++) {14 if(i < rowValues.length) {15 ret[headerValues[i]] = rowValues[i];16 } else {17 ret[headerValues[i]] = null;18 }19 }20 return ret;21}22function mapFormToSystem(systemForm, headerValues) {23 var ret = {};24 for(var i = 0; i < headerValues.length; i++) {25 if(systemForm[headerValues[i]]) {26 ret[headerValues[i].toString()] = systemForm[headerValues[i].toString()];27 } else {28 ret[headerValues[i].toString()] = null;29 }30 }31 return ret;32}33function systemToString(systemData) {34 var st = "systemData:";35 for(var i = 0; i < Object.keys(systemData).length; i++) {36 st += Object.keys(systemData)[i] + " / " + systemData[Object.keys(systemData)[i]] + "\n";37 }38 return st;39}40function ratingFormula(rowNum, colLetter) {41 return '=VLOOKUP(' + colLetter + rowNum + ',{1,"Very Low - 1";1.50,"Low - 2";2.50,"Moderate - 3";3.50,"High - 4";4.50,"Very High - 5"},2,1)'42}43function riskLevelFormula(rowNum, likelihoodRatingCol, impactRatingCol) {44 return '=INDEX(RatingTable,MATCH(' + likelihoodRatingCol + rowNum + ',RatingLikelihood,0), MATCH(' + impactRatingCol + rowNum + ',RatingImpact,0))';45}46function inherentWithNoResidual() {47 var inh = listInherentSystemNames();48 var res = listResidualSystemNames();49 var ret = inh.filter(function (name) { return res.indexOf(name) == -1 }).map(function (value, index, array) { return value.replace("'","").replace('"','')}).sort(); 50 return ret;51}52function listInherentSystemNames() {53 var ss = SpreadsheetApp.getActiveSpreadsheet();54 var sheet = ss.getSheetByName(inherentRiskSheet);55 var values = sheet.getRange(2,1,sheet.getLastRow(),2).getValues();56 var ret = [];57 for(var i = 0; i < values.length; i++) {58 if(values[i][1] && values[i][1] != "" && ret.indexOf(values[i][1]) == -1) {59 ret.push(values[i][1]);60 }61 }62 return ret;63}64function listResidualSystemNames() {65 var ss = SpreadsheetApp.getActiveSpreadsheet();66 var sheet = ss.getSheetByName(residualRiskSheet);67 var values = sheet.getRange(2,1,sheet.getLastRow(),2).getValues();68 var ret = [];69 for(var i = 0; i < values.length; i++) {70 if(values[i][1] && values[i][1] != "" && ret.indexOf(values[i][1]) == -1) {71 ret.push(values[i][1]);72 }73 }74 return ret;...
header-values.any.js
Source: header-values.any.js
1// META: title=Header value test2// META: global=window,worker3// META: timeout=long4"use strict";5// Invalid values6[0, 0x0A, 0x0D].forEach(val => {7 val = "x" + String.fromCharCode(val) + "x"8 // XMLHttpRequest is not available in service workers9 if (!self.GLOBAL.isWorker()) {10 test(() => {11 let xhr = new XMLHttpRequest()12 xhr.open("POST", "/")13 assert_throws_dom("SyntaxError", () => xhr.setRequestHeader("value-test", val))14 }, "XMLHttpRequest with value " + encodeURI(val) + " needs to throw")15 }16 promise_test(t => promise_rejects_js(t, TypeError, fetch("/", { headers: {"value-test": val} })), "fetch() with value " + encodeURI(val) + " needs to throw")17})18// Valid values19let headerValues =[]20for(let i = 0; i < 0x100; i++) {21 if(i === 0 || i === 0x0A || i === 0x0D) {22 continue23 }24 headerValues.push("x" + String.fromCharCode(i) + "x")25}26var url = "../resources/inspect-headers.py?headers="27headerValues.forEach((_, i) => {28 url += "val" + i + "|"29})30// XMLHttpRequest is not available in service workers31if (!self.GLOBAL.isWorker()) {32 async_test((t) => {33 let xhr = new XMLHttpRequest()34 xhr.open("POST", url)35 headerValues.forEach((val, i) => {36 xhr.setRequestHeader("val" + i, val)37 })38 xhr.onload = t.step_func_done(() => {39 headerValues.forEach((val, i) => {40 assert_equals(xhr.getResponseHeader("x-request-val" + i), val)41 })42 })43 xhr.send()44 }, "XMLHttpRequest with all valid values")45}46promise_test((t) => {47 const headers = new Headers48 headerValues.forEach((val, i) => {49 headers.append("val" + i, val)50 })51 return fetch(url, { headers }).then((res) => {52 headerValues.forEach((val, i) => {53 assert_equals(res.headers.get("x-request-val" + i), val)54 })55 })...
CSVExporter.js
Source: CSVExporter.js
1export class CSVExporter {2 static toString (points) {3 let string = '';4 let attributes = Object.keys(points.data)5 .filter(a => a !== 'normal')6 .sort((a, b) => {7 if (a === 'position') return -1;8 if (b === 'position') return 1;9 if (a === 'color') return -1;10 if (b === 'color') return 1;11 });12 let headerValues = [];13 for (let attribute of attributes) {14 let itemSize = points.data[attribute].length / points.numPoints;15 if (attribute === 'position') {16 headerValues = headerValues.concat(['x', 'y', 'z']);17 } else if (attribute === 'color') {18 headerValues = headerValues.concat(['r', 'g', 'b', 'a']);19 } else if (itemSize > 1) {20 for (let i = 0; i < itemSize; i++) {21 headerValues.push(`${attribute}_${i}`);22 }23 } else {24 headerValues.push(attribute);25 }26 }27 string = headerValues.join(', ') + '\n';28 for (let i = 0; i < points.numPoints; i++) {29 let values = [];30 for (let attribute of attributes) {31 let itemSize = points.data[attribute].length / points.numPoints;32 let value = points.data[attribute]33 .subarray(itemSize * i, itemSize * i + itemSize)34 .join(', ');35 values.push(value);36 }37 string += values.join(', ') + '\n';38 }39 return string;40 }...
Using AI Code Generation
1const { webkit } = require('playwright');2(async () => {3 const browser = await webkit.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const headers = await page.route('**/*', route => {7 console.log(route.request().headers());8 route.continue();9 });10 await browser.close();11})();12- Enter Check in date as Next month 15th (May 15) and Check out as start date+513const { webkit } = require('playwright');14(async () => {15 const browser = await webkit.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 await page.click('text="Hotels"');19 await page.fill('#city', 'Goa, India');20 await page.click('text="Goa, India"');21 await page.fill('input[name="checkin"]', '15/05/2021');22 await page.fill('input[name="checkout"]', '20/05/2021');23 await page.click('text="ROOMS & GUESTS"');24 await page.click('button:has-text("2 Adults")');25 await page.click('button:has-text("1 Child")');26 await page.click('text="12"');27 await page.click('button
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const headers = await page._client.send('Network.getAllCookies');7 console.log(headers);8 await browser.close();9})();10[MIT](LICENSE)
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const headers = await page._client.send('Network.getAllCookies');6 console.log(headers);7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const page = await browser.newPage();13 const headers = await page._client.send('Network.getAllCookies');14 console.log(headers);15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const page = await browser.newPage();21 const headers = await page._client.send('Network.getAllCookies');22 console.log(headers);23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const page = await browser.newPage();29 const headers = await page._client.send('Network.getAllCookies');30 console.log(headers);31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const page = await browser.newPage();37 const headers = await page._client.send('Network.getAllCookies');38 console.log(headers);39 await browser.close();40})();
Using AI Code Generation
1import { chromium } from 'playwright';2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const headers = await page._client.send('Network.getAllCookies');7 console.log(headers);8 await browser.close();9})();10[MIT](
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.route('**', route => {7 const headers = route.request().headers();8 headers['foo'] = 'bar';9 route.continue({ headers });10 });11 const headers = await page.evaluate(() => JSON.stringify(window.__PLAYWRIGHT_TEST_HOOKS__.headerValues));12 console.log(headers);13 await browser.close();14})();
Using AI Code Generation
1const {chromium, webkit, firefox} = require('playwright');2const {headerValues} = require('playwright/lib/utils/utils');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const headers = await headerValues(page);8 console.log(headers);9 await browser.close();10})();11### headerValues(page: Page): Promise<Record<string, string>>
Jest + Playwright - Test callbacks of event-based DOM library
firefox browser does not start in playwright
Is it possible to get the selector from a locator object in playwright?
How to run a list of test suites in a single file concurrently in jest?
Running Playwright in Azure Function
firefox browser does not start in playwright
This question is quite close to a "need more focus" question. But let's try to give it some focus:
Does Playwright has access to the cPicker object on the page? Does it has access to the window object?
Yes, you can access both cPicker and the window object inside an evaluate call.
Should I trigger the events from the HTML file itself, and in the callbacks, print in the DOM the result, in some dummy-element, and then infer from that dummy element text that the callbacks fired?
Exactly, or you can assign values to a javascript variable:
const cPicker = new ColorPicker({
onClickOutside(e){
},
onInput(color){
window['color'] = color;
},
onChange(color){
window['result'] = color;
}
})
And then
it('Should call all callbacks with correct arguments', async() => {
await page.goto(`http://localhost:5000/tests/visual/basic.html`, {waitUntil:'load'})
// Wait until the next frame
await page.evaluate(() => new Promise(requestAnimationFrame))
// Act
// Assert
const result = await page.evaluate(() => window['color']);
// Check the value
})
Check out the latest blogs from LambdaTest on this topic:
Native apps are developed specifically for one platform. Hence they are fast and deliver superior performance. They can be downloaded from various app stores and are not accessible through browsers.
One of the essential parts when performing automated UI testing, whether using Selenium or another framework, is identifying the correct web elements the tests will interact with. However, if the web elements are not located correctly, you might get NoSuchElementException in Selenium. This would cause a false negative result because we won’t get to the actual functionality check. Instead, our test will fail simply because it failed to interact with the correct element.
Smartphones have changed the way humans interact with technology. Be it travel, fitness, lifestyle, video games, or even services, it’s all just a few touches away (quite literally so). We only need to look at the growing throngs of smartphone or tablet users vs. desktop users to grasp this reality.
As part of one of my consulting efforts, I worked with a mid-sized company that was looking to move toward a more agile manner of developing software. As with any shift in work style, there is some bewilderment and, for some, considerable anxiety. People are being challenged to leave their comfort zones and embrace a continuously changing, dynamic working environment. And, dare I say it, testing may be the most ‘disturbed’ of the software roles in agile development.
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!!