Best JavaScript code snippet using playwright-internal
index.js
Source:index.js
...30];31function startMeasure(baseName) {32 performance.mark(`${baseName}-start`);33}34function endMeasure(baseName) {35 if (atom.inDevMode()) {36 performance.mark(`${baseName}-end`);37 performance.measure(baseName, `${baseName}-start`, `${baseName}-end`);38 // eslint-disable-next-line no-console39 console.log(`${baseName} took: `, performance.getEntriesByName(baseName)[0].duration);40 performance.clearMarks(`${baseName}-end`);41 performance.clearMeasures(baseName);42 }43 performance.clearMarks(`${baseName}-start`);44}45function createRange(editor, data) {46 if (!Object.hasOwnProperty.call(data, 'line') && !Object.hasOwnProperty.call(data, 'column')) {47 // data.line & data.column might be undefined for non-fatal invalid rules,48 // e.g.: "block-no-empty": "foo"49 // Return `false` so Linter will ignore the range50 return false;51 }52 return rangeFromLineNumber(editor, data.line - 1, data.column - 1);53}54export function activate() {55 startMeasure('linter-stylelint: Activation');56 require('atom-package-deps').install('linter-stylelint');57 subscriptions = new CompositeDisposable();58 subscriptions.add(atom.config.observe('linter-stylelint.useStandard', (value) => {59 useStandard = value;60 }));61 subscriptions.add(atom.config.observe('linter-stylelint.disableWhenNoConfig', (value) => {62 disableWhenNoConfig = value;63 }));64 subscriptions.add(atom.config.observe('linter-stylelint.showIgnored', (value) => {65 showIgnored = value;66 }));67 endMeasure('linter-stylelint: Activation');68}69export function deactivate() {70 subscriptions.dispose();71}72function generateHTMLMessage(message) {73 if (!message.rule || message.rule === 'CssSyntaxError') {74 return escapeHTML()(message.text);75 }76 const ruleParts = message.rule.split('/');77 let url;78 if (ruleParts.length === 1) {79 // Core rule80 url = `http://stylelint.io/user-guide/rules/${ruleParts[0]}`;81 } else {82 // Plugin rule83 const pluginName = ruleParts[0];84 // const ruleName = ruleParts[1];85 switch (pluginName) {86 case 'plugin':87 url = 'https://github.com/AtomLinter/linter-stylelint/tree/master/docs/noRuleNamespace.md';88 break;89 default:90 url = 'https://github.com/AtomLinter/linter-stylelint/tree/master/docs/linkingNewRule.md';91 }92 }93 // Escape any HTML in the message, and replace the rule ID with a link94 return escapeHTML()(message.text).replace(95 `(${message.rule})`, `(<a href="${url}">${message.rule}</a>)`96 );97}98const parseResults = (editor, options, results, filePath) => {99 startMeasure('linter-stylelint: Parsing results');100 if (options.code !== editor.getText()) {101 // The editor contents have changed since the lint was requested, tell102 // Linter not to update the results103 endMeasure('linter-stylelint: Parsing results');104 endMeasure('linter-stylelint: Lint');105 return null;106 }107 if (!results) {108 endMeasure('linter-stylelint: Parsing results');109 endMeasure('linter-stylelint: Lint');110 return [];111 }112 const invalidOptions = results.invalidOptionWarnings.map(msg => ({113 type: 'Error',114 severity: 'error',115 text: msg.text,116 filePath117 }));118 const warnings = results.warnings.map((warning) => {119 // Stylelint only allows 'error' and 'warning' as severity values120 const severity = !warning.severity || warning.severity === 'error' ? 'Error' : 'Warning';121 return {122 type: severity,123 severity: severity.toLowerCase(),124 html: generateHTMLMessage(warning),125 filePath,126 range: createRange(editor, warning)127 };128 });129 const deprecations = results.deprecations.map(deprecation => ({130 type: 'Warning',131 severity: 'warning',132 html: `${escapeHTML()(deprecation.text)} (<a href="${deprecation.reference}">reference</a>)`,133 filePath134 }));135 const ignored = [];136 if (showIgnored && results.ignored) {137 ignored.push({138 type: 'Warning',139 severity: 'warning',140 text: 'This file is ignored',141 filePath142 });143 }144 const toReturn = []145 .concat(invalidOptions)146 .concat(warnings)147 .concat(deprecations)148 .concat(ignored);149 endMeasure('linter-stylelint: Parsing results');150 endMeasure('linter-stylelint: Lint');151 return toReturn;152};153const runStylelint = async (editor, options, filePath) => {154 startMeasure('linter-stylelint: Stylelint');155 let data;156 try {157 data = await stylelint().lint(options);158 } catch (error) {159 endMeasure('linter-stylelint: Stylelint');160 // Was it a code parsing error?161 if (error.line) {162 endMeasure('linter-stylelint: Lint');163 return [{164 type: 'Error',165 severity: 'error',166 text: error.reason || error.message,167 filePath,168 range: createRange(editor, error)169 }];170 }171 // If we got here, stylelint found something really wrong with the172 // configuration, such as extending an invalid configuration173 atom.notifications.addError('Unable to run stylelint', {174 detail: error.reason || error.message,175 dismissable: true176 });177 endMeasure('linter-stylelint: Lint');178 return [];179 }180 endMeasure('linter-stylelint: Stylelint');181 const results = data.results.shift();182 return parseResults(editor, options, results, filePath);183};184export function provideLinter() {185 return {186 name: 'stylelint',187 grammarScopes: baseScopes,188 scope: 'file',189 lintOnFly: true,190 lint: async (editor) => {191 startMeasure('linter-stylelint: Lint');192 const scopes = editor.getLastCursor().getScopeDescriptor().getScopesArray();193 const filePath = editor.getPath();194 const text = editor.getText();195 if (!text) {196 endMeasure('linter-stylelint: Lint');197 return [];198 }199 // Require stylelint-config-standard if it hasn't already been loaded200 if (!presetConfig && useStandard) {201 presetConfig = require('stylelint-config-standard');202 }203 // Setup base config if useStandard() is true204 const defaultConfig = {205 rules: {}206 };207 // Base the config in the project directory208 let [configBasedir] = atom.project.relativizePath(filePath);209 if (configBasedir === null) {210 // Falling back to the file directory if no project is found211 configBasedir = dirname(filePath);212 }213 const rules = useStandard ? assignDeep()({}, presetConfig) : defaultConfig;214 const options = {215 code: text,216 codeFilename: filePath,217 config: rules,218 configBasedir219 };220 if (scopes.includes('source.css.scss') || scopes.includes('source.scss')) {221 options.syntax = 'scss';222 }223 if (scopes.includes('source.css.less') || scopes.includes('source.less')) {224 options.syntax = 'less';225 }226 if (scopes.includes('source.css.postcss.sugarss')) {227 options.syntax = 'sugarss';228 // `stylelint-config-standard` isn't fully compatible with SugarSS229 // See here for details:230 // https://github.com/stylelint/stylelint-config-standard#using-the-config-with-sugarss-syntax231 options.config.rules['block-closing-brace-empty-line-before'] = null;232 options.config.rules['block-closing-brace-newline-after'] = null;233 options.config.rules['block-closing-brace-newline-before'] = null;234 options.config.rules['block-closing-brace-space-before'] = null;235 options.config.rules['block-opening-brace-newline-after'] = null;236 options.config.rules['block-opening-brace-space-after'] = null;237 options.config.rules['block-opening-brace-space-before'] = null;238 options.config.rules['declaration-block-semicolon-newline-after'] = null;239 options.config.rules['declaration-block-semicolon-space-after'] = null;240 options.config.rules['declaration-block-semicolon-space-before'] = null;241 options.config.rules['declaration-block-trailing-semicolon'] = null;242 options.config.rules['declaration-block-trailing-semicolon'] = null;243 }244 startMeasure('linter-stylelint: Create Linter');245 const stylelintLinter = await stylelint().createLinter();246 endMeasure('linter-stylelint: Create Linter');247 startMeasure('linter-stylelint: Config');248 let foundConfig;249 try {250 foundConfig = await stylelintLinter.getConfigForFile(filePath);251 } catch (error) {252 if (!/No configuration provided for .+/.test(error.message)) {253 endMeasure('linter-stylelint: Config');254 // If we got here, stylelint failed to parse the configuration255 // there's no point of re-linting if useStandard is true, because the256 // user does not have the complete set of desired rules parsed257 atom.notifications.addError('Unable to parse stylelint configuration', {258 detail: error.message,259 dismissable: true260 });261 endMeasure('linter-stylelint: Lint');262 return [];263 }264 }265 endMeasure('linter-stylelint: Config');266 if (foundConfig) {267 options.config = assignDeep()(rules, foundConfig.config);268 options.configBasedir = dirname(foundConfig.filepath);269 }270 if (!foundConfig && disableWhenNoConfig) {271 endMeasure('linter-stylelint: Lint');272 return [];273 }274 startMeasure('linter-stylelint: Check ignored');275 let fileIsIgnored;276 try {277 fileIsIgnored = await stylelintLinter.isPathIgnored(filePath);278 } catch (error) {279 // Do nothing, configuration errors should have already been caught and thrown above280 }281 endMeasure('linter-stylelint: Check ignored');282 if (fileIsIgnored) {283 endMeasure('linter-stylelint: Lint');284 if (showIgnored) {285 return [{286 type: 'Warning',287 severity: 'warning',288 text: 'This file is ignored',289 filePath290 }];291 }292 return [];293 }294 const results = await runStylelint(editor, options, filePath);295 return results;296 }297 };...
sampler_spec.js
Source:sampler_spec.js
...278 beginMeasure() {279 ListWrapper.push(this._log, ['beginMeasure']);280 return PromiseWrapper.resolve(null);281 }282 endMeasure(restart) {283 var measureValues = isPresent(this._endMeasure) ? this._endMeasure() : {};284 ListWrapper.push(this._log, ['endMeasure', restart, measureValues]);285 return PromiseWrapper.resolve(measureValues);286 }287}288class MockReporter extends Reporter {289 _log:List;290 constructor(log = null) {291 super();292 if (isBlank(log)) {293 log = [];294 }295 this._log = log;296 }297 reportMeasureValues(values):Promise {...
helpers.js
Source:helpers.js
...11 performance.clearMarks(markName);12 }13 performance.mark(markName);14}15export function endMeasure(baseName) {16 if (atom.inDevMode()) {17 performance.mark(`${baseName}-end`);18 performance.measure(baseName, `${baseName}-start`, `${baseName}-end`);19 const duration = Math.round(performance.getEntriesByName(baseName)[0].duration * 10000) / 10000;20 // eslint-disable-next-line no-console21 console.log(`${baseName} took ${duration} ms`);22 performance.clearMarks(`${baseName}-end`);23 performance.clearMeasures(baseName);24 }25 performance.clearMarks(`${baseName}-start`);26}27export function createRange(editor, data) {28 if (!data ||29 (!Object.hasOwnProperty.call(data, 'line') && !Object.hasOwnProperty.call(data, 'column'))30 ) {31 // data.line & data.column might be undefined for non-fatal invalid rules,32 // e.g.: "block-no-empty": "foo"33 // Return a range encompassing the first line of the file34 return generateRange(editor);35 }36 return generateRange(editor, data.line - 1, data.column - 1);37}38const parseResults = (editor, results, filePath, showIgnored) => {39 startMeasure('linter-stylelint: Parsing results');40 if (!results) {41 endMeasure('linter-stylelint: Parsing results');42 endMeasure('linter-stylelint: Lint');43 return [];44 }45 const invalidOptions = results.invalidOptionWarnings.map(msg => ({46 severity: 'error',47 excerpt: msg.text,48 location: {49 file: filePath,50 position: createRange(editor)51 }52 }));53 const warnings = results.warnings.map((warning) => {54 // Stylelint only allows 'error' and 'warning' as severity values55 const severity = !warning.severity || warning.severity === 'error' ? 'Error' : 'Warning';56 const message = {57 severity: severity.toLowerCase(),58 excerpt: warning.text,59 location: {60 file: filePath,61 position: createRange(editor, warning)62 }63 };64 const ruleParts = warning.rule.split('/');65 if (ruleParts.length === 1) {66 // Core rule67 message.url = `http://stylelint.io/user-guide/rules/${ruleParts[0]}`;68 } else {69 // Plugin rule70 const pluginName = ruleParts[0];71 // const ruleName = ruleParts[1];72 const linterStylelintURL = 'https://github.com/AtomLinter/linter-stylelint/tree/master/docs';73 switch (pluginName) {74 case 'plugin':75 message.url = `${linterStylelintURL}/noRuleNamespace.md`;76 break;77 default:78 message.url = `${linterStylelintURL}/linkingNewRule.md`;79 }80 }81 return message;82 });83 const deprecations = results.deprecations.map(deprecation => ({84 severity: 'warning',85 excerpt: deprecation.text,86 url: deprecation.reference,87 location: {88 file: filePath,89 position: createRange(editor)90 }91 }));92 const ignored = [];93 if (showIgnored && results.ignored) {94 ignored.push({95 severity: 'warning',96 excerpt: 'This file is ignored',97 location: {98 file: filePath,99 position: createRange(editor)100 }101 });102 }103 const toReturn = []104 .concat(invalidOptions)105 .concat(warnings)106 .concat(deprecations)107 .concat(ignored);108 endMeasure('linter-stylelint: Parsing results');109 endMeasure('linter-stylelint: Lint');110 return toReturn;111};112export const runStylelint = async (editor, stylelintOptions, filePath, settings) => {113 startMeasure('linter-stylelint: Stylelint');114 let data;115 try {116 data = await stylelint.lint(stylelintOptions);117 } catch (error) {118 endMeasure('linter-stylelint: Stylelint');119 // Was it a code parsing error?120 if (error.line) {121 endMeasure('linter-stylelint: Lint');122 return [{123 severity: 'error',124 excerpt: error.reason || error.message,125 location: {126 file: filePath,127 position: createRange(editor, error)128 }129 }];130 }131 // If we got here, stylelint found something really wrong with the132 // configuration, such as extending an invalid configuration133 atom.notifications.addError('Unable to run stylelint', {134 detail: error.reason || error.message,135 dismissable: true136 });137 endMeasure('linter-stylelint: Lint');138 return [];139 }140 endMeasure('linter-stylelint: Stylelint');141 const results = data.results.shift();142 if (stylelintOptions.code !== editor.getText()) {143 // The editor contents have changed since the lint was requested, tell144 // Linter not to update the results145 endMeasure('linter-stylelint: Lint');146 return null;147 }148 return parseResults(editor, results, filePath, settings.showIgnored);149};150export function getDefaultConfig(syntax, filePath) {151 const defaultConfig = assignDeep({}, presetConfig);152 if (syntax === 'sugarss') {153 // `stylelint-config-standard` isn't fully compatible with SugarSS154 // See here for details:155 // https://github.com/stylelint/stylelint-config-standard#using-the-config-with-sugarss-syntax156 defaultConfig.rules['block-closing-brace-empty-line-before'] = null;157 defaultConfig.rules['block-closing-brace-newline-after'] = null;158 defaultConfig.rules['block-closing-brace-newline-before'] = null;159 defaultConfig.rules['block-closing-brace-space-before'] = null;...
LineSliceGrid.js
Source:LineSliceGrid.js
1Ext.define('CpsiMapview.view.lineSliceGridExample.LineSliceGrid', {2 extend: 'Ext.grid.Panel',3 xtype: 'cmv_line_slice_grid',4 requires: [5 'CpsiMapview.plugin.LineSliceHighlight'6 ],7 plugins: [{8 ptype: 'cmv_line_slice_highlight'9 }],10 columns: [11 {12 text: 'From',13 dataIndex: 'startMeasure',14 renderer: function(val) {15 return val.toFixed(1) + ' m';16 }17 },18 {19 text: 'To',20 dataIndex: 'endMeasure',21 renderer: function(val) {22 return val.toFixed(1) + ' m';23 }24 },25 {26 text: 'Text',27 dataIndex: 'text'28 }29 ],30 listeners: {31 itemclick: function (_, record) {32 var highlighter = this.getPlugin('cmv_line_slice_highlight');33 highlighter.highlightSlice(this.feature.getGeometry(), record.data.startMeasure, record.data.endMeasure);34 }35 },36 initComponent: function () {37 var map = BasiGX.util.Map.getMapComponent().map;38 var store = Ext.create('Ext.data.Store', {39 data: [40 {startMeasure: 0, endMeasure: 200, text: 'slice 1'},41 {startMeasure: 200, endMeasure: 1000, text: 'slice 2'},42 {startMeasure: 1100, endMeasure: 1800, text: 'slice 3'},43 {startMeasure: 1400, endMeasure: 4000, text: 'slice 4'},44 {startMeasure: 5000, endMeasure: 12000, text: 'slice 5'}45 ]46 });47 this.store = store;48 var geoJson = JSON.stringify({49 'type': 'Feature',50 'geometry': {51 'type': 'LineString',52 'coordinates': [53 [-965068.9613156476, 6917903.9768694835], [-963761.0112796988, 6918876.101896202],54 [-962187.936236463, 6919883.576923893], [-960915.3362014858, 6920608.25194381],55 [-959695.7611679661, 6920024.976927779], [-958264.0861286167, 6919176.576904461],56 [-957645.4611116138, 6918893.776896688], [-961533.9612184886, 6918116.076875313],57 [-964344.28629573, 6914528.051776697], [-965387.1113243919, 6915853.676813131]58 ]59 },60 'properties': null61 });62 this.feature = (new ol.format.GeoJSON()).readFeature(geoJson, {63 featureProjection: 'EPSG:3857',64 dataProjection: 'EPSG:3857'65 });66 var layer = new ol.layer.Vector({67 source: new ol.source.Vector({68 features: [this.feature]69 }),70 map: map,71 style: new ol.style.Style({72 stroke: new ol.style.Stroke({73 color: 'yellow',74 width: 275 })76 }),77 visible: false78 });79 this.callParent(arguments);80 var highlighter = this.getPlugin('cmv_line_slice_highlight');81 highlighter.setStyle(new ol.style.Style({82 stroke: new ol.style.Stroke({83 color: 'blue',84 width: 285 })86 }));87 this.up('cmv_minimizable_window').on('show', function () {88 layer.setVisible(true);89 map.render();90 });91 this.up('cmv_minimizable_window').on('close', function () {92 layer.setVisible(false);93 highlighter.removeHighlight();94 map.render();95 });96 }...
server.js
Source:server.js
1//2// Created by Mingliang Chen on 17/12/24. Merry Christmas3// illuspas[a]gmail.com4// Copyright (c) 2018 Nodemedia. All rights reserved.5//6const OS = require('os');7const Package = require("../../package.json");8function cpuAverage() {9 //Initialise sum of idle and time of cores and fetch CPU info10 let totalIdle = 0, totalTick = 0;11 let cpus = OS.cpus();12 //Loop through CPU cores13 for (let i = 0, len = cpus.length; i < len; i++) {14 //Select CPU core15 let cpu = cpus[i];16 //Total up the time in the cores tick17 for (type in cpu.times) {18 totalTick += cpu.times[type];19 }20 //Total up the idle time of the core21 totalIdle += cpu.times.idle;22 }23 //Return the average Idle and Tick times24 return { idle: totalIdle / cpus.length, total: totalTick / cpus.length };25}26function percentageCPU() {27 return new Promise(function (resolve, reject) {28 let startMeasure = cpuAverage();29 setTimeout(() => {30 let endMeasure = cpuAverage();31 //Calculate the difference in idle and total time between the measures32 let idleDifference = endMeasure.idle - startMeasure.idle;33 let totalDifference = endMeasure.total - startMeasure.total;34 //Calculate the average percentage CPU usage35 let percentageCPU = 100 - ~~(100 * idleDifference / totalDifference);36 resolve(percentageCPU);37 }, 100);38 });39}40function getSessionsInfo(sessions) {41 let info = {42 inbytes: 0,43 outbytes: 0,44 rtmp: 0,45 http: 0,46 ws: 0,47 };48 for (let session of sessions.values()) {49 if (session.TAG === 'relay') continue;50 let socket = session.TAG === 'rtmp' ? session.socket : session.req.socket;51 info.inbytes += socket.bytesRead;52 info.outbytes += socket.bytesWritten;53 info.rtmp += session.TAG === 'rtmp' ? 1 : 0;54 info.http += session.TAG === 'http-flv' ? 1 : 0;55 info.ws += session.TAG === 'websocket-flv' ? 1 : 0;56 }57 return info;58}59function getInfo(req, res, next) {60 let s = this.sessions;61 percentageCPU().then((cpuload) => {62 let sinfo = getSessionsInfo(s);63 let info = {64 os: {65 arch: OS.arch(),66 platform: OS.platform(),67 release: OS.release(),68 },69 cpu: {70 num: OS.cpus().length,71 load: cpuload,72 model: OS.cpus()[0].model,73 speed: OS.cpus()[0].speed,74 },75 mem: {76 totle: OS.totalmem(),77 free: OS.freemem()78 },79 net: {80 inbytes: this.stat.inbytes + sinfo.inbytes,81 outbytes: this.stat.outbytes + sinfo.outbytes,82 },83 nodejs: {84 uptime: Math.floor(process.uptime()),85 version: process.version,86 mem: process.memoryUsage()87 },88 clients: {89 accepted: this.stat.accepted,90 active: this.sessions.size - this.idlePlayers.size,91 idle: this.idlePlayers.size,92 rtmp: sinfo.rtmp,93 http: sinfo.http,94 ws: sinfo.ws95 },96 version: Package.version97 };98 res.json(info);99 });100}...
measure-interval-templates.js
Source:measure-interval-templates.js
1import {Format, Difference} from '../../utilities/date-time.js';2import {Timing} from '../../utilities/timing.js';3import {roundToTwoDecimals} from '../../utilities/number.js';4const makeHtml = (component) => (5`6<h1><gwbw-icon name="straighten"></gwbw-icon> Measure Interval</h1>7<div class="more-info-header">8 <h1 class="invisible"><gwbw-icon name="straighten"></gwbw-icon></h1>9 ${' '}<h3>${component.watch.name}</h3>10</div>11<h2>12 <span class="session-days-range nowrap" title="${Format.dateAndTime(component.startMeasure.targetMoment) + ' - ' + Format.dateAndTime(component.endMeasure.targetMoment)}">13 ${Format.dateRange(component.startMeasure.targetMoment, component.endMeasure.targetMoment)}14 </span>15 <small class="session-duration-in-days nowrap" title="${Format.durationLong(component.endMeasure.targetMoment, component.startMeasure.targetMoment)}">16 (${roundToTwoDecimals(Difference.days(component.startMeasure.targetMoment, component.endMeasure.targetMoment))} days)17 </small>18</h2>19<h3 class="average ${getClasses(component)}">20 Average:${` `}21 <span class="rate ${getRate(component) >= 0 ? `fast` : `slow`}">${getRate(component)} seconds/day</span>22</h3>23<div class="good-bad-message ${getClasses(component)}">24 <h4 class="good"><gwbw-icon name="thumb_up"></gwbw-icon> Good watch</h4>25 <h4 class="bad"><gwbw-icon name="thumb_down"></gwbw-icon> Bad watch</h4>26</div>27<hr>28<div class="positions-detail">29 <gwbw-positions-detail30 watchid="${component.watch._id}"31 startmeasureid="${component.startMeasure._id}"32 endmeasureid="${component.endMeasure._id}"33 goodtoleranceplus="${component.watch.goodTolerancePlus}"34 goodtoleranceminus="${component.watch.goodToleranceMinus}"35 ></gwbw-positions-detail>36</div>37<a class="big-link" href="javascript:history.back();">Back to Measures</button>38`39);40const makeCss = (component) => (41`42<style>43@import "styles/global-styles.css";44h1 gwbw-icon { transform: rotate(90deg); }45.session-days-range { margin-right: .2em; }46p { margin-top: -1.2em; }47.average.good-watch { color: var(--green); }48.average.bad-watch { color: var(--red); }49.rate.fast:before { content: "+"; }50.good-bad-message > * { display: none; margin-top: -1.5em; }51.good-bad-message.good-watch .good { display: block; color: var(--green); }52.good-bad-message.bad-watch .bad { display: block; color: var(--red); }53.positions-detail { margin-bottom: 2em; }54</style>55`56);57const getRate = component => {58 return Timing.rate(59 component.startMeasure.targetMoment, component.startMeasure.moment,60 component.endMeasure.targetMoment, component.endMeasure.moment61 );62};63const getClasses = component => {64 const isGood =65 getRate(component) <= component.watch.goodTolerancePlus &&66 getRate(component) >= -1 * component.watch.goodToleranceMinus;67 return isGood ? `good-watch` : `bad-watch`;68};69export const makeTemplate = (component) => {70 return makeCss(component) + makeHtml(component);...
UIProfiler.js
Source:UIProfiler.js
...22 startMeasure: function(markName) {23 startMeasure(markName);24 },25 endMeasure: function(markName) {26 endMeasure(markName);27 },28 getMeasurements: function(markName) {29 var time = getMeasurements(markName);30 return time.duration;31 }32 };33 };34 return {35 getInstance: function() {36 if (window.performance == null) {37 throw new Error(notSupportedMessage);38 }39 if (!instance) {40 instance = createTimer();...
cpu_usage.js
Source:cpu_usage.js
1/* cpu usage2https://gist.github.com/bag-man/55708093*/4var os = R.node.os;5//Create function to get CPU information6function cpuAverage() {7 //Initialise sum of idle and time of cores and fetch CPU info8 var totalIdle = 0, totalTick = 0;9 var cpus = os.cpus();10 //Loop through CPU cores11 for(var i = 0, len = cpus.length; i < len; i++) {12 //Select CPU core13 var cpu = cpus[i];14 //Total up the time in the cores tick15 for(type in cpu.times) totalTick += cpu.times[type];16 //Total up the idle time of the core17 totalIdle += cpu.times.idle;18 }19 //Return the average Idle and Tick times20 return {idle: totalIdle / cpus.length, total: totalTick / cpus.length};21}22//Grab first CPU Measure23var startMeasure = cpuAverage();24//Set delay for second Measure25R.service.timers.cpu_usage = setInterval(function() { 26 //Grab second Measure27 var endMeasure = cpuAverage(); 28 //Calculate the difference in idle and total time between the measures29 var idleDifference = endMeasure.idle - startMeasure.idle;30 var totalDifference = endMeasure.total - startMeasure.total;31 //Calculate the average percentage CPU usage32 var percentageCPU = 100 - ~~(100 * idleDifference / totalDifference);33 //Output result to console34 //console.log("\r" + percentageCPU + "% CPU Usage.");35 R.status.cpu_usage = percentageCPU;36 startMeasure = endMeasure;...
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.endMeasure('navigation');7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.endMeasure('navigation');15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.endMeasure('navigation');23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.endMeasure('navigation');31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.endMeasure('navigation');39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();46 await page.endMeasure('navigation');47 await browser.close();48})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.endMeasure('test');7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch({ headless: false });12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.endMeasure('test');15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch({ headless: false });20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.endMeasure('test');23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch({ headless: false });28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.endMeasure('test');31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch({ headless: false });36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.endMeasure('test');39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch({ headless: false });44 const context = await browser.newContext();45 const page = await context.newPage();46 await page.endMeasure('test');47 await browser.close();48})();
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.endMeasure('test');7 await browser.close();8})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.evaluate(() => {6 window.__playwright__internal__endMeasure();7 });8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const page = await browser.newPage();14 await page.evaluate(() => {15 window.__playwright__internal__startMeasure();16 });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const page = await browser.newPage();23 await page.evaluate(() => {24 window.__playwright__internal__startMeasure();25 });26 await browser.close();27})();28const { chromium } = require('playwright');29(async () => {30 const browser = await chromium.launch();31 const page = await browser.newPage();32 await page.evaluate(() => {33 window.__playwright__internal__startMeasure();34 });35 await browser.close();36})();37const { chromium } = require('playwright');38(async () => {39 const browser = await chromium.launch();40 const page = await browser.newPage();41 await page.evaluate(() => {42 window.__playwright__internal__startMeasure();43 });44 await browser.close();45})();46const { chromium } = require('playwright');
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.endMeasure('MyMeasure');6 await browser.close();7})();8const { chromium } = require('playwright');9(async () => {10 const browser = await chromium.launch();11 const page = await browser.newPage();12 await page.endMeasure('MyMeasure');13 await browser.close();14})();15const { chromium } = require('playwright');16(async () => {17 const browser = await chromium.launch();18 const page = await browser.newPage();19 await page.endMeasure('MyMeasure');20 await browser.close();21})();22const { chromium } = require('playwright');23(async () => {24 const browser = await chromium.launch();25 const page = await browser.newPage();26 await page.endMeasure('MyMeasure');27 await browser.close();28})();29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const page = await browser.newPage();33 await page.endMeasure('MyMeasure');34 await browser.close();35})();36const { chromium } = require('playwright');37(async () => {
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({4 });5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.endMeasure('testMeasure');8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch({13 });14 const context = await browser.newContext();15 const page = await context.newPage();16 await page.startMeasure('testMeasure');17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch({22 });23 const context = await browser.newContext();24 const page = await context.newPage();25 await page.startMeasure('testMeasure');26 await page.stopMeasure('testMeasure');27 await browser.close();28})();29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch({32 });33 const context = await browser.newContext();34 const page = await context.newPage();35 await page.takeScreenshot();36 await browser.close();37})();38const { chromium } = require('playwright');39(async () => {40 const browser = await chromium.launch({41 });42 const context = await browser.newContext();43 const page = await context.newPage();44 await page.takeVideo();45 await browser.close();46})();
Using AI Code Generation
1const { chromium } = require('playwright');2const { endMeasure } = require('playwright/lib/server/trace/recorder');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.click('text=Get started');8 await page.click('text=Docs');9 await page.click('text=API');10 await page.click('te
Using AI Code Generation
1const { endMeasure } = require('@playwright/test/lib/test');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: `example.png` });8 await browser.close();9 await endMeasure("test.js");10})();11const { endMeasure } = require('@playwright/test/lib/test');12describe('My test suite', () => {13 it('My test', async ({ page }) => {14 await page.screenshot({ path: `example.png` });15 await endMeasure("test.spec.js");16 });17});
Using AI Code Generation
1const { chromium } = require('playwright');2const { endMeasure } = require('playwright/lib/server/trace/recorder/recorderApp');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await endMeasure(page, 'myMeasure');8 await browser.close();9})();10const { chromium } = require('playwright');11const { startMeasure } = require('playwright/lib/server/trace/recorder/recorderApp');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await startMeasure(page, 'myMeasure');17 await browser.close();18})();19const { chromium } = require('playwright');20const { startMeasure, endMeasure } = require('playwright/lib/server/trace/recorder/recorderApp');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await startMeasure(page, 'myMeasure');26 await page.click('text=Get started');27 await endMeasure(page, 'myMeasure');28 await browser.close();29})();30const { chromium } = require('playwright');31const { startMeasure, endMeasure } = require('playwright/lib/server/trace/recorder/recorderApp');32(async () => {33 const browser = await chromium.launch();34 const context = await browser.newContext();35 const page = await context.newPage();36 await startMeasure(page, 'myMeasure');37 await page.click('text=Get started');38 await endMeasure(page, 'myMeasure');39 await browser.close();40})();41const { chromium } = require('playwright');42const { startMeasure
Using AI Code Generation
1const { chromium } = require('playwright');2const { createMeasure } = require('./measure.js');3const { endMeasure } = require('./measure.js');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const measure = createMeasure(page);9 await measure('navigation');10 await endMeasure(page, 'navigation');11 await browser.close();12})();
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!!