How to use printFunction method in Jest

Best JavaScript code snippet using jest

SectionSaddlePointSolver.js

Source:SectionSaddlePointSolver.js Github

copy

Full Screen

1function SectionSaddlePointSolver(functionBoxId, aBoxId, bBoxId, buttonId, solveBoxId) {2 this.functionBox = document.getElementById(functionBoxId)3 this.aBox = document.getElementById(aBoxId)4 this.bBox = document.getElementById(bBoxId)5 this.button = document.getElementById(buttonId)6 this.solveBox = document.getElementById(solveBoxId)7 this.button.addEventListener('click', () => this.Solve())8}9SectionSaddlePointSolver.prototype.ParseFunction = function() {10 let expression = this.functionBox.value.replace(/[\s*]/gi, '')11 let tokens = expression.match(/[-+]?((\d+\/\d+)|(\d+((\.|\,)\d+)?))?(x\^2|y\^2|xy|x|y)?/gi)12 if (tokens.join('') != expression)13 throw "Некорректное выражение..."14 let c = 015 let x = 016 let y = 017 let xy = 018 let xx = 019 let yy = 020 let parts = {21 'x': new Fraction('0'),22 'y': new Fraction('0'),23 'xy': new Fraction('0'),24 'x^2': new Fraction('0'),25 'y^2': new Fraction('0'),26 '': new Fraction('0'),27 }28 for (let token of tokens) {29 if (token == '')30 continue31 let part = ''32 for (let end of ['x^2', 'y^2', 'xy', 'x', 'y']) {33 if (token.endsWith(end)) {34 part = end35 break36 }37 }38 if (!parts[part].isZero())39 throw "Некорректное выражение"40 let value = token.substr(0, token.length - part.length)41 if (value == '+' && part == '')42 throw "Некорректное выражение"43 if (value == '' || value == '+')44 value = '1'45 else if (value == '-')46 value = '-1'47 parts[part] = new Fraction(value)48 }49 return parts50}51SectionSaddlePointSolver.prototype.JoinTokens = function(tokens) {52 let resultTokens = []53 tokens.sort((a, b) => b[1].length - a[1].length)54 for (let token of tokens) {55 let sign = ''56 let coef = token[0].abs()57 if (resultTokens.length == 0) {58 sign = token[0].isNeg() ? '-' : ''59 }60 else {61 sign = token[0].isPos() ? ' + ' : ' - '62 }63 if (coef.isOne() && token[1] != '')64 coef = ''65 else66 coef = coef.html()67 resultTokens.push(`${sign}${coef}${token[1]}`.replace('^2', '<sup>2</sup>'))68 }69 return resultTokens.join('')70}71SectionSaddlePointSolver.prototype.PrintFunction = function(f) {72 let tokens = []73 for (let arg of ['x^2', 'x', 'xy', 'y', 'y^2', '']) {74 if (!(arg in f) || f[arg].isZero())75 continue76 tokens.push([f[arg], arg])77 }78 return this.JoinTokens(tokens)79}80SectionSaddlePointSolver.prototype.EvaluateFunction = function(f, x) {81 return f[''].add(f['y'].mult(x)).add(f['y^2'].mult(x).mult(x))82}83SectionSaddlePointSolver.prototype.Plot = function(a, b, p, f_a_y, f_b_y) {84 let div = document.createElement('div')85 div.id = 'plot'86 let x = []87 let y = []88 let y1 = []89 let y2 = []90 let xi = a91 let h = new Fraction('1/1000')92 while (xi.lt(b.add(h))) {93 x.push(xi.print(2))94 let v1 = this.EvaluateFunction(f_a_y, xi).print(2)95 let v2 = this.EvaluateFunction(f_b_y, xi).print(2)96 if (xi.lt(p)) {97 y.push(v2)98 }99 else {100 y.push(v1)101 }102 y1.push(v1)103 y2.push(v2)104 xi = xi.add(h)105 }106 let e_x = [p, f_a_y['y'].div(f_a_y['y^2'].mult(new Fraction('-2'))), f_b_y['y'].div(f_b_y['y^2'].mult(new Fraction('-2')))]107 let e_y = [this.EvaluateFunction(f_a_y, p), this.EvaluateFunction(f_a_y, e_x[1]), this.EvaluateFunction(f_b_y, e_x[2])]108 let e_texts = [`(${e_x[0]}, ${e_y[0]})`, `(${e_x[1]}, ${e_y[1]})`, `(${e_x[2]}, ${e_y[2]})`]109 let data = { x: x, y: y, mode: 'lines', name: 'F(x(y), y)'};110 let data1 = { x: x, y: y1, mode: 'lines', name: `F(${a}, y)`};111 let data2 = { x: x, y: y2, mode: 'lines', name: `F(${b}, y)`};112 let data3 = { x: e_x.map((v) => v.print(2)), y: e_y.map((v) => v.print(2)), text: e_texts, mode: 'markers', hovertemplate: '<b>%{text}</b>', name: `точки`};113 let layout = {114 width: 500,115 height: 400,116 margin: { l: 20, r: 20, b: 20, t: 20 },117 };118 this.solveBox.appendChild(div)119 return { data: [data1, data2, data, data3], layout: layout }120}121SectionSaddlePointSolver.prototype.SolveXX_XY_YY = function(f, a, b) {122 let yx = f['xy'].div(f['y^2'].mult(new Fraction('-2')))123 let f_x_yx1 = f['x^2']124 let f_x_yx2 = yx.mult(f['xy'])125 let f_x_yx3 = f['y^2'].mult(yx).mult(yx)126 let f_x_yx = f_x_yx1.add(f_x_yx2).add(f_x_yx3)127 let f_x_yx_a = f_x_yx.mult(a).mult(a)128 let f_x_yx_b = f_x_yx.mult(b).mult(b)129 let v_down = f_x_yx_a.gt(f_x_yx_b) ? f_x_yx_a : f_x_yx_b130 let x0 = f_x_yx_a.gt(f_x_yx_b) ? a : b131 this.solveBox.innerHTML += `<span class='math'>v̲ = max<sub>x</sub> min<sub>y</sub> F(x, y)</p>`132 this.solveBox.innerHTML += `<span class='math'>F(x, y) → min<sub>y</sub>: ${this.JoinTokens([[f['xy'], 'x'], [f['y^2'].mult(new Fraction('2')), 'y']])} = 0 → <b>y(x) = ${yx.html()}x</b> ∈ Y</p>`133 this.solveBox.innerHTML += `<span class='math'>F(x, y(x)) = ${this.JoinTokens([[f_x_yx1, 'x^2'], [f_x_yx2, 'x^2'], [f_x_yx3, 'x^2']])} = ${f_x_yx.html()}x<sup>2</sup> → max<br>`134 this.solveBox.innerHTML += `Максимум либо в ${a.html()}, либо в ${b.html()}:<br>`135 this.solveBox.innerHTML += `x = ${a.html()}: ${f_x_yx_a.html()}<br>`136 this.solveBox.innerHTML += `x = ${b.html()}: ${f_x_yx_b.html()}<br>`137 this.solveBox.innerHTML += `<b>x⁰ = ${x0.html()}, v̲ = ${v_down.html()}</b></p><br>`138 let f_a_y = { 'y^2': f['y^2'], 'y': f['xy'].mult(a), '': f['x^2'].mult(a).mult(a) }139 let f_b_y = { 'y^2': f['y^2'], 'y': f['xy'].mult(b), '': f['x^2'].mult(b).mult(b) }140 let pa = f_a_y['y'].div(f_a_y['y^2'].mult(new Fraction('-2')))141 let pb = f_b_y['y'].div(f_b_y['y^2'].mult(new Fraction('-2')))142 let p = f_a_y[''].sub(f_b_y['']).div(f_b_y['y'].sub(f_a_y['y']))143 let y0 = p144 let v_up = f_a_y[''].add(f_a_y['y'].mult(y0)).add(f_a_y['y^2'].mult(y0).mult(y0))145 this.solveBox.innerHTML += `<span class='math'>v̅ = min<sub>y</sub> max<sub>x</sub> F(x, y)</p>`146 this.solveBox.innerHTML += `<span class='math'>Max<sub>x</sub> либо в ${a.html()}, либо в ${b.html()}:</p>`147 this.solveBox.innerHTML += `<span class='math'>F(${a.html()}, y) = ${this.PrintFunction(f_a_y)}</p>`148 this.solveBox.innerHTML += `<span class='math'>F(${b.html()}, y) = ${this.PrintFunction(f_b_y)}</p>`149 this.solveBox.innerHTML += `<span class='math'>x(y) = { ${a.html()}, y &ge; ${p.html()}, иначе ${b.html()} }</p>`150 this.solveBox.innerHTML += `<span class='math'>F(x(y), y) = { ${this.PrintFunction(f_a_y)}, y &ge; ${p.html()}, иначе ${this.PrintFunction(f_b_y)} }</p>`151 let plot = this.Plot(a, b, p, f_a_y, f_b_y)152 this.solveBox.innerHTML += `<span class='math'>У параболы F(${a.html()}, y) вершина находится в ${pa.html()}</p>`153 this.solveBox.innerHTML += `<span class='math'>У параболы F(${b.html()}, y) вершина находится в ${pb.html()}</p>`154 if (pa.gt(p)) {155 y0 = pa156 v_up = f_a_y[''].add(f_a_y['y'].mult(pa)).add(f_a_y['y^2'].mult(pa).mult(pa))157 this.solveBox.innerHTML += `<span class='math'>Точка ${pa.html()} > ${p.html()}</p>`158 }159 else if (pb.lt(p)) {160 y0 = pb161 v_up = f_b_y[''].add(f_b_y['y'].mult(pb)).add(f_b_y['y^2'].mult(pb).mult(pb))162 this.solveBox.innerHTML += `<span class='math'>Точка ${pb.html()} < ${p.html()}</p>`163 }164 this.solveBox.innerHTML += `<b>y⁰ = ${y0.html()}, v̅ = ${v_up.html()}</b></p><br>`165 if (v_down.eq(v_up)) {166 this.solveBox.innerHTML += `<span class='math'>v̅ = v̲ = v → <b>имеется седловая точка</b>: (${x0.html()}, ${y0.html()})</p>`167 }168 else {169 this.solveBox.innerHTML += `<span class='math'>v̅ ≠ v̲ → <b>седловых точек нет</b></p>`170 }171 Plotly.newPlot('plot', plot.data, plot.layout);172}173SectionSaddlePointSolver.prototype.EvaluateF = function(f, x0, y0) {174 let xx = f['x^2'].mult(x0).mult(x0)175 let yy = f['y^2'].mult(y0).mult(y0)176 let xy = f['xy'].mult(x0).mult(y0)177 let x = f['x'].mult(x0)178 let y = f['y'].mult(y0)179 return xx.add(yy).add(xy).add(x).add(y).add(f[''])180}181SectionSaddlePointSolver.prototype.SolveCommon = function(f, a, b) {182 let dx = {183 'x^2': new Fraction('0'),184 'y^2': new Fraction('0'),185 'xy': new Fraction('0'),186 'x': f['x^2'].mult(new Fraction('2')),187 'y': f['xy'],188 '': f['x']189 }190 let dy = {191 'x^2': new Fraction('0'),192 'y^2': new Fraction('0'),193 'xy': new Fraction('0'),194 'x': f['xy'],195 'y': f['y^2'].mult(new Fraction('2')),196 '': f['y']197 }198 let xy = {199 'x^2': new Fraction('0'),200 'y^2': new Fraction('0'),201 'xy': new Fraction('0'),202 'x': new Fraction('0'),203 'y': dx['y'].neg().div(dx['x']),204 '': dx[''].neg().div(dx['x']) 205 }206 let yx = {207 'x^2': new Fraction('0'),208 'y^2': new Fraction('0'),209 'xy': new Fraction('0'),210 'x': dy['x'].neg().div(dy['y']),211 'y': new Fraction('0'),212 '': dy[''].neg().div(dy['y']) 213 }214 let f_xy_y = {215 'x^2': new Fraction('0'),216 'y^2': f['x^2'].mult(xy['y']).mult(xy['y']).add(f['y^2']).add(f['xy'].mult(xy['y'])),217 'xy': new Fraction('0'),218 'x': new Fraction('0'),219 'y': f['x^2'].mult(xy['y']).mult(xy['']).mult(new Fraction('2')).add(f['xy'].mult(xy[''])).add(f['x'].mult(xy['y'])).add(f['y']),220 '': f['x^2'].mult(xy['']).mult(xy['']).add(f['x'].mult(xy[''])).add(f['']),221 }222 let f_x_yx = {223 'y^2': new Fraction('0'),224 'x^2': f['y^2'].mult(yx['x']).mult(yx['x']).add(f['x^2']).add(f['xy'].mult(yx['x'])),225 'xy': new Fraction('0'),226 'y': new Fraction('0'),227 'x': f['y^2'].mult(yx['x']).mult(yx['']).mult(new Fraction('2')).add(f['xy'].mult(yx[''])).add(f['y'].mult(yx['x'])).add(f['x']),228 '': f['y^2'].mult(yx['']).mult(yx['']).add(f['y'].mult(yx[''])).add(f['']),229 }230 this.solveBox.innerHTML += `<span class='math'>max<sub>x</sub> F(x, y): ${this.PrintFunction(dx)} = 0 → x(y) = ${this.PrintFunction(xy)}</p>`231 this.solveBox.innerHTML += `<span class='math'>min<sub>y</sub> F(x(y), y): ${this.PrintFunction(f_xy_y)} → min</p>`232 let y0233 if (f_xy_y['y^2'].isPos()) {234 y0 = f_xy_y['y'].div(f_xy_y['y^2'].mult(new Fraction('-2')))235 this.solveBox.innerHTML += `<span class='math'>Минимум лежит на вершине параболы: </p>`236 }237 else {238 let fa = this.EvaluateF(f_xy_y, new Fraction('0'), a)239 let fb = this.EvaluateF(f_xy_y, new Fraction('0'), b)240 y0 = fa.lt(fb) ? a : b241 this.solveBox.innerHTML += `<span class='math'>Минимум лежит на границе (но это не точно): F(x(y), ${a.html()}) = ${fa.html()}, F(x(y), ${b.html()}) = ${fb.html()}</p>`242 }243 let v_up = this.EvaluateF(f_xy_y, new Fraction('0'), y0)244 this.solveBox.innerHTML += `<span class='math'><b>y⁰ = ${y0.html()}, v̅ = ${v_up.html()}</b></p><br>`245 this.solveBox.innerHTML += `<span class='math'>min<sub>y</sub> F(x, y): ${this.PrintFunction(dy)} = 0 → y(x) = ${this.PrintFunction(yx)}</p>`246 this.solveBox.innerHTML += `<span class='math'>max<sub>x</sub> F(x, y(x)): ${this.PrintFunction(f_x_yx)} → max</p>`247 let x0248 if (f_x_yx['x^2'].isNeg()) {249 x0 = f_x_yx['x'].div(f_x_yx['x^2'].mult(new Fraction('-2')))250 this.solveBox.innerHTML += `<span class='math'>Максимум лежит на вершине параболы: </p>`251 }252 else {253 let fa = this.EvaluateF(f_x_yx, a, new Fraction('0'))254 let fb = this.EvaluateF(f_x_yx, b, new Fraction('0'))255 x0 = fa.gt(fb) ? a : b256 this.solveBox.innerHTML += `<span class='math'>Максимум лежит на границе (но это не точно): F(${a.html()}, y(x)) = ${fa.html()}, F(${b.html()}, y(x)) = ${fb.html()}</p>`257 }258 let v_down = this.EvaluateF(f_x_yx, x0, new Fraction('0'))259 this.solveBox.innerHTML += `<span class='math'><b>x⁰ = ${x0.html()}, v̲ = ${v_down.html()}</b></p><br>`260 if (v_down.eq(v_up)) {261 this.solveBox.innerHTML += `<span class='math'>v̅ = v̲ = v → <b>имеется седловая точка</b>: (${x0.html()}, ${y0.html()})</p>`262 }263 else {264 this.solveBox.innerHTML += `<span class='math'>v̅ ≠ v̲ → <b>седловых точек нет</b></p>`265 }266}267SectionSaddlePointSolver.prototype.Solve = function() {268 try {269 let f = this.ParseFunction()270 let a = new Fraction(this.aBox.value)271 let b = new Fraction(this.bBox.value)272 this.solveBox.innerHTML = `<h2>Решение</h2>`273 this.solveBox.innerHTML += `<span class='math'><b>Введённая функция</b>: ${this.PrintFunction(f)}</p>`274 this.solveBox.innerHTML += `<span class='math'><b>X = Y</b>: [${a.html()}, ${b.html()}]</p><br>`275 if (!f['x'].isZero() || !f['y'].isZero() || !f[''].isZero() || f['x^2'].isNeg() || f['y^2'].isNeg()) {276 this.SolveCommon(f, a, b)277 }278 else {279 this.SolveXX_XY_YY(f, a, b)280 }281 }282 catch (error) {283 alert(error)284 }...

Full Screen

Full Screen

Users.js

Source:Users.js Github

copy

Full Screen

2var bcrypt = require("bcrypt");3const debugPrinter = require("../controllers/helpers/debug/debug_printer");4const User = {};5User.emailExists = async email => {6 debugPrinter.printFunction("User.emailExists");7 try {8 let [r, fields] = await db.execute("SELECT * FROM users WHERE email=?", [email]);9 return r && r.length;10 } catch (err) {11 return false;12 }13};14User.usernameExists = async user => {15 debugPrinter.printFunction("User.usernameExists");16 try {17 let [r, fields] = await db.execute("SELECT * FROM users WHERE username=?", [user]);18 return r && r.length;19 } catch (err) {20 return false;21 }22};23User.create = async (username, name, password, active, usertype, email, title) => {24 debugPrinter.printFunction("User.create");25 let baseSQL = "";26 password = await bcrypt.hash(password, 15);27 if (!((await User.emailExists(email)) || (await User.usernameExists(username)))) {28 switch(usertype){29 case 0:30 baseSQL = "INSERT INTO users (`username`,`name`, `email`, `active`,`usertype`, `password`, `created`, `major`) VALUES (?,?,?,?,?,?, now(), ?);";31 break;32 case 1:33 baseSQL = "INSERT INTO users (`username`,`name`, `email`, `active`,`usertype`, `password`, `created`, `department`) VALUES (?,?,?,?,?,?, now(), ?);";34 break;35 case 2:36 baseSQL = "INSERT INTO users (`username`,`name`, `email`, `active`,`usertype`, `password`, `created`, `company`) VALUES (?,?,?,?,?,?, now(), ?);";37 break;38 default:39 console.log("Usertype not listed");40 }41 let a = await db.execute(baseSQL, [username, name, email, active, usertype, password, title]);42 return a;43 }44};45User.createWithGoogleID = async (username, name, password, active, usertype, email, googleid) => {46 debugPrinter.printFunction("User.createWithGoogleID");47 password = await bcrypt.hash(password, 15);48 if (!((await User.emailExists(email)) || (await User.usernameExists(username)))) {49 let baseSQL = "INSERT INTO users (`username`,`name`, `email`, `active`,`usertype`, `created`, `password`, googleid) VALUES (?,?,?,?,?, now(), ?, ?);";50 let a = await db.execute(baseSQL, [username, name, email, active, usertype, password, googleid]);51 return a;52 }53};54User.getId = async username => {55 debugPrinter.printFunction("User.getId");56 let baseSQL = "SELECT id FROM users WHERE username=?;";57 let [r, fields] = await db.execute(baseSQL, [username]);58 if (r && r.length) {59 return r[0].id;60 } else {61 console.log("error retrieving id");62 return null;63 }64};65User.getUsername = async id => {66 debugPrinter.printFunction("User.getUsername");67 let baseSQL = "SELECT username FROM users WHERE id=?;";68 let [r, fields] = await db.execute(baseSQL, [id]);69 if (r && r.length) {70 return r[0].username;71 } else {72 console.log("error retrieving id");73 return null;74 }75};76// From google ID get user IO77User.getGoogleId = async googleid => {78 debugPrinter.printFunction("User.getGoogleId");79 let baseSQL = "SELECT id FROM users WHERE googleid=?;";80 let [r, fields] = await db.execute(baseSQL, [googleid]);81 if (r && r.length) {82 return r[0].id;83 } else {84 debugPrinter.printWarning(`Google ID: ${googleid} is not in the DB`);85 return null;86 }87};88User.authenticate = async (username, password) => {89 debugPrinter.printFunction("User.authenticate");90 let baseSQL = "SELECT id,username, usertype, lastlogin, password FROM users WHERE username=?;";91 let [r, fields] = await db.execute(baseSQL, [username]);92 // If user stuff exists based on Username93 if (r && r.length) {94 let check = await bcrypt.compare(password, r[0].password);95 let userid = r[0].id;96 let usertype = r[0].usertype;97 let lastlogin = r[0].lastlogin;98 99 // If password is in the DB100 if (check) {101 return [true, userid, usertype, lastlogin];102 }103 else return [false, null];104 }105 // Username does not exist106 else {107 debugPrinter.printWarning(`Username: ${username} is not in the DB`);108 return [false, null];109 }110};111User.updateLastLogin = async (username) => {112 // Update their last login to right now113 let baseSQL2 = "UPDATE `users` SET `lastlogin` = now() WHERE `username`=?;";114 await db.execute(baseSQL2, [username]);115};116User.getLastLogin = async (username) => {117 let baseSQL = "SELECT `lastlogin` FROM users WHERE `username`=?;";118 [r, fields] = await db.execute(baseSQL, [username]);119 if (r && r.length) {120 console.log("r: ");121 console.log(r);122 return r;123 } else {124 return null;125 }126}127// returns a list of any new unseen alerts 128// meaning new profiles relevant to their alert that they have not seen yet129User.hasNewAlerts = async (lastLogin, userid) => {130 console.log("Inside hasNewAlerts");131 let baseSQL = "SELECT * from users WHERE `usertype`=0 AND UNIX_TIMESTAMP(`created`) > UNIX_TIMESTAMP(?);";132 let [r, fields] = await db.execute(baseSQL, [lastLogin]);133 if (r && r.length) {134 console.log("New alert possibly");135 //do second query to find out if new profile matches demographics in alert136 let[r2, fields2] = await User.getAlerts(userid);137 console.log("r2: ");138 console.log(r2);139 //console.log("Fields2.length: ");140 //console.log(fields2.length);141 // if we have any alert parameters set up142 if(r2) {143 console.log("User has an alert set up..");144 console.log("r2: ");145 console.log(r2);146 //cycle through all of our new accounts 147 for(i = 0; i < r.length; i++) {148 console.log("r[i]: ");149 console.log(r[i]);150 //Only have genders to match151 if((r2.ethnicity == null) && (r2.major == null) && (r2.gender[0] != null)) {152 console.log("Only have gender to match");153 console.log(r2.gender[0]);154 if(r2.gender[0] === r[i].gender) return true;155 }156 //Only have major to match157 if((r2.ethnicity == null) && (r2.major[0] != null) && (r2.gender == null)) {158 console.log("Only have major to match");159 console.log(r2.major);160 if(r2.major[0] === r[i].major) return true;161 }162 //gender and major to match163 if((r2.ethnicity == null) && (r2.major[0] != null) && (r2.gender[0] != null)) {164 console.log("Have gender and major to match");165 console.log(r2.gender[0]);166 console.log(r2.major[0]);167 if((r2.gender[0] === r[i].gender) && (r2.major[0] === r[i].major)) return true;168 }169 //Only have ethnicity to match170 if((r2.ethnicity[0] != null) && (r2.major == null) && (r2.gender == null)) {171 console.log("Only have ethnicity to match");172 console.log(r2.ethnicity[0]);173 if(r2.ethnicity[0] === r[i].ethnicity) return true;174 }175 //ethnicity and gender to match176 if((r2.ethnicity[0] != null) && (r2.major == null) && (r2.gender[0] != null)) {177 console.log("Have ethnicity and gender to match");178 console.log(r2.gender[0]);179 console.log(r2.ethnicity[0]);180 if((r2.ethnicity[0] === r[i].ethnicity) && (r2.gender[0] === r[i].gender)) return true;181 }182 183 //ethnicity and major to match184 if((r2.ethnicity[0] != null) && (r2.major[0] != null) && (r2.gender == null)) {185 console.log("Have ethnicity and major to match");186 console.log(r2.ethnicity[0]);187 console.log(r2.major[0]);188 if((r2.ethnicity[0] === r[i].ethnicity) && (r2.major[0] === r[i].major)) return true;189 }190 191 //all three to match192 if((r2.ethnicity[0] != null) && (r2.major[0] != null) && (r2.gender[0] != null)) {193 console.log("Have all three to match");194 console.log(r2.ethnicity[0]);195 console.log(r2.gender[0]);196 console.log(r2.major[0]);197 if((r2.ethnicity[0] === r[i].ethnicity) && (r2.major[0] === r[i].major) &&198 (r2.gender[0] === r[i].gender)) return true;199 }200 }201 console.log("For-loop yields no matches");202 return false; // for-loop yielded nothing203 } else {204 console.log("user has no alerts set up");205 return false; // user has no alerts set up206 }207 }208 else {209 console.log("No new alert");210 return false; // no new accounts to try to match211 }212};213User.checkPassword = async (username, new_password) => {214 debugPrinter.printFunction("User.checkPassword");215 let baseSQL = "SELECT id,username, password FROM users WHERE username=?;";216 let [r, fields] = await db.execute(baseSQL, [username]);217 console.log(r);218 let validResult = r && r.length;219 console.log("validResult: " + validResult);220 if(validResult == 0) return false;221 let isTheSame = await bcrypt.compare(new_password, r[0].password);222 console.log("isTheSame: " + isTheSame);223 return (!isTheSame) ? true : false;224};225User.checkUser = async username => {226 debugPrinter.printFunction("User.checkUser");227 let baseSQL = "SELECT username FROM users WHERE `username`=?;";228 let [r, fields] = await db.execute(baseSQL, [username]);229 //true exists : false doesnt exist230 return r && r.length ? true : false;231};232User.changePassword = async (username, new_password, confirm_password, userid) => {233 debugPrinter.printFunction("User.changePassword");234 if (await User.checkPassword(username, confirm_password)) {235 let baseSQL = "UPDATE `users` SET `password` = ? WHERE `id` = ?;";236 new_password = await bcrypt.hash(new_password, 15);237 let [r, fields] = await db.execute(baseSQL, [new_password, userid]);238 return r;239 } else return null;240};241User.changeEmail = async (new_email, userid) => {242 debugPrinter.printFunction("User.changeEmail");243 if (!(await User.emailExists(new_email))) {244 let baseSQL = "UPDATE `users` SET `email` = ? WHERE `id` = ?;";245 let [r, fields] = await db.execute(baseSQL, [new_email, userid]);246 return r;247 } else return null;248};249User.changeBio = async (new_bio, userid) => {250 debugPrinter.printFunction("User.changeBio");251 // verify user input by taking out ``252 // update the database253 let baseSQL = "UPDATE `users` SET `bio` = ? WHERE `id` = ?;";254 let [r, fields] = await db.execute(baseSQL, [new_bio, userid]);255 return r;256}257// Change Username258User.changeUsername = async (new_username, userid) => {259 debugPrinter.printFunction("User.changeUsername");260 if(!(await User.usernameExists(new_username))) {261 let baseSQL = "UPDATE `users` SET `username` = ? WHERE `id` = ?;";262 let [r, fields] = await db.execute(baseSQL, [new_username, userid]);263 return r;264 } else {265 console.log("Error User.changeUsername: name already exists.");266 return null;267 }268};269// Change name270User.changeName = async (username, new_name, userid) => {271 debugPrinter.printFunction("User.changeName");272 if (!(await User.checkUser(new_name))) {273 let baseSQL = "UPDATE `users` SET `name` = ? WHERE `id` = ?;";274 let [r, fields] = await db.execute(baseSQL, [new_name, userid]);275 return r;276 } else {277 return null;278 }279};280// Change Ethnicity281User.changeEthnicity = async (new_ethnicity, userid) => {282 debugPrinter.printFunction("User.changeEthnicity");283 let baseSQL = "UPDATE `users` SET `ethnicity` = ? WHERE `id` = ?;";284 let [r, fields] = await db.execute(baseSQL, [new_ethnicity, userid]);285 return r;286};287// Change Gender288User.changeGender = async (new_gender, userid) => {289 debugPrinter.printFunction("User.changeGender");290 let baseSQL = "UPDATE `users` SET `gender` = ? WHERE `id` = ?;";291 let [r, fields] = await db.execute(baseSQL, [new_gender, userid]);292 return r;293};294// Change Major295User.changeMajor = async (new_major, userid) => {296 debugPrinter.printFunction("User.changeMajor");297 let baseSQL = "UPDATE `users` SET `major` = ? WHERE `id` = ?;";298 let [r, fields] = await db.execute(baseSQL, [new_major, userid]);299 return r;300};301// Change Company302User.changeCompany = async (new_company, userid) => {303 debugPrinter.printFunction("User.changeCompany");304 let baseSQL = "UPDATE `users` SET `company` = ? WHERE `id` = ?;";305 let [r, fields] = await db.execute(baseSQL, [new_company, userid]);306 return r;307};308// Change Department309User.changeDepartment = async (new_department, userid) => {310 debugPrinter.printFunction("User.changeDepartment");311 let baseSQL = "UPDATE `users` SET `department` = ? WHERE `id` = ?;";312 let [r, fields] = await db.execute(baseSQL, [new_department, userid]);313 return r;314};315User.getInfo = async username => {316 debugPrinter.printFunction("User.getInfo");317 var baseSQL = "SELECT id, username, name, email, usertype, created, title, bio, profilepic, gender, ethnicity, major, company, department, resume FROM users WHERE username=?;";318 let [r, fields] = await db.query(baseSQL, [username]);319 return r;320};321const handler = async value => {322 try {323 return await value.split();324 } catch (err) {325 return await value;326 }327};328// Get all the relevant alerts for an account329User.getAlerts = async user_id => {330 debugPrinter.printFunction("User.getAlerts");331 var baseSQL = "SELECT ethnicity, major, gender FROM alerts WHERE fk_userid=?;";332 let [r, fields] = await db.query(baseSQL, [user_id]);333 if (r && r.length) {334 r[0].ethnicity = await handler(r[0].ethnicity);335 r[0].major = await handler(r[0].major);336 r[0].gender = await handler(r[0].gender);337 return r;338 }339 return false;340};341User.hasAlerts = async user_id => {342 let basesql = "SELECT id FROM alerts WHERE fk_userid=?;";343 let [r, fields] = await db.query(basesql, [user_id]);344 return r && r.length;...

Full Screen

Full Screen

Engine.js

Source:Engine.js Github

copy

Full Screen

...4const User = require("./Users");5const Engine = {};6//grabs n amount of posts from db and returns the data7// Engine.getPosts = async limit => {8// debugPrinter.printFunction("Engine.getPosts");9// let baseSQL =10// "SELECT u.username,u.name,u.profilepic, p.id, p.title, p.description, p.resumePath, p.created FROM users u JOIN posts p ON u.id=fk_userid ORDER BY created DESC LIMIT ?";11// let [r, fields] = await db.query(baseSQL, [limit]);12// return r;13// };14//get 15Engine.getPosts = async limit => {16 debugPrinter.printFunction("Engine.getPosts");17 try {18 let baseSQL = "SELECT * FROM website.users WHERE usertype=0 ORDER BY created DESC LIMIT ?;";19 let [r, fields] = await db.query(baseSQL, [limit]);20 console.log("r: ");21 console.log(r);22 return r;23 } catch (err) {24 res.send(err);25 }26};27// fetch all 28Engine.getAllPosts = async _ => {29 debugPrinter.printFunction("Engine.getPosts");30 let baseSQL = "SELECT * FROM website.users WHERE usertype=0 ORDER BY created DESC";31 let [r, fields] = await db.query(baseSQL);32 return r;33};34Engine.getPostsApiEndpoint = async (limit, filter, order = "DESC") => {35 //filter = created, reviews36 //Display descending: "DESC"37 debugPrinter.printFunction("Engine.getPostsApiEndpoint");38 debugPrinter.printDebug([limit, filter, order]);39 // let baseSQL = "SELECT u.username,u.name, p.id, p.title, p.description, p.resumePath, p.created FROM users u JOIN posts p ON u.id=fk_userid ORDER BY ? ? LIMIT ?";40 let baseSQL = "SELECT u.username, u.name, p.id, p.major, p.description, p.resumePath, p.created FROM users u JOIN posts p ON u.id=fk_userid ORDER BY ? ? LIMIT ?";41 let [r, fields] = await db.query(baseSQL, [filter, order, limit]);42 return r;43};44Engine.search = async search => {45 debugPrinter.printFunction("Engine.search");46 try {47 let baseSQL =48 "SELECT u.id,u.name,u.profilepic, u.major,u.created, u.username, concat_ws(' ', u.name, u.username, u.major) AS haystack FROM users u WHERE u.usertype=0 HAVING haystack like ?;";49 let sqlready = "%" + search + "%";50 let [r, fields] = await db.execute(baseSQL, [sqlready]);51 console.log("r-------");52 console.log(r);53 return r && r.length ? r : await Engine.getPosts(10);54 } catch (err) {55 return false;56 }57};58// get a single review59Engine.getPost = async id => {60 debugPrinter.printFunction("Engine.getPost");61 try {62 var baseSQL = "SELECT id, username, name, email, created, title, bio, profilepic, gender, ethnicity, major, resume FROM users WHERE id=?;";63 let [r, fields] = await db.query(baseSQL, [id]);64 console.log(r)65 return r;66 } catch (err) {67 debugPrinter.printWarning(`Post id: ${id} does not exist in the DB`);68 return null;69 }70};71// Get all reviews from 1 User72Engine.getUserPosts = async username => {73 debugPrinter.printFunction("Engine.getUserPosts");74 try {75 var baseSQL =76 "SELECT p.id as postid, p.role, p.title, p.description, p.resumePath,u.name,u.username, u.profilepic, p.created FROM users u JOIN posts p ON u.id=fk_userid WHERE u.username=?";77 let [r, fields] = await db.query(baseSQL, [username]);78 return r;79 } catch (err) {80 debugPrinter.printWarning(`Username: ${username} does not exist in the DB`);81 return null;82 }83};84Engine.setPost = async (title, description, file, fk_userid) => {85 debugPrinter.printFunction("Engine.setPost");86 try {87 console.log(fk_userid);88 let path = "/assets/" + file.filename;89 let tags = await pdfReader("./public" + path);90 debugPrinter.printDebug(tags);91 // let path = "/assets/" + req.file.filename;92 var baseSQL = "INSERT INTO `website`.`posts`(`title`,`description`,`resumepath`,`created`, `tags`, `fk_userid`) VALUES(?,?,? ,now(), ?,?);";93 let [r, fields] = await db.query(baseSQL, [title, description, path, tags, fk_userid]);94 debugPrinter.printDebug("Response", r);95 return r;96 } catch (err) {97 console.log("Couldnt Create Post");98 return null;99 }100};101// Update profile photo102Engine.updatePFP = async (file, fk_userid) => {103 debugPrinter.printFunction("Engine.updatePFP");104 try {105 console.log(fk_userid);106 let path = "/assets/photos/" + file.filename;107 debugPrinter.printDebug(fk_userid);108 var baseSQL = "UPDATE `website`.`users` SET `profilepic` = ? WHERE `id` = ?;";109 let [r, fields] = await db.query(baseSQL, [path, fk_userid]);110 debugPrinter.printDebug("Response", r);111 return r;112 } catch (err) {113 console.log("Couldnt Create Post");114 return null;115 }116};117Engine.updateRES = async (file, fk_userid) => {118 debugPrinter.printFunction("Engine.updateRES");119 try {120 console.log(fk_userid);121 let path = "/assets/resumes/" + file.filename;122 // let tags = await pdfReader("./public" + path);123 debugPrinter.printDebug(fk_userid);124 // let path = "/assets/" + req.file.filename;125 var baseSQL = "UPDATE `website`.`users` SET `resume` = ? WHERE `id` = ?;";126 let [r, fields] = await db.query(baseSQL, [path, fk_userid]);127 debugPrinter.printDebug("Response", r);128 return r;129 } catch (err) {130 console.log("Couldnt update resume, boo.");131 return null;132 }133};134Engine.getRES = async(userid) => {135 debugPrinter.printFunction("Engine.getRES");136 console.log(userid);137 try {138 var baseSQL = "SELECT resume, name FROM users WHERE id=?";139 let [r, fields] = await db.query(baseSQL, [userid]);140 console.log(r[0]);141 return [r[0].resume, r[0].name];142 } catch (err) {143 console.log("Error, userid does not exist in db.");144 return null;145 }146};147// SELECT u.id, u.ethnicity, u.major, u.profilepic, u.username, u.name FROM users u WHERE `gender`="male" and `major`="Computer Science" and `ethnicity`="hispanic";148const helper_cluster = (x, filter_name, count, base) => {149 if (x) {150 console.log(filter_name + " passed in");151 base += count ? ` and ${filter_name}="${x}"` : `WHERE ${filter_name}="${x}"`;152 return [++count, base];153 }154 return [count, base];155};156Engine.advancedSearch = async advancedSearch => {157 debugPrinter.printFunction("Engine.advancedSearch");158 // WHERE ?=?, and ?159 let options = ["ethnicity", "gender", "major"];160 let base = "",161 count = 0;162 [count, base] = helper_cluster(advancedSearch.ethnicity, options[0], count, base);163 [count, base] = helper_cluster(advancedSearch.gender, options[1], count, base);164 [count, base] = helper_cluster(advancedSearch.major, options[2], count, base);165 base += ";";166 //filter: [eth:[] major:[] gender: []]167 debugPrinter.printFunction("BASE: ");168 debugPrinter.printFunction(base);169 try {170 let baseSQL = "SELECT u.id,u.title, u.ethnicity, u.major, u.profilepic, u.username, u.name FROM users u " + base;171 console.log(baseSQL);172 let [r, fields] = await db.execute(baseSQL);173 return r && r.length ? r : await Engine.getAllPosts();174 } catch (err) {175 return false;176 }177};178const filterHelper = (option, filter_name, count, base) => {179 tempcount = count;180 tempbase = base;181 console.log(option);182 try {183 for (x of option) {184 [tempcount, tempbase] = helper_cluster(x, filter_name, tempcount, tempbase);185 }186 } catch (err) {187 [tempcount, tempbase] = helper_cluster(option, filter_name, tempcount, tempbase);188 }189 return [tempcount, tempbase];190};191// Grabs all filtered results 192Engine.filterSearch = async (filteredSearchArray, lastLogin) => {193 if (!filteredSearchArray) return;194 debugPrinter.printFunction("Engine.filterSearch");195 let options = ["ethnicity", "gender", "major"];196 let base = "",197 count = 0;198 let base2 = " ORDER BY u.created DESC;";199 console.log("Engine.filterSearch");200 console.log(lastLogin); //output one day ahead201 let baseSQL2 = "SELECT * from users WHERE `usertype`=0 AND UNIX_TIMESTAMP(`created`) < UNIX_TIMESTAMP(?);";202 let [r2, fields2] = await db.execute(baseSQL2, [lastLogin]); // this gives us a whole list of all students who are new since last login203 if(r2 && r2.length) {204 console.log("outputting r2: ");205 for(i = 0; i < r2.length; i++){206 console.log(r2[i].username + "\t" + r2[i].created);207 }208 } else { console.log("r2 is empty."); }209 debugPrinter.printSuccess(filteredSearchArray[0].ethnicity);210 [count, base] = filterHelper(filteredSearchArray[0].ethnicity, options[0], count, base);211 [count, base] = filterHelper(filteredSearchArray[0].gender, options[1], count, base);212 [count, base] = filterHelper(filteredSearchArray[0].major, options[2], count, base);213 //filter: [eth:[] major:[] gender: []]214 debugPrinter.printFunction("BASE: ");215 debugPrinter.printFunction(base);216 try {217 //let baseSQL = "SELECT u.id,u.title, u.ethnicity, u.major, u.profilepic, u.username, u.name FROM users u " + base;218 let baseSQL = "SELECT u.id,u.title, u.ethnicity, u.major, u.profilepic, u.username, u.name FROM users u " + base + base2;219 console.log(baseSQL);220 let [r, fields] = await db.execute(baseSQL); // this gives us a list of all relevant search items221 return r && r.length ? r : await Engine.getAllPosts();222 } catch (err) {223 return false;224 }225};...

Full Screen

Full Screen

log.utility.js

Source:log.utility.js Github

copy

Full Screen

...74 ctx = this,75 }) {76 const logMessage = `${ctx.constructor.name}: ${new Date().toLocaleString()}: ${logState}: ${message}`;77 (new LogUtility()).__appendLogFile(logMessage);78 return ctx.__logToConsole ? printFunction(logMessage) : () => printFunction(logMessage);79 }80 async __appendLogFile(message = '') {81 await promisify(fs.appendFile)(this.__logFilePath, `${message}\r\n`);82 }...

Full Screen

Full Screen

djpeg_pre.js

Source:djpeg_pre.js Github

copy

Full Screen

...24 args.push("/input.jpg");25 var Module = {26 "print": function(text) {27 stdout += text + "\n";28 if (typeof printFunction == "function") printFunction(text);29 },30 "printErr": function(text) {31 stderr += text + "\n";32 if (typeof printFunction == "function") printFunction(text);33 },34 // Mounting input file35 "preRun": [function() {36 FS.writeFile("/input.jpg", file, {37 encoding: "binary"38 });39 }],40 "arguments": args,41 "ENVIRONMENT": "SHELL" // maximum compatibility???...

Full Screen

Full Screen

cjpeg_pre.js

Source:cjpeg_pre.js Github

copy

Full Screen

...24 args.push("/input.jpg");25 var Module = {26 "print": function(text) {27 stdout += text + "\n";28 if (typeof printFunction == "function") printFunction(text);29 },30 "printErr": function(text) {31 stderr += text + "\n";32 if (typeof printFunction == "function") printFunction(text);33 },34 // Mounting input file35 "preRun": [function() {36 FS.writeFile("/input.jpg", file, {37 encoding: "binary"38 });39 }],40 "arguments": args,41 "ENVIRONMENT": "SHELL" // maximum compatibility???...

Full Screen

Full Screen

example.js

Source:example.js Github

copy

Full Screen

...11function myFunc2(nameFunction) {12 return "Hello " + nameFunction() + ".";13}14function printName(nameFunction, printFunction) {15 printFunction(myFunc2(nameFunction));16}17printName(function () {18 return "Adam";19}, console.log);20//화살표 문법(람다식) 함수 파라미터 전달21const myFunc3 = (nameFunction) => "Hello " + nameFunction() + ".";22const printName2 = (nameFunction, printFunction) =>23 printFunction(myFunc3(nameFunction));24printName2(function () {25 return "Adam";26}, console.log);27//let, const28function messageFunction(name, weather) {29 let message = "Hello, Adam";30 if (weather === "sunny") {31 let message = "It is a nice day";32 console.log(message);33 } else {34 let message = "It is " + weather + " today";35 console.log(message);36 }37 console.log(message);...

Full Screen

Full Screen

restart.js

Source:restart.js Github

copy

Full Screen

...18}19function writeLog( message, prefix, printFunction ) {20 prefix = typeof prefix !== "undefined" ? prefix : "Debug" // prefix with "Debug"21 printFunction = typeof printFunction !== "undefined" ? printFunction : console.log // log everything with console.log by default22 printFunction( " " + "[" + prefix + "] " + message )23 fs.appendFileSync( "new-ed-info.log", "[" + prefix + "] " + message + "\n" )...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful