language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function processDir(dirPath, logger=console) { let items = readdirSync(dirPath); let packageJson = undefined; for(let item of items) { item = join(dirPath, item); let stat = statSync(item); if(stat.isDirectory()) { try { processDir(item, logger); } catch(err) { logger.warn(err.message); } } else if(basename(item) === 'package.json'){ packageJson = JSON.parse(readFileSync(item,'utf-8')); } } if(packageJson) { processPackageJson(packageJson, items, dirPath, logger); } }
function processDir(dirPath, logger=console) { let items = readdirSync(dirPath); let packageJson = undefined; for(let item of items) { item = join(dirPath, item); let stat = statSync(item); if(stat.isDirectory()) { try { processDir(item, logger); } catch(err) { logger.warn(err.message); } } else if(basename(item) === 'package.json'){ packageJson = JSON.parse(readFileSync(item,'utf-8')); } } if(packageJson) { processPackageJson(packageJson, items, dirPath, logger); } }
JavaScript
function useRaf(callback, isActive) { const savedCallback = react.useRef(); // Remember the latest function. react.useEffect(() => { savedCallback.current = callback; }, [callback]); react.useEffect(() => { let startTime, animationFrame; function tick() { const timeElapsed = Date.now() - startTime; startTime = Date.now(); loop(); savedCallback.current && savedCallback.current(timeElapsed); } function loop() { animationFrame = raf__default['default'](tick); } if (isActive) { startTime = Date.now(); loop(); return () => { raf__default['default'].cancel(animationFrame); }; } }, [isActive]); }
function useRaf(callback, isActive) { const savedCallback = react.useRef(); // Remember the latest function. react.useEffect(() => { savedCallback.current = callback; }, [callback]); react.useEffect(() => { let startTime, animationFrame; function tick() { const timeElapsed = Date.now() - startTime; startTime = Date.now(); loop(); savedCallback.current && savedCallback.current(timeElapsed); } function loop() { animationFrame = raf__default['default'](tick); } if (isActive) { startTime = Date.now(); loop(); return () => { raf__default['default'].cancel(animationFrame); }; } }, [isActive]); }
JavaScript
function useRaf(callback, isActive) { const savedCallback = useRef(); // Remember the latest function. useEffect(() => { savedCallback.current = callback; }, [callback]); useEffect(() => { let startTime, animationFrame; function tick() { const timeElapsed = Date.now() - startTime; startTime = Date.now(); loop(); savedCallback.current && savedCallback.current(timeElapsed); } function loop() { animationFrame = raf(tick); } if (isActive) { startTime = Date.now(); loop(); return () => { raf.cancel(animationFrame); }; } }, [isActive]); }
function useRaf(callback, isActive) { const savedCallback = useRef(); // Remember the latest function. useEffect(() => { savedCallback.current = callback; }, [callback]); useEffect(() => { let startTime, animationFrame; function tick() { const timeElapsed = Date.now() - startTime; startTime = Date.now(); loop(); savedCallback.current && savedCallback.current(timeElapsed); } function loop() { animationFrame = raf(tick); } if (isActive) { startTime = Date.now(); loop(); return () => { raf.cancel(animationFrame); }; } }, [isActive]); }
JavaScript
function handleMouseOverOut(handler, e, relatedNative) { var target = e.currentTarget; var related = e.relatedTarget || e.nativeEvent[relatedNative]; if ((!related || related !== target) && !contains(target, related)) { handler(e); } }
function handleMouseOverOut(handler, e, relatedNative) { var target = e.currentTarget; var related = e.relatedTarget || e.nativeEvent[relatedNative]; if ((!related || related !== target) && !contains(target, related)) { handler(e); } }
JavaScript
function handleMouseOverOut(handler, e, relatedNative) { var target = e.currentTarget; var related = e.relatedTarget || e.nativeEvent[relatedNative]; if ((!related || related !== target) && !(0, _contains.default)(target, related)) { handler(e); } }
function handleMouseOverOut(handler, e, relatedNative) { var target = e.currentTarget; var related = e.relatedTarget || e.nativeEvent[relatedNative]; if ((!related || related !== target) && !(0, _contains.default)(target, related)) { handler(e); } }
JavaScript
function parseIP(target) { /* These three regular expressions are all mutually exclusive, so we just * want the first one that matches the target string, if any do. */ const ipv4Match = IPV4_REGEX.exec(target); const match = ipv4Match || IPV6_REGEX.exec(target) || IPV6_BRACKET_REGEX.exec(target); if (match === null) { return null; } // ipv6 addresses should be bracketed const addr = match[1]; let port; if (match[2]) { port = match[2]; } else { port = DEFAULT_PORT; } return [{ host: addr, port: +port }]; }
function parseIP(target) { /* These three regular expressions are all mutually exclusive, so we just * want the first one that matches the target string, if any do. */ const ipv4Match = IPV4_REGEX.exec(target); const match = ipv4Match || IPV6_REGEX.exec(target) || IPV6_BRACKET_REGEX.exec(target); if (match === null) { return null; } // ipv6 addresses should be bracketed const addr = match[1]; let port; if (match[2]) { port = match[2]; } else { port = DEFAULT_PORT; } return [{ host: addr, port: +port }]; }
JavaScript
startResolution() { if (this.ipResult !== null) { trace('Returning IP address for target ' + this.target); setImmediate(() => { this.listener.onSuccessfulResolution(this.ipResult, null, null); }); return; } if (this.dnsHostname === null) { setImmediate(() => { this.listener.onError({ code: constants_1.Status.UNAVAILABLE, details: `Failed to parse DNS address ${this.target}`, metadata: new metadata_1.Metadata(), }); }); } else { /* We clear out latestLookupResult here to ensure that it contains the * latest result since the last time we started resolving. That way, the * TXT resolution handler can use it, but only if it finishes second. We * don't clear out any previous service config results because it's * better to use a service config that's slightly out of date than to * revert to an effectively blank one. */ this.latestLookupResult = null; const hostname = this.dnsHostname; /* We lookup both address families here and then split them up later * because when looking up a single family, dns.lookup outputs an error * if the name exists but there are no records for that family, and that * error is indistinguishable from other kinds of errors */ this.pendingLookupPromise = dnsLookupPromise(hostname, { all: true }); this.pendingLookupPromise.then((addressList) => { this.pendingLookupPromise = null; const ip4Addresses = addressList.filter((addr) => addr.family === 4); const ip6Addresses = addressList.filter((addr) => addr.family === 6); this.latestLookupResult = mergeArrays(ip6Addresses, ip4Addresses).map((addr) => ({ host: addr.address, port: +this.port })); const allAddressesString = '[' + this.latestLookupResult .map((addr) => addr.host + ':' + addr.port) .join(',') + ']'; trace('Resolved addresses for target ' + this.target + ': ' + allAddressesString); if (this.latestLookupResult.length === 0) { this.listener.onError(this.defaultResolutionError); return; } /* If the TXT lookup has not yet finished, both of the last two * arguments will be null, which is the equivalent of getting an * empty TXT response. When the TXT lookup does finish, its handler * can update the service config by using the same address list */ this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError); }, (err) => { trace('Resolution error for target ' + this.target + ': ' + err.message); this.pendingLookupPromise = null; this.listener.onError(this.defaultResolutionError); }); /* If there already is a still-pending TXT resolution, we can just use * that result when it comes in */ if (this.pendingTxtPromise === null) { /* We handle the TXT query promise differently than the others because * the name resolution attempt as a whole is a success even if the TXT * lookup fails */ this.pendingTxtPromise = resolveTxtPromise(hostname); this.pendingTxtPromise.then((txtRecord) => { this.pendingTxtPromise = null; try { this.latestServiceConfig = service_config_1.extractAndSelectServiceConfig(txtRecord, this.percentage); } catch (err) { this.latestServiceConfigError = { code: constants_1.Status.UNAVAILABLE, details: 'Parsing service config failed', metadata: new metadata_1.Metadata(), }; } if (this.latestLookupResult !== null) { /* We rely here on the assumption that calling this function with * identical parameters will be essentialy idempotent, and calling * it with the same address list and a different service config * should result in a fast and seamless switchover. */ this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError); } }, (err) => { this.latestServiceConfigError = { code: constants_1.Status.UNAVAILABLE, details: 'TXT query failed', metadata: new metadata_1.Metadata(), }; if (this.latestLookupResult !== null) { this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError); } }); } } }
startResolution() { if (this.ipResult !== null) { trace('Returning IP address for target ' + this.target); setImmediate(() => { this.listener.onSuccessfulResolution(this.ipResult, null, null); }); return; } if (this.dnsHostname === null) { setImmediate(() => { this.listener.onError({ code: constants_1.Status.UNAVAILABLE, details: `Failed to parse DNS address ${this.target}`, metadata: new metadata_1.Metadata(), }); }); } else { /* We clear out latestLookupResult here to ensure that it contains the * latest result since the last time we started resolving. That way, the * TXT resolution handler can use it, but only if it finishes second. We * don't clear out any previous service config results because it's * better to use a service config that's slightly out of date than to * revert to an effectively blank one. */ this.latestLookupResult = null; const hostname = this.dnsHostname; /* We lookup both address families here and then split them up later * because when looking up a single family, dns.lookup outputs an error * if the name exists but there are no records for that family, and that * error is indistinguishable from other kinds of errors */ this.pendingLookupPromise = dnsLookupPromise(hostname, { all: true }); this.pendingLookupPromise.then((addressList) => { this.pendingLookupPromise = null; const ip4Addresses = addressList.filter((addr) => addr.family === 4); const ip6Addresses = addressList.filter((addr) => addr.family === 6); this.latestLookupResult = mergeArrays(ip6Addresses, ip4Addresses).map((addr) => ({ host: addr.address, port: +this.port })); const allAddressesString = '[' + this.latestLookupResult .map((addr) => addr.host + ':' + addr.port) .join(',') + ']'; trace('Resolved addresses for target ' + this.target + ': ' + allAddressesString); if (this.latestLookupResult.length === 0) { this.listener.onError(this.defaultResolutionError); return; } /* If the TXT lookup has not yet finished, both of the last two * arguments will be null, which is the equivalent of getting an * empty TXT response. When the TXT lookup does finish, its handler * can update the service config by using the same address list */ this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError); }, (err) => { trace('Resolution error for target ' + this.target + ': ' + err.message); this.pendingLookupPromise = null; this.listener.onError(this.defaultResolutionError); }); /* If there already is a still-pending TXT resolution, we can just use * that result when it comes in */ if (this.pendingTxtPromise === null) { /* We handle the TXT query promise differently than the others because * the name resolution attempt as a whole is a success even if the TXT * lookup fails */ this.pendingTxtPromise = resolveTxtPromise(hostname); this.pendingTxtPromise.then((txtRecord) => { this.pendingTxtPromise = null; try { this.latestServiceConfig = service_config_1.extractAndSelectServiceConfig(txtRecord, this.percentage); } catch (err) { this.latestServiceConfigError = { code: constants_1.Status.UNAVAILABLE, details: 'Parsing service config failed', metadata: new metadata_1.Metadata(), }; } if (this.latestLookupResult !== null) { /* We rely here on the assumption that calling this function with * identical parameters will be essentialy idempotent, and calling * it with the same address list and a different service config * should result in a fast and seamless switchover. */ this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError); } }, (err) => { this.latestServiceConfigError = { code: constants_1.Status.UNAVAILABLE, details: 'TXT query failed', metadata: new metadata_1.Metadata(), }; if (this.latestLookupResult !== null) { this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError); } }); } } }
JavaScript
function createResolver(target, listener) { for (const prefix of Object.keys(registeredResolvers)) { if (target.startsWith(prefix)) { return new registeredResolvers[prefix](target, listener); } } if (defaultResolver !== null) { return new defaultResolver(target, listener); } throw new Error(`No resolver could be created for target ${target}`); }
function createResolver(target, listener) { for (const prefix of Object.keys(registeredResolvers)) { if (target.startsWith(prefix)) { return new registeredResolvers[prefix](target, listener); } } if (defaultResolver !== null) { return new defaultResolver(target, listener); } throw new Error(`No resolver could be created for target ${target}`); }
JavaScript
switchOverReplacementBalancer() { this.innerLoadBalancer.destroy(); this.innerLoadBalancer = this.pendingReplacementLoadBalancer; this.innerLoadBalancer.replaceChannelControlHelper(this.innerChannelControlHelper); this.pendingReplacementLoadBalancer = null; this.innerBalancerState = this.replacementBalancerState; this.innerBalancerPicker = this.replacementBalancerPicker; this.updateState(this.replacementBalancerState, this.replacementBalancerPicker); }
switchOverReplacementBalancer() { this.innerLoadBalancer.destroy(); this.innerLoadBalancer = this.pendingReplacementLoadBalancer; this.innerLoadBalancer.replaceChannelControlHelper(this.innerChannelControlHelper); this.pendingReplacementLoadBalancer = null; this.innerBalancerState = this.replacementBalancerState; this.innerBalancerPicker = this.replacementBalancerPicker; this.updateState(this.replacementBalancerState, this.replacementBalancerPicker); }
JavaScript
function toValidationObject (valid, key, value, rule, attr) { return { valid: valid, rule: rule, attr: attr, value: value, key: key } }
function toValidationObject (valid, key, value, rule, attr) { return { valid: valid, rule: rule, attr: attr, value: value, key: key } }
JavaScript
function validate (schema, RAMLVersion) { if (!schema) { return function () { return { valid: true, errors: [] } } } // RAML version. Defaults to RAML 0.8. RAMLVersion = RAMLVersion || 'RAML08' var validations = {} var validateRule = RAMLVersion === 'RAML10' ? validate.ruleRAML10 : validate.rule if (Array.isArray(schema.type) && schema.type.length === 1) { schema.type = schema.type[0] } var isObjectType = !schema.type || schema.type === 'object' var isEmptyObject = isObjectType && schema.properties && Object.keys(schema.properties).length === 0 if (RAMLVersion === 'RAML10' && (!isObjectType || isEmptyObject)) { validations = validateRule(schema) } else { // Convert all parameters into validation functions. Object.keys(schema).forEach(function (param) { validations[param] = validateRule(schema[param]) }) } /** * The function accepts an object to be validated. All rules are already * precompiled. * * @param {Object} model * @return {Boolean} */ return function (model) { model = model || {} var errors = [] if (RAMLVersion === 'RAML10' && (!isObjectType || isEmptyObject)) { var validation = validations(model, undefined, model) if (!validation.valid) { errors.push(validation) } } else { // Map all validations to their object and filter for failures. errors = Object.keys(validations).map(function (param) { var value = model[param] var validation = validations[param] // Return the validation result. return validation(value, param, model) }).filter(function (validation) { return !validation.valid }) } return { valid: errors.length === 0, errors: errors } } }
function validate (schema, RAMLVersion) { if (!schema) { return function () { return { valid: true, errors: [] } } } // RAML version. Defaults to RAML 0.8. RAMLVersion = RAMLVersion || 'RAML08' var validations = {} var validateRule = RAMLVersion === 'RAML10' ? validate.ruleRAML10 : validate.rule if (Array.isArray(schema.type) && schema.type.length === 1) { schema.type = schema.type[0] } var isObjectType = !schema.type || schema.type === 'object' var isEmptyObject = isObjectType && schema.properties && Object.keys(schema.properties).length === 0 if (RAMLVersion === 'RAML10' && (!isObjectType || isEmptyObject)) { validations = validateRule(schema) } else { // Convert all parameters into validation functions. Object.keys(schema).forEach(function (param) { validations[param] = validateRule(schema[param]) }) } /** * The function accepts an object to be validated. All rules are already * precompiled. * * @param {Object} model * @return {Boolean} */ return function (model) { model = model || {} var errors = [] if (RAMLVersion === 'RAML10' && (!isObjectType || isEmptyObject)) { var validation = validations(model, undefined, model) if (!validation.valid) { errors.push(validation) } } else { // Map all validations to their object and filter for failures. errors = Object.keys(validations).map(function (param) { var value = model[param] var validation = validations[param] // Return the validation result. return validation(value, param, model) }).filter(function (validation) { return !validation.valid }) } return { valid: errors.length === 0, errors: errors } } }
JavaScript
get service() { if (!this.#amfService) { this.#amfService = new AmfService(); } return this.#amfService; }
get service() { if (!this.#amfService) { this.#amfService = new AmfService(); } return this.#amfService; }
JavaScript
async cleanup() { const service = this.service; if (service.source) { await service.cleanup(); } }
async cleanup() { const service = this.service; if (service.source) { await service.cleanup(); } }
JavaScript
async processApiLink(url, mainFile, md5, packaging) { this.loading = true; const bufferOpts = {}; if (packaging && packaging === 'zip') { bufferOpts.zip = true; } if (mainFile) { bufferOpts.mainFile = mainFile; } try { const buffer = await this.downloadRamlData(url); this._checkIntegrity(buffer, md5); const result = await this.processBuffer(buffer); this.loading = false; return result; } catch (cause) { this.loading = false; throw cause; } }
async processApiLink(url, mainFile, md5, packaging) { this.loading = true; const bufferOpts = {}; if (packaging && packaging === 'zip') { bufferOpts.zip = true; } if (mainFile) { bufferOpts.mainFile = mainFile; } try { const buffer = await this.downloadRamlData(url); this._checkIntegrity(buffer, md5); const result = await this.processBuffer(buffer); this.loading = false; return result; } catch (cause) { this.loading = false; throw cause; } }
JavaScript
async processApiFile(file) { this.loading = true; try { const buffer = await this._fileToBuffer(file); const result = await this.processBuffer(buffer); this.loading = false; return result; } catch (cause) { this.loading = false; throw cause; } }
async processApiFile(file) { this.loading = true; try { const buffer = await this._fileToBuffer(file); const result = await this.processBuffer(buffer); this.loading = false; return result; } catch (cause) { this.loading = false; throw cause; } }
JavaScript
async _processCandidates(service, candidates) { try { const file = await this.notifyApiCandidates(candidates); if (!file) { await service.cancel(); } else { return service.parse(file); } } catch (e) { await service.cancel(); throw e; } }
async _processCandidates(service, candidates) { try { const file = await this.notifyApiCandidates(candidates); if (!file) { await service.cancel(); } else { return service.parse(file); } } catch (e) { await service.cancel(); throw e; } }
JavaScript
_createResolverProcess() { const options = { execArgv: [], }; return fork(path.join(__dirname, '..', 'lib', 'amf-resolver.js'), options); }
_createResolverProcess() { const options = { execArgv: [], }; return fork(path.join(__dirname, '..', 'lib', 'amf-resolver.js'), options); }
JavaScript
_killResolver(proc) { if (proc.connected) { proc.disconnect(); } proc.removeAllListeners('message'); proc.removeAllListeners('error'); proc.kill(); }
_killResolver(proc) { if (proc.connected) { proc.disconnect(); } proc.removeAllListeners('message'); proc.removeAllListeners('error'); proc.kill(); }
JavaScript
async cancel() { await this._cleanTempFiles(); this.tmpObj = undefined; this.workingDir = undefined; this.mainFile = undefined; }
async cancel() { await this._cleanTempFiles(); this.tmpObj = undefined; this.workingDir = undefined; this.mainFile = undefined; }
JavaScript
async cleanup() { this._cancelMonitorParser(); this._cancelParseProcTimeout(); const proc = this._parserProc; if (!proc) { return this.cancel(); } return new Promise((resolve) => { this._killParser(); proc.on('exit', () => { this.cancel().then(() => resolve()); }); }); }
async cleanup() { this._cancelMonitorParser(); this._cancelParseProcTimeout(); const proc = this._parserProc; if (!proc) { return this.cancel(); } return new Promise((resolve) => { this._killParser(); proc.on('exit', () => { this.cancel().then(() => resolve()); }); }); }
JavaScript
async resolve(mainFile) { if (this.#tmpIsFile) { return; } if (!this.workingDir) { await this._cleanTempFiles(); throw new Error(`prepare() function not called`); } if (this.mainFile) { return; } if (mainFile) { const file = path.join(this.workingDir, mainFile); const exists = fs.pathExists(file); if (exists) { this.mainFile = mainFile; return; } throw new Error('API main file does not exist.'); } const search = new ApiSearch(this.workingDir); try { const result = await search.findApiFile(); if (!result) { throw new Error('Unable to find API files in the source location'); } if (Array.isArray(result)) { return result; } this.mainFile = result; } catch (cause) { await this._cleanTempFiles(); throw cause; } }
async resolve(mainFile) { if (this.#tmpIsFile) { return; } if (!this.workingDir) { await this._cleanTempFiles(); throw new Error(`prepare() function not called`); } if (this.mainFile) { return; } if (mainFile) { const file = path.join(this.workingDir, mainFile); const exists = fs.pathExists(file); if (exists) { this.mainFile = mainFile; return; } throw new Error('API main file does not exist.'); } const search = new ApiSearch(this.workingDir); try { const result = await search.findApiFile(); if (!result) { throw new Error('Unable to find API files in the source location'); } if (Array.isArray(result)) { return result; } this.mainFile = result; } catch (cause) { await this._cleanTempFiles(); throw cause; } }
JavaScript
async _tmpBuffer(buffer) { const tmp = await file(); this.tmpObj = tmp; this.#tmpIsFile = true; const fd = tmp.fd; await fs.write(fd, buffer); await fs.close(fd); return tmp.path; }
async _tmpBuffer(buffer) { const tmp = await file(); this.tmpObj = tmp; this.#tmpIsFile = true; const fd = tmp.fd; await fs.write(fd, buffer); await fs.close(fd); return tmp.path; }
JavaScript
async _unzip(buffer) { this.tmpObj = await dir(); return new Promise((resolve, reject) => { const stream = new Duplex(); stream.push(buffer); stream.push(null); const extractor = unzipper.Extract({ path: this.tmpObj.path, }); extractor.on('close', () => { resolve(this.tmpObj.path); }); extractor.on('error', (err) => { reject(err); }); stream.pipe(extractor); }); }
async _unzip(buffer) { this.tmpObj = await dir(); return new Promise((resolve, reject) => { const stream = new Duplex(); stream.push(buffer); stream.push(null); const extractor = unzipper.Extract({ path: this.tmpObj.path, }); extractor.on('close', () => { resolve(this.tmpObj.path); }); extractor.on('error', (err) => { reject(err); }); stream.pipe(extractor); }); }
JavaScript
async _removeZipMainFolder(destination) { let files = await fs.readdir(destination); files = files.filter((item) => item !== '__MACOSX'); if (files.length > 1) { return; } const dirPath = path.join(destination, files[0]); const stats = await fs.stat(dirPath); if (stats.isDirectory()) { await fs.copy(dirPath, destination); } }
async _removeZipMainFolder(destination) { let files = await fs.readdir(destination); files = files.filter((item) => item !== '__MACOSX'); if (files.length > 1) { return; } const dirPath = path.join(destination, files[0]); const stats = await fs.stat(dirPath); if (stats.isDirectory()) { await fs.copy(dirPath, destination); } }
JavaScript
_createParserProcess() { if (this._parserProc) { if (this._parserProc.connected) { return this._parserProc; } this._killParser(); } const options = { execArgv: [], }; this._parserProc = fork(`${__dirname}/amf-parser.js`, options); this._parserProc.on('exit', () => { this._cancelParseProcTimeout(); this._cancelMonitorParser(); this._parserProc = undefined; }); return this._parserProc; }
_createParserProcess() { if (this._parserProc) { if (this._parserProc.connected) { return this._parserProc; } this._killParser(); } const options = { execArgv: [], }; this._parserProc = fork(`${__dirname}/amf-parser.js`, options); this._parserProc.on('exit', () => { this._cancelParseProcTimeout(); this._cancelMonitorParser(); this._parserProc = undefined; }); return this._parserProc; }
JavaScript
_killParser() { this._cancelParseProcTimeout(); this._cancelMonitorParser(); if (this._parserProc) { this._parserProc.disconnect(); this._parserProc.removeAllListeners('message'); this._parserProc.removeAllListeners('error'); this._parserProc.removeAllListeners('exit'); this._parserProc.kill(); this._parserProc = undefined; } }
_killParser() { this._cancelParseProcTimeout(); this._cancelMonitorParser(); if (this._parserProc) { this._parserProc.disconnect(); this._parserProc.removeAllListeners('message'); this._parserProc.removeAllListeners('error'); this._parserProc.removeAllListeners('exit'); this._parserProc.kill(); this._parserProc = undefined; } }
JavaScript
_monitorParserProc() { this._parserMonitorTimeout = setTimeout(() => { this._parserMonitorTimeout = undefined; this._killParser(); }, 60000); }
_monitorParserProc() { this._parserMonitorTimeout = setTimeout(() => { this._parserMonitorTimeout = undefined; this._killParser(); }, 60000); }
JavaScript
_cancelMonitorParser() { if (this._parserMonitorTimeout) { clearTimeout(this._parserMonitorTimeout); } }
_cancelMonitorParser() { if (this._parserMonitorTimeout) { clearTimeout(this._parserMonitorTimeout); } }
JavaScript
async findApiFile() { const items = await fs.readdir(this._workingDir); const popularNames = ['api.raml', 'api.yaml', 'api.json']; const exts = ['.raml', '.yaml', '.json']; const ignore = ['__macosx', 'exchange.json', '.ds_store']; const files = []; for (let i = 0; i < items.length; i++) { const item = items[i]; const lower = items[i].toLowerCase(); if (ignore.indexOf(lower) !== -1) { continue; } if (popularNames.indexOf(lower) !== -1) { return item; } const ext = path.extname(lower); if (exts.indexOf(ext) !== -1) { files.push(item); } } if (files.length === 1) { return files[0]; } if (files.length) { return this._decideMainFile(files); } }
async findApiFile() { const items = await fs.readdir(this._workingDir); const popularNames = ['api.raml', 'api.yaml', 'api.json']; const exts = ['.raml', '.yaml', '.json']; const ignore = ['__macosx', 'exchange.json', '.ds_store']; const files = []; for (let i = 0; i < items.length; i++) { const item = items[i]; const lower = items[i].toLowerCase(); if (ignore.indexOf(lower) !== -1) { continue; } if (popularNames.indexOf(lower) !== -1) { return item; } const ext = path.extname(lower); if (exts.indexOf(ext) !== -1) { files.push(item); } } if (files.length === 1) { return files[0]; } if (files.length) { return this._decideMainFile(files); } }
JavaScript
async function processData(data) { const sourceFile = data.source; const type = data.from.type; const contentType = data.from.contentType; const validate = data.validate; if (!initialized) { await amf.Core.init(); } /* eslint-disable-next-line require-atomic-updates */ initialized = true; const file = `file://${sourceFile}`; const parser = amf.Core.parser(type, contentType); const doc = await parser.parseFileAsync(file); if (validate) { await validateDoc(type, doc); } const generator = amf.Core.generator('AMF Graph', 'application/ld+json'); return generator.generateString(doc); }
async function processData(data) { const sourceFile = data.source; const type = data.from.type; const contentType = data.from.contentType; const validate = data.validate; if (!initialized) { await amf.Core.init(); } /* eslint-disable-next-line require-atomic-updates */ initialized = true; const file = `file://${sourceFile}`; const parser = amf.Core.parser(type, contentType); const doc = await parser.parseFileAsync(file); if (validate) { await validateDoc(type, doc); } const generator = amf.Core.generator('AMF Graph', 'application/ld+json'); return generator.generateString(doc); }
JavaScript
function mergeValues( target, container ) { if ( ! target ) { return; } container = container ? container : { }; Object.keys( container ).forEach( function( key /* , index */) { if (( ! target[ key ]) || ( _m.lib.isString( target[ key ]) || _m.lib.isNumber( target[ key ]) || Array.isArray( target[ key ]))) { if ( container[ key ] !== undefined ) { target[ key ] = container[ key ]; } else { delete target[ key ]; } } else if (( target[ key ]) && ( container[ key ] === undefined )) { delete target[ key ]; } else if (( ! ( target[ key ] instanceof Function )) && ( ! ( container[ key ] instanceof Function ))) { mergeValues( target[ key ], container[ key ]); } }); return target; }
function mergeValues( target, container ) { if ( ! target ) { return; } container = container ? container : { }; Object.keys( container ).forEach( function( key /* , index */) { if (( ! target[ key ]) || ( _m.lib.isString( target[ key ]) || _m.lib.isNumber( target[ key ]) || Array.isArray( target[ key ]))) { if ( container[ key ] !== undefined ) { target[ key ] = container[ key ]; } else { delete target[ key ]; } } else if (( target[ key ]) && ( container[ key ] === undefined )) { delete target[ key ]; } else if (( ! ( target[ key ] instanceof Function )) && ( ! ( container[ key ] instanceof Function ))) { mergeValues( target[ key ], container[ key ]); } }); return target; }
JavaScript
function updateValues( target, container ) { if ( ! target ) { return; } container = container ? container : { }; Object.keys( container ).forEach( function( key /* , index */) { if (( target[ key ] === null ) || ( target[ key ] === undefined )) { return; } else if ( container[ key ] === undefined ) { target[ key ] = undefined; } else if ( container[ key ] === null ) { target[ key ] = null; } else if ( typeof( container[ key ]) === _STRINGS.TYPE_OBJECT ) { if (( ! Array.isArray( container[ key ] )) && ( ! ( container[ key ] instanceof String )) && ( typeof( container[ key ]) !== _STRINGS.TYPE_FUNCTION ) && ( ! ( container[ key ] instanceof Date ))) { if ( typeof( target[ key ]) === _STRINGS.TYPE_OBJECT ) { updateValues( target[ key ], container[ key ]); } else target[ key ] = container[ key ]; } else target[ key ] = container[ key ]; } else target[ key ] = container[ key ]; }); return target; }
function updateValues( target, container ) { if ( ! target ) { return; } container = container ? container : { }; Object.keys( container ).forEach( function( key /* , index */) { if (( target[ key ] === null ) || ( target[ key ] === undefined )) { return; } else if ( container[ key ] === undefined ) { target[ key ] = undefined; } else if ( container[ key ] === null ) { target[ key ] = null; } else if ( typeof( container[ key ]) === _STRINGS.TYPE_OBJECT ) { if (( ! Array.isArray( container[ key ] )) && ( ! ( container[ key ] instanceof String )) && ( typeof( container[ key ]) !== _STRINGS.TYPE_FUNCTION ) && ( ! ( container[ key ] instanceof Date ))) { if ( typeof( target[ key ]) === _STRINGS.TYPE_OBJECT ) { updateValues( target[ key ], container[ key ]); } else target[ key ] = container[ key ]; } else target[ key ] = container[ key ]; } else target[ key ] = container[ key ]; }); return target; }
JavaScript
updateWall() { // update the wall Action.getWall(this.limit, this.code,this.getPattern.bind(this)); }
updateWall() { // update the wall Action.getWall(this.limit, this.code,this.getPattern.bind(this)); }
JavaScript
function init() { initButtons(); initLoadEvents(); initModals(); // Update the events every minute. setInterval(function() { dataRefresh(); }, 60 * 1000); }
function init() { initButtons(); initLoadEvents(); initModals(); // Update the events every minute. setInterval(function() { dataRefresh(); }, 60 * 1000); }
JavaScript
function initLoadEvents() { loadEventsAsJSON((os.homedir() + "/Saved Events/events.json"), function(returnJSON) { if (!returnJSON) { loadEventsAsXML((os.homedir() + "/Saved Events/events.xml"), function(returnXML) { if (!returnXML) { fs.mkdir((os.homedir() + "/Saved Events")); } saveEvents(); }); } }); }
function initLoadEvents() { loadEventsAsJSON((os.homedir() + "/Saved Events/events.json"), function(returnJSON) { if (!returnJSON) { loadEventsAsXML((os.homedir() + "/Saved Events/events.xml"), function(returnXML) { if (!returnXML) { fs.mkdir((os.homedir() + "/Saved Events")); } saveEvents(); }); } }); }
JavaScript
function dataRefresh() { currentEvents.sort(compare); saveEvents(); displayEvents(); displayCalendar(); }
function dataRefresh() { currentEvents.sort(compare); saveEvents(); displayEvents(); displayCalendar(); }
JavaScript
function displayEvents() { var eventsDiv = document.getElementById("eventsDiv"); eventsDiv.innerHTML = ""; for (var i = 0; i < currentEvents.length; i++) { var difference = calculateDifference(currentEvents[i].Date[0]._text + " " + currentEvents[i].Time[0]._text); var newHTMLLeft = "<br><span id=\"timeLeftSpan\">"; var style = ""; var eventExpiredColour = "#66ff66"; var eventDoneColour = "#80dfff"; var eventAlmostDoneColour = "#ff6666"; var eventStandardColour = "#ffff80"; var currentHTML = eventsDiv.innerHTML; var theDate = new Date(currentEvents[i].Date[0]._text + " " + currentEvents[i].Time[0]._text) var button3HTML = "<button type=\"button\" class=\"btn btn-secondary\" id=\"eventDoneButton\" onclick=\"donePressed(this)\">Done</button>" if (difference.Days <= 0 && difference.Hours <= 0 && difference.Mins <= 0) { newHTMLLeft = "<br><span id=\"timeLeftSpan\">Event Expired</span>" style = "style=\"background: " + eventExpiredColour + ";\"" button3HTML = ""; } else if (currentEvents[i].Finished[0]._text) { newHTMLLeft = "<br><span id=\"timeLeftSpan\">Event Completed</span>" style = "style=\"background: " + eventDoneColour + ";\"" button3HTML = "<button type=\"button\" class=\"btn btn-secondary\" id=\"eventUndoButton\" onclick=\"undoPressed(this)\">Undo</button>" } else { if (difference.Days !== 0) { newHTMLLeft += difference.Days + " Days "; } if (difference.Hours !== 0) { newHTMLLeft += difference.Hours + " Hours "; } if (difference.Mins !== 0) { newHTMLLeft += difference.Mins + " Mins "; } newHTMLLeft += "Left</span>"; if (difference.Days < 3) { style = "style=\"background: " + eventAlmostDoneColour + ";\"" } else { style = "style=\"background: " + eventStandardColour + ";\"" } } var newHTMLTitle = "<div id=\"colourDiv\" " + style + "></div><div id=\"event\"><div id=\"eventTitle\">" + currentEvents[i].Title[0]._text + "</div>"; var newHTMLDate = "<div id=\"eventDate\">" + theDate.getDate() + "/" + (theDate.getMonth() + 1) + "/" + theDate.getFullYear() + "</div>"; var newHTMLTime = "<div id=\"eventTime\">" + currentEvents[i].Time[0]._text + "</div>"; var buttonHTML = "<button type=\"button\" class=\"btn btn-secondary\" onclick=\"deleteEventPressed(this)\" id=\"eventDeleteButton\">Delete</button>" var button2HTML = "<button type=\"button\" class=\"btn btn-secondary\" id=\"eventEditButton\" onclick=\"editEventPressed(this)\">Edit</button>" var index = "<input type=\"hidden\" name=\"index\" value=" + i + ">" eventsDiv.innerHTML = currentHTML + newHTMLTitle + newHTMLDate + newHTMLTime + newHTMLLeft + buttonHTML + button2HTML + button3HTML + index; } }
function displayEvents() { var eventsDiv = document.getElementById("eventsDiv"); eventsDiv.innerHTML = ""; for (var i = 0; i < currentEvents.length; i++) { var difference = calculateDifference(currentEvents[i].Date[0]._text + " " + currentEvents[i].Time[0]._text); var newHTMLLeft = "<br><span id=\"timeLeftSpan\">"; var style = ""; var eventExpiredColour = "#66ff66"; var eventDoneColour = "#80dfff"; var eventAlmostDoneColour = "#ff6666"; var eventStandardColour = "#ffff80"; var currentHTML = eventsDiv.innerHTML; var theDate = new Date(currentEvents[i].Date[0]._text + " " + currentEvents[i].Time[0]._text) var button3HTML = "<button type=\"button\" class=\"btn btn-secondary\" id=\"eventDoneButton\" onclick=\"donePressed(this)\">Done</button>" if (difference.Days <= 0 && difference.Hours <= 0 && difference.Mins <= 0) { newHTMLLeft = "<br><span id=\"timeLeftSpan\">Event Expired</span>" style = "style=\"background: " + eventExpiredColour + ";\"" button3HTML = ""; } else if (currentEvents[i].Finished[0]._text) { newHTMLLeft = "<br><span id=\"timeLeftSpan\">Event Completed</span>" style = "style=\"background: " + eventDoneColour + ";\"" button3HTML = "<button type=\"button\" class=\"btn btn-secondary\" id=\"eventUndoButton\" onclick=\"undoPressed(this)\">Undo</button>" } else { if (difference.Days !== 0) { newHTMLLeft += difference.Days + " Days "; } if (difference.Hours !== 0) { newHTMLLeft += difference.Hours + " Hours "; } if (difference.Mins !== 0) { newHTMLLeft += difference.Mins + " Mins "; } newHTMLLeft += "Left</span>"; if (difference.Days < 3) { style = "style=\"background: " + eventAlmostDoneColour + ";\"" } else { style = "style=\"background: " + eventStandardColour + ";\"" } } var newHTMLTitle = "<div id=\"colourDiv\" " + style + "></div><div id=\"event\"><div id=\"eventTitle\">" + currentEvents[i].Title[0]._text + "</div>"; var newHTMLDate = "<div id=\"eventDate\">" + theDate.getDate() + "/" + (theDate.getMonth() + 1) + "/" + theDate.getFullYear() + "</div>"; var newHTMLTime = "<div id=\"eventTime\">" + currentEvents[i].Time[0]._text + "</div>"; var buttonHTML = "<button type=\"button\" class=\"btn btn-secondary\" onclick=\"deleteEventPressed(this)\" id=\"eventDeleteButton\">Delete</button>" var button2HTML = "<button type=\"button\" class=\"btn btn-secondary\" id=\"eventEditButton\" onclick=\"editEventPressed(this)\">Edit</button>" var index = "<input type=\"hidden\" name=\"index\" value=" + i + ">" eventsDiv.innerHTML = currentHTML + newHTMLTitle + newHTMLDate + newHTMLTime + newHTMLLeft + buttonHTML + button2HTML + button3HTML + index; } }
JavaScript
function loadEventsAsJSON(filepath, callback) { fs.readFile(filepath, 'utf-8', function (err, data) { if (err) { callback(false); } else { currentEvents = JSON.parse(data); dataRefresh(); callback(true); } }); }
function loadEventsAsJSON(filepath, callback) { fs.readFile(filepath, 'utf-8', function (err, data) { if (err) { callback(false); } else { currentEvents = JSON.parse(data); dataRefresh(); callback(true); } }); }
JavaScript
function loadEventsAsXML(filepath, callback) { fs.readFile(filepath, 'utf-8', function (err, data) { if(err) { callback(false); } else { currentEvents = xmlToJSON.parseString(data).SavedEvents[0].Event; dataRefresh(); callback(true); } }); }
function loadEventsAsXML(filepath, callback) { fs.readFile(filepath, 'utf-8', function (err, data) { if(err) { callback(false); } else { currentEvents = xmlToJSON.parseString(data).SavedEvents[0].Event; dataRefresh(); callback(true); } }); }
JavaScript
function deleteEventPressed(button) { var value = confirm("Are you sure you want to delete this event?"); if (value == true) { var index = button.parentElement.getElementsByTagName("input")[0].value; currentEvents.splice(index, 1); dataRefresh(); } }
function deleteEventPressed(button) { var value = confirm("Are you sure you want to delete this event?"); if (value == true) { var index = button.parentElement.getElementsByTagName("input")[0].value; currentEvents.splice(index, 1); dataRefresh(); } }
JavaScript
function editEventPressed(button) { eventInFocus = button.parentElement.getElementsByTagName("input")[0].value; var editModal = document.getElementById('editModal'); editModal.style.display = "block"; var event = currentEvents[eventInFocus]; updateEditModalTitle(event.Title[0]._text); updateEditModalDate(event.Date[0]._text); var time = convertTo12(event.Time[0]._text); updateEditModalHour(parseInt(time.substring(0,2))); updateEditModalMinute(time.substring(3, 5)); updateEditModalAMPM(time.substring(6)); }
function editEventPressed(button) { eventInFocus = button.parentElement.getElementsByTagName("input")[0].value; var editModal = document.getElementById('editModal'); editModal.style.display = "block"; var event = currentEvents[eventInFocus]; updateEditModalTitle(event.Title[0]._text); updateEditModalDate(event.Date[0]._text); var time = convertTo12(event.Time[0]._text); updateEditModalHour(parseInt(time.substring(0,2))); updateEditModalMinute(time.substring(3, 5)); updateEditModalAMPM(time.substring(6)); }
JavaScript
function donePressed(button) { var index = button.parentElement.getElementsByTagName("input")[0].value; currentEvents[index].Finished[0]._text = true; dataRefresh(); }
function donePressed(button) { var index = button.parentElement.getElementsByTagName("input")[0].value; currentEvents[index].Finished[0]._text = true; dataRefresh(); }
JavaScript
function undoPressed(button) { var index = button.parentElement.getElementsByTagName("input")[0].value; currentEvents[index].Finished[0]._text = false; dataRefresh(); }
function undoPressed(button) { var index = button.parentElement.getElementsByTagName("input")[0].value; currentEvents[index].Finished[0]._text = false; dataRefresh(); }
JavaScript
function compare(a, b) { var aDate = new Date(a.Date[0]._text + " " + a.Time[0]._text); var bDate = new Date(b.Date[0]._text + " " + b.Time[0]._text); var aDifference = calculateDifference(aDate); var bDifference = calculateDifference(bDate); var aBool = a.Finished[0]._text; var bBool = b.Finished[0]._text; // Make sure events that are expired come before events that are done. if (isNegative(aDifference) && bBool && !isNegative(bDifference)) return -1; if (isNegative(bDifference) && aBool && !isNegative(aDifference)) return 1; // Make sure events that are marked done come before events that are not. if (aBool && !bBool) return -1; if (bBool && !aBool) return 1; // Makes sure that events that have less time left come before ones with more. if (aDate.getTime() < bDate.getTime()) return -1; if (aDate.getTime() > bDate.getTime()) return 1; return 0; }
function compare(a, b) { var aDate = new Date(a.Date[0]._text + " " + a.Time[0]._text); var bDate = new Date(b.Date[0]._text + " " + b.Time[0]._text); var aDifference = calculateDifference(aDate); var bDifference = calculateDifference(bDate); var aBool = a.Finished[0]._text; var bBool = b.Finished[0]._text; // Make sure events that are expired come before events that are done. if (isNegative(aDifference) && bBool && !isNegative(bDifference)) return -1; if (isNegative(bDifference) && aBool && !isNegative(aDifference)) return 1; // Make sure events that are marked done come before events that are not. if (aBool && !bBool) return -1; if (bBool && !aBool) return 1; // Makes sure that events that have less time left come before ones with more. if (aDate.getTime() < bDate.getTime()) return -1; if (aDate.getTime() > bDate.getTime()) return 1; return 0; }
JavaScript
function isNegative(difference) { if (difference.Days < 0 || difference.Hours < 0 || difference.Mins < 0) { return true; } return false; }
function isNegative(difference) { if (difference.Days < 0 || difference.Hours < 0 || difference.Mins < 0) { return true; } return false; }
JavaScript
function addEvent(title, date, time) { currentEvents.push({ "Title": [ {"_text" : title} ], "Date": [ {"_text" : date} ], "Time": [ {"_text" : time} ], "Finished": [ {"_text" : false} ] }) dataRefresh(); }
function addEvent(title, date, time) { currentEvents.push({ "Title": [ {"_text" : title} ], "Date": [ {"_text" : date} ], "Time": [ {"_text" : time} ], "Finished": [ {"_text" : false} ] }) dataRefresh(); }
JavaScript
function updateEvent(title, date, time, eventIndex) { currentEvents.splice(eventIndex, 1); addEvent(title, date, time); dataRefresh(); }
function updateEvent(title, date, time, eventIndex) { currentEvents.splice(eventIndex, 1); addEvent(title, date, time); dataRefresh(); }
JavaScript
function fix (str) { if (str.length > 1024) { return str.slice(0, 1024 - 3) + '...' } }
function fix (str) { if (str.length > 1024) { return str.slice(0, 1024 - 3) + '...' } }
JavaScript
function validateForm() { $(".form-control").removeClass("is-invalid"); $(".custom-error").remove(); var duplicate_cards = getDuplicateCards(); $(".hand").each(function() { if ($(this).find(".form-check-input").length === 0 || $(this).find(".form-check-input").is(":checked")) { var card = $(this).find("select[name=suit1]").val() + $(this).find("select[name=number1]").val(); if (duplicate_cards.includes(card)) { var suit = $(this).find("select[name=suit1]") var number = $(this).find("select[name=number1]") var row = $(this).find(".card-one") suit.addClass("is-invalid"); number.addClass("is-invalid"); row.after("<div class='custom-error' style='color:red;font-size:80%;'>Can't have more than one of the same card</div>"); } card = $(this).find("select[name=suit2]").val() + $(this).find("select[name=number2]").val(); if (duplicate_cards.includes(card)) { var suit = $(this).find("select[name=suit2]") var number = $(this).find("select[name=number2]") var row = $(this).find(".card-two") suit.addClass("is-invalid"); number.addClass("is-invalid"); row.after("<div class='custom-error' style='color:red;font-size:80%;'>Can't have more than one of the same card</div>"); } card = $(this).find("select[name=suit3]").val() + $(this).find("select[name=number3]").val(); if (duplicate_cards.includes(card)) { var suit = $(this).find("select[name=suit3]") var number = $(this).find("select[name=number3]") var row = $(this).find(".card-three") suit.addClass("is-invalid"); number.addClass("is-invalid"); row.after("<div class='custom-error' style='color:red;font-size:80%;'>Can't have more than one of the same card</div>"); } } }); }
function validateForm() { $(".form-control").removeClass("is-invalid"); $(".custom-error").remove(); var duplicate_cards = getDuplicateCards(); $(".hand").each(function() { if ($(this).find(".form-check-input").length === 0 || $(this).find(".form-check-input").is(":checked")) { var card = $(this).find("select[name=suit1]").val() + $(this).find("select[name=number1]").val(); if (duplicate_cards.includes(card)) { var suit = $(this).find("select[name=suit1]") var number = $(this).find("select[name=number1]") var row = $(this).find(".card-one") suit.addClass("is-invalid"); number.addClass("is-invalid"); row.after("<div class='custom-error' style='color:red;font-size:80%;'>Can't have more than one of the same card</div>"); } card = $(this).find("select[name=suit2]").val() + $(this).find("select[name=number2]").val(); if (duplicate_cards.includes(card)) { var suit = $(this).find("select[name=suit2]") var number = $(this).find("select[name=number2]") var row = $(this).find(".card-two") suit.addClass("is-invalid"); number.addClass("is-invalid"); row.after("<div class='custom-error' style='color:red;font-size:80%;'>Can't have more than one of the same card</div>"); } card = $(this).find("select[name=suit3]").val() + $(this).find("select[name=number3]").val(); if (duplicate_cards.includes(card)) { var suit = $(this).find("select[name=suit3]") var number = $(this).find("select[name=number3]") var row = $(this).find(".card-three") suit.addClass("is-invalid"); number.addClass("is-invalid"); row.after("<div class='custom-error' style='color:red;font-size:80%;'>Can't have more than one of the same card</div>"); } } }); }
JavaScript
function isAuthenticated({email, password}) { return userdb.users.findIndex( user => user.email === email && user.password === password) !== -1 }
function isAuthenticated({email, password}) { return userdb.users.findIndex( user => user.email === email && user.password === password) !== -1 }
JavaScript
function day1() { var input_textarea = document.querySelector("#day1"); var output_div = document.querySelector("#day1"); var save_button = document.querySelector("#save1"); save_button.addEventListener("click", updateOutput); output_div.textContent = localStorage.getItem(days[0]); input_textarea.value = localStorage.getItem(days[0]); // Name of the cookie is set as the date where the info is entered, and the value is the text content of that day function updateOutput() { localStorage.setItem(days[0], input_textarea.value); let date = new Date(); date.setTime(date.getTime()+(1*24*60*60*1000)); var expires = '; expires='+date.toGMTString(); let day = days[0] let content = input_textarea.value; document.cookie = day + '=' + content + ";expires=" + expires; output_div.textContent = content; input_textarea.value = content; } }
function day1() { var input_textarea = document.querySelector("#day1"); var output_div = document.querySelector("#day1"); var save_button = document.querySelector("#save1"); save_button.addEventListener("click", updateOutput); output_div.textContent = localStorage.getItem(days[0]); input_textarea.value = localStorage.getItem(days[0]); // Name of the cookie is set as the date where the info is entered, and the value is the text content of that day function updateOutput() { localStorage.setItem(days[0], input_textarea.value); let date = new Date(); date.setTime(date.getTime()+(1*24*60*60*1000)); var expires = '; expires='+date.toGMTString(); let day = days[0] let content = input_textarea.value; document.cookie = day + '=' + content + ";expires=" + expires; output_div.textContent = content; input_textarea.value = content; } }
JavaScript
function updateOutput() { localStorage.setItem(days[0], input_textarea.value); let date = new Date(); date.setTime(date.getTime()+(1*24*60*60*1000)); var expires = '; expires='+date.toGMTString(); let day = days[0] let content = input_textarea.value; document.cookie = day + '=' + content + ";expires=" + expires; output_div.textContent = content; input_textarea.value = content; }
function updateOutput() { localStorage.setItem(days[0], input_textarea.value); let date = new Date(); date.setTime(date.getTime()+(1*24*60*60*1000)); var expires = '; expires='+date.toGMTString(); let day = days[0] let content = input_textarea.value; document.cookie = day + '=' + content + ";expires=" + expires; output_div.textContent = content; input_textarea.value = content; }
JavaScript
async function authenticate(username, password) { // let auth = false; await axios .post(`${HOST_ADDRESS}api/login`, { username: username, password: password }) .then(res => { localStorage.setItem(token_name, res.data.token); }) .catch(err => { throw err; }); return "Success"; }
async function authenticate(username, password) { // let auth = false; await axios .post(`${HOST_ADDRESS}api/login`, { username: username, password: password }) .then(res => { localStorage.setItem(token_name, res.data.token); }) .catch(err => { throw err; }); return "Success"; }
JavaScript
generateCards(data) { var tilesPerRow = GLOBAL.TILES_PER_VIEW_X; var tilesPerCol = GLOBAL.TILES_PER_VIEW_Y; this.currentGroup = data.id; this.groupXStart = data.xMin; this.groupXEnd = data.xMax; //console.log("arrrrrrrrrrr"); var key = 'project-' + data.projectId + '-group-' + data.id; //console.log(data.projectId); this.isOfflineGroup = GLOBAL.DB.isOfflineGroup(key); if (this.isOfflineGroup === true) { if (this.lastMode !== 'offline') { this.lastMode = 'offline'; _mapper.props.messageBar.showAlert({ title: 'You are mapping a downloaded group!', message: 'It will work offline! ', alertType: 'info', // See Properties section for full customization // Or check `index.ios.js` or `index.android.js` for a complete example }); } } else { if (this.lastMode !== 'online') { this.lastMode = 'online'; _mapper.props.messageBar.showAlert({ title: 'Online Mapping Activated', message: 'If you want to map offline, download tasks on the project home.', alertType: 'info', // See Properties section for full customization // Or check `index.ios.js` or `index.android.js` for a complete example }); } } var cards = []; // iterate over all the tasksI with an interval of the tilesPerRow variable for (var cardX = parseFloat(data.xMin); cardX < parseFloat(data.xMax); cardX += tilesPerRow) { var cardToPush = { cardX: cardX, tileRows: [], validTiles: 0 } // iterate over Y once and place all X tiles for this Y coordinate in the tile cache. for (var tileY = parseFloat(data.yMax); tileY >= parseFloat(data.yMin); tileY -= 1) { var tileRowObject = { rowYStart: tileY, rowYEnd: tileY, cardXStart: cardX, cardXEnd: cardX, tiles: [] }; for (var tileX = parseFloat(cardX); tileX < parseFloat(cardX) + tilesPerRow; tileX += 1) { if (data.tasks[data.zoomLevel + "-" + tileX + "-" + tileY] !== undefined) { cardToPush.validTiles++; } tileRowObject.tiles.push( data.tasks[data.zoomLevel + "-" + tileX + "-" + tileY] === undefined ? "emptytile" : data.tasks[data.zoomLevel + "-" + tileX + "-" + tileY] ); if (tileY > tileRowObject.rowYEnd) { tileRowObject.rowYEnd = tileY; } if (tileX > tileRowObject.cardXEnd) { tileRowObject.cardXEnd = tileX; } } cardToPush.tileRows.push(tileRowObject); } if (cardToPush.validTiles > 0) { // ensure the card has tiles this.totalRenderedCount++; this.allCards[cardToPush.cardX] = cardToPush cards.push(cardToPush); } } this.setState({ cardsInView: cards }) // when done loading, always go to the beginning //this.hanldeCardRender(0); }
generateCards(data) { var tilesPerRow = GLOBAL.TILES_PER_VIEW_X; var tilesPerCol = GLOBAL.TILES_PER_VIEW_Y; this.currentGroup = data.id; this.groupXStart = data.xMin; this.groupXEnd = data.xMax; //console.log("arrrrrrrrrrr"); var key = 'project-' + data.projectId + '-group-' + data.id; //console.log(data.projectId); this.isOfflineGroup = GLOBAL.DB.isOfflineGroup(key); if (this.isOfflineGroup === true) { if (this.lastMode !== 'offline') { this.lastMode = 'offline'; _mapper.props.messageBar.showAlert({ title: 'You are mapping a downloaded group!', message: 'It will work offline! ', alertType: 'info', // See Properties section for full customization // Or check `index.ios.js` or `index.android.js` for a complete example }); } } else { if (this.lastMode !== 'online') { this.lastMode = 'online'; _mapper.props.messageBar.showAlert({ title: 'Online Mapping Activated', message: 'If you want to map offline, download tasks on the project home.', alertType: 'info', // See Properties section for full customization // Or check `index.ios.js` or `index.android.js` for a complete example }); } } var cards = []; // iterate over all the tasksI with an interval of the tilesPerRow variable for (var cardX = parseFloat(data.xMin); cardX < parseFloat(data.xMax); cardX += tilesPerRow) { var cardToPush = { cardX: cardX, tileRows: [], validTiles: 0 } // iterate over Y once and place all X tiles for this Y coordinate in the tile cache. for (var tileY = parseFloat(data.yMax); tileY >= parseFloat(data.yMin); tileY -= 1) { var tileRowObject = { rowYStart: tileY, rowYEnd: tileY, cardXStart: cardX, cardXEnd: cardX, tiles: [] }; for (var tileX = parseFloat(cardX); tileX < parseFloat(cardX) + tilesPerRow; tileX += 1) { if (data.tasks[data.zoomLevel + "-" + tileX + "-" + tileY] !== undefined) { cardToPush.validTiles++; } tileRowObject.tiles.push( data.tasks[data.zoomLevel + "-" + tileX + "-" + tileY] === undefined ? "emptytile" : data.tasks[data.zoomLevel + "-" + tileX + "-" + tileY] ); if (tileY > tileRowObject.rowYEnd) { tileRowObject.rowYEnd = tileY; } if (tileX > tileRowObject.cardXEnd) { tileRowObject.cardXEnd = tileX; } } cardToPush.tileRows.push(tileRowObject); } if (cardToPush.validTiles > 0) { // ensure the card has tiles this.totalRenderedCount++; this.allCards[cardToPush.cardX] = cardToPush cards.push(cardToPush); } } this.setState({ cardsInView: cards }) // when done loading, always go to the beginning //this.hanldeCardRender(0); }
JavaScript
updateMappedDistance(addedDistance) { var startedDistance = this.distance; var parent = this; console.log("updating mapped distance by:" + addedDistance); store.get('currentUser').then(result => { var currentDistance = -1; var newDistance = -1; if (result !== null && result !== undefined && result.distance !== undefined) { currentDistance = result.distance; newDistance = currentDistance + addedDistance; console.log("checking lvl up"); if (parent.getLevelForExp(newDistance) > parent.getLevelForExp(currentDistance)) { parent.pendingLvlUp = parent.getLevelForExp(newDistance); } store.update('currentUser', { distance: newDistance }).then(data => { parent.refreshDistance(); }); // add the added distance in firebase (never override with local value bc it might reset) if (con.isOnline()) { myUserRef.transaction(function (user) { if (user) { user.distance = user.distance + addedDistance; } return user; }) } } }); }
updateMappedDistance(addedDistance) { var startedDistance = this.distance; var parent = this; console.log("updating mapped distance by:" + addedDistance); store.get('currentUser').then(result => { var currentDistance = -1; var newDistance = -1; if (result !== null && result !== undefined && result.distance !== undefined) { currentDistance = result.distance; newDistance = currentDistance + addedDistance; console.log("checking lvl up"); if (parent.getLevelForExp(newDistance) > parent.getLevelForExp(currentDistance)) { parent.pendingLvlUp = parent.getLevelForExp(newDistance); } store.update('currentUser', { distance: newDistance }).then(data => { parent.refreshDistance(); }); // add the added distance in firebase (never override with local value bc it might reset) if (con.isOnline()) { myUserRef.transaction(function (user) { if (user) { user.distance = user.distance + addedDistance; } return user; }) } } }); }
JavaScript
updateContributions(addedContributions) { var parent = this; store.get('currentUser').then(result => { var currentContributions = -1; var newContributions = -1; if (result !== null && result !== undefined && result.contributions !== undefined) { currentContributions = result.contributions; newContributions = currentContributions + addedContributions; store.update('currentUser', { contributions: newContributions }).then(data => { parent.refreshContributions(); }); // add the added contributions in firebase (never override with local value bc it might reset) if (con.isOnline()) { myUserRef.transaction(function (user) { if (user) { user.contributions = user.contributions + addedContributions; } return user; }) } } }); }
updateContributions(addedContributions) { var parent = this; store.get('currentUser').then(result => { var currentContributions = -1; var newContributions = -1; if (result !== null && result !== undefined && result.contributions !== undefined) { currentContributions = result.contributions; newContributions = currentContributions + addedContributions; store.update('currentUser', { contributions: newContributions }).then(data => { parent.refreshContributions(); }); // add the added contributions in firebase (never override with local value bc it might reset) if (con.isOnline()) { myUserRef.transaction(function (user) { if (user) { user.contributions = user.contributions + addedContributions; } return user; }) } } }); }
JavaScript
refreshDistance() { var parent = this; store.get("currentUser").then(data => { if (data !== null && data !== undefined && data.distance !== undefined) { // we have a valid local distance store parent.distance = data.distance; } }); }
refreshDistance() { var parent = this; store.get("currentUser").then(data => { if (data !== null && data !== undefined && data.distance !== undefined) { // we have a valid local distance store parent.distance = data.distance; } }); }
JavaScript
refreshContributions() { var parent = this; store.get("currentUser").then(data => { if (data !== null && data !== undefined && data.contributions !== undefined) { // we have a valid local distance store parent.contributions = data.contributions; } }); }
refreshContributions() { var parent = this; store.get("currentUser").then(data => { if (data !== null && data !== undefined && data.contributions !== undefined) { // we have a valid local distance store parent.contributions = data.contributions; } }); }
JavaScript
compareAndUpdate() { myUserRef = database.ref("/users/" + auth.getUser().uid); var parent = this; myUserRef.once('value', function (data) { var remoteObj = data.val(); console.log("remote data obj"); console.log(remoteObj); store.get("currentUser").then(local => { if (local !== null && local !== undefined && local.distance !== undefined && local.contributions !== undefined) { // IMPORTANT PART! var localDistance = local.distance; var remoteDistance = remoteObj.distance; var localContributions = local.contributions; var remoteContributions = remoteObj.contributions; console.log("remote distance:" + remoteDistance); console.log("local distance:" + localDistance); // compare and sync the necessary objects // distance mapped if (localDistance > remoteDistance) { myUserRef.update({ distance: localDistance }) parent.refreshDistance(); } else if (remoteDistance > localDistance) { store.update('currentUser', { distance: remoteDistance }).then(data => { parent.refreshDistance(); }) } else { parent.refreshDistance(); } console.log("remote contributions:" + remoteContributions); console.log("local contributions:" + localContributions); // contributions if (localContributions > remoteContributions) { myUserRef.update({ contributions: localContributions }) parent.refreshContributions(); } else if (remoteContributions > localContributions) { store.update('currentUser', { contributions: remoteContributions }).then(data => { parent.refreshContributions(); }) } else { parent.refreshContributions(); } } else { store.update('currentUser', remoteObj).then(data => { parent.refreshDistance(); parent.refreshContributions(); }); } }); }); }
compareAndUpdate() { myUserRef = database.ref("/users/" + auth.getUser().uid); var parent = this; myUserRef.once('value', function (data) { var remoteObj = data.val(); console.log("remote data obj"); console.log(remoteObj); store.get("currentUser").then(local => { if (local !== null && local !== undefined && local.distance !== undefined && local.contributions !== undefined) { // IMPORTANT PART! var localDistance = local.distance; var remoteDistance = remoteObj.distance; var localContributions = local.contributions; var remoteContributions = remoteObj.contributions; console.log("remote distance:" + remoteDistance); console.log("local distance:" + localDistance); // compare and sync the necessary objects // distance mapped if (localDistance > remoteDistance) { myUserRef.update({ distance: localDistance }) parent.refreshDistance(); } else if (remoteDistance > localDistance) { store.update('currentUser', { distance: remoteDistance }).then(data => { parent.refreshDistance(); }) } else { parent.refreshDistance(); } console.log("remote contributions:" + remoteContributions); console.log("local contributions:" + localContributions); // contributions if (localContributions > remoteContributions) { myUserRef.update({ contributions: localContributions }) parent.refreshContributions(); } else if (remoteContributions > localContributions) { store.update('currentUser', { contributions: remoteContributions }).then(data => { parent.refreshContributions(); }) } else { parent.refreshContributions(); } } else { store.update('currentUser', remoteObj).then(data => { parent.refreshDistance(); parent.refreshContributions(); }); } }); }); }
JavaScript
refreshOfflineGroups() { var parent = this; store.get("offlineGroups").then(data => { console.log("setting offline groups"); console.log(data); if (data !== null && data !== undefined && data.offlineGroups !== undefined) { parent.offlineGroups = data.offlineGroups; } }); }
refreshOfflineGroups() { var parent = this; store.get("offlineGroups").then(data => { console.log("setting offline groups"); console.log(data); if (data !== null && data !== undefined && data.offlineGroups !== undefined) { parent.offlineGroups = data.offlineGroups; } }); }
JavaScript
isOfflineGroup(key) { for (var i = 0; i < this.offlineGroups.length; i++) { if (this.offlineGroups[i] === key) { console.log("found offline group!" + key); return true; } } return false; }
isOfflineGroup(key) { for (var i = 0; i < this.offlineGroups.length; i++) { if (this.offlineGroups[i] === key) { console.log("found offline group!" + key); return true; } } return false; }
JavaScript
hasOfflineGroups(project) { for (var i = 0; i < this.offlineGroups.length; i++) { if (this.offlineGroups[i].indexOf(project) !== -1) { return true; } } return false; }
hasOfflineGroups(project) { for (var i = 0; i < this.offlineGroups.length; i++) { if (this.offlineGroups[i].indexOf(project) !== -1) { return true; } } return false; }
JavaScript
hasOpenDownloads(project) { var parent = this; console.log("Checking for open downloads on " + project); if (this.totalRequestsOutstanding2[project] === undefined) { return false; } else if (parent.totalRequestsOutstanding2[project] > 0) { return true; } return false; }
hasOpenDownloads(project) { var parent = this; console.log("Checking for open downloads on " + project); if (this.totalRequestsOutstanding2[project] === undefined) { return false; } else if (parent.totalRequestsOutstanding2[project] > 0) { return true; } return false; }
JavaScript
componentDidMount() { var parent = this; GLOBAL.ANALYTICS.logEvent('mapswipe_open'); MessageBarManager.registerMessageBar(parent.refs.alert); parent.checkInterval = setInterval(function () { if (GLOBAL.DB.getPendingLevelUp() > 0) { parent.openModal3(GLOBAL.DB.getPendingLevelUp()); GLOBAL.DB.setPendingLevelUp(-1); } }, 500); }
componentDidMount() { var parent = this; GLOBAL.ANALYTICS.logEvent('mapswipe_open'); MessageBarManager.registerMessageBar(parent.refs.alert); parent.checkInterval = setInterval(function () { if (GLOBAL.DB.getPendingLevelUp() > 0) { parent.openModal3(GLOBAL.DB.getPendingLevelUp()); GLOBAL.DB.setPendingLevelUp(-1); } }, 500); }
JavaScript
isLoggedIn() { var user = this.firebase.auth().currentUser; //console.log("user logged in said: " + (user != null)); return user != null; }
isLoggedIn() { var user = this.firebase.auth().currentUser; //console.log("user logged in said: " + (user != null)); return user != null; }
JavaScript
addListeners() { //console.log("adde listeners"); var parent = this; this.firebase.auth().onAuthStateChanged(function (user) { parent.hasReceivedLoginStatus = true; if (user) { //console.log("we're signed in"); //console.log((parent.isLoggedIn()) + " login status"); } else { //console.log("not signed in.."); } }); }
addListeners() { //console.log("adde listeners"); var parent = this; this.firebase.auth().onAuthStateChanged(function (user) { parent.hasReceivedLoginStatus = true; if (user) { //console.log("we're signed in"); //console.log((parent.isLoggedIn()) + " login status"); } else { //console.log("not signed in.."); } }); }
JavaScript
function runModifiers(modifiers, data, ends) { var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends)); modifiersToRun.forEach(function (modifier) { if (modifier.function) { console.warn('`modifier.function` is deprecated, use `modifier.fn`!'); } var fn = modifier.function || modifier.fn; if (modifier.enabled && isFunction$1(fn)) { // Add properties to offsets to make them a complete clientRect object // we do this before each modifier to make sure the previous one doesn't // mess with these values data.offsets.popper = getClientRect(data.offsets.popper); data.offsets.reference = getClientRect(data.offsets.reference); data = fn(data, modifier); } }); return data; }
function runModifiers(modifiers, data, ends) { var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends)); modifiersToRun.forEach(function (modifier) { if (modifier.function) { console.warn('`modifier.function` is deprecated, use `modifier.fn`!'); } var fn = modifier.function || modifier.fn; if (modifier.enabled && isFunction$1(fn)) { // Add properties to offsets to make them a complete clientRect object // we do this before each modifier to make sure the previous one doesn't // mess with these values data.offsets.popper = getClientRect(data.offsets.popper); data.offsets.reference = getClientRect(data.offsets.reference); data = fn(data, modifier); } }); return data; }
JavaScript
function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck$1(this, Popper); this.scheduleUpdate = function () { return requestAnimationFrame(_this.update); }; // make update() debounced, so that it only runs at most once-per-tick this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it this.options = _extends$1({}, Popper.Defaults, options); // init state this.state = { isDestroyed: false, isCreated: false, scrollParents: [] }; // get reference and popper elements (allow jQuery wrappers) this.reference = reference.jquery ? reference[0] : reference; this.popper = popper.jquery ? popper[0] : popper; // Deep merge modifiers options this.options.modifiers = {}; Object.keys(_extends$1({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) { _this.options.modifiers[name] = _extends$1({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {}); }); // Refactoring modifiers' list (Object => Array) this.modifiers = Object.keys(this.options.modifiers).map(function (name) { return _extends$1({ name: name }, _this.options.modifiers[name]); }) // sort the modifiers by order .sort(function (a, b) { return a.order - b.order; }); // modifiers have the ability to execute arbitrary code when Popper.js get inited // such code is executed in the same order of its modifier // they could add new properties to their options configuration // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! this.modifiers.forEach(function (modifierOptions) { if (modifierOptions.enabled && isFunction$1(modifierOptions.onLoad)) { modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); } }); // fire the first update to position the popper in the right place this.update(); var eventsEnabled = this.options.eventsEnabled; if (eventsEnabled) { // setup event listeners, they will take care of update the position in specific situations this.enableEventListeners(); } this.state.eventsEnabled = eventsEnabled; }
function Popper(reference, popper) { var _this = this; var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; classCallCheck$1(this, Popper); this.scheduleUpdate = function () { return requestAnimationFrame(_this.update); }; // make update() debounced, so that it only runs at most once-per-tick this.update = debounce(this.update.bind(this)); // with {} we create a new object with the options inside it this.options = _extends$1({}, Popper.Defaults, options); // init state this.state = { isDestroyed: false, isCreated: false, scrollParents: [] }; // get reference and popper elements (allow jQuery wrappers) this.reference = reference.jquery ? reference[0] : reference; this.popper = popper.jquery ? popper[0] : popper; // Deep merge modifiers options this.options.modifiers = {}; Object.keys(_extends$1({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) { _this.options.modifiers[name] = _extends$1({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {}); }); // Refactoring modifiers' list (Object => Array) this.modifiers = Object.keys(this.options.modifiers).map(function (name) { return _extends$1({ name: name }, _this.options.modifiers[name]); }) // sort the modifiers by order .sort(function (a, b) { return a.order - b.order; }); // modifiers have the ability to execute arbitrary code when Popper.js get inited // such code is executed in the same order of its modifier // they could add new properties to their options configuration // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! this.modifiers.forEach(function (modifierOptions) { if (modifierOptions.enabled && isFunction$1(modifierOptions.onLoad)) { modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); } }); // fire the first update to position the popper in the right place this.update(); var eventsEnabled = this.options.eventsEnabled; if (eventsEnabled) { // setup event listeners, they will take care of update the position in specific situations this.enableEventListeners(); } this.state.eventsEnabled = eventsEnabled; }
JavaScript
function Tooltip(reference, options) { classCallCheck(this, Tooltip); _initialiseProps.call(this); // apply user options over default ones options = _extends({}, DEFAULT_OPTIONS, options); reference.jquery && (reference = reference[0]); // cache reference and options this.reference = reference; this.options = options; // get events list var events = typeof options.trigger === 'string' ? options.trigger.split(' ').filter(function (trigger) { return ['click', 'hover', 'focus'].indexOf(trigger) !== -1; }) : []; // set initial state this._isOpen = false; // set event listeners this._setEventListeners(reference, events, options); }
function Tooltip(reference, options) { classCallCheck(this, Tooltip); _initialiseProps.call(this); // apply user options over default ones options = _extends({}, DEFAULT_OPTIONS, options); reference.jquery && (reference = reference[0]); // cache reference and options this.reference = reference; this.options = options; // get events list var events = typeof options.trigger === 'string' ? options.trigger.split(' ').filter(function (trigger) { return ['click', 'hover', 'focus'].indexOf(trigger) !== -1; }) : []; // set initial state this._isOpen = false; // set event listeners this._setEventListeners(reference, events, options); }
JavaScript
function addClasses(el, classes) { var newClasses = convertToArray(classes); var classList = convertToArray(el.className); newClasses.forEach(function (newClass) { if (classList.indexOf(newClass) === -1) { classList.push(newClass); } }); el.className = classList.join(' '); }
function addClasses(el, classes) { var newClasses = convertToArray(classes); var classList = convertToArray(el.className); newClasses.forEach(function (newClass) { if (classList.indexOf(newClass) === -1) { classList.push(newClass); } }); el.className = classList.join(' '); }
JavaScript
appendAction(fact) { if (!fact || this.hasSessionOrAction() || currentUser() !== fact["spacy.domain/sponsor"]) { return; } const session = fact["spacy.domain/session"]; const el = this.actionTemplate(); const idField = el.querySelector("[name=id]"); idField.value = session["spacy.domain/id"]; this.appendChild(el); }
appendAction(fact) { if (!fact || this.hasSessionOrAction() || currentUser() !== fact["spacy.domain/sponsor"]) { return; } const session = fact["spacy.domain/session"]; const el = this.actionTemplate(); const idField = el.querySelector("[name=id]"); idField.value = session["spacy.domain/id"]; this.appendChild(el); }
JavaScript
async function loadImage(imgName) { return cv.imreadAsync("img_in/" + imgName + ".jpg", BW ? cv.IMREAD_GRAYSCALE : cv.IMREAD_COLOR) .then(img => { // Resize input; return img; // .resize(RESIZED_IMG_WIDTH, RESIZED_IMG_WIDTH); }); }
async function loadImage(imgName) { return cv.imreadAsync("img_in/" + imgName + ".jpg", BW ? cv.IMREAD_GRAYSCALE : cv.IMREAD_COLOR) .then(img => { // Resize input; return img; // .resize(RESIZED_IMG_WIDTH, RESIZED_IMG_WIDTH); }); }
JavaScript
async function processImage(img, size, channel) { // Allocate image data; const image = cu.DeviceArray("int", size * size); const image2 = cu.DeviceArray("float", size, size); const image3 = cu.DeviceArray("int", size * size); const kernel_small = cu.DeviceArray("float", KERNEL_SMALL_DIAMETER, KERNEL_SMALL_DIAMETER); const kernel_large = cu.DeviceArray("float", KERNEL_LARGE_DIAMETER, KERNEL_LARGE_DIAMETER); const kernel_unsharpen = cu.DeviceArray("float", KERNEL_UNSHARPEN_DIAMETER, KERNEL_UNSHARPEN_DIAMETER); const maximum_1 = cu.DeviceArray("float", 1); const minimum_1 = cu.DeviceArray("float", 1); const maximum_2 = cu.DeviceArray("float", 1); const minimum_2 = cu.DeviceArray("float", 1); const mask_small = cu.DeviceArray("float", size, size); const mask_large = cu.DeviceArray("float", size, size); const image_unsharpen = cu.DeviceArray("float", size, size); const blurred_small = cu.DeviceArray("float", size, size); const blurred_large = cu.DeviceArray("float", size, size); const blurred_unsharpen = cu.DeviceArray("float", size, size); const lut = cu.DeviceArray("int", CDEPTH); const s0 = System.nanoTime(); // Initialize the LUT; copy_array(LUT[channel], lut); const e0 = System.nanoTime(); console.log("--lut=" + intervalToMs(s0, e0) + " ms"); // Fill the image data; const s1 = System.nanoTime(); // image.copyFrom(img, size * size); copy_array(image, img); const e1 = System.nanoTime(); console.log("--img to device array=" + intervalToMs(s1, e1) + " ms"); const start = System.nanoTime(); // Create Gaussian kernels; gaussian_kernel(kernel_small, KERNEL_SMALL_DIAMETER, KERNEL_SMALL_VARIANCE); gaussian_kernel(kernel_large, KERNEL_LARGE_DIAMETER, KERNEL_LARGE_VARIANCE); gaussian_kernel(kernel_unsharpen, KERNEL_UNSHARPEN_DIAMETER, KERNEL_UNSHARPEN_VARIANCE); // Main GPU computation; // Blur - Small; GAUSSIAN_BLUR_KERNEL([BLOCKS, BLOCKS], [THREADS_2D, THREADS_2D], 4 * KERNEL_SMALL_DIAMETER * KERNEL_SMALL_DIAMETER)( image, blurred_small, size, size, kernel_small, KERNEL_SMALL_DIAMETER); // Blur - Large; GAUSSIAN_BLUR_KERNEL([BLOCKS, BLOCKS], [THREADS_2D, THREADS_2D], 4 * KERNEL_LARGE_DIAMETER * KERNEL_LARGE_DIAMETER)( image, blurred_large, size, size, kernel_large, KERNEL_LARGE_DIAMETER); // Blur - Unsharpen; GAUSSIAN_BLUR_KERNEL([BLOCKS, BLOCKS], [THREADS_2D, THREADS_2D], 4 * KERNEL_UNSHARPEN_DIAMETER * KERNEL_UNSHARPEN_DIAMETER)( image, blurred_unsharpen, size, size, kernel_unsharpen, KERNEL_UNSHARPEN_DIAMETER); // Sobel filter (edge detection); SOBEL_KERNEL([BLOCKS, BLOCKS], [THREADS_2D, THREADS_2D])( blurred_small, mask_small, size, size); SOBEL_KERNEL([BLOCKS, BLOCKS], [THREADS_2D, THREADS_2D])( blurred_large, mask_large, size, size); // Ensure that the output of Sobel is in [0, 1]; MAXIMUM_KERNEL(BLOCKS * 2, THREADS_1D)(mask_small, maximum_1, size * size); MINIMUM_KERNEL(BLOCKS * 2, THREADS_1D)(mask_small, minimum_1, size * size); EXTEND_KERNEL(BLOCKS * 2, THREADS_1D)(mask_small, minimum_1, maximum_1, size * size, 1); // Extend large edge detection mask, and normalize it; MAXIMUM_KERNEL(BLOCKS * 2, THREADS_1D)(mask_large, maximum_2, size * size); MINIMUM_KERNEL(BLOCKS * 2, THREADS_1D)(mask_large, minimum_2, size * size); EXTEND_KERNEL(BLOCKS * 2, THREADS_1D)(mask_large, minimum_2, maximum_2, size * size, 5); // Unsharpen; UNSHARPEN_KERNEL(BLOCKS * 2, THREADS_1D)( image, blurred_unsharpen, image_unsharpen, UNSHARPEN_AMOUNT, size * size); // Combine results; COMBINE_KERNEL(BLOCKS * 2, THREADS_1D)( image_unsharpen, blurred_large, mask_large, image2, size * size); COMBINE_KERNEL_LUT(BLOCKS * 2, THREADS_1D)( image2, blurred_small, mask_small, image3, size * size, lut); // Store the image data. const tmp = image3[0]; // Used only to "sync" the GPU computation and obtain the GPU computation time; const end = System.nanoTime(); console.log("--cuda time=" + intervalToMs(start, end) + " ms"); const s2 = System.nanoTime(); // copy_array(img, image3); img.set(image3); const e2 = System.nanoTime(); console.log("--device array to image=" + intervalToMs(s2, e2) + " ms"); return img; }
async function processImage(img, size, channel) { // Allocate image data; const image = cu.DeviceArray("int", size * size); const image2 = cu.DeviceArray("float", size, size); const image3 = cu.DeviceArray("int", size * size); const kernel_small = cu.DeviceArray("float", KERNEL_SMALL_DIAMETER, KERNEL_SMALL_DIAMETER); const kernel_large = cu.DeviceArray("float", KERNEL_LARGE_DIAMETER, KERNEL_LARGE_DIAMETER); const kernel_unsharpen = cu.DeviceArray("float", KERNEL_UNSHARPEN_DIAMETER, KERNEL_UNSHARPEN_DIAMETER); const maximum_1 = cu.DeviceArray("float", 1); const minimum_1 = cu.DeviceArray("float", 1); const maximum_2 = cu.DeviceArray("float", 1); const minimum_2 = cu.DeviceArray("float", 1); const mask_small = cu.DeviceArray("float", size, size); const mask_large = cu.DeviceArray("float", size, size); const image_unsharpen = cu.DeviceArray("float", size, size); const blurred_small = cu.DeviceArray("float", size, size); const blurred_large = cu.DeviceArray("float", size, size); const blurred_unsharpen = cu.DeviceArray("float", size, size); const lut = cu.DeviceArray("int", CDEPTH); const s0 = System.nanoTime(); // Initialize the LUT; copy_array(LUT[channel], lut); const e0 = System.nanoTime(); console.log("--lut=" + intervalToMs(s0, e0) + " ms"); // Fill the image data; const s1 = System.nanoTime(); // image.copyFrom(img, size * size); copy_array(image, img); const e1 = System.nanoTime(); console.log("--img to device array=" + intervalToMs(s1, e1) + " ms"); const start = System.nanoTime(); // Create Gaussian kernels; gaussian_kernel(kernel_small, KERNEL_SMALL_DIAMETER, KERNEL_SMALL_VARIANCE); gaussian_kernel(kernel_large, KERNEL_LARGE_DIAMETER, KERNEL_LARGE_VARIANCE); gaussian_kernel(kernel_unsharpen, KERNEL_UNSHARPEN_DIAMETER, KERNEL_UNSHARPEN_VARIANCE); // Main GPU computation; // Blur - Small; GAUSSIAN_BLUR_KERNEL([BLOCKS, BLOCKS], [THREADS_2D, THREADS_2D], 4 * KERNEL_SMALL_DIAMETER * KERNEL_SMALL_DIAMETER)( image, blurred_small, size, size, kernel_small, KERNEL_SMALL_DIAMETER); // Blur - Large; GAUSSIAN_BLUR_KERNEL([BLOCKS, BLOCKS], [THREADS_2D, THREADS_2D], 4 * KERNEL_LARGE_DIAMETER * KERNEL_LARGE_DIAMETER)( image, blurred_large, size, size, kernel_large, KERNEL_LARGE_DIAMETER); // Blur - Unsharpen; GAUSSIAN_BLUR_KERNEL([BLOCKS, BLOCKS], [THREADS_2D, THREADS_2D], 4 * KERNEL_UNSHARPEN_DIAMETER * KERNEL_UNSHARPEN_DIAMETER)( image, blurred_unsharpen, size, size, kernel_unsharpen, KERNEL_UNSHARPEN_DIAMETER); // Sobel filter (edge detection); SOBEL_KERNEL([BLOCKS, BLOCKS], [THREADS_2D, THREADS_2D])( blurred_small, mask_small, size, size); SOBEL_KERNEL([BLOCKS, BLOCKS], [THREADS_2D, THREADS_2D])( blurred_large, mask_large, size, size); // Ensure that the output of Sobel is in [0, 1]; MAXIMUM_KERNEL(BLOCKS * 2, THREADS_1D)(mask_small, maximum_1, size * size); MINIMUM_KERNEL(BLOCKS * 2, THREADS_1D)(mask_small, minimum_1, size * size); EXTEND_KERNEL(BLOCKS * 2, THREADS_1D)(mask_small, minimum_1, maximum_1, size * size, 1); // Extend large edge detection mask, and normalize it; MAXIMUM_KERNEL(BLOCKS * 2, THREADS_1D)(mask_large, maximum_2, size * size); MINIMUM_KERNEL(BLOCKS * 2, THREADS_1D)(mask_large, minimum_2, size * size); EXTEND_KERNEL(BLOCKS * 2, THREADS_1D)(mask_large, minimum_2, maximum_2, size * size, 5); // Unsharpen; UNSHARPEN_KERNEL(BLOCKS * 2, THREADS_1D)( image, blurred_unsharpen, image_unsharpen, UNSHARPEN_AMOUNT, size * size); // Combine results; COMBINE_KERNEL(BLOCKS * 2, THREADS_1D)( image_unsharpen, blurred_large, mask_large, image2, size * size); COMBINE_KERNEL_LUT(BLOCKS * 2, THREADS_1D)( image2, blurred_small, mask_small, image3, size * size, lut); // Store the image data. const tmp = image3[0]; // Used only to "sync" the GPU computation and obtain the GPU computation time; const end = System.nanoTime(); console.log("--cuda time=" + intervalToMs(start, end) + " ms"); const s2 = System.nanoTime(); // copy_array(img, image3); img.set(image3); const e2 = System.nanoTime(); console.log("--device array to image=" + intervalToMs(s2, e2) + " ms"); return img; }
JavaScript
async function imagePipeline(imgName, count) { try { // Load image; const start = System.nanoTime(); let img = await loadImage(imgName); const endLoad = System.nanoTime(); // Process image; if (BW) img = await processImageBW(img); else img = await processImageColor(img); const endProcess = System.nanoTime(); // Store image; await storeImage(img, imgName + "_" + count) const endStore = System.nanoTime(); console.log("- total time=" + intervalToMs(start, endStore) + ", load=" + intervalToMs(start, endLoad) + ", processing=" + intervalToMs(endLoad, endProcess) + ", store=" + intervalToMs(endProcess, endStore)); } catch (err) { console.error(err); } }
async function imagePipeline(imgName, count) { try { // Load image; const start = System.nanoTime(); let img = await loadImage(imgName); const endLoad = System.nanoTime(); // Process image; if (BW) img = await processImageBW(img); else img = await processImageColor(img); const endProcess = System.nanoTime(); // Store image; await storeImage(img, imgName + "_" + count) const endStore = System.nanoTime(); console.log("- total time=" + intervalToMs(start, endStore) + ", load=" + intervalToMs(start, endLoad) + ", processing=" + intervalToMs(endLoad, endProcess) + ", store=" + intervalToMs(endProcess, endStore)); } catch (err) { console.error(err); } }
JavaScript
function createRoot(fn) { const prevTracking = tracking, rootUpdate = { _children: [] }; tracking = rootUpdate; const result = fn(() => { _unsubscribe(rootUpdate); tracking = undefined; }); tracking = prevTracking; return result; }
function createRoot(fn) { const prevTracking = tracking, rootUpdate = { _children: [] }; tracking = rootUpdate; const result = fn(() => { _unsubscribe(rootUpdate); tracking = undefined; }); tracking = prevTracking; return result; }
JavaScript
function createComputations1000to1(n, sources) { for (var i = 0; i < n; i++) { createComputation1000(sources, i * 1000); } }
function createComputations1000to1(n, sources) { for (var i = 0; i < n; i++) { createComputation1000(sources, i * 1000); } }
JavaScript
function root(fn) { const prevTracking = tracking; const rootUpdate = () => {}; tracking = rootUpdate; resetUpdate(rootUpdate); const result = fn(() => { _unsubscribe(rootUpdate); tracking = undefined; }); tracking = prevTracking; return result; }
function root(fn) { const prevTracking = tracking; const rootUpdate = () => {}; tracking = rootUpdate; resetUpdate(rootUpdate); const result = fn(() => { _unsubscribe(rootUpdate); tracking = undefined; }); tracking = prevTracking; return result; }
JavaScript
function transaction(fn) { let prevQueue = queue; queue = []; const result = fn(); let q = queue; queue = prevQueue; q.forEach(data => { if (data._pending !== EMPTY_ARR) { const pending = data._pending; data._pending = EMPTY_ARR; data(pending); } }); return result; }
function transaction(fn) { let prevQueue = queue; queue = []; const result = fn(); let q = queue; queue = prevQueue; q.forEach(data => { if (data._pending !== EMPTY_ARR) { const pending = data._pending; data._pending = EMPTY_ARR; data(pending); } }); return result; }
JavaScript
function observable(value) { function data(nextValue) { if (arguments.length === 0) { if (tracking && !data._observers.has(tracking)) { data._observers.add(tracking); tracking._observables.push(data); } return value; } if (queue) { if (data._pending === EMPTY_ARR) { queue.push(data); } data._pending = nextValue; return nextValue; } value = nextValue; // Clear `tracking` otherwise a computed triggered by a set // in another computed is seen as a child of that other computed. const clearedUpdate = tracking; tracking = undefined; // Update can alter data._observers, make a copy before running. data._runObservers = new Set(data._observers); data._runObservers.forEach(observer => (observer._fresh = false)); data._runObservers.forEach(observer => { if (!observer._fresh) observer(); }); tracking = clearedUpdate; return value; } // Tiny indicator that this is an observable function. data._observers = new Set(); // The 'not set' value must be unique, so `nullish` can be set in a transaction. data._pending = EMPTY_ARR; return [data, data]; }
function observable(value) { function data(nextValue) { if (arguments.length === 0) { if (tracking && !data._observers.has(tracking)) { data._observers.add(tracking); tracking._observables.push(data); } return value; } if (queue) { if (data._pending === EMPTY_ARR) { queue.push(data); } data._pending = nextValue; return nextValue; } value = nextValue; // Clear `tracking` otherwise a computed triggered by a set // in another computed is seen as a child of that other computed. const clearedUpdate = tracking; tracking = undefined; // Update can alter data._observers, make a copy before running. data._runObservers = new Set(data._observers); data._runObservers.forEach(observer => (observer._fresh = false)); data._runObservers.forEach(observer => { if (!observer._fresh) observer(); }); tracking = clearedUpdate; return value; } // Tiny indicator that this is an observable function. data._observers = new Set(); // The 'not set' value must be unique, so `nullish` can be set in a transaction. data._pending = EMPTY_ARR; return [data, data]; }
JavaScript
function computed(observer, value) { observer._update = update; // if (tracking == null) { // console.warn("computations created without a root or parent will never be disposed"); // } resetUpdate(update); update(); function update() { const prevTracking = tracking; if (tracking) { tracking._children.push(update); } const prevChildren = update._children; _unsubscribe(update); update._fresh = true; tracking = update; value = observer(value); // If any children computations were removed mark them as fresh. // Check the diff of the children list between pre and post update. prevChildren.forEach(u => { if (update._children.indexOf(u) === -1) { u._fresh = true; } }); // If any children were marked as fresh remove them from the run lists. const allChildren = getChildrenDeep(update._children); allChildren.forEach(removeFreshChildren); tracking = prevTracking; return value; } function data() { if (update._fresh) { update._observables.forEach(o => o()); } else { value = update(); } return value; } return data; }
function computed(observer, value) { observer._update = update; // if (tracking == null) { // console.warn("computations created without a root or parent will never be disposed"); // } resetUpdate(update); update(); function update() { const prevTracking = tracking; if (tracking) { tracking._children.push(update); } const prevChildren = update._children; _unsubscribe(update); update._fresh = true; tracking = update; value = observer(value); // If any children computations were removed mark them as fresh. // Check the diff of the children list between pre and post update. prevChildren.forEach(u => { if (update._children.indexOf(u) === -1) { u._fresh = true; } }); // If any children were marked as fresh remove them from the run lists. const allChildren = getChildrenDeep(update._children); allChildren.forEach(removeFreshChildren); tracking = prevTracking; return value; } function data() { if (update._fresh) { update._observables.forEach(o => o()); } else { value = update(); } return value; } return data; }
JavaScript
function cleanup(fn) { if (tracking) { tracking._cleanups.push(fn); } return fn; }
function cleanup(fn) { if (tracking) { tracking._cleanups.push(fn); } return fn; }
JavaScript
function patchUser(data, userId) { this.logger.debug('Patching user'); return new q.Promise((resolve, reject) => { this.getAuthorization().then((auth) => { this.logger.debug('Got authorization'); this.logger.debug('Sending request'); request .patch(`${this.settings.apiUrl}/users/${userId}`) .send(addContainer(data)) .set('Authorization', auth) .set('Accept', 'application/json') .end((err, res) => { if (err) { this.logger.error('Error while patching user', res.body); reject(res.body); } else { this.logger.debug('Pathed user', userId); resolve(res.body.data); } }); }); }); }
function patchUser(data, userId) { this.logger.debug('Patching user'); return new q.Promise((resolve, reject) => { this.getAuthorization().then((auth) => { this.logger.debug('Got authorization'); this.logger.debug('Sending request'); request .patch(`${this.settings.apiUrl}/users/${userId}`) .send(addContainer(data)) .set('Authorization', auth) .set('Accept', 'application/json') .end((err, res) => { if (err) { this.logger.error('Error while patching user', res.body); reject(res.body); } else { this.logger.debug('Pathed user', userId); resolve(res.body.data); } }); }); }); }
JavaScript
function deleteUser(userId) { return new q.Promise((resolve, reject) => { this.logger.debug(`Deleting user ${userId}`); this.getAuthorization().then((auth) => { this.logger.debug('Got authorization'); request .delete(`${this.settings.apiUrl}/users/${userId}`) .set('Authorization', auth) .set('Accept', 'application/json') .end((err, res) => { if (err) { this.logger.error('Error while deleting user', res.body); reject(res.body); } else { this.logger.debug('Deleted user', userId); resolve(); } }); }); }); }
function deleteUser(userId) { return new q.Promise((resolve, reject) => { this.logger.debug(`Deleting user ${userId}`); this.getAuthorization().then((auth) => { this.logger.debug('Got authorization'); request .delete(`${this.settings.apiUrl}/users/${userId}`) .set('Authorization', auth) .set('Accept', 'application/json') .end((err, res) => { if (err) { this.logger.error('Error while deleting user', res.body); reject(res.body); } else { this.logger.debug('Deleted user', userId); resolve(); } }); }); }); }
JavaScript
function addContainer(data) { return ({ data: { attributes: data, }, }); }
function addContainer(data) { return ({ data: { attributes: data, }, }); }
JavaScript
function updateControls() { var query = $.trim($("input[name=query]").val()); $("#btnPin") .attr("disabled", !taxonTree.getActiveNode()); $("#btnUnpin") .attr("disabled", !taxonTree.isFilterActive()) .toggleClass("btn-success", taxonTree.isFilterActive()); $("#btnResetSearch") .attr("disabled", query.length === 0); $("#btnSearch") .attr("disabled", query.length < 2); }
function updateControls() { var query = $.trim($("input[name=query]").val()); $("#btnPin") .attr("disabled", !taxonTree.getActiveNode()); $("#btnUnpin") .attr("disabled", !taxonTree.isFilterActive()) .toggleClass("btn-success", taxonTree.isFilterActive()); $("#btnResetSearch") .attr("disabled", query.length === 0); $("#btnSearch") .attr("disabled", query.length < 2); }
JavaScript
function _delay(tag, ms, callback) { /*jshint -W040:true */ var self = this; tag = "" + (tag || "default"); if( timerMap[tag] != null ) { clearTimeout(timerMap[tag]); delete timerMap[tag]; // console.log("Cancel timer '" + tag + "'"); } if( ms == null || callback == null ) { return; } // console.log("Start timer '" + tag + "'"); timerMap[tag] = setTimeout(function(){ // console.log("Execute timer '" + tag + "'"); callback.call(self); }, +ms); }
function _delay(tag, ms, callback) { /*jshint -W040:true */ var self = this; tag = "" + (tag || "default"); if( timerMap[tag] != null ) { clearTimeout(timerMap[tag]); delete timerMap[tag]; // console.log("Cancel timer '" + tag + "'"); } if( ms == null || callback == null ) { return; } // console.log("Start timer '" + tag + "'"); timerMap[tag] = setTimeout(function(){ // console.log("Execute timer '" + tag + "'"); callback.call(self); }, +ms); }
JavaScript
function isHandled(object) { //We check for the exsistence of an attributes property if(object.hasOwnProperty('attributes')){ return true; } log.debug('object'+stringify(object)+' is not handled'); return false; }
function isHandled(object) { //We check for the exsistence of an attributes property if(object.hasOwnProperty('attributes')){ return true; } log.debug('object'+stringify(object)+' is not handled'); return false; }
JavaScript
function handle(context) { var object=context.object||{}; var config=context.config; var fields=config.storeFields; var url; var uuid; var field; //Go through all of the targeted fields for(var index in fields){ utility.isPresent(object.attributes,fields[index],function(){ //Current field been examined field=fields[index]; //Obtain the uuid url=object.attributes[field]; uuid=getUUID(url); //Check if it is a valid uuid and create a new url if((uuid)&&(utility.isValidUuid(uuid))){ log.debug('creating a new url for '+url); object.attributes[field]=getUrl(url,config,object); } }); } //log.debug(object); return true; }
function handle(context) { var object=context.object||{}; var config=context.config; var fields=config.storeFields; var url; var uuid; var field; //Go through all of the targeted fields for(var index in fields){ utility.isPresent(object.attributes,fields[index],function(){ //Current field been examined field=fields[index]; //Obtain the uuid url=object.attributes[field]; uuid=getUUID(url); //Check if it is a valid uuid and create a new url if((uuid)&&(utility.isValidUuid(uuid))){ log.debug('creating a new url for '+url); object.attributes[field]=getUrl(url,config,object); } }); } //log.debug(object); return true; }
JavaScript
function dataInjectToRoles(roles, asset) { var roleList = []; var changedRole; //Go through each role utility.each(roles, function (role) { changedRole = dataInjectToRole(role, asset); roleList.push(changedRole); }); return roleList; }
function dataInjectToRoles(roles, asset) { var roleList = []; var changedRole; //Go through each role utility.each(roles, function (role) { changedRole = dataInjectToRole(role, asset); roleList.push(changedRole); }); return roleList; }
JavaScript
function dataInjectToRole(role, asset) { role = inject(role, asset); role = inject(role, asset.attributes); return role; }
function dataInjectToRole(role, asset) { role = inject(role, asset); role = inject(role, asset.attributes); return role; }
JavaScript
function inject(string, object) { //Go through all properties of an object utility.each(object, function (value, key) { string = string.replace('{' + key + '}', value); }); return string; }
function inject(string, object) { //Go through all properties of an object utility.each(object, function (value, key) { string = string.replace('{' + key + '}', value); }); return string; }
JavaScript
function findField(uuid,asset){ var attributes=asset.attributes||{}; for(var field in attributes){ if(attributes[field]==uuid){ return field; } } return null; }
function findField(uuid,asset){ var attributes=asset.attributes||{}; for(var field in attributes){ if(attributes[field]==uuid){ return field; } } return null; }
JavaScript
function addFile(fileObj) { var tenantId = fileObj.tenantId || carbon.server.superTenant.tenantId; var registry = es.server.systemRegistry(tenantId); var resource = {}; resource.content = fileObj.file.getStream(); var extension = ref.getExtension(fileObj.file); resource.mediaType = ref.getMimeType(extension); resource.uuid = uuid.generate(); resource.name = fileObj.file.getName(); resource.properties = {}; resource.properties.extension = extension; var pathSuffix = fileObj.type + "/" + fileObj.assetId + "/" + fileObj.fieldName; var path = pathPrefix + pathSuffix; registry.put(path, resource); return fileObj.fieldName; }
function addFile(fileObj) { var tenantId = fileObj.tenantId || carbon.server.superTenant.tenantId; var registry = es.server.systemRegistry(tenantId); var resource = {}; resource.content = fileObj.file.getStream(); var extension = ref.getExtension(fileObj.file); resource.mediaType = ref.getMimeType(extension); resource.uuid = uuid.generate(); resource.name = fileObj.file.getName(); resource.properties = {}; resource.properties.extension = extension; var pathSuffix = fileObj.type + "/" + fileObj.assetId + "/" + fileObj.fieldName; var path = pathPrefix + pathSuffix; registry.put(path, resource); return fileObj.fieldName; }
JavaScript
function fetchTagsOfType(assetType) { $.ajax({ url: TAG_API + assetType + 's', type: 'GET', success: function (response) { var tags = JSON.parse(response); //console.log('obtaining tags of type.'); fetchTagsOfAsset(assetType, assetId, tags); }, error: function () { //console.log('unable to retrieve tags for ' + assetTYpe); } }); }
function fetchTagsOfType(assetType) { $.ajax({ url: TAG_API + assetType + 's', type: 'GET', success: function (response) { var tags = JSON.parse(response); //console.log('obtaining tags of type.'); fetchTagsOfAsset(assetType, assetId, tags); }, error: function () { //console.log('unable to retrieve tags for ' + assetTYpe); } }); }
JavaScript
function fetchTagsOfAsset(assetType, assetId, masterTags) { $.ajax({ url: TAG_API + assetType + '/' + assetId, type: 'GET', success: function (response) { var tags = JSON.parse(response); //Initialize the tag container $(TAG_CONTAINER).tokenInput(masterTags, {theme: TAG_THEME, prePopulate: tags, preventDuplicates: false, onAdd: onAdd, allowFreeTagging: true, onDelete: onRemove}); } }); }
function fetchTagsOfAsset(assetType, assetId, masterTags) { $.ajax({ url: TAG_API + assetType + '/' + assetId, type: 'GET', success: function (response) { var tags = JSON.parse(response); //Initialize the tag container $(TAG_CONTAINER).tokenInput(masterTags, {theme: TAG_THEME, prePopulate: tags, preventDuplicates: false, onAdd: onAdd, allowFreeTagging: true, onDelete: onRemove}); } }); }
JavaScript
function onAdd(item) { var data = {}; var tags = [item.name]; data['tags'] = tags; //Make an api call to add the tag $.ajax({ url: TAG_API + assetType + '/' + assetId, type: 'PUT', data: JSON.stringify(data), contentType:'application/json; charset=utf-8', dataType:'json', success:function(response){ }, error:function(e){ createMessage(MSG_CONTAINER,ERROR_CSS,'Unable to add the selected tag.'); } }); }
function onAdd(item) { var data = {}; var tags = [item.name]; data['tags'] = tags; //Make an api call to add the tag $.ajax({ url: TAG_API + assetType + '/' + assetId, type: 'PUT', data: JSON.stringify(data), contentType:'application/json; charset=utf-8', dataType:'json', success:function(response){ }, error:function(e){ createMessage(MSG_CONTAINER,ERROR_CSS,'Unable to add the selected tag.'); } }); }
JavaScript
function onRemove(item) { var data = {}; var tags = [item.name]; data['tags'] = tags; //Make an api call to add the tag $.ajax({ url: TAG_API + assetType + '/' + assetId+'/'+item.name, type: 'DELETE', success:function(response){ }, error:function(){ createMessage(MSG_CONTAINER,ERROR_CSS,'Unable to detach the selected tag.'); } }); }
function onRemove(item) { var data = {}; var tags = [item.name]; data['tags'] = tags; //Make an api call to add the tag $.ajax({ url: TAG_API + assetType + '/' + assetId+'/'+item.name, type: 'DELETE', success:function(response){ }, error:function(){ createMessage(MSG_CONTAINER,ERROR_CSS,'Unable to detach the selected tag.'); } }); }
JavaScript
function createMessage(containerElement,cssClass,msg){ var date=new Date(); var time=date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear()+' '+date.getHours()+':'+date.getMinutes() +':'+date.getSeconds(); var infoMessage='<div class="'+cssClass+'">' +'<a data-dismiss="alert" class="close">x</a>' +time+' '+msg+'</div'; //Place the message $(containerElement).html(infoMessage); }
function createMessage(containerElement,cssClass,msg){ var date=new Date(); var time=date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear()+' '+date.getHours()+':'+date.getMinutes() +':'+date.getSeconds(); var infoMessage='<div class="'+cssClass+'">' +'<a data-dismiss="alert" class="close">x</a>' +time+' '+msg+'</div'; //Place the message $(containerElement).html(infoMessage); }
JavaScript
function Node(data) { this.data = data; this.next = null; this.previous = null; }
function Node(data) { this.data = data; this.next = null; this.previous = null; }
JavaScript
function deleteNode(currentNode, ll) { //Removing the head if (currentNode.previous == null) { //Empty list if(currentNode.next!=null){ currentNode.next.previous = null; } ll.head = currentNode.next; } //Removing the tail else if (currentNode.next == null) { //Empty list if(currentNode.previous!=null){ currentNode.previous.next = null; } currentNode.previous = null; } else { currentNode.previous.next = currentNode.next; currentNode.next.previous = currentNode.previous; } }
function deleteNode(currentNode, ll) { //Removing the head if (currentNode.previous == null) { //Empty list if(currentNode.next!=null){ currentNode.next.previous = null; } ll.head = currentNode.next; } //Removing the tail else if (currentNode.next == null) { //Empty list if(currentNode.previous!=null){ currentNode.previous.next = null; } currentNode.previous = null; } else { currentNode.previous.next = currentNode.next; currentNode.next.previous = currentNode.previous; } }