_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q55400
format
train
function format(str, obj) { if (obj instanceof Array) { var i = 0, len = obj.length; //find the matches return str.replace(FORMAT_REGEX, function (m, format, type) { var replacer, ret; if (i < len) { replacer = obj[i++]; } else { ...
javascript
{ "resource": "" }
q55401
style
train
function style(str, options) { var ret = str; if (options) { if (ret instanceof Array) { ret = ret.map(function (s) { return style(s, options); }); } else if (options instanceof Array) { options.forEach(function (option) { ret =...
javascript
{ "resource": "" }
q55402
applyFirst
train
function applyFirst(method, args) { args = Array.prototype.slice.call(arguments).slice(1); if (!isString(method) && !isFunction(method)) { throw new Error(method + " must be the name of a property or function to execute"); } if (isString(method)) { return function () { var sc...
javascript
{ "resource": "" }
q55403
each
train
function each(iterator) { for (var i = 0, length = this.length; i < length; i++) iterator(this[i]); }
javascript
{ "resource": "" }
q55404
asyncForEach
train
function asyncForEach(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.arr; })); }
javascript
{ "resource": "" }
q55405
asyncMap
train
function asyncMap(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.loopResults; })); }
javascript
{ "resource": "" }
q55406
asyncFilter
train
function asyncFilter(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { var loopResults = results.loopResults, resultArr = results.arr; return (isArray(resultArr) ? resultArr : [resultArr]).filter(function (res, i) { ...
javascript
{ "resource": "" }
q55407
asyncEvery
train
function asyncEvery(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.loopResults.every(function (res) { return !!res; }); })); }
javascript
{ "resource": "" }
q55408
asyncSome
train
function asyncSome(promise, iterator, scope, limit) { return asyncArray(asyncLoop(promise, iterator, scope, limit).chain(function (results) { return results.loopResults.some(function (res) { return !!res; }); })); }
javascript
{ "resource": "" }
q55409
asyncZip
train
function asyncZip() { return asyncArray(when.apply(null, argsToArray(arguments)).chain(function (result) { return zip.apply(array, normalizeResult(result).map(function (arg) { return isArray(arg) ? arg : [arg]; })); })); }
javascript
{ "resource": "" }
q55410
train
function (namespaces, defaultNamespace, name) { var self = this; assert(namespaces); assert(name); if (/^\{.+\}/.test(name)) { return name; } else if (/:/.test(name)) { var parts = name.split(':'); assert(parts.length === 2, parts); if (!namespaces[parts[0]]) { t...
javascript
{ "resource": "" }
q55411
createScript
train
function createScript(url, appID) { if (!document) { return; } var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = url+appID; // Attach the script tag to the document head var s = document.getElementsByTagName('head')[0]; s.ap...
javascript
{ "resource": "" }
q55412
train
function() { if ( !(scope.model instanceof Array) ) { scope.model = scope.model ? [ scope.model ] : []; } return scope.model; }
javascript
{ "resource": "" }
q55413
SemanticPopup
train
function SemanticPopup(SemanticPopupLink) { return { restrict: 'A', scope: { /* Required */ smPopup: '=', /* Optional */ smPopupTitle: '=', smPopupHtml: '=', smPopupPosition: '@', smPopupVariation: '@', smPopupSettings: '=', smP...
javascript
{ "resource": "" }
q55414
SemanticPopupInline
train
function SemanticPopupInline(SemanticPopupInlineLink) { return { restrict: 'A', scope: { /* Optional */ smPopupInline: '=', smPopupInlineOnInit: '=', /* Events */ smPopupInlineOnCreate: '=', smPopupInlineOnRemove: '=', smPopupInlineOnShow: '=',...
javascript
{ "resource": "" }
q55415
SemanticPopupDisplay
train
function SemanticPopupDisplay(SemanticPopupDisplayLink) { return { restrict: 'A', scope: { /* Required */ smPopupDisplay: '@', /* Optional */ smPopupDisplaySettings: '=', smPopupDisplayOnInit: '=', /* Events */ smPopupDisplayOnCreate: '=', ...
javascript
{ "resource": "" }
q55416
walk
train
function walk(data, path, result, key) { var fn; switch (type(path)) { case 'string': fn = seekSingle; break; case 'array': fn = seekArray; break; case 'object': fn = seekObject; break; } if (fn) { fn(data, path, result, key); ...
javascript
{ "resource": "" }
q55417
seekSingle
train
function seekSingle(data, pathStr, result, key) { if(pathStr.indexOf('$') < 0){ result[key] = pathStr; }else{ var seek = jsonPath.eval(data, pathStr) || []; result[key] = seek.length ? seek[0] : undefined; } }
javascript
{ "resource": "" }
q55418
seekArray
train
function seekArray(data, pathArr, result, key) { var subpath = pathArr[1]; var path = pathArr[0]; var seek = jsonPath.eval(data, path) || []; if (seek.length && subpath) { result = result[key] = []; seek[0].forEach(function(item, index) { walk(item, subpath, result, index); }...
javascript
{ "resource": "" }
q55419
seekObject
train
function seekObject(data, pathObj, result, key) { if (typeof key !== 'undefined') { result = result[key] = {}; } Object.keys(pathObj).forEach(function(name) { walk(data, pathObj[name], result, name); }); }
javascript
{ "resource": "" }
q55420
train
function(selection, mainTemplate, suggestionsTemplate) { selection = defaults({}, selection, { isMisspelled: false, spellingSuggestions: [] }); var template = getTemplate(mainTemplate, DEFAULT_MAIN_TPL); var suggestionsTpl = getTemplate(suggestionsTemplate, DEFAULT_SUGGESTIONS_TPL); if (selection.i...
javascript
{ "resource": "" }
q55421
resize
train
function resize(w, h) { w && self.view.win.width(w); h && self.view.nav.add(self.view.cwd).height(h); }
javascript
{ "resource": "" }
q55422
dialogResize
train
function dialogResize() { resize(null, self.dialog.height()-self.view.tlb.parent().height()-($.browser.msie ? 47 : 32)) }
javascript
{ "resource": "" }
q55423
reset
train
function reset() { self.media.hide().empty(); self.win.attr('class', 'el-finder-ql').css('z-index', self.fm.zIndex); self.title.empty(); self.ico.removeAttr('style').show(); self.add.hide().empty(); self._hash = ''; }
javascript
{ "resource": "" }
q55424
update
train
function update() { var f = self.fm.getSelected(0); reset(); self._hash = f.hash; self.title.text(f.name); self.win.addClass(self.fm.view.mime2class(f.mime)); self.name.text(f.name); self.kind.text(self.fm.view.mime2kind(f.link ? 'symlink' : f.mime)); self.size.text(self.fm.view.formatSize(f.size)); ...
javascript
{ "resource": "" }
q55425
moveSelection
train
function moveSelection(forward, reset) { var p, _p, cur; if (!$('[key]', self.cwd).length) { return; } if (self.fm.selected.length == 0) { p = $('[key]:'+(forward ? 'first' : 'last'), self.cwd); self.fm.select(p); } else if (reset) { p = $('.ui-selected:'+(forward ? 'last' : 'first'), self....
javascript
{ "resource": "" }
q55426
train
function(oExpression, sIdentifierName) { fCountPrimaryExpression( EPrimaryExpressionCategories.N_IDENTIFIER_NAMES, EValuePrefixes.S_STRING + sIdentifierName); return ['dot', oWalker.walk(oExpression), sIdentifierName]; }
javascript
{ "resource": "" }
q55427
train
function(oExpression, sIdentifierName) { /** * The prefixed String value that is equivalent to the * sequence of terminal symbols that constitute the * encountered identifier name. * @type {string} */ ...
javascript
{ "resource": "" }
q55428
train
function(sIdentifier) { /** * The prefixed representation String of the identifier. * @type {string} */ var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier; return [ 'name', ...
javascript
{ "resource": "" }
q55429
train
function(sStringValue) { /** * The prefixed representation String of the primitive value * of the literal. * @type {string} */ var sPrefixed = EValuePrefixes.S_STRING + sStringVal...
javascript
{ "resource": "" }
q55430
moveTopDown
train
function moveTopDown(node, dx, dy) { var nodes = node.union(node.descendants()); nodes.filter(":childless").positions(function (node, i) { if(typeof node === "number") { node = i; } var pos = node.position(); return { x: pos....
javascript
{ "resource": "" }
q55431
getOutputDir
train
function getOutputDir(output) { var arr = output.split(path.sep); arr.pop(); return arr.join(path.sep); }
javascript
{ "resource": "" }
q55432
getOutputFilePath
train
function getOutputFilePath(input, outputDir, suffix) { var inputArr = input.split(path.sep); var originFileName = inputArr[inputArr.length - 1]; var newFileName = originFileName.replace(/\.png$/, suffix + '.png'); var outputFilePath = path.join(outputDir, newFileName); return outputFilePath; }
javascript
{ "resource": "" }
q55433
getBytes
train
function getBytes(key, callback) { this.redisClient.get(key, function(err, valueBytes) { if (err) { return callback(err) } if (!valueBytes) { return callback(null, null) } callback(null, valueBytes.toString()) }) }
javascript
{ "resource": "" }
q55434
onDecision
train
function onDecision(err, target) { // // If there was no target then this is a 404 by definition // even if it exists in the public registry because of a // potential whitelist. // if (err || !target) { return self.notFound(req, res, err || { message: 'Unknown pkg: ' + pkg }); } /...
javascript
{ "resource": "" }
q55435
implicitGrant
train
function implicitGrant (iconfig) { /* */ let link = iconfig.link ; window.location.href = `${iconfig.host + link.href}?response_type=${link.responseType}&client_id=${iconfig.clientID}`; return new Promise.resolve() }
javascript
{ "resource": "" }
q55436
apiSubmit
train
async function apiSubmit (store, iroute, payload, delay, jobContext, onCompletion, progress){ if (progress) { progress('pending', jobContext); } let job = await iapiCall(store, iroute, API_CALL, payload, 0, null, null, jobContext); if (job.links('state'...
javascript
{ "resource": "" }
q55437
Command
train
function Command(command, options) { var previousPath; this.command = command; // We're on Windows if `process.platform` starts with "win", i.e. "win32". this.isWindows = (process.platform.lastIndexOf('win') === 0); // the cwd and environment of the command are the same as the main node // process by def...
javascript
{ "resource": "" }
q55438
GulpRunner
train
function GulpRunner(template, options) { if (!(this instanceof GulpRunner)) { return new GulpRunner(template, options); } this.command = new Command(template, options || {}); Transform.call(this, { objectMode: true }); }
javascript
{ "resource": "" }
q55439
train
function(arg1) { if (arg1 == null) { return null; } var args = [name, 'root'].concat(grunt.util.toArray(arguments)); return helpers.getFile.apply(helpers, args); }
javascript
{ "resource": "" }
q55440
train
function(files, licenses) { licenses.forEach(function(license) { var fileobj = helpers.expand({filter: 'isFile'}, 'licenses/LICENSE-' + license)[0]; if(fileobj) { files['LICENSE-' + license] = fileobj.rel; } }); }
javascript
{ "resource": "" }
q55441
train
function(srcpath, destpath, options) { // Destpath is optional. if (typeof destpath !== 'string') { options = destpath; destpath = srcpath; } // Ensure srcpath is absolute. if (!grunt.file.isPathAbsolute(srcpath)) { srcpath = init.srcpath(srcpath); ...
javascript
{ "resource": "" }
q55442
train
function(files, props, options) { options = _.defaults(options || {}, { process: function(contents) { return grunt.template.process(contents, {data: props, delimiters: 'init'}); } }); Object.keys(files).forEach(function(destpath) { var o = Object.create(...
javascript
{ "resource": "" }
q55443
Validator
train
function Validator(validatorsNamesList) { // add default embedded validator name validatorsNamesList.unshift('vsGooglePlace'); this._embeddedValidators = vsEmbeddedValidatorsInjector.get(validatorsNamesList); this.error = {}; this.valid = true; }
javascript
{ "resource": "" }
q55444
parseValidatorNames
train
function parseValidatorNames(attrs) { var attrValue = attrs.vsAutocompleteValidator, validatorNames = (attrValue!=="") ? attrValue.trim().split(',') : []; // normalize validator names for (var i = 0; i < validatorNames.length; i++) { validatorNames[i] = attrs.$normalize(validatorNames[i]); } return va...
javascript
{ "resource": "" }
q55445
serialize
train
function serialize(value) { if (Array.isArray(value) === true) { return serializeArray(value); } if (isObject(value) === false) { return serializePrimitive(value); } return serializeObject(value); }
javascript
{ "resource": "" }
q55446
train
function () { var filter = can.route.attr('filter'); return this.todos.filter(function (todo) { if (filter === 'completed') { return todo.attr('complete'); } if (filter === 'active') { return !todo.attr('complete'); } return true; }); }
javascript
{ "resource": "" }
q55447
train
function(el, val) { if (val == null || val === "") { el.removeAttribute("src"); return null; } else { el.setAttribute("src", val); return val; ...
javascript
{ "resource": "" }
q55448
train
function() { if (arguments.length === 0 && can.Control && this instanceof can.Control) { return can.Control.prototype.on.call(this); } else { return can.addEvent.apply(this, arguments); } }
javascript
{ "resource": "" }
q55449
train
function(fullName, klass, proto) { // Figure out what was passed and normalize it. if (typeof fullName !== 'string') { proto = klass; klass = fullName; fullName = null; } ...
javascript
{ "resource": "" }
q55450
train
function() { for (var cid in madeMap) { if (madeMap[cid].added) { delete madeMap[cid].obj._cid; } } madeMap = null; }
javascript
{ "resource": "" }
q55451
train
function() { var computes = this.constructor._computes; this._computedBindings = {}; for (var i = 0, len = computes.length, prop; i < len; i++) { prop = computes[i]; // Make the context of the compute the curren...
javascript
{ "resource": "" }
q55452
train
function(ev, attr, how, newVal, oldVal) { // when a change happens, create the named event. can.batch.trigger(this, { type: attr, batchNum: ev.batchNum }, [newVal, oldVal]); if (h...
javascript
{ "resource": "" }
q55453
train
function(attr, how, newVal, oldVal) { can.batch.trigger(this, "change", can.makeArray(arguments)); }
javascript
{ "resource": "" }
q55454
train
function(callback) { var data = this.__get(); for (var prop in data) { if (data.hasOwnProperty(prop)) { callback(data[prop], prop); } } }
javascript
{ "resource": "" }
q55455
train
function(prop, current) { if (prop in this._data) { // Delete the property from `_data` and the Map // as long as it isn't part of the Map's prototype. delete this._data[prop]; if (!(prop in this.construc...
javascript
{ "resource": "" }
q55456
train
function(value, prop) { // If we are getting an object. if (!(value instanceof can.Map) && can.Map.helpers.canMakeObserve(value)) { var cached = getMapFromObject(value); if (cached) { return cached; ...
javascript
{ "resource": "" }
q55457
train
function(updater) { for (var name in readInfo.observed) { var ob = readInfo.observed[name]; ob.obj.unbind(ob.event, onchanged); } }
javascript
{ "resource": "" }
q55458
train
function(newValue, oldValue, batchNum) { setCached(newValue); updateOnChange(computed, newValue, oldValue, batchNum); }
javascript
{ "resource": "" }
q55459
train
function() { for (var i = 0, len = computes.length; i < len; i++) { computes[i].unbind('change', k); } computes = null; }
javascript
{ "resource": "" }
q55460
train
function(parentValue, nameIndex) { if (nameIndex > defaultPropertyDepth) { defaultObserve = currentObserve; defaultReads = currentReads; ...
javascript
{ "resource": "" }
q55461
train
function() { if (!tornDown) { tornDown = true; unbind(data); can.unbind.call(el, 'removed', teardown); } return true; }
javascript
{ "resource": "" }
q55462
train
function(expr, options) { var value; // if it's a function, wrap its value in a compute // that will only change values from true to false if (can.isFunction(expr)) { value = can.compute.truthy(expr)(); ...
javascript
{ "resource": "" }
q55463
train
function(expr, options) { var fn = options.fn; options.fn = options.inverse; options.inverse = fn; return Mustache._helpers['if'].fn.apply(this, arguments); }
javascript
{ "resource": "" }
q55464
train
function(expr, options) { // Check if this is a list or a compute that resolves to a list, and setup // the incremental live-binding // First, see what we are dealing with. It's ok to read the compute // because can.view.text is only tem...
javascript
{ "resource": "" }
q55465
train
function(expr, options) { var ctx = expr; expr = Mustache.resolve(expr); if ( !! expr) { return options.fn(ctx); } }
javascript
{ "resource": "" }
q55466
train
function(id, src) { return "can.Mustache(function(" + ARG_NAMES + ") { " + new Mustache({ text: src, name: id }) .template.out + " })"; }
javascript
{ "resource": "" }
q55467
train
function(value) { if (value[0] === "{" && value[value.length - 1] === "}") { return value.substr(1, value.length - 2); } return value; }
javascript
{ "resource": "" }
q55468
train
function(ev) { // The attribute value, representing the name of the method to call (i.e. can-submit="foo" foo is the // name of the method) var attr = removeCurly(el.getAttribute(attributeName)), scopeData = data.scope.read(attr, { ...
javascript
{ "resource": "" }
q55469
train
function() { // Get an array of the currently selected values var value = this.get(), currentValue = this.options.value(); // If the compute is a string, set its value to the joined version of the values array (i.e. "fo...
javascript
{ "resource": "" }
q55470
train
function(ev, newVal) { scopePropertyUpdating = name; componentScope.attr(name, newVal); scopePropertyUpdating = null; }
javascript
{ "resource": "" }
q55471
train
function(name) { var parseName = "parse" + can.capitalize(name); return function(data) { // If there's a `parse...` function, use its output. if (this[parseName]) { data = this[parseName].apply(this, arguments); } ...
javascript
{ "resource": "" }
q55472
train
function() { if (!can.route.currentBinding) { can.route._call("bind"); can.route.bind("change", onRouteDataChange); can.route.currentBinding = can.route.defaultBinding; } }
javascript
{ "resource": "" }
q55473
train
function() { var args = can.makeArray(arguments), prop = args.shift(), binding = can.route.bindings[can.route.currentBinding || can.route.defaultBinding], method = binding[prop]; if (method.apply) { ...
javascript
{ "resource": "" }
q55474
toIdentifier
train
function toIdentifier (str) { return str .split(' ') .map(function (token) { return token.slice(0, 1).toUpperCase() + token.slice(1) }) .join('') .replace(/[^ _0-9a-z]/gi, '') }
javascript
{ "resource": "" }
q55475
runCompile
train
function runCompile(file, options) { if (!file) { throw new PluginError('can-compile', 'Missing file option for can-compile'); } var templatePaths = [], latestFile; options = options || {}; function bufferStream (file, enc, cb) { // ignore empty files if (file.isNull()) { cb(); ...
javascript
{ "resource": "" }
q55476
oxdSocketRequest
train
function oxdSocketRequest(port, host, params, command, callback) { // OXD data let data = { command, params }; // Create socket object const client = new net.Socket(); // Initiate a connection on a given socket. client.connect(port, host, () => { data = JSON.stringify(data); console.log(...
javascript
{ "resource": "" }
q55477
showTableData
train
function showTableData() { connection.runSql('select * from Student').then(function (students) { var HtmlString = ""; students.forEach(function (student) { HtmlString += "<tr ItemId=" + student.Id + "><td>" + student.Name + "</td><td>" + student.Gender + "...
javascript
{ "resource": "" }
q55478
Client
train
function Client (options, cb) { if (typeof options == 'string') options = url.parse(options) var req; if (options.protocol == "https:") req = https.request(options); else req = http.request(options); // add the "Icy-MetaData" header req.setHeader('Icy-MetaData', '1'); if ('function' == ty...
javascript
{ "resource": "" }
q55479
icyOnResponse
train
function icyOnResponse (res) { debug('request "response" event'); var s = res; var metaint = res.headers['icy-metaint']; if (metaint) { debug('got metaint: %d', metaint); s = new Reader(metaint); res.pipe(s); s.res = res; Object.keys(res).forEach(function (k) { if ('_' === k[0]) ret...
javascript
{ "resource": "" }
q55480
proxy
train
function proxy (stream, key) { if (key in stream) { debug('not proxying prop "%s" because it already exists on target stream', key); return; } function get () { return stream.res[key]; } function set (v) { return stream.res[key] = v; } Object.defineProperty(stream, key, { configurable...
javascript
{ "resource": "" }
q55481
stringify
train
function stringify (obj) { var s = []; Object.keys(obj).forEach(function (key) { s.push(key); s.push('=\''); s.push(obj[key]); s.push('\';'); }); return s.join(''); }
javascript
{ "resource": "" }
q55482
onMetadata
train
function onMetadata (metadata) { metadata = icy.parse(metadata); console.error('METADATA EVENT:'); console.error(metadata); }
javascript
{ "resource": "" }
q55483
preprocessor
train
function preprocessor (socket) { debug('setting up "data" preprocessor'); function ondata (chunk) { // TODO: don't be lazy, buffer if needed... assert(chunk.length >= 3, 'buffer too small! ' + chunk.length); if (/icy/i.test(chunk.slice(0, 3))) { debug('got ICY response!'); var b = new Buffe...
javascript
{ "resource": "" }
q55484
writeLocationFile
train
function writeLocationFile(location) { log.info('Writing location.js file'); if (process.platform === 'win32') { location = location.replace(/\\/g, '\\\\'); } fs.writeFileSync(path.join(libPath, 'location.js'), 'module.exports.location = \'' + location + '\';'); }
javascript
{ "resource": "" }
q55485
findSuitableTempDirectory
train
function findSuitableTempDirectory(npmConf) { const now = Date.now(); const candidateTmpDirs = [ process.env.TMPDIR || process.env.TEMP || npmConf.get('tmp'), path.join(process.cwd(), 'tmp', '/tmp') ]; for (let i = 0; i < candidateTmpDirs.length; i++) { const candidatePath = path.join(candida...
javascript
{ "resource": "" }
q55486
getRequestOptions
train
function getRequestOptions(conf) { const strictSSL = conf.get('strict-ssl'); let options = { uri: downloadUrl, encoding: null, // Get response as a buffer followRedirect: true, // The default download path redirects to a CDN URL. headers: {}, strictSSL: strictSSL }; let proxyUrl = conf.get...
javascript
{ "resource": "" }
q55487
requestBinary
train
function requestBinary(requestOptions, filePath) { const deferred = kew.defer(); const writePath = filePath + '-download-' + Date.now(); log.info('Receiving...'); let bar = null; requestProgress(request(requestOptions, (error, response, body) => { log.info(''); if (!error && response.statusCode === 2...
javascript
{ "resource": "" }
q55488
extractDownload
train
function extractDownload(filePath, requestOptions, retry) { const deferred = kew.defer(); // extract to a unique directory in case multiple processes are // installing and extracting at once const extractedPath = filePath + '-extract-' + Date.now(); let options = { cwd: extractedPath }; fs.mkdirsSync(extra...
javascript
{ "resource": "" }
q55489
copyIntoPlace
train
function copyIntoPlace(extractedPath, targetPath) { log.info('Removing', targetPath); return kew.nfcall(fs.remove, targetPath).then(function () { // Look for the extracted directory, so we can rename it. const files = fs.readdirSync(extractedPath); for (let i = 0; i < files.length; i++) { const fi...
javascript
{ "resource": "" }
q55490
getPathVariableName
train
function getPathVariableName() { // windows calls it's path 'Path' usually, but this is not guaranteed. if (process.platform === 'win32') { for (const key of Object.keys(process.env)) if (key.match(/^PATH$/i)) return key; return 'Path'; } return "PATH"; }
javascript
{ "resource": "" }
q55491
put
train
function put(key, value, testCacheEnabled) { const cacheEnabled = testCacheEnabled || CACHE_ENABLED; return postgres.put(key, value) .then((res) => { // persist to cache only if cache is set up/enabled, return postgres result regardless if (cacheEnabled) { return redis.put(key, value).then(...
javascript
{ "resource": "" }
q55492
get
train
function get(key) { return redis.get(key) .then(data => { if (isUri(key)) return data; return JSON.parse(data); // Parse non-uri data to match Postgres }) .catch(() => postgres.get(key)); }
javascript
{ "resource": "" }
q55493
batch
train
function batch(ops, testCacheEnabled) { const cacheEnabled = testCacheEnabled || CACHE_ENABLED; return postgres.batch(ops) .then((res) => { if (cacheEnabled) { return redis.batch(ops).then(() => res); } return res; }); }
javascript
{ "resource": "" }
q55494
createDBIfNotExists
train
function createDBIfNotExists() { const tmpClient = knexLib({ client: 'pg', connection: { host: POSTGRES_HOST, user: POSTGRES_USER, password: POSTGRES_PASSWORD, database: 'postgres', port: POSTGRES_PORT }, pool: { min: CONNECTION_POOL_MIN, max: CONNECTION_POOL_MAX } }); ...
javascript
{ "resource": "" }
q55495
connect
train
function connect() { log('debug', `Connecting to Postgres at ${POSTGRES_HOST}:${POSTGRES_PORT}`); knex = knexLib({ client: 'pg', connection: { host: POSTGRES_HOST, user: POSTGRES_USER, password: POSTGRES_PASSWORD, database: POSTGRES_DB, port: POSTGRES_PORT }, pool: { m...
javascript
{ "resource": "" }
q55496
get
train
function get(key) { const dataProp = 'data'; return baseQuery(key) .select(dataProp) .where('id', key) .then(pullValFromRows(key, dataProp)); }
javascript
{ "resource": "" }
q55497
put
train
function put(key, value) { const { schema, table } = findSchemaAndTable(key), map = columnToValueMap('id', key); // create the value map // add data to the map columnToValueMap('data', wrapInObject(key, parseOrNot(value)), map); let url; if (isUri(key)) { url = decode(key.split('/_uris/').pop()); ...
javascript
{ "resource": "" }
q55498
patch
train
function patch(prop) { return (key, value) => { const { schema, table } = findSchemaAndTable(key); return raw('UPDATE ?? SET ?? = ?? || ? WHERE id = ?', [`${schema ? `${schema}.` : ''}${table}`, prop, prop, JSON.stringify(value), key]); }; }
javascript
{ "resource": "" }
q55499
createReadStream
train
function createReadStream(options) { const { prefix, values, keys } = options, transform = TransformStream(options), selects = []; if (keys) selects.push('id'); if (values) selects.push('data'); baseQuery(prefix) .select(...selects) .where('id', 'like', `${prefix}%`) .pipe(transform); r...
javascript
{ "resource": "" }