_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q39800 | toBoolean | train | function toBoolean(val, def) {
if (is_1.isBoolean(val))
return val;
if (!is_1.isValue(val))
return toDefault(null, def);
val = val.toString();
return (parseFloat(val) > 0 ||
is_1.isInfinite(val) ||
val === 'true' ||
val === 'yes' ||
val === '1' ||
val === '+');
} | javascript | {
"resource": ""
} |
q39801 | toDate | train | function toDate(val, format, def) {
if (is_1.isDate(format)) {
def = format;
format = undefined;
}
var opts = format;
// Date format options a simple timezine
// ex: 'America/Los_Angeles'.
if (is_1.isString(opts)) {
opts = {
timeZone: format
};
}
// This just checks loosely if string is
// date like string, below parse should
// catch majority of scenarios.
function canParse() {
return !/^[0-9]+$/.test(val) &&
(is_1.isString(val) && /[0-9]/g.test(val) &&
/(\.|\/|-|:)/g.test(val));
}
function parseDate() {
var epoch = Date.parse(val);
if (!isNaN(epoch)) {
var date = from_1.fromEpoch(epoch);
if (opts) {
opts.locales = opts.locales || 'en-US';
date = new Date(date.toLocaleString(opts.locales, opts));
}
return date;
}
return toDefault(null, def);
}
if (is_1.isDate(val))
return val;
if (!canParse())
return toDefault(null, def);
return function_1.tryWrap(parseDate)(def);
} | javascript | {
"resource": ""
} |
q39802 | canParse | train | function canParse() {
return !/^[0-9]+$/.test(val) &&
(is_1.isString(val) && /[0-9]/g.test(val) &&
/(\.|\/|-|:)/g.test(val));
} | javascript | {
"resource": ""
} |
q39803 | toDefault | train | function toDefault(val, def) {
if (is_1.isValue(val) && !(is_1.isEmpty(val) && !is_1.isEmpty(def)))
return val;
return is_1.isValue(def) ? def : null;
} | javascript | {
"resource": ""
} |
q39804 | toEpoch | train | function toEpoch(val, def) {
return toDefault((is_1.isDate(val) && val.getTime()), def);
} | javascript | {
"resource": ""
} |
q39805 | toFloat | train | function toFloat(val, def) {
if (is_1.isFloat(val))
return val;
if (!is_1.isValue(val))
return toDefault(null, def);
var parsed = function_1.tryWrap(parseFloat, val)(def);
if (is_1.isFloat(parsed) || is_1.isNumber(parsed))
return parsed;
if (toBoolean(val))
return 1;
return 0;
} | javascript | {
"resource": ""
} |
q39806 | toJSON | train | function toJSON(obj, pretty, def) {
if (is_1.isString(pretty)) {
def = pretty;
pretty = undefined;
}
var tabs = 0;
pretty = is_1.isBoolean(pretty) ? 2 : pretty;
tabs = pretty ? pretty : tabs;
if (!is_1.isObject(obj))
return toDefault(null, def);
return function_1.tryWrap(JSON.stringify, obj, null, tabs)(def);
} | javascript | {
"resource": ""
} |
q39807 | toInteger | train | function toInteger(val, def) {
if (!is_1.isValue(val))
return toDefault(null, def);
var parsed = function_1.tryWrap(parseInt, val)(def);
if (is_1.isInteger(parsed))
return parsed;
if (toBoolean(val))
return 1;
return 0;
} | javascript | {
"resource": ""
} |
q39808 | toMap | train | function toMap(val, id, def) {
if (is_1.isValue(id) && !is_1.isString(id)) {
def = id;
id = undefined;
}
if (is_1.isPlainObject(val))
return val;
if (!is_1.isValue(val) || (!is_1.isString(val) && !is_1.isArray(val)))
return toDefault(null, def);
// Default id key.
id = id || '$id';
var exp = /(\/|\.|,|;|\|)/g;
var i = 0;
var obj = {};
if (is_1.isString(val)) {
// simple string.
if (!exp.test(val))
return { 0: val };
// split string into array, iterate.
val = string_1.split(val);
val.forEach(function (v, i) { return obj[i] = v; });
return obj;
}
while (i < val.length) {
if (is_1.isString(val[i])) {
obj[i] = val[i];
}
else if (is_1.isPlainObject(val[i])) {
var itm = Object.assign({}, val[i]);
var key = itm[id] ? itm[id] : i;
obj[key] = itm[id] ? object_1.del(itm, id) : itm;
}
i++;
}
return obj;
} | javascript | {
"resource": ""
} |
q39809 | toNested | train | function toNested(val, def) {
function nest(src) {
var dest = {};
for (var p in src) {
if (src.hasOwnProperty(p))
if (/\./g.test(p))
object_1.set(dest, p, src[p]);
else
dest[p] = src[p];
}
return dest;
}
return function_1.tryWrap(nest, val)(def);
} | javascript | {
"resource": ""
} |
q39810 | toRegExp | train | function toRegExp(val, def) {
var exp = /^\/.+\/(g|i|m)?([m,i,u,y]{1,4})?/;
var optsExp = /(g|i|m)?([m,i,u,y]{1,4})?$/;
if (is_1.isRegExp(val))
return val;
if (!is_1.isValue(val) || !is_1.isString(val))
return toDefault(null, def);
function regExpFromStr() {
var opts;
if (exp.test(val)) {
opts = optsExp.exec(val)[0];
val = val.replace(/^\//, '').replace(optsExp, '').replace(/\/$/, '');
}
return new RegExp(val, opts);
}
return function_1.tryWrap(regExpFromStr)(def);
} | javascript | {
"resource": ""
} |
q39811 | toUnnested | train | function toUnnested(obj, prefix, def) {
if (is_1.isValue(prefix) && !is_1.isBoolean(prefix)) {
def = prefix;
prefix = undefined;
}
var dupes = 0;
function unnest(src, dest, pre) {
dest = dest || {};
for (var p in src) {
if (dupes > 0)
return;
if (src.hasOwnProperty(p)) {
if (is_1.isPlainObject(src[p])) {
var parent = prefix !== false &&
(pre && pre.length) ?
pre + '.' + p : p;
unnest(src[p], dest, parent);
}
else {
var name = prefix !== false &&
pre && pre.length ?
pre + '.' + p : p;
if (dest[name])
dupes += 1;
else
dest[name] = src[p];
}
}
}
if (dupes > 0)
return null;
return dest;
}
return function_1.tryWrap(unnest, object_1.clone(obj))(def);
} | javascript | {
"resource": ""
} |
q39812 | toWindow | train | function toWindow(key, val, exclude) {
/* istanbul ignore if */
if (!is_1.isBrowser())
return;
exclude = toArray(exclude);
var _keys, i;
// key/val was passed.
if (is_1.isString(key)) {
if (!is_1.isPlainObject(val)) {
window[key] = val;
}
else {
var obj = {};
_keys = array_1.keys(val);
i = _keys.length;
while (i--) {
if (!array_1.contains(exclude, _keys[i]))
obj[_keys[i]] = val[_keys[i]];
}
window[key] = obj;
}
}
// object passed to key.
else if (is_1.isPlainObject(key)) {
_keys = array_1.keys(key);
i = _keys.length;
while (i--) {
if (!array_1.contains(exclude, _keys[i]))
window[_keys[i]] = key[_keys[i]];
}
}
} | javascript | {
"resource": ""
} |
q39813 | train | function(child, parent, protoProps, staticProps) {
// Inherit prototype properties from parent
// Set the prototype chain to inherit without calling parent's constructor function.
SharedConstructor.prototype = parent.prototype;
child.prototype = new SharedConstructor();
child.prototype.constructor = child;
// Extend with prototype and static properties
extendObj(child.prototype, protoProps);
extendObj(child, staticProps);
// Set a convenience property in case the parent's prototype is needed later.
child.__super__ = parent.prototype;
// Copy references to static methods we want to extend
child.extendWithConstructor = Constructr.extendWithConstructor;
child.extend = Constructr.extend;
child.mixes = Constructr.mixes;
child.def = Constructr.def;
return child;
} | javascript | {
"resource": ""
} | |
q39814 | train | function(opts) {
EventEmitter.call(this);
this.reqId = 1;
this.opts = opts;
this.id = opts.id;
this.socket = null;
this.callbacks = {};
this.type = opts.type;
this.info = opts.info;
this.state = ST_INITED;
this.consoleService = opts.consoleService;
} | javascript | {
"resource": ""
} | |
q39815 | call | train | function call(handle, route, err, req, res, next) {
var arity = handle.length;
var hasError = Boolean(err);
debug('%s %s : %s', handle.name || '<anonymous>', route, req.originalUrl);
try {
if (hasError && arity === 4) {
// error-handling middleware
handle(err, req, res, next);
return;
} else if (!hasError && arity < 4) {
// request-handling middleware
handle(req, res, next);
return;
}
} catch (e) {
// reset the error
err = e;
}
// continue
next(err);
} | javascript | {
"resource": ""
} |
q39816 | lintAllFiles | train | function lintAllFiles (src, options)
{
glob(src,
function (err, files)
{
if (err) throw err;
for (var i = 0, l = files.length; i < l; i++)
{
jsHintHelper.lintFile(files[i], options.rules);
}
}
);
} | javascript | {
"resource": ""
} |
q39817 | mergeRecursive | train | function mergeRecursive(key, defaults, app) {
key = key ? key.toUpperCase() : null
if (app === undefined || app == undefine || process.env[key] == undefine)
return undefine
var config = defaults
var atOverrideVal = app === null ? false : atLeaf(app)
var atDefaultVal = defaults === null || atLeaf(defaults)
if (atOverrideVal || atDefaultVal) {
if (process.env[key] !== undefined) config = process.env[key]
else if (app !== null) config = app
if (config == '{{required}}')
throw Error(`Configure failed. Override or environment var required for config.${key}`)
if (config === false || config && atLeaf(config)) {
if (config != undefine) $logConfig(key, config)
return config
}
}
for (var attr in defaults) {
var childKey = key ? `${key}_${attr}` : attr
var childOverrides = app && app.hasOwnProperty(attr) ? app[attr] : null
config[attr] = mergeRecursive(childKey, defaults[attr], childOverrides)
if (config[attr] == undefine)
delete config[attr]
}
for (var attr in app) {
if (!(defaults||{}).hasOwnProperty(attr)) { // && app[attr]
var childKey = key ? `${key}_${attr}` : attr
config[attr] = mergeRecursive(childKey, null, app[attr])
if (config[attr] == undefine)
delete config[attr]
}
}
return config
} | javascript | {
"resource": ""
} |
q39818 | s3streamer | train | function s3streamer(s3, opts) {
var headers = (opts || {}).headers || { }
return function (file, filename, mimetype, encoding, callback) {
headers['Content-Type'] = mimetype
var buf = Buffer(0)
file.on('data', function (chunk) {
buf = Buffer.concat([buf, chunk])
})
file.on('end', function () {
s3.putBuffer(buf, filename, headers, function (err, s3resp) {
if (err) {
return callback(err)
} else if (s3resp.statusCode < 200 || s3resp.statusCode > 299) {
return callback(new Error('Error uploading to s3: ' + s3resp.statusCode), s3resp)
}
s3resp.resume() // This finalizes the stream response
callback()
})
})
}
} | javascript | {
"resource": ""
} |
q39819 | train | function () {
'use strict';
// default options for angularTemplatecache gulp task
var options = {
config: {
compilePatternsOnImport: false,
dataSource: 'pattern',
dataFileName: 'pattern.yml',
htmlTemplateDest: './source/_patterns',
stylesDest: './source/css/scss',
scriptsDest: './source/js',
cssCompiler: 'sass', // sass, less, stylus, none
templateEngine: 'twig',
templateEngineOptions: {
base: 'node_modules/pattern-library/patterns/',
async: false
},
templateDonut: {
twig: './node_modules/pattern-importer/templates/donut.twig'
},
convertCategoryTitles: true
},
src: ['./node_modules/pattern-library/patterns/**/pattern.yml'],
taskName: 'patterns-import', // default task name
dependencies: [] // gulp tasks which should be run before this task
};
return options;
} | javascript | {
"resource": ""
} | |
q39820 | Pool | train | function Pool(config) {
if(!(this instanceof Pool)) {
return new Pool(config);
}
var self = this;
if(!config) { throw new TypeError("config not set"); }
self._pool = require('mysql').createPool(config);
self._get_connection = Q.nfbind(self._pool.getConnection.bind(self._pool));
db.Pool.call(this);
} | javascript | {
"resource": ""
} |
q39821 | _filesToString | train | function _filesToString (files, encoding, separator, callback) {
if ("undefined" === typeof files) {
throw new ReferenceError("missing \"files\" argument");
}
else if ("object" !== typeof files || !(files instanceof Array)) {
throw new TypeError("\"files\" argument is not an Array");
}
else if ("undefined" === typeof callback && "undefined" === typeof separator && "undefined" === typeof encoding) {
throw new ReferenceError("missing \"callback\" argument");
}
else if ("function" !== typeof callback && "function" !== typeof separator && "function" !== typeof encoding) {
throw new TypeError("\"callback\" argument is not a function");
}
else {
let _callback = callback;
if ("undefined" === typeof _callback) {
if ("undefined" === typeof separator) {
_callback = encoding;
}
else {
_callback = separator;
}
}
filesToStreamProm(files, "string" === typeof separator ? separator : " ").then((readStream) => {
return new Promise((resolve, reject) => {
let data = "";
let error = false;
readStream.once("error", (_err) => {
error = true;
reject(_err);
}).on("data", (chunk) => {
data += chunk.toString("string" === typeof encoding ? encoding : "utf8");
}).once("end", () => {
if (!error) {
resolve(data);
}
});
});
}).then((data) => {
_callback(null, data);
}).catch(_callback);
}
} | javascript | {
"resource": ""
} |
q39822 | insert | train | function insert (table, object, fields) {
var input = this
if (input instanceof Array) {
insertArray.call(input, table, object, fields)
} else {
insertObject.call(input, table, object, fields)
}
} | javascript | {
"resource": ""
} |
q39823 | insertArray | train | function insertArray (table, object, fields) {
var input = this
input.forEach(function addRow (entry, rowNo) {
var tableRow = fields.map(function cell (fieldName) {
return getCellContent.call(entry, object.fields[fieldName], rowNo)
})
table.push(tableRow)
})
} | javascript | {
"resource": ""
} |
q39824 | insertObject | train | function insertObject (table, object, fields) {
var input = this
fields.forEach(function addField (field) {
var cells = {}
cells[field] = getCellContent.call(input, object.fields[field])
table.push(cells)
})
} | javascript | {
"resource": ""
} |
q39825 | getCellContent | train | function getCellContent (field) {
var entry = this
var args = Array.prototype.slice.call(arguments, 1)
if (typeof field === 'string') {
return field
}
if (typeof field === 'function') {
var value
try {
value = field.apply(entry, args)
} catch (e) {
value = '(err)'
}
if (value === undefined || value === null) {
return ''
}
return value.toString()
}
return ''
} | javascript | {
"resource": ""
} |
q39826 | readBuffer | train | async function readBuffer(path) {
const rs = createReadStream(path)
/** @type {Buffer} */
const res = await collect(rs, { binary: true })
return res
} | javascript | {
"resource": ""
} |
q39827 | train | function(data, done) {
this._data.push(this._clone(data));
var ret = this._data.length;
done(null, ret);
} | javascript | {
"resource": ""
} | |
q39828 | train | function(data, done) {
if(!this._key) {
done('no key found for metadata');
return;
}
var key = data[this._key.getName()];
var ix = -1;
for(var i = 0; i < this._data.length; i++) {
if(this._data[i][this._key.getName()] === key) {
ix = i;
break;
}
}
if(ix === -1) {
this._data.push(this._clone(data));
} else {
this._data[ix] = this._clone(data);
}
done(null);
} | javascript | {
"resource": ""
} | |
q39829 | train | function(key, done) {
if(!this._key) {
done('no key found for metadata');
return;
}
var ret = null; // if not found return null
for(var i = 0; i < this._data.length; i++) {
if(this._data[i][this._key.getName()] === key) {
ret = this._clone(this._data[i]);
break;
}
}
done(null, ret);
} | javascript | {
"resource": ""
} | |
q39830 | purgeResource | train | function purgeResource(resource, archive) {
if (!resource.purge) { return true; }
var criteria = resource.purge();
var deferred = Q.defer();
archive.bind(resource.name);
archive[resource.name].remove(criteria, function (err, results) {
err ? deferred.reject(err) : deferred.resolve(results);
});
return deferred.promise;
} | javascript | {
"resource": ""
} |
q39831 | MandrillProvider | train | function MandrillProvider(apiKey, options) {
if (typeof apiKey !== 'string') {
throw new Error('Invalid parameters');
}
options = options || {};
if (typeof options.async === 'undefined')
options.async = false;
if (typeof options.apiSecure === 'undefined')
options.apiSecure = true;
options.apiHostname = options.apiHostname || 'mandrillapp.com';
options.apiPort = options.apiPort || (options.apiSecure ? 443 : 80);
this.apiKey = apiKey;
this.options = options;
} | javascript | {
"resource": ""
} |
q39832 | train | function (event){
//IE compatibility
event = event || window.event;
//Mozilla, Opera, & Legacy
if(event && event.type && (/DOMContentLoaded|load/).test(event.type)) {
fireDOMReady();
//Legacy
} else if(document.readyState) {
if ((/loaded|complete/).test(doc.readyState)) {
fireDOMReady();
//IE, courtesy of Diego Perini (http://javascript.nwbox.com/IEContentLoaded/)
} else if(document.documentElement.doScroll) {
try {
ready || document.documentElement.doScroll('left');
} catch(ex) {
return;
}
//If no error was thrown, the DOM must be ready
fireDOMReady();
}
}
} | javascript | {
"resource": ""
} | |
q39833 | train | function() {
if (!ready) {
ready = true;
//Call the stack of onload functions in given context or window object
for (var i=0, len=stack.length; i < len; i++) {
stack[i][0].call(stack[i][1]);
}
//Clean up after the DOM is ready
if (document.removeEventListener) {
document.removeEventListener("DOMContentLoaded", onStateChange, false);
}
//Clear the interval
clearInterval(timer);
//Null the timer and event handlers to release memory
document.onreadystatechange = window.onload = timer = null;
}
} | javascript | {
"resource": ""
} | |
q39834 | runScript | train | function runScript(script, context) {
if (typeof script.useModuleLoader == 'undefined') {
// if it is not explicitly defined whether we should use modeule loader or not
// we assume we should use module loader for .js files
script.useModuleLoader = path.extname(script.path).toLowerCase() == '.js';
}
var source;
var relativePath;
if (script.plugin) {
source = 'plugin ' + script.plugin.id;
relativePath = path.join('plugins', script.plugin.id, script.path);
} else if (script.useModuleLoader) {
source = 'config.xml';
relativePath = path.normalize(script.path);
} else {
source = 'hooks directory';
relativePath = path.join('hooks', context.hook, script.path);
}
events.emit('verbose', 'Executing script found in ' + source + ' for hook "' + context.hook + '": ' + relativePath);
if(script.useModuleLoader) {
return runScriptViaModuleLoader(script, context);
} else {
return runScriptViaChildProcessSpawn(script, context);
}
} | javascript | {
"resource": ""
} |
q39835 | runScriptViaModuleLoader | train | function runScriptViaModuleLoader(script, context) {
if(!fs.existsSync(script.fullPath)) {
events.emit('warn', 'Script file does\'t exist and will be skipped: ' + script.fullPath);
return Q();
}
var scriptFn = require(script.fullPath);
context.scriptLocation = script.fullPath;
context.opts.plugin = script.plugin;
// We can't run script if it is a plain Node script - it will run its commands when we require it.
// This is not a desired case as we want to pass context, but added for compatibility.
if (scriptFn instanceof Function) {
// If hook is async it can return promise instance and we will handle it.
return Q(scriptFn(context));
} else {
return Q();
}
} | javascript | {
"resource": ""
} |
q39836 | runScriptViaChildProcessSpawn | train | function runScriptViaChildProcessSpawn(script, context) {
var opts = context.opts;
var command = script.fullPath;
var args = [opts.projectRoot];
if (fs.statSync(script.fullPath).isDirectory()) {
events.emit('verbose', 'Skipped directory "' + script.fullPath + '" within hook directory');
return Q();
}
if (isWindows) {
// TODO: Make shebang sniffing a setting (not everyone will want this).
var interpreter = extractSheBangInterpreter(script.fullPath);
// we have shebang, so try to run this script using correct interpreter
if (interpreter) {
args.unshift(command);
command = interpreter;
}
}
var execOpts = {cwd: opts.projectRoot, printCommand: true, stdio: 'inherit'};
execOpts.env = {};
execOpts.env.CORDOVA_VERSION = require('../../package').version;
execOpts.env.CORDOVA_PLATFORMS = opts.platforms ? opts.platforms.join() : '';
execOpts.env.CORDOVA_PLUGINS = opts.plugins ? opts.plugins.join() : '';
execOpts.env.CORDOVA_HOOK = script.fullPath;
execOpts.env.CORDOVA_CMDLINE = process.argv.join(' ');
return superspawn.spawn(command, args, execOpts)
.catch(function(err) {
// Don't treat non-executable files as errors. They could be READMEs, or Windows-only scripts.
if (!isWindows && err.code == 'EACCES') {
events.emit('verbose', 'Skipped non-executable file: ' + script.fullPath);
} else {
throw new Error('Hook failed with error code ' + err.code + ': ' + script.fullPath);
}
});
} | javascript | {
"resource": ""
} |
q39837 | extractSheBangInterpreter | train | function extractSheBangInterpreter(fullpath) {
var fileChunk;
var octetsRead;
var fileData;
var hookFd = fs.openSync(fullpath, 'r');
try {
// this is a modern cluster size. no need to read less
fileData = new Buffer(4096);
octetsRead = fs.readSync(hookFd, fileData, 0, 4096, 0);
fileChunk = fileData.toString();
} finally {
fs.closeSync(hookFd);
}
var hookCmd, shMatch;
// Filter out /usr/bin/env so that "/usr/bin/env node" works like "node".
var shebangMatch = fileChunk.match(/^#!(?:\/usr\/bin\/env )?([^\r\n]+)/m);
if (octetsRead == 4096 && !fileChunk.match(/[\r\n]/))
events.emit('warn', 'shebang is too long for "' + fullpath + '"');
if (shebangMatch)
hookCmd = shebangMatch[1];
// Likewise, make /usr/bin/bash work like "bash".
if (hookCmd)
shMatch = hookCmd.match(/bin\/((?:ba)?sh)$/);
if (shMatch)
hookCmd = shMatch[1];
return hookCmd;
} | javascript | {
"resource": ""
} |
q39838 | train | function (options) {
var self = this
PPUnit.super_.call(self)
options = options || {}
self.concurrency = options.concurrency || -1
self.rootSuite = new Suite(undefined)
self.rootSuite.timeout(2000)
self.rootSuite.globallyExclusive()
self.rootSuite.locallyExclusiveTests()
self.allTests = []
self.failures = []
self.tickId = 0
self.stats = {
suites: 0
, tests: 0
, skipped: 0
, passes: 0
, failures: 0
, completed: 0
, startTime: 0
, maxConcurrency: 0
, currentlyRunning: 0
, end: undefined
, duration: undefined
}
self._queue = []
self._nextId = 1
self._files = []
self._bailing = false
process.on('SIGINT', function () {
self._bail()
})
} | javascript | {
"resource": ""
} | |
q39839 | addAdapter | train | function addAdapter (state, name, config, logger) {
if (_.isFunction(name)) {
logger = name
name = logger.name
config = config || {}
} else if (_.isFunction(config)) {
logger = config
if (_.isObject(name)) {
config = name
name = logger.name
} else {
config = {}
}
} else if (_.isObject(name)) {
logger = name
name = logger.name
config = config || {}
} else if (config && config.fatal) {
logger = config
config = {}
}
addLogger(state, name, config, logger)
} | javascript | {
"resource": ""
} |
q39840 | addFilter | train | function addFilter (config, filter) {
if (filter) {
if (filter[ 0 ] === '-') {
config.filters.ignore[ filter ] = new RegExp('^' + filter.slice(1).replace(/[*]/g, '.*?') + '$')
} else {
config.filters.should[ filter ] = new RegExp('^' + filter.replace(/[*]/g, '.*?') + '$')
}
}
} | javascript | {
"resource": ""
} |
q39841 | addLogger | train | function addLogger (state, name, config, adapter) {
config = Object.assign({}, defaultConfig, config)
setFilters(config)
const logger = {
name: name,
config: config,
adapter: adapter,
addFilter: addFilter.bind(null, config),
removeFilter: removeFilter.bind(null, config),
setFilter: setFilter.bind(null, config),
setFilters: setFilters.bind(null, config)
}
if (config.namespaceInit) {
logger.init = memoize(adapter)
}
logger.log = onEntry.bind(null, logger)
state.loggers[ name ] = logger
} | javascript | {
"resource": ""
} |
q39842 | attach | train | function attach (state, logger, namespace) {
_.each(levels, function (level, name) {
logger[ name ] = prepMessage.bind(null, state, name, namespace)
})
} | javascript | {
"resource": ""
} |
q39843 | init | train | function init (state, namespace) {
namespace = namespace || 'deftly'
const logger = { namespace: namespace }
attach(state, logger, namespace)
return logger
} | javascript | {
"resource": ""
} |
q39844 | log | train | function log (state, type, namespace, message) {
const level = levels[ type ]
_.each(state.loggers, function (logger) {
logger.log({
type: type,
level: level,
namespace: namespace,
message: message
})
})
} | javascript | {
"resource": ""
} |
q39845 | prepMessage | train | function prepMessage (state, level, namespace, message) {
if (_.isString(message)) {
const formatArgs = Array.prototype.slice.call(arguments, 3)
message = format.apply(null, formatArgs)
}
log(state, level, namespace, message)
} | javascript | {
"resource": ""
} |
q39846 | removeFilter | train | function removeFilter (config, filter) {
if (filter) {
if (config.filters.ignore[ filter ]) {
delete config.filters.ignore[ filter ]
} else {
delete config.filters.should[ filter ]
}
}
} | javascript | {
"resource": ""
} |
q39847 | setFilters | train | function setFilters (config) {
const parts = config.filter.split(/[\s,]+/)
config.filters = {
should: {},
ignore: {}
}
_.each(parts, addFilter.bind(null, config))
} | javascript | {
"resource": ""
} |
q39848 | shouldRender | train | function shouldRender (config, entry) {
// if we're below the log level, return false
if (config.level < entry.level) {
return false
}
// if we match the ignore list at all, return false
const ignoreMatch = _.find(_.values(config.filters.ignore), ignore => {
return ignore.test(entry.namespace)
})
if (ignoreMatch) {
return false
}
// if a should filter exists but we don't have a match, return false
let shouldFiltered = false
const shouldMatch = _.find(_.values(config.filters.should), should => {
shouldFiltered = true
return should.test(entry.namespace)
})
if ((shouldFiltered && !shouldMatch)) {
return false
}
return true
} | javascript | {
"resource": ""
} |
q39849 | initTerminateHandlers | train | function initTerminateHandlers() {
var readLine;
if (process.platform === "win32"){
readLine = require("readline");
readLine.createInterface ({
input: process.stdin,
output: process.stdout
}).on("SIGINT", function () {
process.emit("SIGINT");
});
}
// handle INTERRUPT (CTRL+C) and TERM/KILL signals
process.on('exit', function () {
if (server) {
console.log(chalk.blue('*'), 'Shutting down server');
server.stop();
}
console.log(); // extra blank line
});
process.on('SIGINT', function () {
console.log(chalk.blue.bold('!'), chalk.yellow.bold('SIGINT'), 'detected');
process.exit();
});
process.on('SIGTERM', function () {
console.log(chalk.blue.bold('!'), chalk.yellow.bold('SIGTERM'), 'detected');
process.exit(0);
});
} | javascript | {
"resource": ""
} |
q39850 | fetch_object_by_uuid | train | function fetch_object_by_uuid(data, prop, uuid) {
if(!is_object(data)) { return error('fetch_object_by_uuid(data, ..., ...) not object: '+ data); }
if(!is_string(prop)) { return error('fetch_object_by_uuid(..., prop, ...) not string: '+ prop); }
if(!is_uuid(uuid)) { return warn('Property ' + prop + ' was not uuid: ' + uuid); }
if(data.documents[uuid] === undefined) {
data.documents[uuid] = get_document(uuid);
} else {
return warn('Document already fetched: ' + uuid);
}
} | javascript | {
"resource": ""
} |
q39851 | setDomAttrs | train | function setDomAttrs(attrs, el) {
for (let attr in attrs) {
if (!attrs.hasOwnProperty(attr)) { continue; }
switch (attr) {
case 'className':
case 'id':
el[attr] = attrs[attr];
break;
default:
el.setAttribute(attr, attrs[attr]);
break;
}
}
return el;
} | javascript | {
"resource": ""
} |
q39852 | del | train | async function del(owner, repo) {
const endpoint = `/user/starred/${owner}/${repo}`
const { statusCode } = await this._request({
method: 'PUT',
data: {},
endpoint,
})
if (statusCode != 204) {
throw new Error(`Unexpected status code ${statusCode}.`)
}
} | javascript | {
"resource": ""
} |
q39853 | objCleaner | train | function objCleaner(obj, removeTypes) {
var defaultRemoveTypes = [null, 'undefined', false, '', [], {}];
var key;
function allowEmptyObject() {
var i;
for (i = 0; i < removeTypes.length; i++) {
if (removeTypes[i] instanceof Object && Object.keys(removeTypes[i]).length === 0) {
return false;
}
}
return true;
}
function allowEmptyArray() {
var i;
for (i = 0; i < removeTypes.length; i++) {
if (Array.isArray(removeTypes[i]) && removeTypes[i].length === 0) {
return false;
}
}
return true;
}
if (!(obj instanceof Object || Array.isArray(obj))) {
throw new Error('Argument must be an object or Array');
}
if (typeof removeTypes === 'undefined') {
removeTypes = defaultRemoveTypes;
}
for (key in obj) {
if (typeof obj[key] === 'object') {
if (obj[key] && Object.keys(obj[key]).length) {
obj[key] = objCleaner(obj[key], removeTypes);
} else {
obj[key] = allowEmptyObject() ? obj[key] : null;
}
}
if (Array.isArray(obj[key])) {
if (obj[key] && obj[key].length) {
obj[key] = objCleaner(obj[key], removeTypes);
} else {
obj[key] = allowEmptyArray() ? obj[key] : null;
}
}
if (obj instanceof Object && obj.hasOwnProperty(key)) {
removeTypes.forEach(function (typeVal) {
if (typeof obj[key] === typeVal || obj[key] === typeVal) {
delete obj[key];
}
});
}
if (Array.isArray(obj) && obj.length) {
removeTypes.forEach(function (typeVal, index) {
if (typeof obj[key] === typeVal || obj[key] === typeVal) {
obj.splice(key, 1);
}
});
}
}
return obj;
} | javascript | {
"resource": ""
} |
q39854 | createClient | train | function createClient(redisClientOptions) {
const client = redis.createClient(redisClientOptions);
if (!client._options) {
client._options = redisClientOptions;
}
return client;
} | javascript | {
"resource": ""
} |
q39855 | PactPublisher | train | function PactPublisher (configOrVersion, brokerBaseUrl, pacts) {
var _version, _brokerBaseUrl, _pacts;
if (!_.contains(['object', 'string'], typeof configOrVersion)) {
throw new TypeError('Invalid first parameter provided constructing Pact Publisher. Expected a config object or version string for first parameter.');
}
_version = configOrVersion.appVersion || configOrVersion;
_brokerBaseUrl = configOrVersion.brokerBaseUrl || brokerBaseUrl;
_pacts = configOrVersion.pacts || pacts;
_logging = _.isBoolean(configOrVersion.logging) ? configOrVersion.logging : true;
if (!_.isString(_version)) {
throw new Error("Expected a string for version number parameter.");
}
if (!_.isString(_brokerBaseUrl)) {
throw new Error("Expected a string for broker base URL parameter.");
}
if (_pacts !== undefined && !(_.isString(_pacts) || _.isArray(_pacts))) {
throw new Error("Expected a string or array for pacts parameter.");
}
this._appVersion = _version;
this._pactBrokerBaseUrl = _brokerBaseUrl;
this._pactUrl = "{pactBaseUrl}/pacts/provider/{provider}/consumer/{consumer}/version/{version}".replace("{pactBaseUrl}", this._pactBrokerBaseUrl).replace('{version}', this._appVersion);
this._logging = _logging;
if (_.isString(_pacts)) {
if (!fs.existsSync(_pacts)) {
throw new Error("Pact directory " + _pacts + " does not exist");
}
this._enqueuedPactFiles = fs.readdirSync(_pacts).filter(function (file) {
return path.extname(file) === '.json';
}).map(function (file) {
return _pacts + '/' + file;
});
} else if (_.isArray(_pacts)) {
this._enqueuedPactFiles = _pacts;
} else {
this._enqueuedPactFiles = [];
}
} | javascript | {
"resource": ""
} |
q39856 | train | function(opts) {
Widget.call(this);
var input = Widget.tag("input");
this._input = input;
var that = this;
this.addClass("wdg-input");
if (typeof opts !== 'object') opts = {};
if (typeof opts.type !== 'string') opts.type = 'text';
input.attr("type", opts.type);
if (typeof opts.placeholder === 'string') {
input.attr("placeholder", opts.placeholder);
}
if (typeof opts.size !== 'undefined') {
opts.size = parseInt(opts.size) || 8;
input.attr("size", opts.size);
}
if (typeof opts.width !== 'undefined') {
input.css("width", opts.width);
}
var onValid = opts.onValid;
if (typeof onValid === 'object' && typeof onValid.enabled === 'function') {
opts.onValid = function(v) {
onValid.enabled(v);
};
}
else if (typeof onValid !== 'function') opts.onValid = null;
if (typeof opts.validator === 'object') {
var rx = opts.validator;
opts.validator = function(v) {
return rx.test(v);
};
}
this._valid = 0;
if (typeof opts.validator === 'function') {
input.addEvent(
"keyup",
function() {
opts.validator.call(this);
}
);
}
input.addEvent(
"keyup",
function() {
that.fireChange();
}
);
if (typeof opts.onEnter === 'object' && typeof opts.onEnter.fire === 'function') {
var onEnter = opts.onEnter;
this.Enter(function() {
onEnter.fire();
});
}
input.addEvent(
"keyup",
function(evt) {
if (that._valid > -1 && evt.keyCode == 13) {
// On rend l'événement asynchrone pour éviter les
// problèmes de clavier virtuel qui reste affiché.
window.setTimeout(
function() {
that.fireEnter();
}
);
} else {
that.validate();
}
}
);
if (typeof opts.value !== 'string') {
opts.value = "";
}
input.addEvent(
"focus",
function() {
that.selectAll();
}
);
this._opts = opts;
this.val(opts.value);
if (typeof opts.label !== 'undefined') {
var label = Widget.div("label").text(opts.label).attr("title", opts.label);
this.append(label);
}
this.append(input);
} | javascript | {
"resource": ""
} | |
q39857 | train | function( fileName ) {
// console.log('Read configuration from ' + fileName);
var pathSep = require('path').sep;
var inFileName = process.cwd() + pathSep + fileName;
var config = require( inFileName );
// TODO: validate config
for ( var procs in config ) {
if ( config.hasOwnProperty(procs) ) {
config[procs].forEach(function(proc){
if ( proc.hasOwnProperty('fileName') ) {
proc.fileName = process.cwd() + pathSep + proc.fileName;
}
});
}
}
return config;
} | javascript | {
"resource": ""
} | |
q39858 | saveSync | train | function saveSync(store, conf) {
try {
this.save(store, conf);
}catch(e) {
log.warning('failed to save rdb snapshot: %s', e.message);
}
} | javascript | {
"resource": ""
} |
q39859 | train | function () {
var emptyFunction = new RegExp(/(\{\s\})|(\{\})/),
publicMethods = {};
for (property in this.settings) {
if (typeof this.settings[property] == 'function' &&
typeof this[property] == 'function') {
var method = this.settings[property];
if (emptyFunction.test(method)) {
publicMethods[property] = this[property];
} else {
var defaultMethodName = this.createDefaultMethodName(property);
publicMethods[property] = this.settings[property];
publicMethods[defaultMethodName] = this[property];
}
}
}
publicMethods.stylings = this.stylings;
return publicMethods;
} | javascript | {
"resource": ""
} | |
q39860 | train | function(name) {
if (/[A-Z]/.test(name.charAt(0)))
return "default" + name;
var firstLetter = name.charAt(0);
return "default" + firstLetter.toUpperCase() + name.substring(1);
} | javascript | {
"resource": ""
} | |
q39861 | train | function (primary, secondary) {
var primary = primary || {};
for (var property in secondary)
if (secondary.hasOwnProperty(property))
primary[property] = secondary[property];
return primary;
} | javascript | {
"resource": ""
} | |
q39862 | train | function (event) {
var self = this;
if (this.invalidElements.length > 0)
event.preventDefault();
// Even if the invalidElements count
// does not indicate any invalidated
// elements, the plugin should make
// sure that there are none that did
// somehow bypass the control. This
// is an issue mainly when submitting
// without editing a form.
for (var validationType in self.validate) {
var invalidFields = self.getElementsByPattern(self.validate[validationType], self.patterns[validationType], validationType);
if (invalidFields.length > 0) {
this.invalidElements = invalidFields;
event.preventDefault();
// The warning method
self.publicInterface.onInvalidation(invalidFields, this.legends[validationType]);
}
}
} | javascript | {
"resource": ""
} | |
q39863 | train | function(event) {
var target = event.target;
if (this.checkElementByPattern(target)) {
if (this.invalidElements.indexOf(target) > -1)
this.invalidElements.splice(this.invalidElements.indexOf(target), 1);
this.publicInterface.onValidation([target]);
} else {
if (this.invalidElements.indexOf(target) === -1)
this.invalidElements.push(target);
var legend = this.legends[this.currentValidationType] || this.legends.unknown;
this.publicInterface.onInvalidation([target], legend);
}
} | javascript | {
"resource": ""
} | |
q39864 | train | function (event) {
// Check if the node is a child of the plugin's element.
if (event.relatedNode === this.element) {
var attributeValues = event.target.getAttribute("data-validate");
if (attributeValues !== null) {
attributeValues = this.splitStringByComma(attributeValues);
for (var x = 0; x < attributeValues.length; x++) {
var key = attributeValues[x];
if (key === undefined || key === null)
continue;
this.validate[key].push(event.target);
}
}
if (event.target.hasAttribute("data-length") &&
this.validate["length"].indexOf(event.target) === -1)
this.validate["length"].push(event.target);
}
} | javascript | {
"resource": ""
} | |
q39865 | train | function (elements, legend) {
var elements = elements || [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].classList.contains(this.stylings.error) === false)
elements[i].classList.add(this.stylings.error);
var legend = elements[i].getAttribute("data-label") || legend;
var parent = elements[i].parentNode;
parent.setAttribute("data-hint", legend);
if (i === 0)
elements[i].focus();
}
} | javascript | {
"resource": ""
} | |
q39866 | train | function (elements) {
var elements = elements || [];
for (var i = 0; i < elements.length; i++) {
if (elements[i].classList.contains(this.stylings.error)) {
elements[i].classList.remove(this.stylings.error);
var parent = elements[i].parentNode;
parent.removeAttribute("data-hint");
}
}
} | javascript | {
"resource": ""
} | |
q39867 | train | function (elements, attribute, value) {
var foundElements = [], value = value || null;
for (i = 0; i < elements.length; i++) {
// If the value parameter is set, return only the
// elements that has the given attribute value.
if (value !== null) {
if (elements[i].getAttribute(attribute) === value)
foundElements.push(elements[i]);
} else {
if (elements[i].getAttribute(attribute) !== null)
foundElements.push(elements[i]);
}
}
return foundElements;
} | javascript | {
"resource": ""
} | |
q39868 | train | function (elements, attribute) {
var foundElements = {};
for (i = 0; i < elements.length; i++) {
var attributeValues = elements[i].getAttribute(attribute);
if (attributeValues === undefined || attributeValues === null)
continue;
// Elements can have multiple attribute values,
// the string should be delimited by a comma.
attributeValues = this.splitStringByComma(attributeValues);
for (var x = 0; x < attributeValues.length; x++) {
// The attribute value will also serve as the
// key in the object that will be returned.
var key = attributeValues[x];
if (key === undefined || key === null)
continue;
// The key must exist in the element as an
// array, otherwise push() will fail.
if (foundElements[key] === undefined || foundElements[key].constructor !== Array)
foundElements[key] = [];
foundElements[key].push(elements[i]);
}
}
return foundElements;
} | javascript | {
"resource": ""
} | |
q39869 | train | function (element) {
// Begin with checking the validate
var elementAsArray = [ element ],
validationType = element.getAttribute("data-validate") || null;
invalidElement = [];
if (validationType !== null) {
validationType = this.splitStringByComma(validationType);
for (var i = 0; i < validationType.length; i++) {
invalidElement = this.getElementsByPattern(elementAsArray, this.patterns[validationType[i]], validationType[i]);
if (invalidElement.length > 0) {
this.currentValidationType = validationType[i];
return false;
}
}
}
// As data-validate="length" has already been checked,
// only check the elements with data-length set.
if (element.getAttribute("data-length") === null ||
validationType !== null && validationType.indexOf("length") !== -1)
return true;
validationType = "length";
invalidElement = this.getElementsByPattern(elementAsArray, this.patterns[validationType], validationType);
if (invalidElement.length > 0)
return false;
return true;
} | javascript | {
"resource": ""
} | |
q39870 | requireDependencies | train | function requireDependencies(dependencies) {
var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var promise = new _es6Promise.Promise(function (succeed, fail) {
var requirements = {};
// no requirements
if (!(dependencies instanceof Array)) {
return succeed(requirements);
}
// check if succeeded
function checkStatus() {
if (Object.keys(requirements).length === dependencies.length) {
succeed(requirements);
}
}
dependencies.forEach(function (dependency) {
if (packages.has(dependency)) {
requirements[dependency] = packages.get(dependency);
} else {
events.once("load:" + dependency, function (requirement) {
requirements[dependency] = requirement;
checkStatus();
});
}
});
// First check
checkStatus();
});
return typeof callback === "function" ? promise.then(callback) : promise;
} | javascript | {
"resource": ""
} |
q39871 | definePackage | train | function definePackage(name, dependencies, callback) {
// Adjust arguments
if (typeof name === "function") {
callback = name;
name = null;
dependencies = null;
} else if (typeof dependencies === "function") {
callback = dependencies;
dependencies = null;
if (name instanceof Array) {
dependencies = name;
name = null;
}
}
// Check name conflicts
if (typeof name === "string") {
if (packages.has(name)) {
throw new Error("Package '" + name + "' is already loaded!");
}
}
// Resolve timeout
var timeout = _config2.default.get('package_timeout', 5000),
timer = null;
return new _es6Promise.Promise(function (succeed, fail) {
// Start timeout
if (typeof timeout === "number") {
timer = setTimeout(function () {
timer = null;
if (_config2.default.get("debug", true)) {
throw new Error("Package '" + name + "' timed out!");
}
}, timeout);
}
// Resolve dependencies
requireDependencies(dependencies).then(function (requirements) {
try {
// register package
var register = function register(pack) {
// cancel timeout
if (timer) {
clearTimeout(timer);
timer = null;
}
if (pack === false) {
return;
}
if (typeof name === "string") {
packages.set(name, pack);
events.emit("load:" + name, packages.get(name));
}
return succeed(pack);
};
// Check boot response
var bootResponse = typeof callback === "function" ? callback(requirements) : callback;return bootResponse instanceof _es6Promise.Promise ? bootResponse.then(register) : register(bootResponse);
} catch (ex) {
if (_config2.default.get("debug", true)) {
console.error(ex);
}
return fail(ex);
}
});
});
} | javascript | {
"resource": ""
} |
q39872 | wrapAll | train | function wrapAll(callback) {
// Prepare packages
var packs = {};
packages.forEach(function (pack, name) {
packs[name] = pack;
});
return callback(packs);
} | javascript | {
"resource": ""
} |
q39873 | isEmptyObject | train | function isEmptyObject(obj) {
if (obj === null) {
return true;
}
if (!isObject(obj)) {
return false;
}
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key]) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q39874 | dashToCamelCase | train | function dashToCamelCase(dashCase) {
if (!dashCase) { return dashCase; }
var parts = dashCase.split('-');
var camelCase = parts[0];
var part;
for (var i = 1; i < parts.length; i++) {
part = parts[i];
camelCase += part.substring(0, 1).toUpperCase() + part.substring(1);
}
return camelCase;
} | javascript | {
"resource": ""
} |
q39875 | train | function (route, parameters) {
return new Promise((resolve, reject) => {
request.get({
url: baseUrl + route + '?' + querystring.stringify(parameters)
}, (error, response, body) => {
if (error) {
reject(error);
} else if (response && body) {
var result;
try {
result = JSON.parse(body);
} catch (e) {
reject(e);
}
if (result.error == 'Method not allowed') {
this._post(route, parameters).then(
res => { resolve(res) },
err => { reject(err) }
);
} else {
resolve(result);
}
} else {
reject(response);
}
});
});
} | javascript | {
"resource": ""
} | |
q39876 | train | function (route, parameters) {
return new Promise((resolve, reject) => {
request.post({
url: baseUrl + route,
qs: parameters
}, (error, response, body) => {
if (error) {
reject(error);
} else { resolve('POST sent to ' + baseUrl + route + '\n' + JSON.stringify(parameters)); }
});
});
} | javascript | {
"resource": ""
} | |
q39877 | GET | train | function GET(uri, params) {
const reqUrl = `${uri}${url.format({ query: params })}`;
log(`request URL: ${reqUrl}`);
return fetch(reqUrl)
.then(function handleGetRequest(res) {
const status = res.status;
const statusText = res.statusText;
log(`status code: ${status}`);
log(`status text: ${statusText}`);
if (status !== 200) {
const err = new Error(`Request failed: ${statusText}`);
err.status = status;
throw err;
}
return res.json();
})
.then(data => {
const posts = data.posts;
log(`${posts.length} posts were fetched`);
return posts;
})
.catch(err => {
log('catched err: ', err);
throw err;
});
} | javascript | {
"resource": ""
} |
q39878 | jsonSchemaTypeToGraphQL | train | function jsonSchemaTypeToGraphQL(jsonSchemaType, schemaName) {
if (jsonSchemaType === "array") {
if (graphQLObjectTypes[schemaName]) {
return new GraphQLList(graphQLObjectTypes[schemaName]);
} else {
const translated = {
pilots: "people",
characters: "people",
residents: "people"
}[schemaName];
if (! translated) {
throw new Error(`no type ${schemaName}`);
}
const type = graphQLObjectTypes[translated];
if (! type) {
throw new Error(`no GraphQL type ${schemaName}`);
}
return new GraphQLList(type);
}
}
return {
string: GraphQLString,
date: GraphQLString,
integer: GraphQLInt,
}[jsonSchemaType];
} | javascript | {
"resource": ""
} |
q39879 | fetchPageOfType | train | function fetchPageOfType(typePluralName, pageNumber) {
let url = `http://swapi.co/api/${typePluralName}/`;
if (pageNumber) {
url += `?page=${pageNumber}`;
};
return restLoader.load(url).then((data) => {
// Paginated results have a different shape
return data.results;
});
} | javascript | {
"resource": ""
} |
q39880 | rgb2hsl | train | function rgb2hsl() {
const
R = this.R,
G = this.G,
B = this.B,
min = Math.min( R, G, B ),
max = Math.max( R, G, B ),
delta = max - min;
this.L = 0.5 * ( max + min );
if ( delta < 0.000001 ) {
this.H = 0;
this.S = 0;
} else {
this.S = delta / ( 1 - Math.abs( ( 2 * this.L ) - 1 ) );
if ( max === R ) {
if ( G >= B ) {
this.H = INV6 * ( ( G - B ) / delta );
} else {
this.H = 1 - ( INV6 * ( ( B - G ) / delta ) );
}
} else if ( max === G ) {
this.H = INV6 * ( 2 + ( ( B - R ) / delta ) );
} else {
this.H = INV6 * ( 4 + ( ( R - G ) / delta ) );
}
}
} | javascript | {
"resource": ""
} |
q39881 | getConf | train | function getConf( path, environment, callback, context ) {
// relative paths need to be auto-prefixed with the environment
if ( path.match( /^[^\.]/ ) ) {
path = "." + environment + "." + path;
}
if ( !context ) {
context = {
pathsSeen: {}
};
}
// avoid circular references
if ( context.pathsSeen[path] ) {
callback( undefined );
return;
}
context.pathsSeen[path] = true;
// calculate catch all path
var catchAllPath = ".*." + path.replace( /^\.[^\.]*\./, '' );
if ( catchAllPath === path ) {
catchAllPath = false;
}
// try exact path
moduleConfig.storage.getConf( path, function ( err, conf ) {
// if there was an error, don't try for wildcard
if ( err ) {
callback( undefined );
}
// not found, try wildcard
else if ( conf === null && catchAllPath ) {
moduleConfig.storage.getConf( catchAllPath, function ( err, conf ) {
// error searching for wild card
if ( err ) {
callback( undefined );
}
// wild card found
else {
applyAbstractions( conf, environment, context, callback );
}
} );
}
// exact path found
else {
applyAbstractions( conf, environment, context, callback );
}
} );
} | javascript | {
"resource": ""
} |
q39882 | getPath | train | function getPath( req, res, next ) {
var path = req.path.replace( /\..*$/, '' ).replace( /\//g, '.' ).replace( /^\.conf/, '' ).replace( /\.$/, '' ).trim();
if ( path.length < 1 ) {
path = null;
}
var outputFilter = req.path.trim().match( /\.(.*)$/ );
if ( outputFilter ) {
outputFilter = outputFilter[1].trim();
}
if ( typeof outputFilter !== 'string' || outputFilter.length < 1 ) {
outputFilter = 'json';
}
req.confPath = path;
req.outputFilter = outputFilter;
return next();
} | javascript | {
"resource": ""
} |
q39883 | configureExpress | train | function configureExpress() {
// create configuration routes
moduleConfig.express.get( /^\/conf.*/, checkAuth, getPath, getMiddlewareWrapper( onGetConf ) );
moduleConfig.express.post( /^\/conf.*/, storeRequestBody, checkAuth, getPath, getMiddlewareWrapper( onPostConf ) );
moduleConfig.express.delete( /^\/conf.*/, checkAuth, getPath, getMiddlewareWrapper( onDeleteConf ) );
// create auth management routes
moduleConfig.express.post( "/auth", checkAuth, getMiddlewareWrapper( onPostAuth ) );
moduleConfig.express.delete( "/auth", checkAuth, getMiddlewareWrapper( onDeleteAuth ) );
} | javascript | {
"resource": ""
} |
q39884 | getMiddlewareWrapper | train | function getMiddlewareWrapper( middleware ) {
return function ( req, res, next ) {
try {
middleware( req, res, next );
}
catch ( e ) {
getResponder( req, res )( 500 );
}
};
} | javascript | {
"resource": ""
} |
q39885 | getResponder | train | function getResponder( req, res ) {
return function ( code, body, contentType ) {
if ( code !== 200 ) {
body = "";
contentType = "text/html; charset=utf-8";
}
if ( !contentType ) {
contentType = "text/html; charset=utf-8";
}
res.writeHead( code, {
"Content-type": contentType
} );
res.end( body );
};
} | javascript | {
"resource": ""
} |
q39886 | SendgridProvider | train | function SendgridProvider(apiUser, apiKey, options) {
if (typeof apiUser !== 'string'
|| typeof apiKey !== 'string') {
throw new Error('Invalid parameters');
}
options = options || {};
if (typeof options.apiSecure === 'undefined')
options.apiSecure = true;
options.apiHostname = options.apiHostname || 'api.sendgrid.com';
options.apiPort = options.apiPort || (options.apiSecure ? 443 : 80);
this.apiUser = apiUser;
this.apiKey = apiKey;
this.options = options;
} | javascript | {
"resource": ""
} |
q39887 | consume | train | function consume(exchangeName, topics, handler) {
// Setup chain
var messageHandler = function(message) {
// make sure we don't have things like buffers
message.content = JSON.parse(message.content.toString());
topics.forEach(function(topic){
statusProvider.setEventConsumeExample(
exchangeName,
topic,
message.content
);
});
chain(message, handler)
};
rabbitmq.connectExchange(exchangeName, topics, messageHandler);
// add consume events to status provider
topics.forEach(function(topic){
statusProvider.addEventConsume(exchangeName, topic, false);
});
} | javascript | {
"resource": ""
} |
q39888 | consumeShared | train | function consumeShared(exchangeName, topics, queueName, handler, fetchCount = 1) {
var messageHandler = function(message) {
// make sure we don't have things like buffers
message.content = JSON.parse(message.content.toString());
topics.forEach(function(topic){
statusProvider.setEventConsumeExample(
exchangeName,
topic,
message.content
);
});
chain(message, handler)
};
rabbitmq.connectExchangeSharedQueue(exchangeName, topics, queueName, messageHandler, { prefetch: fetchCount });
// add consume events to status provider
topics.forEach(function(topic){
statusProvider.addEventConsume(exchangeName, topic, true, queueName);
});
} | javascript | {
"resource": ""
} |
q39889 | upper | train | function upper (value) {
if (value === null || value === undefined) {
return value
}
return String.prototype.toUpperCase.call(value)
} | javascript | {
"resource": ""
} |
q39890 | iftr | train | function iftr(conditionResult, trueValue, falseValue) {
if (conditionResult && (0, _is.isDefined)(trueValue)) return trueValue;
if (!conditionResult && (0, _is.isDefined)(falseValue)) return falseValue;
} | javascript | {
"resource": ""
} |
q39891 | train | function() {
switch(self.command) {
case constants.WHOIS:
return (self.params[0][0] == 'A');
case constants.PASSWORD:
return true;
case constants.NUMERICINFO:
case constants.GENERALINFO: // client-to-server
return (self.params.length < 2) || (self.params[0][0] == 'c');
case constants.SERVERMESSAGE:
return true;
default:
return false;
}
} | javascript | {
"resource": ""
} | |
q39892 | merge | train | function merge(need, options, level){
// 如果没有传第三个参数,默认无限递归右边覆盖左边
if (level == undefined) level = -1;
if (options === undefined) options = {};
if (need.length == 1) return need[0];
var res = {};
for (var i = 0; i < need.length; i++){
_merge(res, need[i], options, level - 1);
}
return res;
} | javascript | {
"resource": ""
} |
q39893 | Loop | train | function Loop(name, deps, fragment, loopFn, options) {
if (!(this instanceof Loop)) {
return new Loop(name, deps, fragment, loopFn, options);
}
Task.apply(this, Array.prototype.slice.call(arguments));
this.fragment = fragment;
this.loopFn = (_.isFunction(loopFn)) ? loopFn : function (input) { return [input]; };
this.options = options || {};
} | javascript | {
"resource": ""
} |
q39894 | createTables | train | function createTables() {
// setup config
var config = require('../config/config.js')
var db = wc_db.getConnection(config.db)
var sql = fs.readFileSync('model/Media.sql').toString()
debug(sql)
db.query(sql).then(function(ret){
debug(ret)
}).catch(function(err) {
debug(err)
})
var sql = fs.readFileSync('model/Rating.sql').toString()
debug(sql)
db.query(sql).then(function(ret){
debug(ret)
}).catch(function(err) {
debug(err)
})
var sql = fs.readFileSync('model/Tag.sql').toString()
debug(sql)
db.query(sql).then(function(ret){
debug(ret)
}).catch(function(err) {
debug(err)
})
var sql = fs.readFileSync('model/MediaTag.sql').toString()
debug(sql)
db.query(sql).then(function(ret){
debug(ret)
}).catch(function(err) {
debug(err)
})
var sql = fs.readFileSync('model/Fragment.sql').toString()
debug(sql)
db.query(sql).then(function(ret){
debug(ret)
}).catch(function(err) {
debug(err)
})
var sql = fs.readFileSync('model/Meta.sql').toString()
debug(sql)
db.query(sql).then(function(ret){
debug(ret)
}).catch(function(err) {
debug(err)
})
var sql = fs.readFileSync('model/User.sql').toString()
debug(sql)
db.query(sql).then(function(ret){
debug(ret)
}).catch(function(err) {
debug(err)
})
} | javascript | {
"resource": ""
} |
q39895 | addMedia | train | function addMedia(uri, contentType, safe) {
if (!uri || uri === '') {
return 'You must enter a valid uri'
}
safe = safe || 0
return new Promise((resolve, reject) => {
var config = require('../config/config.js')
var conn = wc_db.getConnection(config.db)
// sniff content type
if (!contentType) {
// image
if (uri.indexOf('.jpg') !== -1) {
contentType = 'image'
}
if (uri.indexOf('.png') !== -1) {
contentType = 'image'
}
if (uri.indexOf('.gif') !== -1) {
contentType = 'image'
}
if (uri.indexOf('.svg') !== -1) {
contentType = 'image'
}
// video
if (uri.indexOf('.mp4') !== -1) {
contentType = 'video'
}
if (uri.indexOf('.mpg') !== -1) {
contentType = 'video'
}
if (uri.indexOf('.mov') !== -1) {
contentType = 'video'
}
if (uri.indexOf('.wmv') !== -1) {
contentType = 'video'
}
if (uri.indexOf('.avi') !== -1) {
contentType = 'video'
}
if (uri.indexOf('.m4v') !== -1) {
contentType = 'video'
}
if (uri.indexOf('.mkv') !== -1) {
contentType = 'video'
}
// audio
if (uri.indexOf('.mp3') !== -1) {
contentType = 'audio'
}
if (uri.indexOf('.ogg') !== -1) {
contentType = 'video'
}
if (uri.indexOf('.flv') !== -1) {
contentType = 'video'
}
}
var sql = 'INSERT into Media values (NULL, :uri, NULL, NULL, NULL, :contentType, ' + safe + ')'
conn.query(sql, { replacements: { "uri" : uri, "contentType" : contentType } }).then(function(ret){
return resolve({"ret" : ret, "conn" : conn})
}).catch(function(err) {
return reject(err)
})
})
} | javascript | {
"resource": ""
} |
q39896 | addRating | train | function addRating(rating, config, conn) {
// validate
if (!rating.uri || rating.uri === '') {
return 'You must enter a valid uri'
}
if (!rating.reviewer || rating.reviewer === '') {
return 'You must enter a valid reviewer'
}
if (isNaN(rating.rating)) {
return 'You must enter a valid rating'
}
// defaults
config = config || require('../config/config.js')
debug(rating)
// main
return new Promise((resolve, reject) => {
if (!conn) {
var conn = wc_db.getConnection(config.db)
}
insertRating(rating, config, conn).then(function(ret) {
return resolve({"ret": ret, "conn": conn})
}).catch(function(err) {
debug('addRating', 'updating instead of insert')
return updateRating(rating, config, conn)
}).then(function(ret){
return resolve({"ret": ret, "conn": conn})
}).catch(function(){
return reject({"ret": ret, "conn": conn})
})
})
} | javascript | {
"resource": ""
} |
q39897 | addMeta | train | function addMeta(params, config, conn) {
params = params || {}
// validate
if (!params.uri || params.uri === '') {
return 'You must enter a valid uri'
}
// defaults
config = config || require('../config/config.js')
debug(params)
// main
// main
return new Promise((resolve, reject) => {
if (!conn) {
var conn = wc_db.getConnection(config.db)
}
if (!params.subtitlesURI) {
params.subtitlesURI = null
}
if (!params.charenc) {
params.charenc = null
}
var sql = 'INSERT into Meta select a.id, :length, :subtitlesURI, :charenc from Media a where a.uri = :uri ;'
debug('addMeta', sql, params)
conn.query(sql, { replacements: { "length" : params.length, "subtitlesURI": params.subtitlesURI, "uri" : params.uri, "charenc" : params.charenc } }).then(function(ret){
return resolve({"ret" : ret, "conn" : conn})
}).catch(function(err) {
return reject({"err" : err, "conn" : conn})
})
})
} | javascript | {
"resource": ""
} |
q39898 | addFragment | train | function addFragment(params, config, conn) {
// validate
if ( (!params.id || params.id === '') && (!params.uri || params.uri === '') ) {
return 'You must enter a valid id or uri'
}
// defaults
config = config || require('../config/config.js')
debug(params)
// main
return new Promise((resolve, reject) => {
if (!conn) {
var conn = wc_db.getConnection(config.db)
}
var sql
if (params.id) {
sql = 'INSERT into Fragment values (:id, :start, :end, NULL, NOW(), 1)'
} else {
sql = 'INSERT into Fragment Select m.id, :start, :end, NULL, NOW(), u.id from Media m, User u where m.uri = :uri and u.uri = :webid'
}
debug(sql)
conn.query(sql, { replacements: { "id" : params.id, "start" : params.start, "end" : params.end, "uri" : params.uri, "webid" : params.webid } }).then(function(ret){
return resolve({"ret" : ret, "conn" : conn})
}).catch(function(err) {
return reject({"err" : err, "conn" : conn})
})
})
} | javascript | {
"resource": ""
} |
q39899 | insertRating | train | function insertRating(rating, config, conn) {
// validate
if ( (!rating.uri || rating.uri === '') && (!rating.cacheURI || rating.cacheURI === '') ) {
return 'You must enter a valid uri'
}
if (!rating.reviewer || rating.reviewer === '') {
return 'You must enter a valid reviewer'
}
// defaults
config = config || require('../config/config.js')
// main
return new Promise((resolve, reject) => {
if (!conn) {
var conn = wc_db.getConnection(config.db)
}
var sql
if (rating.uri) {
sql = 'INSERT into Rating values (NULL, :uri, :rating, NULL, :reviewer, NULL, NOW())'
} else {
sql = 'INSERT into Rating SELECT NULL, a.uri, :rating, NULL, :reviewer, NULL, NOW() from Media a where a.cacheURI = :cacheURI '
}
debug('insertRating', sql, rating)
conn.query(sql, { replacements: { "uri" : rating.uri, "cacheURI" : rating.cacheURI, "reviewer" : rating.reviewer, "rating" : rating.rating ? rating.rating : null } }).then(function(ret){
return resolve({"ret" : ret, "conn" : conn})
}).catch(function(err) {
return reject({"err" : err, "conn" : conn})
})
})
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.