Best JavaScript code snippet using wpt
index.js
Source:index.js
1var app = new Vue({2 el: "#app",3 data: {4 langDict: {},5 normalLang: [6 { code: "auto", lang: "èªå¨æ£æµ" },7 { code: "zh-CN", lang: "ä¸æ" },8 { code: "en", lang: "è±è¯" }9 ],10 searchEngine: "baidu",11 searchEngineList: [12 {13 value: "google",14 label: "è°·æ"15 },16 {17 value: "baidu",18 label: "ç¾åº¦"19 },20 {21 value: "youdao",22 label: "æé"23 }24 ],25 searchString: "ç»é¥¼å¹²å¿çç¿»è¯å·¥å
·1.0",26 translateResult: null,27 sourceLang: { code: "auto", lang: "èªå¨æ£æµ" },28 sourceLangList: [],29 resultLang: { code: "en", lang: "å¤è¯" },30 resultLangList: [],31 getTsTimer: null,32 loadingTsFlag: false,33 sourceAudioUri: "",34 resultAudioUri: "",35 selectLangFlag: false,36 selectLangType: ""37 },38 computed: {39 normalLangFormat: function() {40 if (this.searchEngine === "youdao") {41 return this.normalLang.slice(1);42 } else {43 if (this.selectLangType === "source") {44 return this.normalLang;45 } else if (this.selectLangType === "result") {46 return this.normalLang.slice(1);47 }48 }49 return [];50 },51 searchResult: function() {52 var result = this.translateResult;53 return result && result.result ? result.result.join(", ") : "";54 },55 word_name: function() {56 if (this.simple_means) {57 return this.simple_means.word_name || "";58 }59 return "";60 },61 simple_means: function() {62 // ç®æéä¹63 return this.getChainProperty(this.translateResult, [64 "raw",65 "dict_result",66 "simple_means"67 ]);68 },69 word_parts: function() {70 var res = [];71 if (this.sourceLang.code === 'en') {72 if (this.simple_means) {73 var parts = this.simple_means.symbols;74 if (Array.isArray(parts)) {75 parts.forEach((item) => {76 if (Array.isArray(item.parts)) {77 res = res.concat(item.parts);78 }79 })80 }81 }82 } else {83 var tag = this.getChainProperty(this.translateResult, [84 "raw",85 "liju_result",86 "tag"87 ]);88 if (Array.isArray(tag)) {89 res.push({part: '', means: tag})90 }91 }92 return res;93 },94 word_exchange: function() {95 if (this.simple_means) {96 var exc = this.simple_means.exchange;97 if (exc) {98 var res = [];99 var dict = this.langDict.exchange;100 Object.keys(exc).forEach((key) => {101 if (Array.isArray(exc[key])) {102 res.push({key: dict.codeToName(key), val: exc[key].join('; ')})103 }104 })105 return res;106 }107 }108 return [];109 },110 keywords: function() {111 // éç¹è¯æ±112 return this.getChainProperty(this.translateResult, [113 "raw",114 "trans_result",115 "keywords"116 ]);117 },118 showSourceAudioIcon: function() {119 if (this.searchEngine === "baidu") {120 return true;121 }122 return false;123 },124 showResultAudioIcon: function() {125 if (this.searchEngine !== "google") {126 return true;127 }128 return false;129 }130 },131 watch: {132 searchString: function(newVal) {133 if (newVal === "") {134 this.translateResult = null;135 } else {136 this.getTsFn();137 }138 },139 searchEngine: function(newVal) {140 if (newVal === "youdao" && this.sourceLang.code === 'auto') {141 this.sourceLang = { code: "zh-CN", lang: "ä¸æ" };142 }143 }144 },145 created: function() {146 this.langDict = window.LD;147 this.loadingTsFlag = true;148 this.getTranslate();149 this.searchEngine === "baidu" && this.getAudioUri("source");150 },151 methods: {152 getTsFn: function() {153 clearTimeout(this.getTsTimer);154 this.loadingTsFlag = true;155 this.getTsTimer = setTimeout(() => {156 this.getTranslate();157 this.searchEngine === "baidu" && this.getAudioUri("source");158 }, 40);159 },160 getTranslate: function() {161 if (this.searchString === "") {162 this.loadingTsFlag = false;163 return;164 }165 var timer = this.getTsTimer;166 this.loadingTsFlag = true;167 var params = {};168 this.postData("./translate", {169 text: this.searchString,170 engine: this.searchEngine,171 from:172 this.sourceLang.code === "auto" ? undefined : this.sourceLang.code,173 to: this.resultLang.code174 })175 .then(res => {176 // 对æåä¸ä¸ªè¯·æ±èµå¼177 if (timer === this.getTsTimer) {178 this.translateResult = res;179 var dict = this.langDict.google;180 if (res.from) {181 this.sourceLang = {code: res.from, lang: dict.codeToName(res.from)};182 }183 if (res.to) {184 this.resultLang = {code: res.to, lang: dict.codeToName(res.to)};185 }186 this.searchEngine !== "google" && this.getAudioUri("result");187 }188 })189 .catch(err => {190 this.showMsg(err, "error");191 })192 .then(() => {193 timer === this.getTsTimer && (this.loadingTsFlag = false);194 });195 },196 getAudioUri: function(type) {197 var text = type === "source" ? this.searchString : this.searchResult;198 if (text === "") return;199 this.postData("./audio", {200 text: type === "source" ? this.searchString : this.searchResult,201 engine: this.searchEngine202 })203 .then(res => {204 if (type === "source") {205 this.sourceAudioUri = res.audioUri;206 } else if (type === "result") {207 this.resultAudioUri = res.audioUri;208 }209 })210 .catch(err => {211 this.showMsg(err, "error");212 });213 },214 selectLang: function(item) {215 if (this.selectLangType === "source") {216 this.sourceLang = item;217 this.searchEngine === "youdao" &&218 item.code !== "zh-CN" &&219 (this.resultLang = { code: "zh-CN", lang: "ä¸æ" });220 } else if (this.selectLangType === "result") {221 this.resultLang = item;222 this.searchEngine === "youdao" &&223 item.code !== "zh-CN" &&224 (this.sourceLang = { code: "zh-CN", lang: "ä¸æ" });225 }226 this.selectLangFlag = false;227 this.getTsFn();228 },229 clearText: function() {230 this.searchString = "";231 this.sourceAudioUri = "";232 this.resultAudioUri = "";233 },234 copyText: function(type) {235 var input = this.$refs.input;236 switch (type) {237 case "source":238 input.value = this.searchString;239 break;240 case "result":241 input.value = this.searchResult;242 break;243 }244 input.select(); // éæ©å¯¹è±¡245 document.execCommand("copy"); // æ§è¡æµè§å¨å¤å¶å½ä»¤246 input.blur();247 this.showMsg("å¤å¶æå", "success");248 },249 exchangeLang: function() {250 var tmp = this.sourceLang;251 this.sourceLang = this.resultLang;252 this.resultLang = tmp;253 this.searchString = this.searchResult;254 this.getTsFn();255 },256 getChainProperty: function(origin, chainArr) {257 var res = origin;258 while (chainArr.length > 0) {259 if (!res) {260 return null;261 }262 var cur = chainArr.shift();263 res = res[cur];264 }265 return res;266 },267 showMsg: function(msg, type = "info") {268 this.$Message[type](msg);269 },270 postData: function(url, data) {271 // Default options are marked with *272 return fetch(url, {273 body: JSON.stringify(data), // must match 'Content-Type' header274 cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached275 credentials: "same-origin", // include, same-origin, *omit276 headers: {277 "user-agent": "Mozilla/4.0 MDN Example",278 "content-type": "application/json"279 },280 method: "POST", // *GET, POST, PUT, DELETE, etc.281 mode: "cors", // no-cors, cors, *same-origin282 redirect: "follow", // manual, *follow, error283 referrer: "no-referrer" // *client, no-referrer284 }).then(response => response.json()); // parses response to JSON285 }286 }...
vowel-trainer.ts
Source:vowel-trainer.ts
1import { Component, ViewChild, NgZone } from "@angular/core";2import { Events, IonicPage, NavController, NavParams } from "ionic-angular";3import {4 AppDataProvider,5 Word,6 Talker,7 WordTypes,8} from "../../providers/app-data/app-data";9import { ExampleWordPage } from "../../pages/example-word/example-word";10import { VocalTractAnimationComponent } from "../../components/vocal-tract-animation/vocal-tract-animation";11import { AudioProvider, AudioPlayer } from "../../providers/audio/audio";12import { KeywordComponent } from "../../components/keyword/keyword";13import * as mdColors from "material-colors";14enum ViewState {15 Audio,16 Video,17 Animation,18 Recording,19 Examples,20}21@IonicPage()22@Component({23 selector: "page-vowel-trainer",24 templateUrl: "vowel-trainer.html",25})26export class VowelTrainerPage {27 @ViewChild(VocalTractAnimationComponent)28 vocalTractAnimation: VocalTractAnimationComponent;29 @ViewChild("keyword") keyword: KeywordComponent;30 @ViewChild("keywordVowel") keywordVowel: KeywordComponent;31 public readonly ViewState = ViewState;32 private viewState: ViewState;33 public talker: Talker;34 public keywordExampleMap: any;35 public player: AudioPlayer;36 public backgroundColor: string = mdColors.yellow[500];37 constructor(38 public navCtrl: NavController,39 public navParams: NavParams,40 private appData: AppDataProvider,41 private audio: AudioProvider,42 public ngZone: NgZone,43 public events: Events44 ) {45 this.viewState = ViewState.Audio;46 this.talker = appData.getTalker();47 this.keywordExampleMap = appData.keywordExampleMap;48 this.player = this.audio.player;49 this.events.subscribe("svg:loaded", () => {50 this.setUpAnimation();51 });52 }53 ngAfterViewInit() {54 this.player.initialise();55 this.setWords();56 }57 goHome() {58 this.audio.stop();59 this.navCtrl.pop();60 }61 changeViewState(viewState: ViewState) {62 if (this.viewState !== viewState) {63 this.viewState = viewState;64 if (this.viewState === ViewState.Animation) {65 this.setUpAnimation();66 }67 }68 }69 setUpAnimation() {70 if (this.vocalTractAnimation.ready()) {71 this.vocalTractAnimation.setUpVowelAnimation(72 this.getWord().description,73 this.getVowelUri()74 );75 }76 }77 isViewState(viewState: ViewState) {78 if (this.viewState === viewState) {79 return "true";80 }81 }82 getKeyword(highlightVowel: boolean = false): string {83 let word: Word = this.getWord();84 if (highlightVowel) {85 return word.highlight.replace(86 /([^<]*)<([a-z]+)>(.*)/, // '<span class="keyword-display">$1$2$3</span>');87 // tslint:disable-next-line: max-line-length88 '<span class="keyword-display lowlight">$1</span><span class="keyword-display highlight">$2</span><span class="keyword-display lowlight">$3</span>'89 );90 }91 return `<span class="keyword-display">${word.display}</span>`;92 }93 getWord(): Word {94 let word: Word = this.appData.getKeyword();95 if (word === undefined) {96 global.console.error(`No entry for keyword ${word.id}`);97 }98 return word;99 }100 getExampleWords() {101 let word = this.getWord();102 let examples = this.appData.keywordExampleMap[word.hvd];103 return examples.slice(0, 2);104 }105 getExampleWordImageUri(word: string) {106 let uri: string = this.appData.getImageUri(word, WordTypes.ExampleWords);107 return uri;108 }109 getExampleWord(wordId: string) {110 return this.appData.exampleWords[wordId];111 }112 // ionViewDidLoad() {}113 goBack() {114 this.navCtrl.pop();115 }116 showExampleWord(index: number) {117 this.appData.setExampleWordIndex(index);118 this.navCtrl.push(ExampleWordPage);119 }120 setWords() {121 this.keywordVowel.setUri(this.getVowelUri());122 this.keyword.setUri(this.getKeywordUri());123 this.setUpAnimation();124 }125 playExampleWord(word: string, index: number) {126 let uri = this.appData.getAudioUri(127 this.appData.getTalker().id,128 word,129 WordTypes.ExampleWords130 );131 this.player132 .playUrl(uri)133 .then(() => {134 this.showExampleWord(index);135 })136 // tslint:disable-next-line: no-empty137 .catch(() => { });138 }139 getKeywordUri() {140 let uri = this.appData.getAudioUri(141 this.appData.talker.id,142 this.appData.getKeyword().id,143 WordTypes.Keywords144 );145 return uri;146 }147 getVowelUri() {148 let uri = this.appData.getAudioUri(149 this.appData.talker.id,150 this.appData.getKeyword().hvd,151 WordTypes.Vowels152 );153 return uri;154 }155 getKeywordImageUri() {156 let uri: string = this.appData.getImageUri(157 this.appData.getKeyword().id,158 WordTypes.Keywords159 );160 return uri;161 }...
useDataService.ts
Source:useDataService.ts
1import axios, { AxiosInstance } from "axios";2import config from "../config";3import { useAuth0 } from "@auth0/auth0-react";4import { useCallback } from "react";5export interface UseDataServiceOutput {6 _axios: AxiosInstance;7 destroy(request: DestroyRequest): Promise<unknown>;8 insert(request: InsertRequest): Promise<unknown>;9 query<T = unknown>(request: QueryRequest): Promise<T[]>;10 update(request: UpdateRequest): Promise<unknown>;11 getAudioUri(file_key: string): Promise<string>;12 putAudioFile(blob: Blob): Promise<string>;13}14const _axios = axios.create({15 baseURL: config.apiBaseUrl16});17const useDataservice = (): UseDataServiceOutput => {18 const { getAccessTokenSilently } = useAuth0();19 const putAudioFile = useCallback(20 async (blob: Blob): Promise<string> => {21 const token = await getAccessTokenSilently();22 const formData = new FormData();23 formData.append("file", blob);24 const {25 data: { file_key }26 } = await _axios.post<{ file_key: string }>("/file", formData, {27 headers: {28 Authorization: `Bearer ${token}`,29 "Content-Type": "multipart/form-data"30 }31 });32 return file_key;33 },34 [getAccessTokenSilently]35 );36 const getAudioUri = useCallback(37 async (file_key: string): Promise<string> => {38 const token = await getAccessTokenSilently();39 const { data } = await _axios.get<Blob>("/file", {40 params: { file_key },41 headers: {42 Authorization: `Bearer ${token}`43 },44 responseType: "blob"45 });46 const dataUrl = await new Promise<string>((resolve) => {47 const reader = new FileReader();48 reader.onload = () => {49 const data = reader.result as string;50 resolve(data);51 };52 reader.readAsDataURL(data);53 });54 return dataUrl;55 },56 [getAccessTokenSilently]57 );58 const destroy = useCallback(59 async (request: DestroyRequest): Promise<unknown> => {60 const token = await getAccessTokenSilently();61 const { data } = await _axios.post("/destroy", request, {62 headers: {63 Authorization: `Bearer ${token}`64 }65 });66 return data;67 },68 [getAccessTokenSilently]69 );70 const insert = useCallback(71 async (request: InsertRequest): Promise<unknown> => {72 const token = await getAccessTokenSilently();73 const { data } = await _axios.post("/insert", request, {74 headers: {75 Authorization: `Bearer ${token}`76 }77 });78 return data;79 },80 [getAccessTokenSilently]81 );82 const query = useCallback(83 async <T = unknown>(request: QueryRequest): Promise<T[]> => {84 const token = await getAccessTokenSilently();85 const { data } = await _axios.post<T[]>("/query", request, {86 headers: {87 Authorization: `Bearer ${token}`88 }89 });90 return data;91 },92 [getAccessTokenSilently]93 );94 const update = useCallback(95 async (request: UpdateRequest): Promise<unknown> => {96 const token = await getAccessTokenSilently();97 const { data } = await _axios.post("/update", request, {98 headers: {99 Authorization: `Bearer ${token}`100 }101 });102 return data;103 },104 [getAccessTokenSilently]105 );106 return { _axios, destroy, insert, query, update, getAudioUri, putAudioFile };107};108export default useDataservice;109export interface DestroyRequest {110 table: string;111 where: number[] | { [key: string]: unknown };112}113export interface InsertRequest {114 table: string;115 values: { [key: string]: unknown } | { [key: string]: unknown }[];116}117export interface QueryRequest {118 table: string;119 where?: { [key: string]: unknown };120 skip?: number;121 take?: number;122 select?: string[];123 relations?: string[];124 order?: {125 [key: string]: "ASC" | "DESC";126 };127}128export interface UpdateRequest {129 table: string;130 where: { [key: string]: unknown };131 values: { [key: string]: unknown };...
Using AI Code Generation
1const wptools = require('wptools');2wptools.getAudioURI('Albert Einstein', (err, res) => {3 if (err) {4 console.log(err);5 } else {6 console.log(res);7 }8});
Using AI Code Generation
1var wptoolkit = require("wptoolkit");2var audioURI = wptoolkit.getAudioURI();3var wptoolkit = require("wptoolkit");4var audioURI = wptoolkit.getAudioURI();5var wptoolkit = require("wptoolkit");6var audioURI = wptoolkit.getAudioURI();7var wptoolkit = require("wptoolkit");8var audioURI = wptoolkit.getAudioURI();9var wptoolkit = require("wptoolkit");10var audioURI = wptoolkit.getAudioURI();11var wptoolkit = require("wptoolkit");12var audioURI = wptoolkit.getAudioURI();13var wptoolkit = require("wptoolkit");14var audioURI = wptoolkit.getAudioURI();15var wptoolkit = require("wptoolkit");16var audioURI = wptoolkit.getAudioURI();17var wptoolkit = require("wptoolkit");18var audioURI = wptoolkit.getAudioURI();19var wptoolkit = require("wptoolkit");20var audioURI = wptoolkit.getAudioURI();21var wptoolkit = require("wptoolkit");22var audioURI = wptoolkit.getAudioURI();23var wptoolkit = require("wptoolkit");24var audioURI = wptoolkit.getAudioURI();25var wptoolkit = require("wptoolkit");26var audioURI = wptoolkit.getAudioURI();
Using AI Code Generation
1const wptools = require('wptools');2const wiki = wptools.page('John Lennon');3wiki.getAudioURI((err, res) => {4 if (err) {5 console.log(err);6 } else {7 console.log(res);8 }9});
Using AI Code Generation
1var wptools = require('wptools');2var wiki = wptools.page('Adele');3wiki.getAudioURI(function(err, audio) {4 console.log(audio);5});6var wptools = require('wptools');7var wiki = wptools.page('Adele');8wiki.getAudioURI(function(err, audio) {9 console.log(audio);10});11var wptools = require('wptools');12var wiki = wptools.page('Adele');13wiki.getAudioURI(function(err, audio) {14 console.log(audio);15});16var wptools = require('wptools');17var wiki = wptools.page('Adele');18wiki.getAudioURI(function(err, audio) {19 console.log(audio);20});21var wptools = require('wptools');22var wiki = wptools.page('Adele');23wiki.getAudioURI(function(err, audio) {24 console.log(audio);25});26var wptools = require('wptools');27var wiki = wptools.page('Adele');28wiki.getAudioURI(function(err, audio) {29 console.log(audio);30});31var wptools = require('wptools');32var wiki = wptools.page('Adele');33wiki.getAudioURI(function(err, audio) {34 console.log(audio);35});36var wptools = require('wptools');37var wiki = wptools.page('Adele');38wiki.getAudioURI(function(err, audio) {39 console.log(audio);40});41var wptools = require('wptools');42var wiki = wptools.page('Adele');43wiki.getAudioURI(function(err, audio) {44 console.log(audio);45});46var wptools = require('wptools');47var wiki = wptools.page('Adele');
Using AI Code Generation
1var wptoolkit = require('wptoolkit');2var wp = new wptoolkit();3 if(err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9var wptoolkit = require('wptoolkit');10var wp = new wptoolkit();11 if(err) {12 console.log(err);13 } else {14 console.log(data);15 }16});
Using AI Code Generation
1var wptoolkit = require('wptoolkit');2var audio = wptoolkit.getAudioURI('audio.wav');3var audio = new Audio(audio);4audio.play();5var wptoolkit = require('wptoolkit');6var audio = wptoolkit.getAudioURI('audio.wav');7var audio = new Audio(audio);8audio.play();9var wptoolkit = require('wptoolkit');10var audio = wptoolkit.getAudioURI('audio.wav');11var audio = new Audio(audio);12audio.play();13var wptoolkit = require('wptoolkit');14var audio = wptoolkit.getAudioURI('audio.wav');15var audio = new Audio(audio);16audio.play();17var wptoolkit = require('wptoolkit');18var audio = wptoolkit.getAudioURI('audio.wav');19var audio = new Audio(audio);20audio.play();21var wptoolkit = require('wptoolkit');22var audio = wptoolkit.getAudioURI('audio.wav');23var audio = new Audio(audio);24audio.play();25var wptoolkit = require('wptoolkit');26var audio = wptoolkit.getAudioURI('audio.wav');
Using AI Code Generation
1var wptoolkit = require('wptoolkit');2var options = {3};4wptoolkit.getAudioURI(options, function (err, data) {5 console.log(data);6});7var wptoolkit = require('wptoolkit');8var options = {9};10wptoolkit.getVideoURI(options, function (err, data) {11 console.log(data);12});13var wptoolkit = require('wptoolkit');14var options = {15};16wptoolkit.getVideoInfo(options, function (err, data) {17 console.log(data);18});19var wptoolkit = require('wptoolkit');20var options = {21};22wptoolkit.getVideoInfo(options, function (err, data) {23 console.log(data);24});25var wptoolkit = require('wptoolkit');26var options = {27};28wptoolkit.getVideoInfo(options, function (err, data) {29 console.log(data);30});31var wptoolkit = require('wptoolkit');32var options = {33};34wptoolkit.getVideoInfo(options, function (err, data) {35 console.log(data);36});37var wptoolkit = require('wptoolkit');38var options = {
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!!