Best JavaScript code snippet using appium-base-driver
pooling.js
Source:pooling.js
...26 });27 context('when the pool is not full', () => {28 it('should retrieve a valid connection', () => {29 const client = mysqlx.getClient(config);30 return expect(client.getSession()).to.be.fulfilled31 .then(session => {32 return expect(session.inspect()).to.deep.include({ pooling: true });33 })34 .then(() => {35 return client.close();36 });37 });38 it('should allow to retrieve connections in parallel', () => {39 const client = mysqlx.getClient(config);40 return expect(Promise.all([client.getSession(), client.getSession()])).to.be.fulfilled41 .then(() => {42 return client.close();43 });44 });45 it('should start from a clean session slate', () => {46 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 2 } });47 const expected = [[null]];48 const actual = [];49 return client.getSession()50 .then(session => {51 return session.sql('SET @a = 5').execute()52 .then(() => session.close());53 })54 .then(() => {55 return client.getSession();56 })57 .then(session => {58 return session.sql('SELECT @a = 5').execute(row => actual.push(row))59 .then(() => session.close());60 })61 .then(() => {62 expect(actual).to.deep.equal(expected);63 return client.close();64 });65 });66 it('it should not fail to retrieve a connection with short maximum idle times', () => {67 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 4, maxIdleTime: 1 } });68 return client.getSession()69 .then(() => client.getSession())70 .then(() => client.getSession())71 .then(() => expect(client.getSession()).to.be.fulfilled)72 .then(() => client.close());73 });74 });75 context('when the pool is full', () => {76 context('and there are idle connections', () => {77 it('should wait indefinetily for a valid connection with the default timeout', () => {78 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1 } });79 return client.getSession()80 .then(session => {81 return session.close();82 })83 .then(() => {84 return new Promise((resolve, reject) => {85 // wait for a few millis before passing86 setTimeout(resolve, 1000);87 client.getSession().then(resolve).catch(reject);88 });89 })90 .then(() => {91 return client.close();92 });93 });94 it('should retrieve a valid connection if one is made available and there is no queueTimeout', () => {95 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 2 } });96 return Promise.all([client.getSession(), client.getSession()])97 .then(sessions => {98 return expect(Promise.all([client.getSession(), sessions[0].close(), sessions[1].close(), client.getSession()])).to.be.fulfilled;99 })100 .then(() => {101 return client.close();102 });103 });104 it('should retrieve a valid connection if one is made available before exceeding the queueTimeout', () => {105 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1, queueTimeout: 2000 } });106 return client.getSession()107 .then(session => {108 const delayed = new Promise(resolve => {109 setTimeout(() => session.close().then(resolve), 500);110 });111 return expect(Promise.all([client.getSession(), delayed])).to.be.fulfilled;112 })113 .then(() => {114 return client.close();115 });116 });117 it('should retrieve a valid connection if the timeout is above the maximum idle time', function () {118 const maxIdleTime = 100;119 const queueTimeout = maxIdleTime * 50;120 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1, maxIdleTime, queueTimeout } });121 return client.getSession()122 .then(session => {123 return session.close();124 })125 .then(() => {126 return new Promise((resolve, reject) => {127 setTimeout(() => client.getSession().then(resolve).catch(reject), maxIdleTime * 10);128 });129 })130 .then(session => {131 return expect(session.inspect()).to.deep.include({ pooling: true });132 })133 .then(() => {134 return client.close();135 });136 });137 it('should start from a clean session slate', () => {138 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1 } });139 const expected = [[null]];140 const actual = [];141 return client.getSession()142 .then(session => {143 return session.sql('SET @a = 5').execute()144 .then(() => session.close());145 })146 .then(() => {147 return client.getSession();148 })149 .then(session => {150 return session.sql('SELECT @a = 5').execute(row => actual.push(row))151 .then(() => session.close());152 })153 .then(() => {154 expect(actual).to.deep.equal(expected);155 return client.close();156 });157 });158 it('should fail if the timeout is exceeded', () => {159 const queueTimeout = 100;160 const maxIdleTime = queueTimeout * 10;161 const error = `Could not retrieve a connection from the pool. Timeout of ${queueTimeout} ms was exceeded.`;162 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1, maxIdleTime, queueTimeout } });163 return client.getSession()164 .then(() => {165 return expect(client.getSession()).to.be.rejectedWith(error);166 })167 .then(() => {168 return client.close();169 });170 });171 it('prioritizes idle connections instead of unused ones', () => {172 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 3 } });173 const connections = [];174 return client.getSession()175 .then(session1 => {176 return session1.sql('SELECT CONNECTION_ID()')177 .execute(row => connections.push(row[0]))178 .then(() => client.getSession())179 .then(session2 => {180 return session2.sql('SELECT CONNECTION_ID()')181 .execute(row => connections.push(row[0]))182 // close the second session183 .then(() => session2.close());184 })185 .then(() => client.getSession())186 .then(session3 => {187 return session3.sql('SELECT CONNECTION_ID()')188 .execute(row => connections.push(row[0]))189 // close the first session190 .then(() => session1.close());191 })192 .then(() => client.getSession())193 .then(session4 => {194 return session4.sql('SELECT CONNECTION_ID()')195 .execute(row => connections.push(row[0]));196 });197 })198 .then(() => {199 expect(connections).to.have.lengthOf(4);200 expect(connections[2]).to.equal(connections[1]);201 expect(connections[3]).to.equal(connections[0]);202 return client.close();203 });204 });205 it('prioritizes idle connections instead of closed ones', () => {206 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 3, maxIdleTime: 10 } });207 const connections = [];208 return client.getSession()209 .then(session1 => {210 return session1.sql('SELECT CONNECTION_ID()')211 .execute(row => connections.push(row[0]))212 .then(() => client.getSession())213 .then(session2 => {214 return session2.sql('SELECT CONNECTION_ID()')215 .execute(row => connections.push(row[0]))216 // close the second session217 .then(() => session2.close());218 })219 .then(() => new Promise(resolve => {220 setTimeout(() => client.getSession().then(resolve), 100);221 }))222 .then(session3 => {223 return session3.sql('SELECT CONNECTION_ID()')224 .execute(row => connections.push(row[0]))225 // close the first session226 .then(() => session1.close());227 })228 .then(() => new Promise(resolve => {229 setTimeout(() => client.getSession().then(resolve), 100);230 }))231 .then(session4 => {232 return session4.sql('SELECT CONNECTION_ID()')233 .execute(row => connections.push(row[0]));234 });235 })236 .then(() => {237 expect(connections).to.have.lengthOf(4);238 expect(connections[2]).to.equal(connections[1]);239 expect(connections[3]).to.equal(connections[0]);240 return client.close();241 });242 });243 it('re-uses idle connections after some period of inactivity', () => {244 const baseConfig = Object.assign({}, config, { connectTimeout: 100 });245 const client = mysqlx.getClient(baseConfig, { pooling: { maxSize: 2 } });246 const connections = [];247 return client.getSession()248 .then(session1 => {249 return session1.sql('SELECT CONNECTION_ID()')250 .execute(row => connections.push(row[0]))251 .then(() => session1.close());252 })253 .then(() => {254 return new Promise(resolve => setTimeout(() => client.getSession().then(resolve), 200));255 })256 .then(session2 => {257 return session2.sql('SELECT CONNECTION_ID()')258 .execute(row => connections.push(row[0]))259 .then(() => session2.close());260 })261 .then(() => {262 expect(connections).to.have.lengthOf(2);263 expect(connections[1]).to.equal(connections[0]);264 return client.close();265 });266 });267 });268 context('and there are no idle connections', () => {269 it('should wait indefinetily for a valid connection with the default timeout', () => {270 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1 } });271 return client.getSession()272 .then(() => {273 return new Promise((resolve, reject) => {274 // wait for a few millis before passing275 setTimeout(resolve, 1000);276 client.getSession().then(resolve).catch(reject);277 });278 })279 .then(() => {280 return client.close();281 });282 });283 it('should fail after the timeout is exceeded', () => {284 const queueTimeout = 200;285 const error = `Could not retrieve a connection from the pool. Timeout of ${queueTimeout} ms was exceeded.`;286 const client = mysqlx.getClient(config, { pooling: { enabled: true, maxSize: 1, queueTimeout } });287 return client.getSession()288 .then(() => {289 return expect(client.getSession()).to.be.rejectedWith(error);290 })291 .then(() => {292 return client.close();293 });294 });295 });296 });297 context('session state', () => {298 it('should make idle connections unusable', () => {299 const maxIdleTime = 1;300 const client = mysqlx.getClient(config, { pooling: { maxIdleTime } });301 const error = 'This session was closed. Use "mysqlx.getSession()" or "mysqlx.getClient()" to create a new one.';302 return client.getSession()303 .then(session => {304 return session.close()305 .then(() => {306 return new Promise(resolve => setTimeout(resolve, maxIdleTime * 10));307 })308 .then(() => {309 return expect(session.getSchemas()).to.be.rejectedWith(error);310 });311 })312 .then(() => {313 return client.close();314 });315 });316 context('killing connections', () => {317 it('should not fail when closing connections that have been killed', () => {318 const client = mysqlx.getClient(config, { pooling: { maxSize: 2 } });319 const connections = [];320 return client.getSession()321 .then(session1 => {322 return session1.sql('SELECT CONNECTION_ID()').execute(row => connections.push(row[0]))323 .then(() => {324 return session1.close();325 });326 })327 .then(() => {328 return Promise.all([client.getSession(), client.getSession()]);329 })330 .then(sessions => {331 // sessions[0] should have the same id as session1332 return sessions[1].sql(`KILL ${connections[0]}`)333 .execute()334 .then(() => {335 return expect(sessions[0].close()).to.be.fulfilled;336 });337 })338 .then(() => {339 return client.close();340 });341 });342 it('should properly re-use a connection that has been killed', () => {343 const client = mysqlx.getClient(config, { pooling: { maxSize: 2 } });344 const connections = [];345 return client.getSession()346 .then(session1 => {347 return session1.sql('SELECT CONNECTION_ID()')348 .execute(row => connections.push(row[0]))349 .then(() => {350 return session1.close();351 });352 })353 .then(() => {354 return Promise.all([client.getSession(), client.getSession()]);355 })356 .then(sessions => {357 return Promise.all([sessions[0].close(), sessions[1].sql(`KILL ${connections[0]}`).execute()]);358 })359 .then(() => {360 return expect(client.getSession()).to.be.fulfilled;361 })362 .then(session4 => {363 return session4.sql('SELECT CONNECTION_ID()')364 .execute(row => connections.push(row[0]));365 })366 .then(() => {367 expect(connections).to.have.lengthOf(2);368 // session1 and session4 should have different ids since the connection was re-created369 expect(connections[0]).to.not.equal(connections[1]);370 return client.close();371 });372 });373 });374 });375 context('closing the pool', () => {376 it('closes all the active connections in the server', () => {377 const client = mysqlx.getClient(config, { pooling: { maxSize: 3 } });378 const processIds = [];379 const connectionIds = [];380 const trackConnectionId = () => {381 return client.getSession()382 .then(session => {383 return session.sql('SELECT CONNECTION_ID()')384 .execute(row => connectionIds.push(row[0]));385 });386 };387 return Promise.all([trackConnectionId(), trackConnectionId(), trackConnectionId()])388 .then(() => client.close())389 .then(() => mysqlx.getSession(config))390 .then(session => {391 return session.sql('SHOW PROCESSLIST')392 .execute(row => processIds.push(row[0]))393 .then(() => session.close());394 })395 .then(() => {396 expect(processIds).to.not.include.members(connectionIds);397 });398 });399 });...
account_control.js
Source:account_control.js
...31import("etherpad.pad.padutils");32import("etherpad.pad.padusers");33import("etherpad.collab.collab_server");34function onRequest() {35 if (!getSession().tempFormData) {36 getSession().tempFormData = {};37 }38 return false; // path not handled here39}40//--------------------------------------------------------------------------------41// helpers42//--------------------------------------------------------------------------------43function _redirOnError(m, clearQuery) {44 if (m) {45 getSession().accountFormError = m;46 var dest = request.url;47 if (clearQuery) {48 dest = request.path;49 }50 response.redirect(dest);51 }52}53function setSigninNotice(m) {54 getSession().accountSigninNotice = m;55}56function setSessionError(m) {57 getSession().accountFormError = m;58}59function _topDiv(id, name) {60 var m = getSession()[name];61 if (m) {62 delete getSession()[name];63 return DIV({id: id}, m);64 } else {65 return '';66 }67}68function _messageDiv() { return _topDiv('account-message', 'accountMessage'); }69function _errorDiv() { return _topDiv('account-error', 'accountFormError'); }70function _signinNoticeDiv() { return _topDiv('signin-notice', 'accountSigninNotice'); }71function _renderTemplate(name, data) {72 data.messageDiv = _messageDiv;73 data.errorDiv = _errorDiv;74 data.signinNotice = _signinNoticeDiv;75 data.tempFormData = getSession().tempFormData;76 renderFramed('pro/account/'+name+'.ejs', data);77}78//----------------------------------------------------------------79// /ep/account/80//----------------------------------------------------------------81function render_main_get() {82 _renderTemplate('my-account', {83 account: getSessionProAccount(),84 changePass: getSession().changePass85 });86}87function render_update_info_get() {88 response.redirect('/ep/account/');89}90function render_update_info_post() {91 var fullName = request.params.fullName;92 var email = trim(request.params.email);93 getSession().tempFormData.email = email;94 getSession().tempFormData.fullName = fullName;95 _redirOnError(pro_accounts.validateEmail(email));96 _redirOnError(pro_accounts.validateFullName(fullName));97 98 pro_accounts.setEmail(getSessionProAccount(), email);99 pro_accounts.setFullName(getSessionProAccount(), fullName);100 getSession().accountMessage = "Info updated.";101 response.redirect('/ep/account/');102}103function render_update_password_get() {104 response.redirect('/ep/account/');105}106function render_update_password_post() {107 var password = request.params.password;108 var passwordConfirm = request.params.passwordConfirm;109 if (password != passwordConfirm) { _redirOnError('Passwords did not match.'); }110 _redirOnError(pro_accounts.validatePassword(password));111 112 pro_accounts.setPassword(getSessionProAccount(), password);113 if (getSession().changePass) {114 delete getSession().changePass;115 response.redirect('/');116 }117 getSession().accountMessage = "Password updated.";118 response.redirect('/ep/account/');119}120//--------------------------------------------------------------------------------121// signin/signout122//--------------------------------------------------------------------------------123function render_sign_in_get() {124 if (request.params.uid && request.params.tp) {125 var m = pro_accounts.authenticateTempSignIn(Number(request.params.uid), request.params.tp);126 if (m) {127 getSession().accountFormError = m;128 response.redirect('/ep/account/');129 }130 }131 if (request.params.instantSigninKey) {132 _attemptInstantSignin(request.params.instantSigninKey);133 }134 if (getSession().recentlySignedOut && getSession().accountFormError) {135 delete getSession().accountFormError;136 delete getSession().recentlySignedOut;137 }138 // Note: must check isAccountSignedIn before calling checkAutoSignin()!139 if (pro_accounts.isAccountSignedIn()) {140 _redirectToPostSigninDestination();141 }142 pro_account_auto_signin.checkAutoSignin();143 var domainRecord = domains.getRequestDomainRecord();144 var showGuestBox = false;145 if (request.params.guest && request.params.padId) {146 showGuestBox = true;147 }148 _renderTemplate('signin', {149 domain: pro_utils.getFullProDomain(),150 siteName: toHTML(pro_config.getConfig().siteName),151 email: getSession().tempFormData.email || "",152 password: getSession().tempFormData.password || "",153 rememberMe: getSession().tempFormData.rememberMe || false,154 showGuestBox: showGuestBox,155 localPadId: request.params.padId156 });157}158function _attemptInstantSignin(key) {159 // See src/etherpad/control/global_pro_account_control.js160 var email = null;161 var password = null;162 syncedWithCache('global_signin_passwords', function(c) {163 if (c[key]) {164 email = c[key].email;165 password = c[key].password;166 }167 delete c[key];168 });169 getSession().tempFormData.email = email;170 _redirOnError(pro_accounts.authenticateSignIn(email, password), true);171}172function render_sign_in_post() {173 var email = trim(request.params.email);174 var password = request.params.password;175 getSession().tempFormData.email = email;176 getSession().tempFormData.rememberMe = request.params.rememberMe;177 _redirOnError(pro_accounts.authenticateSignIn(email, password));178 pro_account_auto_signin.setAutoSigninCookie(request.params.rememberMe);179 _redirectToPostSigninDestination();180}181function render_guest_sign_in_get() {182 var localPadId = request.params.padId;183 var domainId = domains.getRequestDomainId();184 var globalPadId = padutils.makeGlobalId(domainId, localPadId);185 var userId = padusers.getUserId();186 pro_account_auto_signin.checkAutoSignin();187 pad_security.clearKnockStatus(userId, globalPadId);188 _renderTemplate('signin-guest', {189 localPadId: localPadId,190 errorMessage: getSession().guestAccessError,191 siteName: toHTML(pro_config.getConfig().siteName),192 guestName: padusers.getUserName() || ""193 });194}195function render_guest_sign_in_post() {196 function _err(m) {197 if (m) {198 getSession().guestAccessError = m;199 response.redirect(request.url);200 }201 }202 var displayName = request.params.guestDisplayName;203 var localPadId = request.params.localPadId;204 if (!(displayName && displayName.length > 0)) {205 _err("Please enter a display name");206 }207 getSession().guestDisplayName = displayName;208 response.redirect('/ep/account/guest-knock?padId='+encodeURIComponent(localPadId)+209 "&guestDisplayName="+encodeURIComponent(displayName));210}211function render_guest_knock_get() {212 var localPadId = request.params.padId;213 helpers.addClientVars({214 localPadId: localPadId,215 guestDisplayName: request.params.guestDisplayName,216 padUrl: "http://"+httpHost(request.host)+"/"+localPadId217 });218 _renderTemplate('guest-knock', {});219}220function render_guest_knock_post() {221 var localPadId = request.params.padId;222 var displayName = request.params.guestDisplayName;223 var domainId = domains.getRequestDomainId();224 var globalPadId = padutils.makeGlobalId(domainId, localPadId);225 var userId = padusers.getUserId();226 response.setContentType("text/plain; charset=utf-8");227 // has the knock already been answsered?228 var currentAnswer = pad_security.getKnockAnswer(userId, globalPadId);229 if (currentAnswer) {230 response.write(currentAnswer);231 } else {232 collab_server.guestKnock(globalPadId, userId, displayName);233 response.write("wait");234 }235}236function _redirectToPostSigninDestination() {237 var cont = request.params.cont;238 if (!cont) { cont = '/'; }239 response.redirect(cont);240}241function render_sign_out() {242 pro_account_auto_signin.setAutoSigninCookie(false);243 pro_accounts.signOut();244 delete getSession().padPasswordAuth;245 getSession().recentlySignedOut = true;246 response.redirect("/");247}248//--------------------------------------------------------------------------------249// create-admin-account (eepnet only)250//--------------------------------------------------------------------------------251function render_create_admin_account_get() {252 if (pro_accounts.doesAdminExist()) {253 renderFramedError("An admin account already exists on this domain.");254 response.stop();255 }256 _renderTemplate('create-admin-account', {});257}258function render_create_admin_account_post() {259 var email = trim(request.params.email);260 var password = request.params.password;261 var passwordConfirm = request.params.passwordConfirm;262 var fullName = request.params.fullName;263 getSession().tempFormData.email = email;264 getSession().tempFormData.fullName = fullName;265 if (password != passwordConfirm) { _redirOnError('Passwords did not match.'); }266 _redirOnError(pro_accounts.validateEmail(email));267 _redirOnError(pro_accounts.validateFullName(fullName));268 _redirOnError(pro_accounts.validatePassword(password));269 pro_accounts.createNewAccount(null, fullName, email, password, true);270 var u = pro_accounts.getAccountByEmail(email, null);271 // TODO: should we send a welcome email here?272 //pro_accounts.sendWelcomeEmail(u);273 _redirOnError(pro_accounts.authenticateSignIn(email, password));274 response.redirect("/");275}276//--------------------------------------------------------------------------------277// forgot password278//--------------------------------------------------------------------------------279function render_forgot_password_get() {280 if (request.params.instantSubmit && request.params.email) {281 render_forgot_password_post();282 } else {283 _renderTemplate('forgot-password', {284 email: getSession().tempFormData.email || ""285 });286 }287}288function render_forgot_password_post() {289 var email = trim(request.params.email);290 getSession().tempFormData.email = email;291 var u = pro_accounts.getAccountByEmail(email, null);292 if (!u) {293 _redirOnError("Account not found: "+email);294 }295 var tempPass = stringutils.randomString(10);296 pro_accounts.setTempPassword(u, tempPass);297 var subj = "EtherPad: Request to reset your password on "+request.domain;298 var body = renderTemplateAsString('pro/account/forgot-password-email.ejs', {299 account: u,300 recoverUrl: pro_accounts.getTempSigninUrl(u, tempPass)301 });302 var fromAddr = pro_utils.getEmailFromAddr();303 sendEmail(u.email, fromAddr, subj, {}, body);304 getSession().accountMessage = "An email has been sent to "+u.email+" with instructions to reset the password.";305 response.redirect(request.path);...
edit.js
Source:edit.js
...16 editor.lastValue = null;17 statusBar = new StatusBar(editor, document.getElementById("statusBar"));18 var ext = op.ext;19 if (ext == 'js')20 editor.getSession().setMode("ace/mode/javascript");21 else if (ext == "json" || ext == "json6")22 editor.getSession().setMode("ace/mode/json");23 else if (ext == "jsx" || ext == "es" || ext == "es6")24 editor.getSession().setMode("ace/mode/jsx");25 else if (ext == 'xml' || ext == "xsl")26 editor.getSession().setMode("ace/mode/xml");27 else if (ext == 'xsd')28 editor.getSession().setMode("ace/mode/scheme");29 else if (ext == "conf")30 editor.getSession().setMode("ace/mode/nix");31 else if (ext == 'css' || ext == "scss")32 editor.getSession().setMode("ace/mode/scss");33 else if (ext == "lua")34 editor.getSession().setMode("ace/mode/lua");35 else if (ext == "sql")36 editor.getSession().setMode("ace/mode/mysql");37 else if (ext == "less")38 editor.getSession().setMode("ace/mode/less");39 else if (ext == 'md')40 editor.getSession().setMode("ace/mode/markdown");41 else if (ext == "html")42 editor.getSession().setMode("ace/mode/html");43 else if (ext == "java")44 editor.getSession().setMode("ace/mode/java");45 else if (ext == "jsp")46 editor.getSession().setMode("ace/mode/jsp");47 else if (ext == "vm")48 editor.getSession().setMode("ace/mode/velocity");49 else if (ext == "ftl")50 editor.getSession().setMode("ace/mode/ftl");51 else if (ext == "go")52 editor.getSession().setMode("ace/mode/golang");53 else if (ext == "py")54 editor.getSession().setMode("ace/mode/python");55 else if (ext == "php" || ext == "php5" || ext == "php6")56 editor.getSession().setMode("ace/mode/php")57 else if (ext == "jade")58 editor.getSession().setMode("ace/mode/jade");59 else if (ext == "ejs")60 editor.getSession().setMode("ace/mode/ejs");61 else if (ext == "sh")62 editor.getSession().setMode("ace/mode/sh");63 else if (ext == "coffee")64 editor.getSession().setMode("ace/mode/coffee");65 else if (ext == "cpp" || ext == "c")66 editor.getSession().setMode("ace/mode/c_cpp");67 else if (ext == "ts")68 editor.getSession().setMode("ace/mode/typescript");69 else70 editor.getSession().setMode("ace/mode/text");71 editor.getSession().setUseWrapMode(true);72 editor.getSession().setWrapLimitRange();73 editor.commands.addCommands([{74 name: "showSettingsMenu",75 bindKey: {76 win: "Ctrl-s",77 mac: "Command-s",78 sender: "editor"79 },80 exec: function (editor) {81 var value = editor.getValue();82 var oldValue = editor.lastValue;83 if (oldValue != value) {84 jQuery.post("save", {85 content: value,86 ext: editor.ext,87 path: editor.path,88 "mtime": editor.lastModifiedTime89 }, function (result) {90 Utils.handleResult(result, function () {91 if (result && result.code == "1") {92 editor.lastValue = value;93 editor.lastModifiedTime = result.mtime;94 editor.isChanged = false;95 onHandleChanged(editor.isChanged);96 onHandleNotify("<span style='color: red;'>ä¿åæåï½ï½<span>");97 } else {98 onHandleNotify("<span style='color: red;'>" + result.message || "ä¿å失败ï¼è¯·ç¨ååè¯ï½ï½" + "<span>");99 }100 });101 });102 } else {103 onHandleNotify("<span style='color: red;'>ä¿åæåï½ï½<span>");104 }105 },106 readOnly: true107 }]);108 editor.commands.addCommands([{109 name: "toggleUserWrap",110 bindKey: {111 win: "Ctrl-w",112 mac: "Command-w",113 sender: "editor"114 },115 exec: function (editor) {116 var isOn = editor.isWrapOn;117 if (isOn) {118 editor.getSession().setUseWrapMode(false);119 onHandleNotify("<span style='color: red;'>èªå¨æ¢è¡å
³éï½ï½<span>");120 } else {121 editor.getSession().setUseWrapMode(true);122 editor.getSession().setWrapLimitRange();123 onHandleNotify("<span style='color: red;'>èªå¨æ¢è¡æå¼ï½ï½<span>");124 }125 editor.isWrapOn = !isOn;126 },127 readOnly: false128 }, {129 name: "changeThmeme",130 bindKey: {131 win: "Alt-t",132 mac: "Command-t"133 },134 exec: function (editor) {135 editor.setTheme(Theme.getNextTheme());136 onHandleNotify("<span style='color: red;'>Themeæ¹ä¸ºï¼" + Theme.getCurrentThemeName() + "<span>");137 }138 }, {139 name: "bueatifyCode",140 bindKey: {141 win: "Ctrl-b",142 mac: "Command-b"143 },144 exec: function (editor) {145 if (editor.languageMode == "js" || editor.languageMode == "xml"146 || editor.languageMode == "html") {147 var Beautify = ace.require("ace/ext/beautify");148 Beautify.beautify(editor.getSession());149 onHandleNotify("<span style='color: red;'>ç¾å" + editor.languageMode + "代ç <span>");150 } else if(editor.languageMode == "json"){151 var value = editor.getValue();152 var newValue = vkbeautify.json(value, 4);153 editor.getSession().doc.setValue(newValue);154 onHandleNotify("<span style='color: red;'>ç¾å" + editor.languageMode + "代ç <span>");155 } else if(editor.languageMode == "css"){156 var value = editor.getValue();157 var newValue = vkbeautify.css(value, '. . . .');158 editor.getSession().doc.setValue(newValue);159 onHandleNotify("<span style='color: red;'>ç¾å" + editor.languageMode + "代ç <span>");160 } else if(editor.languageMode == "sql"){161 var value = editor.getValue();162 var newValue = vkbeautify.sql(value, '----');163 editor.getSession().doc.setValue(newValue);164 onHandleNotify("<span style='color: red;'>ç¾å" + editor.languageMode + "代ç <span>");165 }166 else if (editor.languageMode == "xml" || editor.languageMode == "xsd") {167 var value = editor.getValue();168 var newValue = vkbeautify.xml(value, 4);169 editor.getSession().doc.setValue(newValue);170 onHandleNotify("<span style='color: red;'>ç¾å" + editor.languageMode + "代ç <span>");171 } else {172 onHandleNotify("<span style='color: red;'>ä¸æ¯æè¯¥æ ¼å¼çç¾å<span>");173 }174 }175 }]);176 editor.lastValue = editor.getValue();177 editor.on("change", Utils.throttle(function(){178 var currentValue = editor.getValue();179 editor.isChanged = currentValue != editor.lastValue;180 onHandleChanged(editor.isChanged);181 }, 100));182 onHandleChanged(editor.isChanged);183 return editor;...
http.js
Source:http.js
...27Vue.prototype.$close=false;28axios.interceptors.request.use(29 config => {30 config.headers['Content-Type'] = 'application/x-www-form-urlencoded';31 // config.data.append("channelCode",getSession("channelCode"));32 if(config.method=='post' || config.method=='put'){33 if(config.url == '/api/upload'){34 config.data.append("channel",getSession("channelCode"));35 config.data.append("relation",getSession("userRelation"));36 // config.data.append("app_key",appkey);37 // config.data.append("sign",getSession("sign"));38 // config.data.append("user_agent",ua);39 config.headers['Content-Type'] = 'multipart\n' +40 ' config.data.append("token",getSession("token"));/form-data';41 }else{42 config.data = {43 ...config.data,44 // app_key: appkey,45 token: getSession("token"),46 channel:getSession("channelCode"),47 relation:getSession("userRelation"),48 // sign: getSession("sign"),49 // user_agent: ua50 }51 config.data = qs.stringify(config.data)52 }53 }else if(config.method=='get'){54 config.params = {55 // app_key: appkey,56 token: getSession("token"),57 channel:getSession("channelCode"),58 relation:getSession("userRelation"),59 // sign: getSession("sign"),60 // user_agent: ua,61 ...config.params62 }63 config.paramsSerializer=function(params) {64 return qs.stringify(config.params)65 }66 }else if(config.method =='delete'){67 config.params = {68 // app_key: appkey,69 token: getSession("token"),70 channel:getSession("channelCode"),71 relation:getSession("userRelation"),72 // sign: getSession("sign"),73 // user_agent: ua,74 ...config.params75 }76 config.paramsSerializer=function(params) {77 return qs.stringify(config.params)78 }79 }80 return config;81 },82 error => {83 return Promise.reject(err);84 }85);86axios.interceptors.response.use(...
latex-min.js
Source:latex-min.js
1var editor = ace.edit("code"),2 $result = $("#east");3editor.setTheme("ace/theme/crimson_editor");4editor.getSession().setMode("ace/mode/tex");5editor.getSession().setUseWrapMode(!0);6editor.focus();7$("#code").resize(function() {8 editor.resize(!0);9 editor.focus()10});11$("#codebox").tabs({12 onSelect: function(a, b) {13 editor.resize(!0);14 editor.focus()15 }16});17$("#clear").click(function() {18 editor.getValue().length && $.messager.confirm("Alert", "Do you really want to remove the code?", function(a) {19 a && (a = document.querySelector(".ace_editor").env.editor, a.selection.getCursor(), a.setValue(""), $result.html(""))20 }).window({21 width: 40022 })23});24var edit = document.querySelector(".ace_editor").env.editor,25 latex;26$(".keyboard li").click(function() {27 $(this);28 var a = $(this).html(),29 b = a.match(/(.*)MathJax-Element-(\d+)(.*)/);30 b ? latex = $("#MathJax-Element-" + b[2]).html() : a.match(/Space/) ? latex = "\\:" : a.match(/Quad/) ? latex = "\\quad" : a.match(/Enter/) && (latex = "\\\\");31 edit.selection.getCursor();32 edit.insert(latex)33});34editor.on("change", function() {35 var a = editor.getValue();36 0 >= a.length && ($result.html(""), result);37 $result.html("$" + a + "$");38 MathJax.typeset(document.querySelectorAll("#east"));39});40$("#undo").click(function() {41 editor.getSession().getUndoManager().hasUndo() && editor.getSession().getUndoManager().undo(!1)42});43$("#redo").click(function() {44 editor.getSession().getUndoManager().hasRedo() && editor.getSession().getUndoManager().redo(!1)45});46var clipboard;47$("#cut").click(function() {48 var a = editor.getSelectionRange();49 editor.getSession().getTextRange(a) && (clipboard = editor.getSession().getTextRange(a), editor.getSession().remove(a))50});51$("#delete").click(function() {52 var a = editor.getSelectionRange();53 editor.getSession().getTextRange(a) && editor.getSession().remove(a)54});55$("#copy").click(function() {56 var a = editor.getSelectionRange();57 editor.getSession().getTextRange(a) && (clipboard = editor.getSession().getTextRange(a))58});59$("#paste").click(function() {60 var a = editor.getCursorPosition();61 editor.getSession().insert(a, clipboard)62});63$("#select").click(function() {64 editor.getSelection().selectAll()65});66$("#find").click(function() {67 editor.execCommand("find")68});69$("#findreplace").click(function() {70 editor.execCommand("replace")71});72function setEditorTheme(a) {73 editor.setTheme("ace/theme/" + a)74}75function setEditorSoftWrap(a) {76 "true" === a ? editor.getSession().setUseWrapMode(!0) : "false" === a ? editor.getSession().setUseWrapMode(!1) : (editor.getSession().setUseWrapMode(!0), editor.getSession().setWrapLimitRange(parseInt(a), parseInt(a)))77}78function setEditorFontSize(a) {79 editor_font_size = parseInt(a);80 editor.setFontSize(editor_font_size);81 $("#east").css("font-size", editor_font_size)82}83function download(a) {84 var b = editor.getValue();85 if (0 >= b.length) return $.messager.alert("Alert", "Please type some code to generate image"), !1;86 $.ajax({87 url: "https://tools.tutorialspoint.com/process_latex.php",88 method: "POST",89 data: {90 type: a,91 code: b92 },93 dataType: "json",94 beforeSend: function() {95 $("#loading").css({96 visibility: "visible"97 })98 },99 success: function(a) {100 $("#loading").css({101 visibility: "hidden"102 });103 $("#download").attr("src", a.file)104 },105 error: function(a) {106 $("#loading").css({107 visibility: "hidden"108 });109 $("#download").attr("src", a.file)110 }111 })112}113function setEditorTabSize(a) {114 editor_tab_size = parseInt(a);115 editor.getSession().setTabSize(editor_tab_size)116}117function setEditorInvisible(a) {118 editor.setShowInvisibles(a)119}120function setEditorGutter(a) {121 editor.renderer.setShowGutter(a)122}123$("div#loading").css({124 visibility: "hidden"125});126$("form#ff").css({127 visibility: "visible"...
JSONEditorPostView.js
Source:JSONEditorPostView.js
...20 render:function () {21 var _this = this;22 ace.require("ace/ext/language_tools");23 var editor = ace.edit("jsoneditor");24 var requestBodyObject = editor.getSession().getValue();25 var request = $.ajax({26 url:cluster.get("connectionRootURL") + this.model.endpoint,27 type:this.model.action,28 data:requestBodyObject29 });30 request.success(function (data, textStatus, jqXHR) {31 _this.resultBody = JSON.stringify(data, undefined, 2);32 var output = ace.edit("jsonoutput");33 output.getSession().setMode("ace/mode/json");34 output.setTheme("ace/theme/monokai");35 output.setShowPrintMargin(false);36 output.setFontSize(13);37 output.getSession().setUseSoftTabs(true);38 output.getSession().setUseWrapMode(true);39 output.setValue(_this.resultBody);40 output.getSession().selection.clearSelection();41 output.setOptions({42 readOnly:true43 });44 output.moveCursorTo(1, 1);45 output.getSession().foldAll(1, 10000);46 });47 request.error(function (data, textStatus, jqXHR) {48 _this.resultBody = JSON.stringify(data, undefined, 2);49 var output = ace.edit("jsonoutput");50 output.getSession().setMode("ace/mode/json");51 output.setTheme("ace/theme/monokai");52 output.setShowPrintMargin(false);53 output.setFontSize(13);54 output.getSession().setUseSoftTabs(true);55 output.getSession().setUseWrapMode(true);56 output.setValue(_this.resultBody);57 output.getSession().selection.clearSelection();58 output.setOptions({59 readOnly:true60 });61 output.moveCursorTo(1, 1);62 //output.getSession().foldAll(1, 10000);63 });64 request.complete(function (jqXHR, textStatus) {65// TODO: may be a good place to add help or response information.66 });67 return this;68 }...
editor_code.js
Source:editor_code.js
...11$(function() {12 // Javascript editor13 var js_editor = ace.edit("javascript_editor");14 js_editor.setTheme("ace/theme/monokai");15 js_editor.getSession().setMode("ace/mode/javascript");16 js_editor.setShowPrintMargin(false);17 // HTML editor18 var html_editor = ace.edit("html_editor");19 html_editor.setTheme("ace/theme/monokai");20 html_editor.getSession().setMode("ace/mode/html");21 html_editor.setShowPrintMargin(false);22 // CSS editor23 var css_editor = ace.edit("css_editor");24 css_editor.setTheme("ace/theme/monokai");25 css_editor.getSession().setMode("ace/mode/css");26 css_editor.setShowPrintMargin(false);27 // JSON editor28 var json_editor = ace.edit("json_editor");29 json_editor.setTheme("ace/theme/monokai");30 json_editor.getSession().setMode("ace/mode/json");31 json_editor.setShowPrintMargin(false);32 // LESS editor33 var less_editor = ace.edit("less_editor");34 less_editor.setTheme("ace/theme/monokai");35 less_editor.getSession().setMode("ace/mode/less");36 less_editor.setShowPrintMargin(false);37 // PHP editor38 var php_editor = ace.edit("php_editor");39 php_editor.setTheme("ace/theme/monokai");40 php_editor.getSession().setMode("ace/mode/php");41 php_editor.setShowPrintMargin(false);42 // Ruby editor43 var ruby_editor = ace.edit("ruby_editor");44 ruby_editor.setTheme("ace/theme/monokai");45 ruby_editor.getSession().setMode("ace/mode/ruby");46 ruby_editor.setShowPrintMargin(false);47 // SASS editor48 var sass_editor = ace.edit("sass_editor");49 sass_editor.setTheme("ace/theme/monokai");50 sass_editor.getSession().setMode("ace/mode/sass");51 sass_editor.setShowPrintMargin(false);52 // Coffee editor53 var coffee_editor = ace.edit("coffee_editor");54 coffee_editor.setTheme("ace/theme/monokai");55 coffee_editor.getSession().setMode("ace/mode/coffee");56 coffee_editor.setShowPrintMargin(false);57 // Handlebars editor58 var handlebars_editor = ace.edit("handlebars_editor");59 handlebars_editor.setTheme("ace/theme/monokai");60 handlebars_editor.getSession().setMode("ace/mode/handlebars");61 handlebars_editor.setShowPrintMargin(false);...
editor.js
Source:editor.js
...11$('div.code-editor').each(function () {12 var editor = ace.edit(this);13 var textarea = document.querySelector('input[name=html]');14 editor.setTheme('ace/theme/chrome');15 editor.getSession().setMode('ace/mode/html');16 editor.getSession().setUseWrapMode(true);17 editor.getSession().setUseSoftTabs(true);18 editor.setShowPrintMargin(false);19 editor.getSession().on('change', function () {20 textarea.value = editor.getSession().getValue();21 });22 textarea.value = editor.getSession().getValue();23});24$('div[class*="code-editor-"]').each(function () {25 var input = $(this).siblings('input')[0];26 var mode = 'html';27 var editor = ace.edit(this);28 if ($(this).hasClass('code-editor-text')) {29 mode = 'plain_text';30 } else if ($(this).hasClass('code-editor-mjml')) {31 mode = 'html';32 editor.getSession().setUseWorker(false);33 } else if ($(this).hasClass('code-editor-css')) {34 mode = 'css';35 } else if ($(this).hasClass('code-editor-javascript')) {36 mode = 'javascript';37 } else if ($(this).hasClass('code-editor-json')) {38 mode = 'json';39 } else if ($(this).hasClass('code-editor-handlebars')) {40 mode = 'handlebars';41 }42 editor.setTheme('ace/theme/chrome');43 editor.setShowPrintMargin(false);44 editor.getSession().setMode('ace/mode/' + mode);45 editor.getSession().setUseWrapMode(true);46 editor.getSession().setUseSoftTabs(true);47 editor.getSession().setValue(input.value);48 editor.getSession().on('change', function () {49 input.value = editor.getSession().getValue();50 });...
Using AI Code Generation
1var wd = require('wd');2var asserters = wd.asserters;3var chai = require('chai');4var chaiAsPromised = require('chai-as-promised');5chai.use(chaiAsPromised);6var expect = chai.expect;7var should = chai.should();8var driver = wd.promiseChainRemote("localhost", 4723);9driver.init({browserName: 'chrome'});10driver.getSession().then(function (session) {11 console.log(session);12});13{14 "value": {15 }16}
Using AI Code Generation
1const wdio = require('webdriverio');2const opts = {3 capabilities: {4 }5};6async function main() {7 const client = await wdio.remote(opts);8 const sessionId = await client.getSessionId();9 console.log('Session ID: ' + sessionId);10 const session = await client.session(sessionId);11 console.log('Session: ' + session);12 console.log(JSON.stringify(session, null, 2));13 client.deleteSession();14}15main();16Session: {"capabilities":{"firstMatch":[{"appium:app":"/path/to/your.apk","appium:automationName":"UiAutomator2","appium:deviceName":"Android Emulator","appium:platformName":"Android","appium:platformVersion":"8.0","platformName":"Android"}]},"sessionId":"6b9f3b3d-8a52-4e39-9d2a-1d6b0c2e1a6e"}17{18 "capabilities": {19 {20 }21 },22}
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var driver = new webdriver.Builder()3.forBrowser('chrome')4.build();5driver.getSession().then(function(session) {6driver.quit();7});
Using AI Code Generation
1const { AppiumDriver } = require('appium-base-driver');2const { AppiumService } = require('appium');3const { AppiumServer } = require('appium/build/lib/appium');4const { AppiumDriver } = require('appium-base-driver');5const server = new AppiumServer();6server.start();7const driver = new AppiumDriver();8const session = await driver.getSession();9console.log(session);10const { AppiumDriver } = require('appium-base-driver');11const { AppiumService } = require('appium');12const { AppiumServer } = require('appium/build/lib/appium');13const { AppiumDriver } = require('appium-base-driver');14const server = new AppiumServer();15server.start();16const driver = new AppiumDriver();17const session = await driver.getSession();18console.log(session);
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!!