Best JavaScript code snippet using wpt
Settings.js
Source:Settings.js
1class Settings {2 // VSObj is passed in because this file is used both in the background (where VSObj with be VSb) and in the content scripts where VSObj will be VSc3 constructor(VSObj) {4console.log('%cSettings.constructor', 'background-color: orange; color: white');5 this.VSObj = VSObj;6 this.constants = {7 "muteCategories": ['diety', 'profanity', 'explicit', 'racism', 'additional'],8 "builtInFudgeFactorStart": -0.25, // in general we just need to shift forward by this much, plus whatever else the user specifies9 "debug": true,10 "state": "dev"11 };12 this.itemsDefault = {13 "muteDietyDefault": true,14 "dietyListDefault": [ 'oh my god', 'my god', 'thank god', 'thank the gods', 'gods', 'god', 'oh my lord', 'oh dear lord', 'my lord', 'dear lord', 'good heavens', 'heavens', 'bloody', 'jesus', 'christ'],15 "muteProfanityDefault": true,16 "profanityListDefault": [ 'damn', 'dammit', 'the hell', 'hell', 'shit', 'mother fucker', 'fucker', 'fuck', 'fucking', 'bad ass', 'ass', 'son of a bitch', 'bitch'],17 "muteExplicitDefault": true,18 "explicitListDefault": ['sexy', 'sex','suck', 'boner', 'penis', 'tits', 'boobs'],19 "muteRacismDefault": true,20 "racismListDefault": ['nigger','niggers', 'niggra', 'niggras', 'gypped', 'gyp'],21 "muteAdditionalDefault": true,22 "additionalListDefault": [],23 "disableVSFromIconDefault": false,24 "fudgeFactorStartDefault": 0,25 "fudgeFactorDurationDefault": 0,26 "fileRetrievalMethodsDefault": [27 {"name":"find_local_BrowserVFS_auto", "active":false},28 {"name":"find_remote_auto", "active":false},29 {"name":"find_local_manual", "active":false},30 ],31 "showLogoDefault": true,32 "logoSizeDefault": "small",33 "logoPositionDefault": "topright",34 "debuggingDefault": false,35 "currentLocaleDefault": "en-US",36 "trialPeriodDaysDefault": 12037 };38 this.items = {};39 this.storageObj = {};40 this.nameArray = Object.keys(this.itemsDefault).map(function(item) {41 return item.replace(/Default/, '');42 });43console.log('\n\nthis.nameArray = ', this.nameArray, '\n\n');44 };45 sync(bSave) {46console.log('%cSettings.sync', 'background-color: orange; color: white');47 let save = (bSave) ? true : false;48 this.VSObj.port.postMessage({"event": {"name":"SettingsSync" }});49 };50 settingsUpdated(event) {51console.log('\n\n\n\%cConfig.updateSettings', 'background-color: orange; color: white');52console.trace();53// this.settings = event.Config.settings;54// if (typeof event.save != 'undefined' && event.save) {55// this.saveStorage(function(){56// //console.log('updated settings saved');57// });58// }59 this.readStorage(VSc.WordsToMute.reset, VSc.WordsToMute);60 document.dispatchEvent(new CustomEvent('MC_Settings_Updated', {"detail": VSc.Config.settings}));61 };62// readStorage(callBack, callBackContext) {63// console.log('%cSettings.readStorage', 'background-color: orange; color: white');64// console.trace();65// var that = this;66// this.readStorage.callBack = callBack;67// let storageKeys = {};68//69// for (let i = 0; i < this.nameArray.length; i++) {70// //console.log('<storageKeys[this.nameArray['+i+']]> storageKeys['+this.nameArray[i]+'] = this.itemsDefault['+this.nameArray[i] + 'Default\'];');71// storageKeys[this.nameArray[i]] = this.itemsDefault[this.nameArray[i] + 'Default'];72// }73// console.log('\tabout to call chrome.storage.sync.get with a callback of Settings.chromeStorageSyncGetCallback - %cAsynchronus', 'background-color: red; color:white; font-weight:bold');74// chrome.storage.sync.get(storageKeys,75// function chromeStorageSyncGetCallback(items) {76// console.log('%cSettings.chromeStorageSyncGetCallback', 'background-color: orange; color: white');77// for (let i = 0; i < this.nameArray.length; i++) {78// //console.log('typeof items['+this.nameArray[i]+'] = ', typeof items[this.nameArray[i]]);79// this.items[this.nameArray[i]] = items[this.nameArray[i]];80// }81// console.log('this.items = ', this.items);82// //document.dispatchEvent(new CustomEvent('MC_Settings_Read', {"detail": VSc.Settings.settings}));83// //document.dispatchEvent(new CustomEvent('MC_Settings_Updated', {"detail": VSc.Config.Settings.items}));84// document.dispatchEvent(new CustomEvent('MC_Settings_Updated', {"detail": this.items}));85//86// if (callBackContext) {87// callBack.call(callBackContext);88// } else {89// callBack();90// }91// }.bind(this)92// );93// };94readStorage(readerPromise) {95console.groupCollapsed('%cSettings.readStorage', 'background-color: orange; color: white');96console.trace();97console.groupEnd();98console.log('readerPromise = ', readerPromise);99 let storageKeys = {};100console.log('%cthis.nameArray = %O', 'background-color: orange; color: white', this.nameArray);101 for (let i = 0; i < this.nameArray.length; i++) {102 //console.log('<storageKeys[this.nameArray['+i+']]> storageKeys['+this.nameArray[i]+'] = this.itemsDefault['+this.nameArray[i] + 'Default\'];');103 storageKeys[this.nameArray[i]] = this.itemsDefault[this.nameArray[i] + 'Default'];104 }105console.log('storageKeys = ' , storageKeys);106console.log('\tabout to call chrome.storage.sync.get with a callback of Settings.chromeStorageSyncGetCallback - %cAsynchronus', 'background-color: red; color:white; font-weight:bold');107 chrome.storage.sync.get(storageKeys,108 function chromeStorageSyncGetCallback(items) {109console.log('%cSettings.chromeStorageSyncGetCallback', 'background-color: orange; color: white');110 for (let i = 0; i < this.nameArray.length; i++) {111 //console.log('typeof items['+this.nameArray[i]+'] = ', typeof items[this.nameArray[i]]);112 this.items[this.nameArray[i]] = items[this.nameArray[i]];113 }114console.log('\t%cthis.items = %o', 'background-color: orange; color: white', this.items);115 //document.dispatchEvent(new CustomEvent('MC_Settings_Read', {"detail": VSc.Settings.settings}));116 //document.dispatchEvent(new CustomEvent('MC_Settings_Updated', {"detail": VSc.Config.Settings.items}));117 document.dispatchEvent(new CustomEvent('MC_Settings_Updated', {"detail": this.items}));118console.log('\t%cabout to call readerPromise.resolver()', 'background-color: orange; color: white', '\n\treaderPromise = ', readerPromise);119 readerPromise.resolver(this.items);120 }.bind(this)121 );122};123saveStorage(writerPromise, WordsToMuteHasChanged) {124console.log('%cSettings.saveStorage', 'background-color: orange; color: white');125 let storageKeys = {};126 for (let i = 0; i < this.nameArray.length; i++) {127 storageKeys[this.nameArray[i]] = this.items[this.nameArray[i]];128 }129 chrome.storage.sync.set(storageKeys,130 function saveStorageCallback() {131console.log('%cSettings.saveStorageCallback', 'background-color: orange; color: white');132console.log('this = ', this);133 // if the WordsToMute has changed and we're in a state where we've already made our edl file remake the AudioMutes section134 if (WordsToMuteHasChanged) {135 document.dispatchEvent(new CustomEvent('MC_WordsToMuteChanged'));136 }137 this.sync();138 writerPromise.resolver();139 }.bind(this)140 );141};142// saveStorage(callBack, WordsToMuteHasChanged) {143// console.log('%cSettings.saveStorage', 'background-color: orange; color: white');144// let storageKeys = {};145//146// for (let i = 0; i < this.nameArray.length; i++) {147// storageKeys[this.nameArray[i]] = this.items[this.nameArray[i]];148// }149// chrome.storage.sync.set(storageKeys,150// function saveStorageCallback() {151// console.log('%cSettings.saveStorageCallback', 'background-color: orange; color: white');152// console.log('this = ', this);153// // if the WordsToMute has changed and we're in a state where we've already made our edl file remake the AudioMutes section154// if (WordsToMuteHasChanged) {155// document.dispatchEvent(new CustomEvent('MC_WordsToMuteChanged'));156// }157// this.sync();158// callBack();159// }.bind(this)160// );161// };162 resetToDefaults(callBack) {163console.log('%cSettings.resetToDefaults', 'background-color: orange; color: white');164 for (let i = 0; i < this.nameArray.length; i++) {165 this.items[this.nameArray[i]] = this.itemsDefault[this.nameArray[i] + 'Default'];166 }167 var writerPromise = new Promise(function(resolve, reject){168 this.resolver = resolve;169 this.rejector = reject;170 }.bind(this));171 writerPromise.resolver = this.resolver;172 writerPromise.rejector = this.rejector;173 writerPromise.then(function(){174 if (callBack) {175 callBack();176 }177 });178 this.saveStorage(writerPromise, false); // <---- Don't know if this is false or true. Have to figure it out179 };...
db.ts
Source:db.ts
1import { socketRouter } from "../router.ts";2import { database } from "../../db/mod.ts";3import { Writer } from "../../db/mod.ts";4/** ã¦ã¼ã¶ã¼ããéä¿¡ããã¦ãããã¼ã¿(k-vå½¢å¼)ã®å¶é(kã®æ°ã®æ大å¤) */5const DATA_MAX_LENGTH = 20;6const ERR_FAILED_TO_VERIFY_TOKEN = "error: failed to verify token.";7const ERR_INVALID_DATA_FORMAT =8 "error: data format is invalid. The data must be json data with up to 20 keys in one hierarchy and an associative array of numbers, and the time property is required.";9const ERR_INTERNAL_SERVER_ERROR = "error: Internal Server Error";10function closeSocket(11 socket: WebSocket,12 event: Event,13 code: number,14 reason: string,15) {16 console.error("close socket:\n", reason, "event:\n", Deno.inspect(event));17 socket.close(code, reason);18}19socketRouter.set(20 new URLPattern({ pathname: "/ws/send/:id" }),21 ({ socket, match: { pathname: { groups: { id } } } }) => {22 addTokenMessageListener(socket, id);23 },24);25function addTokenMessageListener(socket: WebSocket, id: string) {26 // 1åç®ã®æ¥ç¶ã¯èªè¨¼ãã¼ã¯ã³ãåãä»ãã27 socket.addEventListener("message", function firstListener(event) {28 try {29 socket.removeEventListener("message", firstListener);30 if (typeof event.data !== "string") {31 return closeSocket(socket, event, 1008, ERR_FAILED_TO_VERIFY_TOKEN);32 }33 const writerPromise = database.getWriter(id, event.data);34 writerPromise.then((writer) => {35 if (!writer) {36 return closeSocket(socket, event, 1008, ERR_FAILED_TO_VERIFY_TOKEN);37 }38 });39 addDataMessageListener(40 socket,41 new BroadcastChannel(`data.${id}`),42 writerPromise,43 );44 } catch (e) {45 console.error(e);46 return closeSocket(socket, event, 1001, ERR_INTERNAL_SERVER_ERROR);47 }48 });49}50function addDataMessageListener(51 socket: WebSocket,52 channel: BroadcastChannel,53 writerPromise: Promise<Writer | null>,54) {55 // 2åç®ã®æ¥ç¶ä»¥éã¯ãã¼ã¿ãåãä»ãã56 socket.addEventListener("close", () => {57 channel.close();58 });59 socket.addEventListener("error", () => {60 channel.close();61 });62 socket.addEventListener("message", async (event) => {63 try {64 const writer = await writerPromise;65 if (!writer) {66 return closeSocket(socket, event, 1008, ERR_FAILED_TO_VERIFY_TOKEN);67 }68 let data: json;69 try {70 data = JSON.parse(event.data);71 } catch (e) {72 console.error(e);73 return closeSocket(socket, event, 1003, ERR_INVALID_DATA_FORMAT);74 }75 if (!validateData(data)) {76 return closeSocket(socket, event, 1003, ERR_INVALID_DATA_FORMAT);77 }78 channel.postMessage(event.data);79 await writer.write(data);80 } catch (e) {81 console.error(e);82 return closeSocket(socket, event, 1001, ERR_INTERNAL_SERVER_ERROR);83 }84 });85}86type json =87 | string88 | number89 | boolean90 | null91 | json[]92 | { [key: string]: json };93function validateData(94 data: json,95): data is { time: number; [key: string]: number } {96 if (!data || typeof data !== "object" || Array.isArray(data)) {97 return false;98 }99 const keys = Object.keys(data);100 if (DATA_MAX_LENGTH + 1 /*time propertyã®å*/ < keys.length) {101 return false;102 }103 if (typeof data["time"] !== "number") {104 return false;105 }106 for (const key of keys) {107 if (typeof data[key] !== "number") {108 return false;109 }110 }111 return true;...
XLSXLoader.js
Source:XLSXLoader.js
...15 _data.push(flatten(row));16 });17 let writer = new XLSXWriter(this.config._target.path, {} /* options */);18 let writerPromise = promisify(XLSXWriter.write);19 writerPromise(this.config._target.path, _data);20 return Promise.resolve(true);21 }22}...
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3var writeStream = fs.createWriteStream('output.txt');4var writerPromise = wptools.writerPromise(writeStream);5wptools.page('Barack Obama').then(page => page.get()).then(page => page.infobox(writerPromise)).then(() => writeStream.end());6const wptools = require('wptools');7const fs = require('fs');8var writeStream = fs.createWriteStream('output.txt');9var writerPromise = wptools.writerPromise(writeStream);10wptools.page('Barack Obama').then(page => page.get()).then(page => page.infobox(writerPromise)).then(() => writeStream.end());11const wptools = require('wptools');12const fs = require('fs');13var writeStream = fs.createWriteStream('output.txt');14var writerPromise = wptools.writerPromise(writeStream);15wptools.page('Barack Obama').then(page => page.get()).then(page => page.infobox(writerPromise)).then(() => writeStream.end());16const wptools = require('wptools');17const fs = require('fs');18var writeStream = fs.createWriteStream('output.txt');19var writerPromise = wptools.writerPromise(writeStream);20wptools.page('Barack Obama').then(page => page.get()).then(page => page.infobox(writerPromise)).then(() => writeStream.end());21const wptools = require('wptools');22const fs = require('fs');23var writeStream = fs.createWriteStream('output.txt');24var writerPromise = wptools.writerPromise(writeStream);25wptools.page('Barack Obama').then(page => page.get()).then(page => page.infobox(writerPromise)).then(() => writeStream.end());
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const writerPromise = wptools.writerPromise;4const writer = fs.createWriteStream('test.txt');5writerPromise('Barack Obama', writer)6.then(() => {7 console.log('done');8})9.catch((err) => {10 console.log(err);11});
Using AI Code Generation
1var wptools = require('wptools');2var fs = require('fs');3var path = require('path');4var writerPromise = require('wptools/lib/writerPromise');5var dir = path.join(__dirname, 'data');6var file = path.join(dir, 'test.json');7wptools.page('Barack Obama').get().then(function(page) {8 return writerPromise(page, file);9}).then(function() {10 console.log('Data written to ' + file);11}).catch(function(err) {12 console.log(err);13});
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const writeStream = fs.createWriteStream('output.txt');4const page = wptools.page('Albert Einstein');5page.get()6 .then((page) => {7 return page.writerPromise();8 })9 .then((writer) => {10 writer.pipe(writeStream);11 })12 .catch((error) => {13 console.log(error);14 });
Using AI Code Generation
1const wptools = require('wptools');2const fs = require('fs');3const page = wptools.page('Albert_Einstein');4page.get()5 .then((page) => {6 return page.writerPromise('Albert_Einstein.json');7 })8 .then((data) => {9 console.log('Data written to Albert_Einstein.json');10 })11 .catch((error) => {12 console.log(error);13 });
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!!