language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
becSetConnectionState(State) { try { if (this.becConnectionState !== State) { this.setState("info.connection", State, true); this.becConnectionState = State; } } catch (err) { this.ReportingError(err, MsgErrUnknown, "becSetConnectionState"); } }
becSetConnectionState(State) { try { if (this.becConnectionState !== State) { this.setState("info.connection", State, true); this.becConnectionState = State; } } catch (err) { this.ReportingError(err, MsgErrUnknown, "becSetConnectionState"); } }
JavaScript
async becConnectionCheck() { var _a; try { const becResult = await (this.bec.get(this.becURLCheck)); if (becResult.status === 200) { this.becSetConnectionState(true); return true; } else { this.becSetConnectionState(false); return false; } } catch (err) { if (((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 403) { this.becSetConnectionState(false); return false; } else if (err.code === "EAI_AGAIN" && err.syscall === "getaddrinfo") { this.log.error(MsgErrConnection); this.becSetConnectionState(false); return false; } else { this.ReportingError(err, MsgErrUnknown, "becConnectionCheck"); this.becSetConnectionState(false); return false; } } }
async becConnectionCheck() { var _a; try { const becResult = await (this.bec.get(this.becURLCheck)); if (becResult.status === 200) { this.becSetConnectionState(true); return true; } else { this.becSetConnectionState(false); return false; } } catch (err) { if (((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 403) { this.becSetConnectionState(false); return false; } else if (err.code === "EAI_AGAIN" && err.syscall === "getaddrinfo") { this.log.error(MsgErrConnection); this.becSetConnectionState(false); return false; } else { this.ReportingError(err, MsgErrUnknown, "becConnectionCheck"); this.becSetConnectionState(false); return false; } } }
JavaScript
async becConnectionLogin() { var _a, _b; try { const becResult = await (this.bec.post(this.becURLLogin, { "username": this.config.user_name, "password": this.config.user_password, "rememberme": false })); if (becResult.data["user"]["email"] === this.config.user_name) { const becCookie = Cookies.parse(becResult.headers["set-cookie"][0]); this.bec.defaults.headers.Cookie = `JSESSIONID=${becCookie.JSESSIONID}`; this.bec.defaults.headers["DNT"] = 1; this.bec.defaults.headers["Protect-From"] = "CSRF"; this.becSetConnectionState(true); this.ReportingInfo("Debug", "Connection", MsgInfoLogin); return true; } else { this.becSetConnectionState(false); return false; } } catch (err) { if (((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 403) { this.log.error(MsgErrLogin); this.becSetConnectionState(false); return false; } else if (((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) >= 500) { this.log.error(MsgErrBoschSide); this.becSetConnectionState(false); return false; } else if (err.code === "EAI_AGAIN" && err.syscall === "getaddrinfo") { this.log.error(MsgErrConnection); this.becSetConnectionState(false); return false; } else { this.ReportingError(err, MsgErrUnknown, "becConnectionLogin"); this.becSetConnectionState(false); return false; } } }
async becConnectionLogin() { var _a, _b; try { const becResult = await (this.bec.post(this.becURLLogin, { "username": this.config.user_name, "password": this.config.user_password, "rememberme": false })); if (becResult.data["user"]["email"] === this.config.user_name) { const becCookie = Cookies.parse(becResult.headers["set-cookie"][0]); this.bec.defaults.headers.Cookie = `JSESSIONID=${becCookie.JSESSIONID}`; this.bec.defaults.headers["DNT"] = 1; this.bec.defaults.headers["Protect-From"] = "CSRF"; this.becSetConnectionState(true); this.ReportingInfo("Debug", "Connection", MsgInfoLogin); return true; } else { this.becSetConnectionState(false); return false; } } catch (err) { if (((_a = err.response) === null || _a === void 0 ? void 0 : _a.status) === 403) { this.log.error(MsgErrLogin); this.becSetConnectionState(false); return false; } else if (((_b = err.response) === null || _b === void 0 ? void 0 : _b.status) >= 500) { this.log.error(MsgErrBoschSide); this.becSetConnectionState(false); return false; } else if (err.code === "EAI_AGAIN" && err.syscall === "getaddrinfo") { this.log.error(MsgErrConnection); this.becSetConnectionState(false); return false; } else { this.ReportingError(err, MsgErrUnknown, "becConnectionLogin"); this.becSetConnectionState(false); return false; } } }
JavaScript
async becConnection() { if (this.becConnectionState === true) { if (await this.becConnectionCheck() === true) { return true; } else { return await this.becConnectionLogin(); } } else { return await this.becConnectionLogin(); } }
async becConnection() { if (this.becConnectionState === true) { if (await this.becConnectionCheck() === true) { return true; } else { return await this.becConnectionLogin(); } } else { return await this.becConnectionLogin(); } }
JavaScript
cast(value, jsType) { if (value == null) return value; switch (jsType) { case JSON: if (!value) return null; // type === JSONB if (typeof value === 'object') return value; return JSON.parse(value); case Date: return value instanceof Date ? value : new Date(value); // node-sqlite3 doesn't convert TINYINT(1) to boolean by default case Boolean: return Boolean(value); case Number: // pg may return string return Number(value); case Buffer: if (Buffer.isBuffer(value)) return value; return Buffer.from(value); default: return value; } }
cast(value, jsType) { if (value == null) return value; switch (jsType) { case JSON: if (!value) return null; // type === JSONB if (typeof value === 'object') return value; return JSON.parse(value); case Date: return value instanceof Date ? value : new Date(value); // node-sqlite3 doesn't convert TINYINT(1) to boolean by default case Boolean: return Boolean(value); case Number: // pg may return string return Number(value); case Buffer: if (Buffer.isBuffer(value)) return value; return Buffer.from(value); default: return value; } }
JavaScript
uncast(value, type) { if (value == null) return value; if (value != null && typeof value === 'object') { if (type === JSON && typeof value.toObject === 'function') { return JSON.stringify(value.toObject()); } if (type === Date && typeof value.toDate === 'function') { return value.toDate(); } if (type === String && typeof value.toString === 'function') { return value.toString(); } } switch (type) { case JSON: return JSON.stringify(value); case Date: return value instanceof Date ? value : new Date(value); default: return value; } }
uncast(value, type) { if (value == null) return value; if (value != null && typeof value === 'object') { if (type === JSON && typeof value.toObject === 'function') { return JSON.stringify(value.toObject()); } if (type === Date && typeof value.toDate === 'function') { return value.toDate(); } if (type === String && typeof value.toString === 'function') { return value.toString(); } } switch (type) { case JSON: return JSON.stringify(value); case Date: return value instanceof Date ? value : new Date(value); default: return value; } }
JavaScript
emit(type, data = {}) { type = `${this.identifier}:${type}` Object.assign(data, { controller: this }) const event = new CustomEvent(type, { detail: data, bubbles: true }) return this.element.dispatchEvent(event) }
emit(type, data = {}) { type = `${this.identifier}:${type}` Object.assign(data, { controller: this }) const event = new CustomEvent(type, { detail: data, bubbles: true }) return this.element.dispatchEvent(event) }
JavaScript
on(type, callback, options = {}) { this.element.addEventListener(type, callback, options) const handle = () => this.element.removeEventListener(type, callback, options) this.eventListeners.push(handle) }
on(type, callback, options = {}) { this.element.addEventListener(type, callback, options) const handle = () => this.element.removeEventListener(type, callback, options) this.eventListeners.push(handle) }
JavaScript
function renderImageToCanvas(img, canvas, options, doSquash) { var iw = img.naturalWidth; var ih = img.naturalHeight; if (!(iw + ih)) return; var width = options.width; var height = options.height; var ctx = canvas.getContext('2d'); ctx.save(); var subsampled = detectSubsampling(img); if (subsampled) { iw /= 2; ih /= 2; } // size of tiling canvas var d = 1024; var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; var tmpCtx = tmpCanvas.getContext('2d'); var vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1; var dw = Math.ceil(d * width / iw); var dh = Math.ceil(d * height / ih / vertSquashRatio); var sy = 0; var dy = 0; while (sy < ih) { var sx = 0; var dx = 0; while (sx < iw) { tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; }
function renderImageToCanvas(img, canvas, options, doSquash) { var iw = img.naturalWidth; var ih = img.naturalHeight; if (!(iw + ih)) return; var width = options.width; var height = options.height; var ctx = canvas.getContext('2d'); ctx.save(); var subsampled = detectSubsampling(img); if (subsampled) { iw /= 2; ih /= 2; } // size of tiling canvas var d = 1024; var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; var tmpCtx = tmpCanvas.getContext('2d'); var vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1; var dw = Math.ceil(d * width / iw); var dh = Math.ceil(d * height / ih / vertSquashRatio); var sy = 0; var dy = 0; while (sy < ih) { var sx = 0; var dx = 0; while (sx < iw) { tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; }
JavaScript
function detectSubsampling(img) { var iw = img.naturalWidth; var ih = img.naturalHeight; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } }
function detectSubsampling(img) { var iw = img.naturalWidth; var ih = img.naturalHeight; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } }
JavaScript
function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. var sy = 0; var ey = ih; var py = ih; while (py > sy) { var alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = ey + sy >> 1; } var ratio = py / ih; return ratio === 0 ? 1 : ratio; }
function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. var sy = 0; var ey = ih; var py = ih; while (py > sy) { var alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = ey + sy >> 1; } var ratio = py / ih; return ratio === 0 ? 1 : ratio; }
JavaScript
function supportAutoOrientation(callback) { var testImageURL = 'data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAA' + 'AAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA' + 'QEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE' + 'BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/x' + 'ABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAA' + 'AAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQ' + 'voP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXw' + 'H/9k='; var img = document.createElement('img'); img.onload = function () { var orientation = img.width === 2 && img.height === 3; callback(orientation); }; img.src = testImageURL; }
function supportAutoOrientation(callback) { var testImageURL = 'data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAA' + 'AAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA' + 'QEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE' + 'BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/x' + 'ABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAA' + 'AAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQ' + 'voP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXw' + 'H/9k='; var img = document.createElement('img'); img.onload = function () { var orientation = img.width === 2 && img.height === 3; callback(orientation); }; img.src = testImageURL; }
JavaScript
function renderImageToCanvas (img, canvas, options, doSquash) { let iw = img.naturalWidth let ih = img.naturalHeight if (!(iw + ih)) return const width = options.width const height = options.height const ctx = canvas.getContext('2d') ctx.save() const subsampled = detectSubsampling(img) if (subsampled) { iw /= 2 ih /= 2 } // size of tiling canvas const d = 1024 let tmpCanvas = document.createElement('canvas') tmpCanvas.width = tmpCanvas.height = d let tmpCtx = tmpCanvas.getContext('2d') const vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1 const dw = Math.ceil(d * width / iw) const dh = Math.ceil(d * height / ih / vertSquashRatio) let sy = 0 let dy = 0 while (sy < ih) { let sx = 0 let dx = 0 while (sx < iw) { tmpCtx.clearRect(0, 0, d, d) tmpCtx.drawImage(img, -sx, -sy) ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh) sx += d dx += dw } sy += d dy += dh } ctx.restore() tmpCanvas = tmpCtx = null }
function renderImageToCanvas (img, canvas, options, doSquash) { let iw = img.naturalWidth let ih = img.naturalHeight if (!(iw + ih)) return const width = options.width const height = options.height const ctx = canvas.getContext('2d') ctx.save() const subsampled = detectSubsampling(img) if (subsampled) { iw /= 2 ih /= 2 } // size of tiling canvas const d = 1024 let tmpCanvas = document.createElement('canvas') tmpCanvas.width = tmpCanvas.height = d let tmpCtx = tmpCanvas.getContext('2d') const vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1 const dw = Math.ceil(d * width / iw) const dh = Math.ceil(d * height / ih / vertSquashRatio) let sy = 0 let dy = 0 while (sy < ih) { let sx = 0 let dx = 0 while (sx < iw) { tmpCtx.clearRect(0, 0, d, d) tmpCtx.drawImage(img, -sx, -sy) ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh) sx += d dx += dw } sy += d dy += dh } ctx.restore() tmpCanvas = tmpCtx = null }
JavaScript
function detectSubsampling (img) { const iw = img.naturalWidth const ih = img.naturalHeight if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image const canvas = document.createElement('canvas') canvas.width = canvas.height = 1 const ctx = canvas.getContext('2d') ctx.drawImage(img, -iw + 1, 0) // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0 } else { return false } }
function detectSubsampling (img) { const iw = img.naturalWidth const ih = img.naturalHeight if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image const canvas = document.createElement('canvas') canvas.width = canvas.height = 1 const ctx = canvas.getContext('2d') ctx.drawImage(img, -iw + 1, 0) // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0 } else { return false } }
JavaScript
function detectVerticalSquash (img, iw, ih) { const canvas = document.createElement('canvas') canvas.width = 1 canvas.height = ih const ctx = canvas.getContext('2d') ctx.drawImage(img, 0, 0) const data = ctx.getImageData(0, 0, 1, ih).data // search image edge pixel position in case it is squashed vertically. let sy = 0 let ey = ih let py = ih while (py > sy) { const alpha = data[(py - 1) * 4 + 3] if (alpha === 0) { ey = py } else { sy = py } py = (ey + sy) >> 1 } const ratio = (py / ih) return (ratio === 0) ? 1 : ratio }
function detectVerticalSquash (img, iw, ih) { const canvas = document.createElement('canvas') canvas.width = 1 canvas.height = ih const ctx = canvas.getContext('2d') ctx.drawImage(img, 0, 0) const data = ctx.getImageData(0, 0, 1, ih).data // search image edge pixel position in case it is squashed vertically. let sy = 0 let ey = ih let py = ih while (py > sy) { const alpha = data[(py - 1) * 4 + 3] if (alpha === 0) { ey = py } else { sy = py } py = (ey + sy) >> 1 } const ratio = (py / ih) return (ratio === 0) ? 1 : ratio }
JavaScript
function supportAutoOrientation (callback) { const testImageURL = 'data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAA' + 'AAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA' + 'QEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE' + 'BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/x' + 'ABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAA' + 'AAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQ' + 'voP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXw' + 'H/9k=' const img = document.createElement('img') img.onload = function () { const orientation = img.width === 2 && img.height === 3 callback(orientation) } img.src = testImageURL }
function supportAutoOrientation (callback) { const testImageURL = 'data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAA' + 'AAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA' + 'QEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE' + 'BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/x' + 'ABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAA' + 'AAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQ' + 'voP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXw' + 'H/9k=' const img = document.createElement('img') img.onload = function () { const orientation = img.width === 2 && img.height === 3 callback(orientation) } img.src = testImageURL }
JavaScript
function createShader( gl , vertSource , fragSource , uniforms , attributes) { //Compile vertex shader var vertShader = gl.createShader(gl.VERTEX_SHADER) gl.shaderSource(vertShader, vertSource) gl.compileShader(vertShader) if(!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) { throw new Error("Error compiling vertex shader: " + gl.getShaderInfoLog(vertShader)) } //Compile fragment shader var fragShader = gl.createShader(gl.FRAGMENT_SHADER) gl.shaderSource(fragShader, fragSource) gl.compileShader(fragShader) if(!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) { throw new Error("Error compiling fragment shader: " + gl.getShaderInfoLog(fragShader)) } //Link program var program = gl.createProgram() gl.attachShader(program, fragShader) gl.attachShader(program, vertShader) gl.linkProgram(program) if(!gl.getProgramParameter(program, gl.LINK_STATUS)) { throw new Error("Error linking shader program: " + gl.getProgramInfoLog (program)) } //Create location vector var locations = new Array(uniforms.length) var doLink = relinkUniforms.bind(undefined, gl, program, locations, uniforms) doLink() //Return final linked shader object var shader = new Shader( gl, program, createAttributeWrapper( gl, program, attributes, doLink), { uniforms: makeReflect(uniforms), attributes: makeReflect(attributes) }, vertShader, fragShader ) Object.defineProperty(shader, "uniforms", createUniformWrapper( gl, program, uniforms, locations )) return shader }
function createShader( gl , vertSource , fragSource , uniforms , attributes) { //Compile vertex shader var vertShader = gl.createShader(gl.VERTEX_SHADER) gl.shaderSource(vertShader, vertSource) gl.compileShader(vertShader) if(!gl.getShaderParameter(vertShader, gl.COMPILE_STATUS)) { throw new Error("Error compiling vertex shader: " + gl.getShaderInfoLog(vertShader)) } //Compile fragment shader var fragShader = gl.createShader(gl.FRAGMENT_SHADER) gl.shaderSource(fragShader, fragSource) gl.compileShader(fragShader) if(!gl.getShaderParameter(fragShader, gl.COMPILE_STATUS)) { throw new Error("Error compiling fragment shader: " + gl.getShaderInfoLog(fragShader)) } //Link program var program = gl.createProgram() gl.attachShader(program, fragShader) gl.attachShader(program, vertShader) gl.linkProgram(program) if(!gl.getProgramParameter(program, gl.LINK_STATUS)) { throw new Error("Error linking shader program: " + gl.getProgramInfoLog (program)) } //Create location vector var locations = new Array(uniforms.length) var doLink = relinkUniforms.bind(undefined, gl, program, locations, uniforms) doLink() //Return final linked shader object var shader = new Shader( gl, program, createAttributeWrapper( gl, program, attributes, doLink), { uniforms: makeReflect(uniforms), attributes: makeReflect(attributes) }, vertShader, fragShader ) Object.defineProperty(shader, "uniforms", createUniformWrapper( gl, program, uniforms, locations )) return shader }
JavaScript
function through (write, end) { write = write || function (data) { this.emit('data', data) } end = end || function () { this.emit('end') } var ended = false, destroyed = false var stream = new Stream(), buffer = [] stream.buffer = buffer stream.readable = stream.writable = true stream.paused = false stream.write = function (data) { write.call(this, data) return !stream.paused } function drain() { while(buffer.length && !stream.paused) { var data = buffer.shift() if(null === data) return stream.emit('end') else stream.emit('data', data) } } stream.queue = function (data) { buffer.push(data) drain() } //this will be registered as the first 'end' listener //must call destroy next tick, to make sure we're after any //stream piped from here. //this is only a problem if end is not emitted synchronously. //a nicer way to do this is to make sure this is the last listener for 'end' stream.on('end', function () { stream.readable = false if(!stream.writable) process.nextTick(function () { stream.destroy() }) }) function _end () { stream.writable = false end.call(stream) if(!stream.readable) stream.destroy() } stream.end = function (data) { if(ended) return ended = true if(arguments.length) stream.write(data) _end() // will emit or queue } stream.destroy = function () { if(destroyed) return destroyed = true ended = true buffer.length = 0 stream.writable = stream.readable = false stream.emit('close') } stream.pause = function () { if(stream.paused) return stream.paused = true stream.emit('pause') } stream.resume = function () { if(stream.paused) { stream.paused = false } drain() //may have become paused again, //as drain emits 'data'. if(!stream.paused) stream.emit('drain') } return stream }
function through (write, end) { write = write || function (data) { this.emit('data', data) } end = end || function () { this.emit('end') } var ended = false, destroyed = false var stream = new Stream(), buffer = [] stream.buffer = buffer stream.readable = stream.writable = true stream.paused = false stream.write = function (data) { write.call(this, data) return !stream.paused } function drain() { while(buffer.length && !stream.paused) { var data = buffer.shift() if(null === data) return stream.emit('end') else stream.emit('data', data) } } stream.queue = function (data) { buffer.push(data) drain() } //this will be registered as the first 'end' listener //must call destroy next tick, to make sure we're after any //stream piped from here. //this is only a problem if end is not emitted synchronously. //a nicer way to do this is to make sure this is the last listener for 'end' stream.on('end', function () { stream.readable = false if(!stream.writable) process.nextTick(function () { stream.destroy() }) }) function _end () { stream.writable = false end.call(stream) if(!stream.readable) stream.destroy() } stream.end = function (data) { if(ended) return ended = true if(arguments.length) stream.write(data) _end() // will emit or queue } stream.destroy = function () { if(destroyed) return destroyed = true ended = true buffer.length = 0 stream.writable = stream.readable = false stream.emit('close') } stream.pause = function () { if(stream.paused) return stream.paused = true stream.emit('pause') } stream.resume = function () { if(stream.paused) { stream.paused = false } drain() //may have become paused again, //as drain emits 'data'. if(!stream.paused) stream.emit('drain') } return stream }
JavaScript
function changeElement( imageNum ) { var title = document.getElementsByClassName('imgTitle')[imageNum].innerHTML; document.getElementById('slideShowText').innerHTML = title; }
function changeElement( imageNum ) { var title = document.getElementsByClassName('imgTitle')[imageNum].innerHTML; document.getElementById('slideShowText').innerHTML = title; }
JavaScript
async function createBlogPostArchive({ posts, gatsbyUtilities }) { const graphqlResult = await gatsbyUtilities.graphql(/* GraphQL */ ` { wp { readingSettings { postsPerPage } } } `); const { postsPerPage } = graphqlResult.data.wp.readingSettings; const postsChunkedIntoArchivePages = chunk(posts, postsPerPage); const totalPages = postsChunkedIntoArchivePages.length; return Promise.all( postsChunkedIntoArchivePages.map(async (_posts, index) => { const pageNumber = index + 1; const getPagePath = (page) => { if (page > 0 && page <= totalPages) { // Since our homepage is our blog page // we want the first page to be "/archive" and any additional pages // to be numbered. // "/archive/2" for example return page === 1 ? "/archive" : `/archive/${page}`; } return null; }; // createPage is an action passed to createPages // See https://www.gatsbyjs.com/docs/actions#createPage for more info await gatsbyUtilities.actions.createPage({ path: getPagePath(pageNumber), // use the blog post archive template as the page component component: path.resolve("./src/templates/blog-post-archive.tsx"), // `context` is available in the template as a prop and // as a variable in GraphQL. context: { // the index of our loop is the offset of which posts we want to display // so for page 1, 0 * 10 = 0 offset, for page 2, 1 * 10 = 10 posts offset, // etc offset: index * postsPerPage, // We need to tell the template how many posts to display too postsPerPage, nextPagePath: getPagePath(pageNumber + 1), previousPagePath: getPagePath(pageNumber - 1), }, }); }), ); }
async function createBlogPostArchive({ posts, gatsbyUtilities }) { const graphqlResult = await gatsbyUtilities.graphql(/* GraphQL */ ` { wp { readingSettings { postsPerPage } } } `); const { postsPerPage } = graphqlResult.data.wp.readingSettings; const postsChunkedIntoArchivePages = chunk(posts, postsPerPage); const totalPages = postsChunkedIntoArchivePages.length; return Promise.all( postsChunkedIntoArchivePages.map(async (_posts, index) => { const pageNumber = index + 1; const getPagePath = (page) => { if (page > 0 && page <= totalPages) { // Since our homepage is our blog page // we want the first page to be "/archive" and any additional pages // to be numbered. // "/archive/2" for example return page === 1 ? "/archive" : `/archive/${page}`; } return null; }; // createPage is an action passed to createPages // See https://www.gatsbyjs.com/docs/actions#createPage for more info await gatsbyUtilities.actions.createPage({ path: getPagePath(pageNumber), // use the blog post archive template as the page component component: path.resolve("./src/templates/blog-post-archive.tsx"), // `context` is available in the template as a prop and // as a variable in GraphQL. context: { // the index of our loop is the offset of which posts we want to display // so for page 1, 0 * 10 = 0 offset, for page 2, 1 * 10 = 10 posts offset, // etc offset: index * postsPerPage, // We need to tell the template how many posts to display too postsPerPage, nextPagePath: getPagePath(pageNumber + 1), previousPagePath: getPagePath(pageNumber - 1), }, }); }), ); }
JavaScript
function describeSegments(segs) { if (segs.length == 0) return "none"; else if (segs.length == 1) { var mode = segs[0].mode; var Mode = qrcodegen.QrSegment.Mode; if (mode == Mode.NUMERIC) return "numeric"; if (mode == Mode.ALPHANUMERIC) return "alphanumeric"; if (mode == Mode.BYTE) return "byte"; if (mode == Mode.KANJI) return "kanji"; return "unknown"; } else return "multiple"; }
function describeSegments(segs) { if (segs.length == 0) return "none"; else if (segs.length == 1) { var mode = segs[0].mode; var Mode = qrcodegen.QrSegment.Mode; if (mode == Mode.NUMERIC) return "numeric"; if (mode == Mode.ALPHANUMERIC) return "alphanumeric"; if (mode == Mode.BYTE) return "byte"; if (mode == Mode.KANJI) return "kanji"; return "unknown"; } else return "multiple"; }
JavaScript
function countUnicodeChars(str) { var result = 0; for (var i = 0; i < str.length; i++, result++) { var c = str.charCodeAt(i); if (c < 0xD800 || c >= 0xE000) continue; else if (0xD800 <= c && c < 0xDC00 && i + 1 < str.length) { // High surrogate i++; var d = str.charCodeAt(i); if (0xDC00 <= d && d < 0xE000) // Low surrogate continue; } throw "Invalid UTF-16 string"; } return result; }
function countUnicodeChars(str) { var result = 0; for (var i = 0; i < str.length; i++, result++) { var c = str.charCodeAt(i); if (c < 0xD800 || c >= 0xE000) continue; else if (0xD800 <= c && c < 0xDC00 && i + 1 < str.length) { // High surrogate i++; var d = str.charCodeAt(i); if (0xDC00 <= d && d < 0xE000) // Low surrogate continue; } throw "Invalid UTF-16 string"; } return result; }
JavaScript
addRow(row) { if (row.length !== this.width) { throw new Error('In order to add a row to a Matrix, it must have the same length as Matrix width'); } this.height++; this.elements = this.elements.concat(row); this._callOnChanged(enforce); return this; }
addRow(row) { if (row.length !== this.width) { throw new Error('In order to add a row to a Matrix, it must have the same length as Matrix width'); } this.height++; this.elements = this.elements.concat(row); this._callOnChanged(enforce); return this; }
JavaScript
addCol(col) { if (col.length !== this.height) { throw new Error('In order to add a column to a Matrix, it must have the same length as Matrix height'); } for (let i = 0; i < this.height; i++) { this.elements.splice(this.width * i, 0, col[i]); } this._callOnChanged(enforce); return this; }
addCol(col) { if (col.length !== this.height) { throw new Error('In order to add a column to a Matrix, it must have the same length as Matrix height'); } for (let i = 0; i < this.height; i++) { this.elements.splice(this.width * i, 0, col[i]); } this._callOnChanged(enforce); return this; }
JavaScript
add(b) { if (this.width !== b.width || this.height !== b.height) { throw new Error('In order to add two matrices their width and height must be the same'); } const res = new this.constructor(this.height, this.width); for (let i in this.elements) { res.elements[i] = this.elements[i] + b.elements[i]; } res._callOnChanged(enforce); return res; }
add(b) { if (this.width !== b.width || this.height !== b.height) { throw new Error('In order to add two matrices their width and height must be the same'); } const res = new this.constructor(this.height, this.width); for (let i in this.elements) { res.elements[i] = this.elements[i] + b.elements[i]; } res._callOnChanged(enforce); return res; }
JavaScript
transpose() { const res = new this.constructor(this.width, this.height); for (let i = 0; i < this.height; i++) { for (let j = 0; j < this.width; j++) { res.set(j, i, this.get(i, j)); } } return res; }
transpose() { const res = new this.constructor(this.width, this.height); for (let i = 0; i < this.height; i++) { for (let j = 0; j < this.width; j++) { res.set(j, i, this.get(i, j)); } } return res; }
JavaScript
mult(b) { if (this.width !== b.height) { throw new Error('In order to multiply matrices the number of columns in the first one must be equal to the number of rows in the second one!'); } const res = new this.constructor(this.height, b.width); for (let i = 0; i < res.height; i++) { for (let j = 0; j < res.width; j++) { res.set(i, j, 0); for (let g = 0; g < b.height; g++) { res.addTo(i, j, this.get(i, g) * b.get(g, j)); } } } return res; }
mult(b) { if (this.width !== b.height) { throw new Error('In order to multiply matrices the number of columns in the first one must be equal to the number of rows in the second one!'); } const res = new this.constructor(this.height, b.width); for (let i = 0; i < res.height; i++) { for (let j = 0; j < res.width; j++) { res.set(i, j, 0); for (let g = 0; g < b.height; g++) { res.addTo(i, j, this.get(i, g) * b.get(g, j)); } } } return res; }
JavaScript
static Identity(size) { const res = new this.constructor(size, size); for (let i = 0; i < size; i++) { res.set(i, i, 1); } return res; }
static Identity(size) { const res = new this.constructor(size, size); for (let i = 0; i < size; i++) { res.set(i, i, 1); } return res; }
JavaScript
function binarize(matrix) { for (let i in matrix.elements) { matrix.elements[i] %= 2; } }
function binarize(matrix) { for (let i in matrix.elements) { matrix.elements[i] %= 2; } }
JavaScript
function onContentTap(gestureEvt) { if(sideMenuCtrl.getOpenAmount() !== 0) { sideMenuCtrl.close(); gestureEvt.gesture.srcEvent.preventDefault(); startCoord = null; primaryScrollAxis = null; } else if(!startCoord) { startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent); } }
function onContentTap(gestureEvt) { if(sideMenuCtrl.getOpenAmount() !== 0) { sideMenuCtrl.close(); gestureEvt.gesture.srcEvent.preventDefault(); startCoord = null; primaryScrollAxis = null; } else if(!startCoord) { startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent); } }
JavaScript
oldSchoolModificator(){ var generalAdmissionWrapper = document.createElement("div"); generalAdmissionWrapper.classList.add("general-admission", "modificator"); var generalAdmission = document.createElement("div"), generalAdmissionText = document.createTextNode('GENERAL ADMISSION'); generalAdmission.appendChild(generalAdmissionText); generalAdmissionWrapper.appendChild(generalAdmission); this.eventsRootContainer.appendChild(generalAdmissionWrapper); }
oldSchoolModificator(){ var generalAdmissionWrapper = document.createElement("div"); generalAdmissionWrapper.classList.add("general-admission", "modificator"); var generalAdmission = document.createElement("div"), generalAdmissionText = document.createTextNode('GENERAL ADMISSION'); generalAdmission.appendChild(generalAdmissionText); generalAdmissionWrapper.appendChild(generalAdmission); this.eventsRootContainer.appendChild(generalAdmissionWrapper); }
JavaScript
function readMessageCatalog(messageCatalogPath) { const input = fs.readFileSync(messageCatalogPath); // parse PO file into an object in gettext-parser format // https://github.com/smhg/gettext-parser#data-structure-of-parsed-mopo-files const rawPO = gettextParser.po.parse(input); // convert from gettext-parser format to gettext.js format // https://github.com/smhg/gettext-parser#data-structure-of-parsed-mopo-files // https://github.com/guillaumepotier/gettext.js#required-json-format const formattedPO = { '': { language: rawPO.headers.Language, 'plural-forms': rawPO.headers['Plural-Forms'], }, }; // leave out the empty message which contains the header string delete rawPO.translations['']['']; Object.keys(rawPO.translations['']).forEach((msgid) => { if (rawPO.translations[''][msgid].msgstr.length === 1) { [formattedPO[msgid]] = rawPO.translations[''][msgid].msgstr; } else { formattedPO[msgid] = rawPO.translations[''][msgid].msgstr; } }); return formattedPO; }
function readMessageCatalog(messageCatalogPath) { const input = fs.readFileSync(messageCatalogPath); // parse PO file into an object in gettext-parser format // https://github.com/smhg/gettext-parser#data-structure-of-parsed-mopo-files const rawPO = gettextParser.po.parse(input); // convert from gettext-parser format to gettext.js format // https://github.com/smhg/gettext-parser#data-structure-of-parsed-mopo-files // https://github.com/guillaumepotier/gettext.js#required-json-format const formattedPO = { '': { language: rawPO.headers.Language, 'plural-forms': rawPO.headers['Plural-Forms'], }, }; // leave out the empty message which contains the header string delete rawPO.translations['']['']; Object.keys(rawPO.translations['']).forEach((msgid) => { if (rawPO.translations[''][msgid].msgstr.length === 1) { [formattedPO[msgid]] = rawPO.translations[''][msgid].msgstr; } else { formattedPO[msgid] = rawPO.translations[''][msgid].msgstr; } }); return formattedPO; }
JavaScript
function loadMessageCatalogs() { // load each language's message catalog PO file into an object // for easy access when we switch languages const languages = fs.readdirSync(`${__dirname}/../static/internationalization/locales`); if (languages) { languages.forEach((language) => { const messageCatalogPath = `${__dirname}/../static/internationalization/locales/${language}/LC_MESSAGES/messages.po`; i18n.loadJSON(readMessageCatalog(messageCatalogPath), 'messages'); }); } logger.debug('loaded message catalogs'); }
function loadMessageCatalogs() { // load each language's message catalog PO file into an object // for easy access when we switch languages const languages = fs.readdirSync(`${__dirname}/../static/internationalization/locales`); if (languages) { languages.forEach((language) => { const messageCatalogPath = `${__dirname}/../static/internationalization/locales/${language}/LC_MESSAGES/messages.po`; i18n.loadJSON(readMessageCatalog(messageCatalogPath), 'messages'); }); } logger.debug('loaded message catalogs'); }
JavaScript
function signToken(user) { const payload = { username: user.username, }; const secret = process.env.JWT_SECRET || "is it secret, is it safe?"; const options = { expiresIn: "1h", }; return jwt.sign(payload, secret, options); // notice the return }
function signToken(user) { const payload = { username: user.username, }; const secret = process.env.JWT_SECRET || "is it secret, is it safe?"; const options = { expiresIn: "1h", }; return jwt.sign(payload, secret, options); // notice the return }
JavaScript
function changeImage() { var image = document.getElementById(select_id); if(image.src="img/down_arrow.png" | c[select_id-1]==0) { image.src = 'img/top_arrow.png'; c[select_id-1]=1; } else if(image.src="img/top_arrow.png" | c[select_id-1]==1) { image.src = 'img/down_arrow.png'; c[select_id-1]=0; } else{ image.src = 'img/down_arrow.png'; } console.log("IMAGE HAS BEEN CHANGED",c); }
function changeImage() { var image = document.getElementById(select_id); if(image.src="img/down_arrow.png" | c[select_id-1]==0) { image.src = 'img/top_arrow.png'; c[select_id-1]=1; } else if(image.src="img/top_arrow.png" | c[select_id-1]==1) { image.src = 'img/down_arrow.png'; c[select_id-1]=0; } else{ image.src = 'img/down_arrow.png'; } console.log("IMAGE HAS BEEN CHANGED",c); }
JavaScript
function displayShoppingCart(){ var orderedProductsTblBody=document.getElementById("orderedProductsTblBody"); //ensure we delete all previously added rows from ordered products table while(orderedProductsTblBody.rows.length>0) { orderedProductsTblBody.deleteRow(0); } //variable to hold total price of shopping cart var cart_total_price=0; //iterate over array of objects for(var product in shoppingCart){ //add new row var row=orderedProductsTblBody.insertRow(); //create three cells for product properties var cellName = row.insertCell(0); var cellDescription = row.insertCell(1); var cellPrice = row.insertCell(2); cellPrice.align="right"; //fill cells with values from current product object of our array cellName.innerHTML = shoppingCart[product].Name; cellDescription.innerHTML = shoppingCart[product].Description; cellPrice.innerHTML = shoppingCart[product].Price; cart_total_price+=shoppingCart[product].Price; } //fill total cost of our shopping cart document.getElementById("cart_total").innerHTML=cart_total_price; }
function displayShoppingCart(){ var orderedProductsTblBody=document.getElementById("orderedProductsTblBody"); //ensure we delete all previously added rows from ordered products table while(orderedProductsTblBody.rows.length>0) { orderedProductsTblBody.deleteRow(0); } //variable to hold total price of shopping cart var cart_total_price=0; //iterate over array of objects for(var product in shoppingCart){ //add new row var row=orderedProductsTblBody.insertRow(); //create three cells for product properties var cellName = row.insertCell(0); var cellDescription = row.insertCell(1); var cellPrice = row.insertCell(2); cellPrice.align="right"; //fill cells with values from current product object of our array cellName.innerHTML = shoppingCart[product].Name; cellDescription.innerHTML = shoppingCart[product].Description; cellPrice.innerHTML = shoppingCart[product].Price; cart_total_price+=shoppingCart[product].Price; } //fill total cost of our shopping cart document.getElementById("cart_total").innerHTML=cart_total_price; }
JavaScript
_loading() { return { loadSharedConfig() { this.loadClientConfig(); }, }; }
_loading() { return { loadSharedConfig() { this.loadClientConfig(); }, }; }
JavaScript
_end() { return { end() { if (!this.options.skipInstall) { this.rebuildClient(); } }, }; }
_end() { return { end() { if (!this.options.skipInstall) { this.rebuildClient(); } }, }; }
JavaScript
function lineProcessor(string) { const parsed = string.match(parseRegex); if (!parsed) { throw new Error('unable to parse string'); } return { mention: parsed[1], // 1st capture group date: parsed[2], // 2nd capture group sentence: parsed[3], // 3rd capture group }; }
function lineProcessor(string) { const parsed = string.match(parseRegex); if (!parsed) { throw new Error('unable to parse string'); } return { mention: parsed[1], // 1st capture group date: parsed[2], // 2nd capture group sentence: parsed[3], // 3rd capture group }; }
JavaScript
function chatParser(string) { const separator = process.env.SEPARATOR || '#-#-#'; const lines = separeStrings(string, separator).split(separator); const results = []; for (let i = 0; i < lines.length; i += 1) { try { const line = lineProcessor(lines[i]); results.push(line); } catch (error) { throw new Error(error); } } return results.map(defineType); }
function chatParser(string) { const separator = process.env.SEPARATOR || '#-#-#'; const lines = separeStrings(string, separator).split(separator); const results = []; for (let i = 0; i < lines.length; i += 1) { try { const line = lineProcessor(lines[i]); results.push(line); } catch (error) { throw new Error(error); } } return results.map(defineType); }
JavaScript
function separeStrings(string, separator) { // Marks a string to be splitted over newlines (most common case) const newLineRegex = new RegExp(/(?<=\n)/); // Marks a string to be splitted over the date if no newlines are present const dateSplittingRegex = new RegExp(/(?<!^|[^\S])((?:[0-9]{2}:?){3})/); const regex = new RegExp(`${newLineRegex.source}|${dateSplittingRegex.source}`, 'gm'); return string.replace(regex, `${separator}$1`); }
function separeStrings(string, separator) { // Marks a string to be splitted over newlines (most common case) const newLineRegex = new RegExp(/(?<=\n)/); // Marks a string to be splitted over the date if no newlines are present const dateSplittingRegex = new RegExp(/(?<!^|[^\S])((?:[0-9]{2}:?){3})/); const regex = new RegExp(`${newLineRegex.source}|${dateSplittingRegex.source}`, 'gm'); return string.replace(regex, `${separator}$1`); }
JavaScript
function authorChecker(first, second) { const firstAuthor = trimmer(first.mention); const secondAuthor = trimmer(second.mention); return (firstAuthor === secondAuthor); }
function authorChecker(first, second) { const firstAuthor = trimmer(first.mention); const secondAuthor = trimmer(second.mention); return (firstAuthor === secondAuthor); }
JavaScript
function defineType(message, index, array) { return { mention: message.mention, date: message.date, sentence: message.sentence, type: authorChecker(array[0], message) ? 'customer' : 'agent', }; }
function defineType(message, index, array) { return { mention: message.mention, date: message.date, sentence: message.sentence, type: authorChecker(array[0], message) ? 'customer' : 'agent', }; }
JavaScript
function sendEmail(e) { e.preventDefault() emailjs .sendForm( "service_dlvr0hu", "template_7yopkfp", e.target, "user_XfxilZn7B9YfIGaDPhQHY" ) .then( result => { console.log(result.text) }, error => { console.log(error.text) } ) e.target.reset() }
function sendEmail(e) { e.preventDefault() emailjs .sendForm( "service_dlvr0hu", "template_7yopkfp", e.target, "user_XfxilZn7B9YfIGaDPhQHY" ) .then( result => { console.log(result.text) }, error => { console.log(error.text) } ) e.target.reset() }
JavaScript
function then (onFulfilled, onRejected) { var vow = Deferred(); bindHandlers(onFulfilled, onRejected, vow); return vow.promise; }
function then (onFulfilled, onRejected) { var vow = Deferred(); bindHandlers(onFulfilled, onRejected, vow); return vow.promise; }
JavaScript
function applyAllPending (apply, value) { // Already fulfilled or rejected, ignore silently if (!pendingHandlers) { return; } var bindings = pendingHandlers; pendingHandlers = undef; // The promise is no longer pending, so we can swap bindHandlers // to something more direct bindHandlers = function (onFulfilled, onRejected, vow) { nextTurn(function () { apply(value, onFulfilled, onRejected, vow.fulfill, vow.reject); }); }; // Call all the pending handlers nextTurn(function () { for (var i = 0, len = bindings.length; i < len; i++) { bindings[i](apply, value); } }); }
function applyAllPending (apply, value) { // Already fulfilled or rejected, ignore silently if (!pendingHandlers) { return; } var bindings = pendingHandlers; pendingHandlers = undef; // The promise is no longer pending, so we can swap bindHandlers // to something more direct bindHandlers = function (onFulfilled, onRejected, vow) { nextTurn(function () { apply(value, onFulfilled, onRejected, vow.fulfill, vow.reject); }); }; // Call all the pending handlers nextTurn(function () { for (var i = 0, len = bindings.length; i < len; i++) { bindings[i](apply, value); } }); }
JavaScript
function apply (val, handler, fallback, fulfillNext, rejectNext) { var result; try { if (typeof handler === 'function') { result = handler(val); if (result && typeof result.then === 'function') { result.then(fulfillNext, rejectNext); } else { fulfillNext(result); } } else { fallback(val); } } catch (e) { rejectNext(e); } }
function apply (val, handler, fallback, fulfillNext, rejectNext) { var result; try { if (typeof handler === 'function') { result = handler(val); if (result && typeof result.then === 'function') { result.then(fulfillNext, rejectNext); } else { fulfillNext(result); } } else { fallback(val); } } catch (e) { rejectNext(e); } }
JavaScript
function iosSwrveFrameworkEdit() { const appName = appConfig.name(); const iosPath = path.join('platforms', 'ios'); const projPath = path.join(iosPath, `${appName}.xcodeproj`, 'project.pbxproj'); const proj = xcode.project(projPath); const buildPhaseComment = 'Swrve-Framework-Script'; proj.parseSync(); var currentBuildPhases = proj.hash.project.objects['PBXNativeTarget'][proj.getFirstTarget().uuid]['buildPhases']; // Iterates through the current xcode Build Phases and checks for the existence of our script for (var i = 0; i < currentBuildPhases.length; i++) { if (currentBuildPhases[i].comment == buildPhaseComment) { console.log(`Swrve: ${buildPhaseComment} is already in Build Phases`); return; } } var frameworkEditScript = fs.readFileSync( path.join('plugins', 'cordova-plugin-swrve', 'swrve-utils', 'ios', 'framework-edit-script.txt'), 'utf8' ); var options = { shellPath: '/bin/sh', shellScript: frameworkEditScript, inputPaths: [], outputPaths: [] }; proj.addBuildPhase([], 'PBXShellScriptBuildPhase', `${buildPhaseComment}`, proj.getFirstTarget().uuid, options); fs.writeFileSync(projPath, proj.writeSync()); }
function iosSwrveFrameworkEdit() { const appName = appConfig.name(); const iosPath = path.join('platforms', 'ios'); const projPath = path.join(iosPath, `${appName}.xcodeproj`, 'project.pbxproj'); const proj = xcode.project(projPath); const buildPhaseComment = 'Swrve-Framework-Script'; proj.parseSync(); var currentBuildPhases = proj.hash.project.objects['PBXNativeTarget'][proj.getFirstTarget().uuid]['buildPhases']; // Iterates through the current xcode Build Phases and checks for the existence of our script for (var i = 0; i < currentBuildPhases.length; i++) { if (currentBuildPhases[i].comment == buildPhaseComment) { console.log(`Swrve: ${buildPhaseComment} is already in Build Phases`); return; } } var frameworkEditScript = fs.readFileSync( path.join('plugins', 'cordova-plugin-swrve', 'swrve-utils', 'ios', 'framework-edit-script.txt'), 'utf8' ); var options = { shellPath: '/bin/sh', shellScript: frameworkEditScript, inputPaths: [], outputPaths: [] }; proj.addBuildPhase([], 'PBXShellScriptBuildPhase', `${buildPhaseComment}`, proj.getFirstTarget().uuid, options); fs.writeFileSync(projPath, proj.writeSync()); }
JavaScript
function findController() { for (var j in controllers) { var controller = controllers[j]; for (var i = 0; i < controller.buttons.length; ++i) { var val = controller.buttons[i]; var pressed = val == 1.0; if (typeof(val) == "object") { pressed = val.pressed; val = val.value; } if (pressed) { cur_controller_index = j; } } } }
function findController() { for (var j in controllers) { var controller = controllers[j]; for (var i = 0; i < controller.buttons.length; ++i) { var val = controller.buttons[i]; var pressed = val == 1.0; if (typeof(val) == "object") { pressed = val.pressed; val = val.value; } if (pressed) { cur_controller_index = j; } } } }
JavaScript
function applyMiddleware(...middlewares) { return createStore => (...args) => { const store = createStore(...args) let dispatch = () => { throw new Error( 'Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.' ) } const middlewareAPI = { getState: store.getState, dispatch: (...args) => dispatch(...args) } // middlewareAPI 作为参数执行一遍所有的中间件 const chain = middlewares.map(middleware => middleware(middlewareAPI)) // 根据 compose 生产的其实是类似 mid1(mid2(mid3(store.dispatch))) // 所以在数组最后的 middleware 其实是第一个执行的 dispatch = compose(...chain)(store.dispatch) return { ...store, dispatch } } }
function applyMiddleware(...middlewares) { return createStore => (...args) => { const store = createStore(...args) let dispatch = () => { throw new Error( 'Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.' ) } const middlewareAPI = { getState: store.getState, dispatch: (...args) => dispatch(...args) } // middlewareAPI 作为参数执行一遍所有的中间件 const chain = middlewares.map(middleware => middleware(middlewareAPI)) // 根据 compose 生产的其实是类似 mid1(mid2(mid3(store.dispatch))) // 所以在数组最后的 middleware 其实是第一个执行的 dispatch = compose(...chain)(store.dispatch) return { ...store, dispatch } } }
JavaScript
function isPlainObject(obj) { if (typeof obj !== 'object' || obj === null) return false /** * 循环找到原型链的顶层,然后和第一层原型对比是否相等 * 不知道为什么要循环,不直接 * let proto = Object.getPrototypeOf(obj) * return !!proto && Object.getPrototypeOf(proto) === null */ let proto = obj while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto) } return Object.getPrototypeOf(obj) === proto }
function isPlainObject(obj) { if (typeof obj !== 'object' || obj === null) return false /** * 循环找到原型链的顶层,然后和第一层原型对比是否相等 * 不知道为什么要循环,不直接 * let proto = Object.getPrototypeOf(obj) * return !!proto && Object.getPrototypeOf(proto) === null */ let proto = obj while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto) } return Object.getPrototypeOf(obj) === proto }
JavaScript
function cambiarCategoria(id, token) { /* Lanza una peticion ajax con el id de la categoria que quiere mostrar. */ $.ajax({ url: '/cambiarCategoria', method: 'post', data: { '_token': token, 'id': id }, error: function (response) { /* Si la peticion ajax terorna error lanza un pop up comunicando el error. */ alert(response['statusText']); }, success: function (response) { /* Si la peticion ajax funciona correctamente lista todos los videos de esa categoria y muestra la categoria. */ document.getElementById('productes').innerHTML = response; } }); }
function cambiarCategoria(id, token) { /* Lanza una peticion ajax con el id de la categoria que quiere mostrar. */ $.ajax({ url: '/cambiarCategoria', method: 'post', data: { '_token': token, 'id': id }, error: function (response) { /* Si la peticion ajax terorna error lanza un pop up comunicando el error. */ alert(response['statusText']); }, success: function (response) { /* Si la peticion ajax funciona correctamente lista todos los videos de esa categoria y muestra la categoria. */ document.getElementById('productes').innerHTML = response; } }); }
JavaScript
function onSaveSale() { var recieved_amount = $('input#recieved').val(); var recieveable_amount = $('input#payable').val(); var pntType = $('#payment_type').val(); var transCode = $('#transCode').val(); var custId = $('#select_customer').val(); var tax = $('input.tax_value').val(); $.ajax({ type: "POST", url: "sale", dataType: "json", // data: {'_token': $('input[name=_token]').val()}, data: {'custID': custId, 'payment': pntType, 'recieved': recieved_amount, 'recieveable': recieveable_amount, 'transCode': transCode, 'tax': tax, '_token': $('input[name=_token]').val() }, success: function (response) { $('#inv_message').css('display', 'block'); $('#inv_message').attr('style', response.style); $('#inv_message').html(response.sale_msg); $('#inv_message').fadeOut(4000); // $('#sale_section').load(' #sale_section'); setTimeout(function () { location.reload(); }, 5000); }, error: function (error) { console.log(error); } }); }
function onSaveSale() { var recieved_amount = $('input#recieved').val(); var recieveable_amount = $('input#payable').val(); var pntType = $('#payment_type').val(); var transCode = $('#transCode').val(); var custId = $('#select_customer').val(); var tax = $('input.tax_value').val(); $.ajax({ type: "POST", url: "sale", dataType: "json", // data: {'_token': $('input[name=_token]').val()}, data: {'custID': custId, 'payment': pntType, 'recieved': recieved_amount, 'recieveable': recieveable_amount, 'transCode': transCode, 'tax': tax, '_token': $('input[name=_token]').val() }, success: function (response) { $('#inv_message').css('display', 'block'); $('#inv_message').attr('style', response.style); $('#inv_message').html(response.sale_msg); $('#inv_message').fadeOut(4000); // $('#sale_section').load(' #sale_section'); setTimeout(function () { location.reload(); }, 5000); }, error: function (error) { console.log(error); } }); }
JavaScript
function deleteInvoice() { var invId = $('input[name=cust_inv_id]').val(); $.ajax({ type: "POST", url: "invoice/test", data: {'invId': invId, '_token': $('input[name=_token]').val()}, dataType: "json", success: function (response) { console.log(response.msg); // $('#data_tbl_purchase_history').load(' #data_tbl_purchase_history'); }, error: function (error) { console.log(error); } }); }
function deleteInvoice() { var invId = $('input[name=cust_inv_id]').val(); $.ajax({ type: "POST", url: "invoice/test", data: {'invId': invId, '_token': $('input[name=_token]').val()}, dataType: "json", success: function (response) { console.log(response.msg); // $('#data_tbl_purchase_history').load(' #data_tbl_purchase_history'); }, error: function (error) { console.log(error); } }); }
JavaScript
function onSaveSale() { var totalToPay = $('input#total_to_pay').val(); var recieved_amount = 0; var recieveable_amount = 0; if ($('#paid_all').is(':checked')) { recieved_amount = $('span#sub_total').data('sub-total'); } else { recieved_amount = $('input#recieved').val(); recieveable_amount = $('input#payable').val(); } // var recieved_amount = $('input#recieved').val(); // var recieveable_amount = $('input#payable').val(); var pntType = $('#payment_type').val(); var transCode = $('#transCode').val(); var tax = $('input.tax_value').val(); $.ajax({ type: "POST", url: "/sale", dataType: "json", // data: {'_token': $('input[name=_token]').val()}, data: { 'custID': cid, 'payment': pntType, 'recieved': recieved_amount, 'recieveable': recieveable_amount, 'totalToPay': totalToPay, 'transCode': transCode, 'tax': tax, '_token': $('input[name=_token]').val() }, success: function (response) { $('#inv_message').css('display', 'block'); $('#inv_message').attr('style', response.style); $('#inv_message').html(response.sale_msg); $('#inv_message').fadeOut(4000); _invoiceID = response.invoice_id; onPrintInvoice(cid, _invoiceID); // $('#sale_section').load(' #sale_section'); // setTimeout(function () { location.reload(); }, 5000); }, error: function (error) { console.log(error); } }); }
function onSaveSale() { var totalToPay = $('input#total_to_pay').val(); var recieved_amount = 0; var recieveable_amount = 0; if ($('#paid_all').is(':checked')) { recieved_amount = $('span#sub_total').data('sub-total'); } else { recieved_amount = $('input#recieved').val(); recieveable_amount = $('input#payable').val(); } // var recieved_amount = $('input#recieved').val(); // var recieveable_amount = $('input#payable').val(); var pntType = $('#payment_type').val(); var transCode = $('#transCode').val(); var tax = $('input.tax_value').val(); $.ajax({ type: "POST", url: "/sale", dataType: "json", // data: {'_token': $('input[name=_token]').val()}, data: { 'custID': cid, 'payment': pntType, 'recieved': recieved_amount, 'recieveable': recieveable_amount, 'totalToPay': totalToPay, 'transCode': transCode, 'tax': tax, '_token': $('input[name=_token]').val() }, success: function (response) { $('#inv_message').css('display', 'block'); $('#inv_message').attr('style', response.style); $('#inv_message').html(response.sale_msg); $('#inv_message').fadeOut(4000); _invoiceID = response.invoice_id; onPrintInvoice(cid, _invoiceID); // $('#sale_section').load(' #sale_section'); // setTimeout(function () { location.reload(); }, 5000); }, error: function (error) { console.log(error); } }); }
JavaScript
function deleteInvoice() { var invId = $('input[name=cust_inv_id]').val(); $.ajax({ type: "POST", url: "invoice/test", data: {'invId': invId, '_token': $('input[name=_token]').val()}, dataType: "json", success: function (response) { console.log(response.msg); // $('#data_tbl_purchase_history').load(' #data_tbl_purchase_history'); }, error: function (error) { console.log(error); } }); }
function deleteInvoice() { var invId = $('input[name=cust_inv_id]').val(); $.ajax({ type: "POST", url: "invoice/test", data: {'invId': invId, '_token': $('input[name=_token]').val()}, dataType: "json", success: function (response) { console.log(response.msg); // $('#data_tbl_purchase_history').load(' #data_tbl_purchase_history'); }, error: function (error) { console.log(error); } }); }
JavaScript
function onUserCount() { var compId = $('input[name=input_comp_id]').val(); var userCount = $('select[name=company_user_count]').val(); $.ajax({ type: "POST", url: "company/userCount", data: {'compId': compId, 'userCount': userCount, '_token': $('input[name=_token]').val()}, dataType: "json", success: function (response) { $('#modal-edit-user-count').modal('hide'); $('#status-msg').css('display', 'block'); $('#status-msg').attr('style', response.style); $('#status-msg').html(response.count_msg); $('#data_comp_tbl').load(' #data_comp_tbl'); }, error: function (error) { console.log(error); } }); }
function onUserCount() { var compId = $('input[name=input_comp_id]').val(); var userCount = $('select[name=company_user_count]').val(); $.ajax({ type: "POST", url: "company/userCount", data: {'compId': compId, 'userCount': userCount, '_token': $('input[name=_token]').val()}, dataType: "json", success: function (response) { $('#modal-edit-user-count').modal('hide'); $('#status-msg').css('display', 'block'); $('#status-msg').attr('style', response.style); $('#status-msg').html(response.count_msg); $('#data_comp_tbl').load(' #data_comp_tbl'); }, error: function (error) { console.log(error); } }); }
JavaScript
function moduleLoaded(libModule) { if (dso.global) { mergeLibSymbols(libModule); } dso.module = libModule; }
function moduleLoaded(libModule) { if (dso.global) { mergeLibSymbols(libModule); } dso.module = libModule; }
JavaScript
function watchForNotifications(ws, connectionState) { client.watch(tube).onSuccess(function(data) { client.reserve().onSuccess(function(job) { console.log('received job: ' + job.data); if (connectionState.connected) { process.nextTick(function() { watchForNotifications(ws, connectionState); }); processNotification(ws, job, connectionState, function() { client.deleteJob(job.id).onSuccess(function(del_msg) { }); }); } }); }); }
function watchForNotifications(ws, connectionState) { client.watch(tube).onSuccess(function(data) { client.reserve().onSuccess(function(job) { console.log('received job: ' + job.data); if (connectionState.connected) { process.nextTick(function() { watchForNotifications(ws, connectionState); }); processNotification(ws, job, connectionState, function() { client.deleteJob(job.id).onSuccess(function(del_msg) { }); }); } }); }); }
JavaScript
function processNotification(ws, job, connectionState, callback) { var components = job.data.split("|"); var message = { type: components[0] === 'robot_registered' ? 'register' : 'unregister', data: { name: components[1] } }; var json = JSON.stringify(message); ws.send(json, function(err) { if (err) { console.log(err); connectionState.connected = false; } }); callback(); }
function processNotification(ws, job, connectionState, callback) { var components = job.data.split("|"); var message = { type: components[0] === 'robot_registered' ? 'register' : 'unregister', data: { name: components[1] } }; var json = JSON.stringify(message); ws.send(json, function(err) { if (err) { console.log(err); connectionState.connected = false; } }); callback(); }
JavaScript
function groupSegsByDay(segs) { var segsByDay = []; // sparse array var i; var seg; for (i = 0; i < segs.length; i++) { seg = segs[i]; (segsByDay[seg.dayIndex] || (segsByDay[seg.dayIndex] = [])) .push(seg); } return segsByDay; }
function groupSegsByDay(segs) { var segsByDay = []; // sparse array var i; var seg; for (i = 0; i < segs.length; i++) { seg = segs[i]; (segsByDay[seg.dayIndex] || (segsByDay[seg.dayIndex] = [])) .push(seg); } return segsByDay; }
JavaScript
function refresh() { var that = this; var current = that._current || {}; var theme = _getTheme(current.name || current); that._themeName = theme.name; that._defaultPalette = theme.defaultPalette; that._font = _extend({}, theme.font, current.font); that._themeSection && _each(that._themeSection.split('.'), function (_, path) { theme = _extend(true, {}, theme[path]); }); that._theme = _extend(true, {}, theme, (0, _type.isString)(current) ? {} : current); that._initializeTheme(); if ((0, _utils.parseScalar)(that._rtl, that._theme.rtlEnabled)) { _extend(true, that._theme, that._theme._rtl); } that._callback(); return that; }
function refresh() { var that = this; var current = that._current || {}; var theme = _getTheme(current.name || current); that._themeName = theme.name; that._defaultPalette = theme.defaultPalette; that._font = _extend({}, theme.font, current.font); that._themeSection && _each(that._themeSection.split('.'), function (_, path) { theme = _extend(true, {}, theme[path]); }); that._theme = _extend(true, {}, theme, (0, _type.isString)(current) ? {} : current); that._initializeTheme(); if ((0, _utils.parseScalar)(that._rtl, that._theme.rtlEnabled)) { _extend(true, that._theme, that._theme._rtl); } that._callback(); return that; }
JavaScript
function checkForTilde(destinationPath) { /** If the first part of the path contains a ~, we'll assume the user intends for their project to install relative to their home directory on a Unix machine and throw an error. */ if (destinationPath.split('/')[0].includes('~')) { console.log(colors.error(` Uh-oh, check your desired project path! It looks like you made a reference to your home directory: ~/ Due to cross platform compatibility with non-Unix systems, that causes some problems. Try again using absolute paths like /Users/<your username>/path/to/project `)); throw new Error(`Bad path, we're sorry...`); } /** If any other part of the path contains a ~, we'll just give them a helpful warning. */ if (destinationPath.includes('~')) { console.log(colors.warn(` Be careful, it looks like your project path contains a "~". If you remove this directory, be very careful about running "rm -rf \\~" You could accidentally destroy your home directory! `)); } }
function checkForTilde(destinationPath) { /** If the first part of the path contains a ~, we'll assume the user intends for their project to install relative to their home directory on a Unix machine and throw an error. */ if (destinationPath.split('/')[0].includes('~')) { console.log(colors.error(` Uh-oh, check your desired project path! It looks like you made a reference to your home directory: ~/ Due to cross platform compatibility with non-Unix systems, that causes some problems. Try again using absolute paths like /Users/<your username>/path/to/project `)); throw new Error(`Bad path, we're sorry...`); } /** If any other part of the path contains a ~, we'll just give them a helpful warning. */ if (destinationPath.includes('~')) { console.log(colors.warn(` Be careful, it looks like your project path contains a "~". If you remove this directory, be very careful about running "rm -rf \\~" You could accidentally destroy your home directory! `)); } }
JavaScript
function createApplication(options) { const {path: destinationPath, runtime} = options; return isDirectoryEmpty(destinationPath) .then(isEmpty => { if (isEmpty) { return true; } else { return shouldOverwrite(destinationPath); } }) .then(proceed => { if (proceed) { return createFiles(options).then(() => { projectCreated(destinationPath); }); } }); }
function createApplication(options) { const {path: destinationPath, runtime} = options; return isDirectoryEmpty(destinationPath) .then(isEmpty => { if (isEmpty) { return true; } else { return shouldOverwrite(destinationPath); } }) .then(proceed => { if (proceed) { return createFiles(options).then(() => { projectCreated(destinationPath); }); } }); }
JavaScript
function projectCreated(destinationPath) { const successMessage = `To install the project dependencies: cd ${destinationPath} && npm install To upload to your device: Development: npm run dev Production: npm run deploy`; console.log(colors.help(successMessage)); }
function projectCreated(destinationPath) { const successMessage = `To install the project dependencies: cd ${destinationPath} && npm install To upload to your device: Development: npm run dev Production: npm run deploy`; console.log(colors.help(successMessage)); }
JavaScript
function makeDirectory(directory) { return new Promise((resolve, reject) => { mkdirp(directory, err => { if (err) reject(err); else resolve(); }); }); }
function makeDirectory(directory) { return new Promise((resolve, reject) => { mkdirp(directory, err => { if (err) reject(err); else resolve(); }); }); }
JavaScript
function createFiles(options) { const {port, baud_rate, path: destinationPath, runtime} = options; const app_name = path.basename(path.resolve(destinationPath)); const templatesPath = path.join(__dirname, "..", "templates"); const scriptPath = path.join(templatesPath, runtime, "scripts"); checkForTilde(destinationPath); return makeDirectory(path.join(destinationPath, 'scripts')) .then(() => makeDirectory(path.join(destinationPath, 'build'))) .then(() => { /* Copy templates */ fs.readdir(scriptPath, (err, files) => { if (err) throw err; files.forEach(file => copy(path.join(scriptPath, file), path.join(destinationPath, "scripts", file))); }); /* Create package.json for project */ const pkg = createPackageJSON(app_name, runtime); write(path.join(destinationPath, "package.json"), JSON.stringify(pkg, null, 2)); copy(path.join(templatesPath, 'main.js'), path.join(destinationPath, 'main.js')); copy(path.join(templatesPath, 'dot-gitignore'), path.join(destinationPath, '.gitignore')); copy(path.join(templatesPath, 'dot-gitattributes'), path.join(destinationPath, '.gitattributes')); /* Create devices.json and finish */ const deviceJSONOptions = { port, baud_rate, runtime, destinationPath }; return createDevicesJSON(deviceJSONOptions); }); }
function createFiles(options) { const {port, baud_rate, path: destinationPath, runtime} = options; const app_name = path.basename(path.resolve(destinationPath)); const templatesPath = path.join(__dirname, "..", "templates"); const scriptPath = path.join(templatesPath, runtime, "scripts"); checkForTilde(destinationPath); return makeDirectory(path.join(destinationPath, 'scripts')) .then(() => makeDirectory(path.join(destinationPath, 'build'))) .then(() => { /* Copy templates */ fs.readdir(scriptPath, (err, files) => { if (err) throw err; files.forEach(file => copy(path.join(scriptPath, file), path.join(destinationPath, "scripts", file))); }); /* Create package.json for project */ const pkg = createPackageJSON(app_name, runtime); write(path.join(destinationPath, "package.json"), JSON.stringify(pkg, null, 2)); copy(path.join(templatesPath, 'main.js'), path.join(destinationPath, 'main.js')); copy(path.join(templatesPath, 'dot-gitignore'), path.join(destinationPath, '.gitignore')); copy(path.join(templatesPath, 'dot-gitattributes'), path.join(destinationPath, '.gitattributes')); /* Create devices.json and finish */ const deviceJSONOptions = { port, baud_rate, runtime, destinationPath }; return createDevicesJSON(deviceJSONOptions); }); }
JavaScript
function createPackageJSON(app_name, runtime) { const strategy = `thingssdk-${runtime}-strategy`; const strategyVersions = { espruino: "~1.0.3" }; const pkg = { name: app_name, version: '0.0.0', private: true, main: 'main.js', scripts: { dev: "node ./scripts/upload development && npm run repl", deploy: "node ./scripts/upload production", repl: "node ./scripts/repl", postinstall: "rimraf node_modules/bluetooth-hci-socket" }, devDependencies: { "thingssdk-deployer": "~1.0.1", [strategy]: strategyVersions[runtime] } }; return pkg; }
function createPackageJSON(app_name, runtime) { const strategy = `thingssdk-${runtime}-strategy`; const strategyVersions = { espruino: "~1.0.3" }; const pkg = { name: app_name, version: '0.0.0', private: true, main: 'main.js', scripts: { dev: "node ./scripts/upload development && npm run repl", deploy: "node ./scripts/upload production", repl: "node ./scripts/repl", postinstall: "rimraf node_modules/bluetooth-hci-socket" }, devDependencies: { "thingssdk-deployer": "~1.0.1", [strategy]: strategyVersions[runtime] } }; return pkg; }
JavaScript
function Syscoin (SignerIn, blockbookURL, network) { this.blockbookURL = blockbookURL if (SignerIn) { this.Signer = SignerIn this.Signer.blockbookURL = blockbookURL this.network = network || this.Signer.Signer.network } else { this.Signer = null this.network = network || utils.syscoinNetworks.mainnet } }
function Syscoin (SignerIn, blockbookURL, network) { this.blockbookURL = blockbookURL if (SignerIn) { this.Signer = SignerIn this.Signer.blockbookURL = blockbookURL this.network = network || this.Signer.Signer.network } else { this.Signer = null this.network = network || utils.syscoinNetworks.mainnet } }
JavaScript
function calcTopHeight() { // geting all the elements with the class of .card-top-area cardTopArea = $('.card-top-area'); // getting all the elements with the class of .card-top-area-wrapper cardTopAreaWrapper = $('.card-top-area-wrapper'); // making array empty each time while calling this function heightsArr = []; // looping through cardTopArea array to get the height of each element $.each(cardTopArea, function (indexInArray, eachElement) { heightsArr.push(eachElement.offsetHeight); }); // getting max height from heightsArr maxHeight = heightsArr.reduce(function(a, b) { return Math.max(a, b); }); // applying max height to each element so that we could have top area properly aligned of each card $.each(cardTopAreaWrapper, function (indexInArray, eachElement) { eachElement.style.height = maxHeight + 'px'; }); }
function calcTopHeight() { // geting all the elements with the class of .card-top-area cardTopArea = $('.card-top-area'); // getting all the elements with the class of .card-top-area-wrapper cardTopAreaWrapper = $('.card-top-area-wrapper'); // making array empty each time while calling this function heightsArr = []; // looping through cardTopArea array to get the height of each element $.each(cardTopArea, function (indexInArray, eachElement) { heightsArr.push(eachElement.offsetHeight); }); // getting max height from heightsArr maxHeight = heightsArr.reduce(function(a, b) { return Math.max(a, b); }); // applying max height to each element so that we could have top area properly aligned of each card $.each(cardTopAreaWrapper, function (indexInArray, eachElement) { eachElement.style.height = maxHeight + 'px'; }); }
JavaScript
function min(values) { if (values.length === 0) { return undefined; } return values.reduce((smallest, candidate) => { return ( smallest < candidate ? smallest : candidate ); }); }
function min(values) { if (values.length === 0) { return undefined; } return values.reduce((smallest, candidate) => { return ( smallest < candidate ? smallest : candidate ); }); }
JavaScript
function max(values) { if (values.length === 0) { return undefined; } return values.reduce((biggest, candidate) => { return ( biggest > candidate ? biggest : candidate ); }); }
function max(values) { if (values.length === 0) { return undefined; } return values.reduce((biggest, candidate) => { return ( biggest > candidate ? biggest : candidate ); }); }
JavaScript
function ranges(bars, groups) { // The width of a bar depends on the max minus the min bar overall const minBar = min(bars), maxBar = max(bars), width = ( maxBar - minBar ) / groups; // Intializes return and loop values let ranges = [], start = minBar; for(let i = 0; i < groups; i++) { // Ceils each number ranges.push({ min: ceil(start), max: start = ceil(( start + width )) }); } return ranges; }
function ranges(bars, groups) { // The width of a bar depends on the max minus the min bar overall const minBar = min(bars), maxBar = max(bars), width = ( maxBar - minBar ) / groups; // Intializes return and loop values let ranges = [], start = minBar; for(let i = 0; i < groups; i++) { // Ceils each number ranges.push({ min: ceil(start), max: start = ceil(( start + width )) }); } return ranges; }
JavaScript
function within(ranges, volume) { // Helper fn taking an x and // checking if it's in a given range // of min and max. const between = function(x, min, max) { return x >= min && x <= max; }; let index = 0, matched; // Optimized for of loop for early exit for (let i = 0, len = ranges.length; i < len; i++) { let range = ranges[i]; if (between(volume, range.min, range.max)) { matched = index; break; } ++index; } return matched; }
function within(ranges, volume) { // Helper fn taking an x and // checking if it's in a given range // of min and max. const between = function(x, min, max) { return x >= min && x <= max; }; let index = 0, matched; // Optimized for of loop for early exit for (let i = 0, len = ranges.length; i < len; i++) { let range = ranges[i]; if (between(volume, range.min, range.max)) { matched = index; break; } ++index; } return matched; }
JavaScript
function findConversation(partiOne, partiTwo, done) { console.log('findConversation'); Conversation.findOne({ $and: [ { participants: partiOne }, { participants: partiTwo } ] }).exec(function (err, conversation) { if (err) return done(err) if (conversation) return done(false, conversation) return done(false) }); }
function findConversation(partiOne, partiTwo, done) { console.log('findConversation'); Conversation.findOne({ $and: [ { participants: partiOne }, { participants: partiTwo } ] }).exec(function (err, conversation) { if (err) return done(err) if (conversation) return done(false, conversation) return done(false) }); }
JavaScript
function createConversation(participants, done) { console.log('creating new conversation' + participants); var conversation = new Conversation({participants: participants}); conversation.save(function (err, newConversation) { if (err) return done(err) //err = true return done(false, newConversation) // err = false }); }
function createConversation(participants, done) { console.log('creating new conversation' + participants); var conversation = new Conversation({participants: participants}); conversation.save(function (err, newConversation) { if (err) return done(err) //err = true return done(false, newConversation) // err = false }); }
JavaScript
function findMessages(conversationID, done) { Message.find({conversationId: conversationID}).select('createdAt body author').sort('createdAt').populate({path: 'author', select: 'firstName lastName'}).exec(function (err, messages) { if (err) return done(err); return done(false, messages) }); }
function findMessages(conversationID, done) { Message.find({conversationId: conversationID}).select('createdAt body author').sort('createdAt').populate({path: 'author', select: 'firstName lastName'}).exec(function (err, messages) { if (err) return done(err); return done(false, messages) }); }
JavaScript
function createMessage(conversation, msg, user, done) { console.log('creating new message'); var message = new Message({conversationId: conversation, body: msg, author: user}); message.save(function (err, newMessage) { if (err) return done(err) // err = true return done(false, newMessage) // err = false }); }
function createMessage(conversation, msg, user, done) { console.log('creating new message'); var message = new Message({conversationId: conversation, body: msg, author: user}); message.save(function (err, newMessage) { if (err) return done(err) // err = true return done(false, newMessage) // err = false }); }
JavaScript
function CustomAvatarCollection(props) { const {persons} = props; return ( <> {Object.values(persons).map((person, i) => { return ( <div className={classes.MiniPersonProfile} key={person._id || i}> <Link to={{ pathname: `/person/${person._id}`, state: { person: person, }}} style={{textDecoration: 'none'}} > <Avatar alt={`${person.first_name} ${person.last_name}`} {...!person.image && stringAvatar(`${person.first_name} ${person.last_name || ''}`)} src={getImageSrcFromBuffer(person.image)} sx={{ 'width': '30px', 'height': '30px', }} /> </Link> <p data-testid="name-element">{person.first_name}</p> </div>); })} </> ); }
function CustomAvatarCollection(props) { const {persons} = props; return ( <> {Object.values(persons).map((person, i) => { return ( <div className={classes.MiniPersonProfile} key={person._id || i}> <Link to={{ pathname: `/person/${person._id}`, state: { person: person, }}} style={{textDecoration: 'none'}} > <Avatar alt={`${person.first_name} ${person.last_name}`} {...!person.image && stringAvatar(`${person.first_name} ${person.last_name || ''}`)} src={getImageSrcFromBuffer(person.image)} sx={{ 'width': '30px', 'height': '30px', }} /> </Link> <p data-testid="name-element">{person.first_name}</p> </div>); })} </> ); }
JavaScript
function EncounterDetailsModal(props) { const {open, onClose, onDelete, className, encounter} = props; return ( <CustomModal open={open} onClose={onClose} hasCancel={false} hasConfirm={false} className={className} onDelete={onDelete} > <div className={classes.ContentContainer}> <div className={classes.Content}> <h1 className={classes.EncounterTitle} data-testid={'title-element'}> {encounter.title} </h1> <div className={classes.SubtitleContainer}> <h3 className={classes.EncounterSubtitle}>You encountered: </h3> <CustomAvatarCollection persons={encounter.persons}/> </div> <div className={classes.EncounterProperty} data-testid="date-met-element" > {'Date we met: '} {encounter.date ? getLongDateStringWithSlashes(encounter.date) : <UnknownDetail/>} </div> <div className={classes.EncounterProperty} data-testid="location-element" > {'Location: '} {encounter.location ? encounter.location : <UnknownDetail/>} </div> <h2>Details:</h2> <p className={classes.EncounterDetails} data-testid="details-element"> {encounter.description} </p> </div> <div> <CustomButton className={classes.DeleteButton} btnText={'Delete'} onClick={onDelete}/> </div> </div> </CustomModal> ); }
function EncounterDetailsModal(props) { const {open, onClose, onDelete, className, encounter} = props; return ( <CustomModal open={open} onClose={onClose} hasCancel={false} hasConfirm={false} className={className} onDelete={onDelete} > <div className={classes.ContentContainer}> <div className={classes.Content}> <h1 className={classes.EncounterTitle} data-testid={'title-element'}> {encounter.title} </h1> <div className={classes.SubtitleContainer}> <h3 className={classes.EncounterSubtitle}>You encountered: </h3> <CustomAvatarCollection persons={encounter.persons}/> </div> <div className={classes.EncounterProperty} data-testid="date-met-element" > {'Date we met: '} {encounter.date ? getLongDateStringWithSlashes(encounter.date) : <UnknownDetail/>} </div> <div className={classes.EncounterProperty} data-testid="location-element" > {'Location: '} {encounter.location ? encounter.location : <UnknownDetail/>} </div> <h2>Details:</h2> <p className={classes.EncounterDetails} data-testid="details-element"> {encounter.description} </p> </div> <div> <CustomButton className={classes.DeleteButton} btnText={'Delete'} onClick={onDelete}/> </div> </div> </CustomModal> ); }
JavaScript
function fillSidebarWithNodes (nodes, filter) { function scope (items) { var filtered = nodes[items] var fullList = $('#full-list') fullList.replaceWith(sidebarItemsTemplate({'nodes': filtered, 'group': ''})) } const moduleType = helpers.getModuleType() filter = filter || moduleType scope(filter) setupSelected(['#', filter, '-list'].join('')) $('#full-list li a').on('click', e => { var $target = $(e.target) if ($target.hasClass('expand')) { e.preventDefault() $(e.target).closest('li').toggleClass('open') } else { $('#full-list .clicked li.active').removeClass('active') $(e.target).closest('li').addClass('active') } }) }
function fillSidebarWithNodes (nodes, filter) { function scope (items) { var filtered = nodes[items] var fullList = $('#full-list') fullList.replaceWith(sidebarItemsTemplate({'nodes': filtered, 'group': ''})) } const moduleType = helpers.getModuleType() filter = filter || moduleType scope(filter) setupSelected(['#', filter, '-list'].join('')) $('#full-list li a').on('click', e => { var $target = $(e.target) if ($target.hasClass('expand')) { e.preventDefault() $(e.target).closest('li').toggleClass('open') } else { $('#full-list .clicked li.active').removeClass('active') $(e.target).closest('li').addClass('active') } }) }
JavaScript
initializeState() { ArcLayer.prototype.initializeState.call(this); const attributeManager = this.getAttributeManager(); /* eslint-disable max-len */ attributeManager.addInstanced({ randomValue: { size: 1, transition: true, accessor: 'getRandomValue', defaultValue: 1.0 } }); }
initializeState() { ArcLayer.prototype.initializeState.call(this); const attributeManager = this.getAttributeManager(); /* eslint-disable max-len */ attributeManager.addInstanced({ randomValue: { size: 1, transition: true, accessor: 'getRandomValue', defaultValue: 1.0 } }); }
JavaScript
renderLayers() { const {id, data, strokeWidth = 5} = this.props; console.log(data); return [ new TextLayer({ id: `${id}-text`, data: data, getPosition: d => d.source.coordinates, getText: d => d.label, getSize: 32, getAngle: 0, getTextAnchor: 'middle', getAlignmentBaseline: 'center' }), new MyArcLayer({ id: `${id}-arc`, data: data, getSourcePosition: d => d.source.coordinates, getTargetPosition: d => d.target.coordinates, getSourceColor: d => [16, 52, 166], getTargetColor: d => [0, 0, 0], getWidth: strokeWidth, getRandomValue: d => Math.random() })/*, new ArcLayer({ id: `${id}-arc2`, data: data, getSourcePosition: d => d.source.coordinates, getTargetPosition: d => d.target.coordinates, getSourceColor: d => [16, 52, 166], getTargetColor: d => [0, 0, 0], getWidth: strokeWidth, getRandomValue: d => Math.random() })*/ ] }
renderLayers() { const {id, data, strokeWidth = 5} = this.props; console.log(data); return [ new TextLayer({ id: `${id}-text`, data: data, getPosition: d => d.source.coordinates, getText: d => d.label, getSize: 32, getAngle: 0, getTextAnchor: 'middle', getAlignmentBaseline: 'center' }), new MyArcLayer({ id: `${id}-arc`, data: data, getSourcePosition: d => d.source.coordinates, getTargetPosition: d => d.target.coordinates, getSourceColor: d => [16, 52, 166], getTargetColor: d => [0, 0, 0], getWidth: strokeWidth, getRandomValue: d => Math.random() })/*, new ArcLayer({ id: `${id}-arc2`, data: data, getSourcePosition: d => d.source.coordinates, getTargetPosition: d => d.target.coordinates, getSourceColor: d => [16, 52, 166], getTargetColor: d => [0, 0, 0], getWidth: strokeWidth, getRandomValue: d => Math.random() })*/ ] }
JavaScript
_renderLayers() { return [ new ArcTextLayer({ id: 'ArcTextLayer', strokeWidth: 5, data: this.state.arcs }) ]; }
_renderLayers() { return [ new ArcTextLayer({ id: 'ArcTextLayer', strokeWidth: 5, data: this.state.arcs }) ]; }
JavaScript
function normalizePort(val) { const port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; }
function normalizePort(val) { const port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; }
JavaScript
function onError(error) { if (error.syscall !== 'listen') { throw error; } const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } }
function onError(error) { if (error.syscall !== 'listen') { throw error; } const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } }
JavaScript
function onListening() { const addr = server.address(); const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind); }
function onListening() { const addr = server.address(); const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind); }
JavaScript
function errorHandler(err, req, res, next) { debug(err.toString()); // error response res.status(err.status || 500); res.json({ error: `${err.expose ? err.message : statusCodes[err.status || 500]}` }); }
function errorHandler(err, req, res, next) { debug(err.toString()); // error response res.status(err.status || 500); res.json({ error: `${err.expose ? err.message : statusCodes[err.status || 500]}` }); }
JavaScript
function observeIntersection(observerCallback) { // Send request to received records. nonSensitiveDataPostMessage('send-intersections'); return listenParent('intersection', data => { observerCallback(data.changes); }); }
function observeIntersection(observerCallback) { // Send request to received records. nonSensitiveDataPostMessage('send-intersections'); return listenParent('intersection', data => { observerCallback(data.changes); }); }
JavaScript
function onResizeSuccess(observerCallback) { return listenParent('embed-resize-changed', data => { observerCallback(data.requestedHeight); }); }
function onResizeSuccess(observerCallback) { return listenParent('embed-resize-changed', data => { observerCallback(data.requestedHeight); }); }
JavaScript
function onResizeDenied(observerCallback) { return listenParent('embed-resize-denied', data => { observerCallback(data.requestedHeight); }); }
function onResizeDenied(observerCallback) { return listenParent('embed-resize-denied', data => { observerCallback(data.requestedHeight); }); }
JavaScript
function reportRenderedEntityIdentifier(entityId) { assert(typeof entityId == 'string', 'entityId should be a string %s', entityId); nonSensitiveDataPostMessage('entity-id', { id: entityId }); }
function reportRenderedEntityIdentifier(entityId) { assert(typeof entityId == 'string', 'entityId should be a string %s', entityId); nonSensitiveDataPostMessage('entity-id', { id: entityId }); }
JavaScript
function validateParentOrigin(window, parentLocation) { const ancestors = window.location.ancestorOrigins; // Currently only webkit and blink based browsers support // ancestorOrigins. In that case we proceed but mark the origin // as non-validated. if (!ancestors || !ancestors.length) { parentLocation.originValidated = false; return; } assert(ancestors[0] == parentLocation.origin, 'Parent origin mismatch: %s, %s', ancestors[0], parentLocation.origin); parentLocation.originValidated = true; }
function validateParentOrigin(window, parentLocation) { const ancestors = window.location.ancestorOrigins; // Currently only webkit and blink based browsers support // ancestorOrigins. In that case we proceed but mark the origin // as non-validated. if (!ancestors || !ancestors.length) { parentLocation.originValidated = false; return; } assert(ancestors[0] == parentLocation.origin, 'Parent origin mismatch: %s, %s', ancestors[0], parentLocation.origin); parentLocation.originValidated = true; }
JavaScript
addListener(config, listener) { const eventType = config['on']; if (eventType === AnalyticsEventType.VISIBLE) { if (this.viewer_.isVisible()) { listener(new AnalyticsEvent(AnalyticsEventType.VISIBLE)); } else { this.viewer_.onVisibilityChanged(() => { if (this.viewer_.isVisible()) { listener(new AnalyticsEvent(AnalyticsEventType.VISIBLE)); } }); } } else if (eventType === AnalyticsEventType.CLICK) { if (!config['selector']) { console./*OK*/error(this.TAG_, 'Missing required selector on click trigger'); return; } this.ensureClickListener_(); this.clickObservable_.add( this.createSelectiveListener_(listener, config['selector'])); } else if (eventType === AnalyticsEventType.SCROLL) { if (!config['scrollSpec']) { console./*OK*/error(this.TAG_, 'Missing scrollSpec on scroll trigger.'); return; } this.registerScrollTrigger_(config['scrollSpec'], listener); // Trigger an event to fire events that might have already happened. const size = this.viewport_.getSize(); this.onScroll_({ top: this.viewport_.getScrollTop(), left: this.viewport_.getScrollLeft(), width: size.width, height: size.height }); } else if (eventType === AnalyticsEventType.TIMER) { if (this.isTimerSpecValid_(config['timerSpec'])) { this.createTimerListener_(listener, config['timerSpec']); } } else { let observers = this.observers_[eventType]; if (!observers) { observers = new Observable(); this.observers_[eventType] = observers; } observers.add(listener); } }
addListener(config, listener) { const eventType = config['on']; if (eventType === AnalyticsEventType.VISIBLE) { if (this.viewer_.isVisible()) { listener(new AnalyticsEvent(AnalyticsEventType.VISIBLE)); } else { this.viewer_.onVisibilityChanged(() => { if (this.viewer_.isVisible()) { listener(new AnalyticsEvent(AnalyticsEventType.VISIBLE)); } }); } } else if (eventType === AnalyticsEventType.CLICK) { if (!config['selector']) { console./*OK*/error(this.TAG_, 'Missing required selector on click trigger'); return; } this.ensureClickListener_(); this.clickObservable_.add( this.createSelectiveListener_(listener, config['selector'])); } else if (eventType === AnalyticsEventType.SCROLL) { if (!config['scrollSpec']) { console./*OK*/error(this.TAG_, 'Missing scrollSpec on scroll trigger.'); return; } this.registerScrollTrigger_(config['scrollSpec'], listener); // Trigger an event to fire events that might have already happened. const size = this.viewport_.getSize(); this.onScroll_({ top: this.viewport_.getScrollTop(), left: this.viewport_.getScrollLeft(), width: size.width, height: size.height }); } else if (eventType === AnalyticsEventType.TIMER) { if (this.isTimerSpecValid_(config['timerSpec'])) { this.createTimerListener_(listener, config['timerSpec']); } } else { let observers = this.observers_[eventType]; if (!observers) { observers = new Observable(); this.observers_[eventType] = observers; } observers.add(listener); } }
JavaScript
triggerEvent(eventType) { const observers = this.observers_[eventType]; if (observers) { observers.fire(new AnalyticsEvent(eventType)); } }
triggerEvent(eventType) { const observers = this.observers_[eventType]; if (observers) { observers.fire(new AnalyticsEvent(eventType)); } }
JavaScript
registerScrollTrigger_(config, listener) { if (!Array.isArray(config['verticalBoundaries']) && !Array.isArray(config['horizontalBoundaries'])) { console./*OK*/error(this.TAG_, "Boundaries are required for the scroll " + "trigger to work."); return; } // Ensure that the scroll events are being listened to. if (!this.scrollHandlerRegistered_) { this.scrollHandlerRegistered_ = true; this.viewport_.onChanged(this.onScroll_.bind(this)); } /** * @param {!Object.<number, boolean>} bounds. * @param {number} scrollPos Number representing the current scroll * position. */ const triggerScrollEvents = function(bounds, scrollPos) { if (!scrollPos) { return; } // Goes through each of the boundaries and fires an event if it has not // been fired so far and it should be. for (const b in bounds) { if (!bounds.hasOwnProperty(b) || b > scrollPos || bounds[b]) { continue; } bounds[b] = true; listener(new AnalyticsEvent(AnalyticsEventType.SCROLL)); } }; const boundsV = this.normalizeBoundaries_(config['verticalBoundaries']); const boundsH = this.normalizeBoundaries_(config['horizontalBoundaries']); this.scrollObservable_.add(e => { // Calculates percentage scrolled by adding screen height/width to // top/left and dividing by the total scroll height/width. triggerScrollEvents(boundsV, (e.top + e.height) * 100 / this.viewport_.getScrollHeight()); triggerScrollEvents(boundsH, (e.left + e.width) * 100 / this.viewport_.getScrollWidth()); }); }
registerScrollTrigger_(config, listener) { if (!Array.isArray(config['verticalBoundaries']) && !Array.isArray(config['horizontalBoundaries'])) { console./*OK*/error(this.TAG_, "Boundaries are required for the scroll " + "trigger to work."); return; } // Ensure that the scroll events are being listened to. if (!this.scrollHandlerRegistered_) { this.scrollHandlerRegistered_ = true; this.viewport_.onChanged(this.onScroll_.bind(this)); } /** * @param {!Object.<number, boolean>} bounds. * @param {number} scrollPos Number representing the current scroll * position. */ const triggerScrollEvents = function(bounds, scrollPos) { if (!scrollPos) { return; } // Goes through each of the boundaries and fires an event if it has not // been fired so far and it should be. for (const b in bounds) { if (!bounds.hasOwnProperty(b) || b > scrollPos || bounds[b]) { continue; } bounds[b] = true; listener(new AnalyticsEvent(AnalyticsEventType.SCROLL)); } }; const boundsV = this.normalizeBoundaries_(config['verticalBoundaries']); const boundsH = this.normalizeBoundaries_(config['horizontalBoundaries']); this.scrollObservable_.add(e => { // Calculates percentage scrolled by adding screen height/width to // top/left and dividing by the total scroll height/width. triggerScrollEvents(boundsV, (e.top + e.height) * 100 / this.viewport_.getScrollHeight()); triggerScrollEvents(boundsH, (e.left + e.width) * 100 / this.viewport_.getScrollWidth()); }); }
JavaScript
normalizeBoundaries_(bounds) { const result = {}; if (!bounds || !Array.isArray(bounds)) { return result; } for (let b = 0; b < bounds.length; b++) { let bound = bounds[b]; if (typeof bound !== 'number' || !isFinite(bound)) { console./*OK*/error(this.TAG_, 'Scroll trigger boundaries must be finite.'); return result; } bound = Math.min(Math.round(bound / SCROLL_PRECISION_PERCENT) * SCROLL_PRECISION_PERCENT, 100); result[bound] = false; } return result; }
normalizeBoundaries_(bounds) { const result = {}; if (!bounds || !Array.isArray(bounds)) { return result; } for (let b = 0; b < bounds.length; b++) { let bound = bounds[b]; if (typeof bound !== 'number' || !isFinite(bound)) { console./*OK*/error(this.TAG_, 'Scroll trigger boundaries must be finite.'); return result; } bound = Math.min(Math.round(bound / SCROLL_PRECISION_PERCENT) * SCROLL_PRECISION_PERCENT, 100); result[bound] = false; } return result; }
JavaScript
preconnectCallback(onLayout) { // We always need the bootstrap. prefetchBootstrap(this.getWin()); const type = this.element.getAttribute('type'); const prefetch = adPrefetch[type]; const preconnect = adPreconnect[type]; if (typeof prefetch == 'string') { this.preconnect.prefetch(prefetch); } else if (prefetch) { prefetch.forEach(p => { this.preconnect.prefetch(p); }); } if (typeof preconnect == 'string') { this.preconnect.url(preconnect, onLayout); } else if (preconnect) { preconnect.forEach(p => { this.preconnect.url(p, onLayout); }); } // If fully qualified src for ad script is specified we preconnect to it. const src = this.element.getAttribute('src'); if (src) { // We only preconnect to the src because we cannot know whether the URL // will have caching headers set. this.preconnect.url(src); } }
preconnectCallback(onLayout) { // We always need the bootstrap. prefetchBootstrap(this.getWin()); const type = this.element.getAttribute('type'); const prefetch = adPrefetch[type]; const preconnect = adPreconnect[type]; if (typeof prefetch == 'string') { this.preconnect.prefetch(prefetch); } else if (prefetch) { prefetch.forEach(p => { this.preconnect.prefetch(p); }); } if (typeof preconnect == 'string') { this.preconnect.url(preconnect, onLayout); } else if (preconnect) { preconnect.forEach(p => { this.preconnect.url(p, onLayout); }); } // If fully qualified src for ad script is specified we preconnect to it. const src = this.element.getAttribute('src'); if (src) { // We only preconnect to the src because we cannot know whether the URL // will have caching headers set. this.preconnect.url(src); } }
JavaScript
maybeUnpause_() { if (this.paused_) { this.paused_ = false; toggle(this.iframe_, true); } }
maybeUnpause_() { if (this.paused_) { this.paused_ = false; toggle(this.iframe_, true); } }
JavaScript
updateHeight_(newHeight) { this.attemptChangeHeight(newHeight, () => { const targetOrigin = this.iframe_.src ? parseUrl(this.iframe_.src).origin : '*'; postMessage( this.iframe_, 'embed-size-changed', {requestedHeight: newHeight}, targetOrigin, /* opt_is3P */ true); }); }
updateHeight_(newHeight) { this.attemptChangeHeight(newHeight, () => { const targetOrigin = this.iframe_.src ? parseUrl(this.iframe_.src).origin : '*'; postMessage( this.iframe_, 'embed-size-changed', {requestedHeight: newHeight}, targetOrigin, /* opt_is3P */ true); }); }