_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q37400
CommandArgLength
train
function CommandArgLength(cmd) { this.name = CommandArgLength.name; if(arguments.length > 1) { cmd = slice.call(arguments, 0).join(' '); } StoreError.apply( this, [null, 'wrong number of arguments for \'%s\' command', cmd]); }
javascript
{ "resource": "" }
q37401
ConfigValue
train
function ConfigValue(key, value) { this.name = ConfigValue.name; StoreError.apply( this, [null, 'invalid argument \'%s\' for CONFIG SET \'%s\'', value, key]); }
javascript
{ "resource": "" }
q37402
exposeSwagger
train
function exposeSwagger(path, options) { if (typeof path !== 'string') { options = path; path = null; } path = path || '/swagger.json'; options = options || {}; var needCors = options.cors; delete options.cors; var beautify = options.beautify; delete options.beautify; beautify = beautify === true ? ' ' : beautify; this.__swaggerDocURL = path; this.__swaggerDocJSON = JSON.stringify( this.swaggerDoc(options), null, beautify ); if (needCors !== false) { this.get(path, cors(), swaggerJSON.bind(this)); } else { this.get(path, swaggerJSON.bind(this)); } return this; }
javascript
{ "resource": "" }
q37403
exposeSwaggerUi
train
function exposeSwaggerUi(path, options) { if (typeof path !== 'string') { options = path; path = null; } options = options || {}; var swaggerDoc = options.swaggerDoc; delete options.swaggerDoc; if (!this.__swaggerDocURL) { this.exposeSwagger(swaggerDoc || '', options); }; var uiPath = _path.join(__dirname, '../swagger-ui'); this.__swaggerUiStaticMiddleware = serveStatic(uiPath, {}); this.__swaggerUiPath = path || '/swagger-ui'; this.use(this.__swaggerUiPath, swaggerUi.bind(this)); return this; }
javascript
{ "resource": "" }
q37404
getJSON
train
function getJSON(jsonUrl, done) { var parsedUrl = url.parse(jsonUrl); var options = { "host" : parsedUrl.hostname, "hostname": parsedUrl.hostname, "port" : parsedUrl.port || 80, "path" : parsedUrl.pathname, "method" : "GET", // "agent" : false, }; debug && console.error("prepublish:getJSON('" + jsonUrl + "', done)"); debug && console.error("options=" + util.inspect(options)); var req = http.get(options, function (res) { debug && console.error("STATUS: " + res.statusCode); debug && console.error("HEADERS: " + JSON.stringify(res.headers)); res.setEncoding('utf8'); var data = ''; res.on('data', function (chunk) { debug && console.error('getJSON: chunk="' + chunk + '"'); data += chunk; }); res.on('end', function() { debug && console.error('getJSON: end of request.'); done(JSON.parse(data)); }); }); req.on('error', function(error) { console.error("ERROR: " + error.message); }); }
javascript
{ "resource": "" }
q37405
main
train
function main() { var database = fs.createWriteStream('./lib/database-min.js', { flags: 'w', encoding: 'utf8' }); var testFile; fs.mkdir('./data', 493, function (error) { // 493 == 0755 (no octal in strict mode.) // ignore errors. }); database.write("// Do not edit this file, your changes will be lost.\n"); database.write("module.exports = { \n"); getJSON('http://alscan.info/agent_groups/groups.json', function (groups) { var s = JSON.stringify(groups); database.write("groups:" + s + ",\n"); testFile = fs.createWriteStream('./data/groups.json', { flags: 'w', encoding: 'utf8' }); testFile.write(s+"\n"); testFile.end(); getJSON('http://alscan.info/agent_sources/sources.json', function (sources) { var s = JSON.stringify(sources); database.write("sources:" + s + ",\n"); testFile = fs.createWriteStream('./data/sources.json', { flags: 'w', encoding: 'utf8' }); testFile.write(s+"\n"); testFile.end(); getJSON('http://alscan.info/patterns/patterns.json', function (patterns) { database.write("patterns:[\n"); patterns.forEach(function (pattern) { database.write("{p: new RegExp('" + pattern.pattern + "'), x:" + agentdb.getX(pattern.groupId, pattern.sourceId) + "},"); }); database.write("],\n"); testFile = fs.createWriteStream('./data/patterns.json', { flags: 'w', encoding: 'utf8' }); testFile.write(JSON.stringify(patterns)+"\n"); testFile.end(); getJSON('http://alscan.info/agents/agents.json', function (agents) { var hash = new HashTable(HASH_TABLE_SIZE, HASH_TABLE_SEED, HASH_TABLE_MULTIPLIER); agents.forEach(function (agent) { if (agent.status < 2) { var obj = { a: agent.agent, x: agentdb.getX(agent.groupId, agent.sourceId) }; hash.add('a', obj); } }); database.write("table:" + JSON.stringify(hash.table) + ",\n"); database.write("HASH_TABLE_SIZE:" + HASH_TABLE_SIZE + ",\n"); database.write("HASH_TABLE_SEED:" + HASH_TABLE_SEED + ",\n"); database.write("HASH_TABLE_MULTIPLIER:" + HASH_TABLE_MULTIPLIER + ",\n"); database.write("hash: undefined\n}\n"); testFile = fs.createWriteStream('./data/agents.json', { flags: 'w', encoding: 'utf8' }); testFile.write(JSON.stringify(agents)+"\n"); testFile.end(); if (debug) { var history = hash.getHistory(); console.log("Hash table history"); for (var n=0; n < history.length; n++) { console.log(" Depth=" + n + ", count=" + history[n] + ", percent=" + (history[n] / HASH_TABLE_SIZE)); } } }); }); }); }); }
javascript
{ "resource": "" }
q37406
datePlusFrequency
train
function datePlusFrequency(date, frequency) { var minutes; date = date || new Date(); // default is today frequency = frequency || 'hourly'; // default is hourly switch (frequency) { case 'none': minutes = 525949; // set far in future break; case 'instant': minutes = 1; break; case 'hourly': minutes = 60; break; case 'daily': minutes = 1440; break; case 'weekly': minutes = 10080; break; default: minutes = 0; } return new Date(date.getTime() + (minutes * 60000)); }
javascript
{ "resource": "" }
q37407
serializeAllDates
train
function serializeAllDates(obj) { // if it is a date, then return serialized version if (_.isDate(obj)) { return serializeDate(obj); } // if array or object, loop over it if (_.isArray(obj) || _.isObject(obj)) { _.forEach(obj, function (item, key) { obj[key] = serializeAllDates(item); }); } return obj; }
javascript
{ "resource": "" }
q37408
train
function (object) { var result = { }; for (var i in object) { if (!object.hasOwnProperty(i)) continue; if (isObject(object[i])) { var flatObject = this.flatten(object[i]); for (var x in flatObject) { if (!flatObject.hasOwnProperty(x)) continue; result[i + '.' + x] = flatObject[x]; } } else { result[i] = object[i]; } } return result; }
javascript
{ "resource": "" }
q37409
readFileSync_
train
function readFileSync_(path){ if(file_values_[path]){ return file_values_[path]; } try { file_values_[path]=fs.readFileSync(path,'utf-8'); return file_values_[path]; }catch(e){ return null; } }
javascript
{ "resource": "" }
q37410
train
function(doc){ var vs=doc.split("\r\n"); if(vs.length==1){ vs=doc.split("\n"); } if(vs[vs.length-1]==''){ vs.pop(); } return vs; }
javascript
{ "resource": "" }
q37411
toExpr
train
function toExpr(value,line){ var token=[]; var ctoken=token; var newToken; var stacks=[]; var c; var ss=''; for(var i=0;i<value.length;i++){ c=value[i]; switch(c){ case ' ': case "\t": case ",": if(ss!=""){ ctoken.push(ss); ss=""; } break; case '(': if(ss!=""){ console.log("warning: no space before '(' in line "+line+" at "+(i+1)); ctoken.push(ss); ss=""; } stacks.push(ctoken); newToken=[]; ctoken.push(newToken); ctoken=newToken; break; case ')': if(ss!=""){ ctoken.push(ss); ss=""; } if(stacks.length>0){ ctoken=stacks.pop(); }else{ console.log("error: unmatched ')' in line "+line+" at "+(i+1)); return null; } break; default: ss+=c; break; } } if(ss!=''){ ctoken.push(ss); } // remove last '*/', '###' var ltoken=null; if(token&&(token.length>0)){ ltoken=token[token.length-1]; if((typeof ltoken=='string')&&((ltoken=='*/')||(ltoken=='###'))){ ltoken.pop(); } } return token; }
javascript
{ "resource": "" }
q37412
makeFromFile
train
function makeFromFile(makefile,target){ var read; var basedir='.'; if(makefile){ read = fs.createReadStream(makefile, {encoding: 'utf8'}); basedir=mpath.dirname(makefile); }else{ process.stdin.resume(); process.stdin.setEncoding('utf8'); read = process.stdin; } read.on('data', function (data){ try { var o=JSON.parse(data); make(basedir, o, target); }catch(e){ console.log(e); } }); }
javascript
{ "resource": "" }
q37413
_parse_lazy
train
function _parse_lazy(eof, productions, table, rule, tape, nonterminal, production) { var shallow_materialize = /*#__PURE__*/ function () { var _ref = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(expected) { return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _children_next_lazy2.default)(eof, productions, table, tape, expected); case 2: return _context.abrupt("return", _context.sent); case 3: case "end": return _context.stop(); } } }, _callee, this); })); return function shallow_materialize(_x) { return _ref.apply(this, arguments); }; }(); var iterator = (0, _ast.rmap)(shallow_materialize, rule)[Symbol.asyncIterator](); return { 'type': 'node', nonterminal: nonterminal, production: production, children: new _ast.Children(iterator, rule.length) }; }
javascript
{ "resource": "" }
q37414
complexReturn
train
function complexReturn(result, data) { var complex = new String(result); for (var key in data) { complex[key] = data[key]; } return complex; }
javascript
{ "resource": "" }
q37415
Sample
train
function Sample(val, timeStamp, persistObj) { this.min = val; this.max = val; this.sigma = new StandardDeviation(val); this.average = new Average(val); this.timeStamp = timeStamp; if (persistObj) { var that = this; persistObj.on('reset', function (timeStamp) { that.reset(timeStamp); }); } }
javascript
{ "resource": "" }
q37416
isHtmlFileUptodate
train
function isHtmlFileUptodate(source) { var dependencies = source.tag("dependencies") || []; var i, dep, file, prj = source.prj(), stat, mtime = source.modificationTime(); for (i = 0 ; i < dependencies.length ; i++) { dep = dependencies[i]; file = prj.srcOrLibPath(dep); if (file) { stat = FS.statSync(file); if (stat.mtime > mtime) return false; } } return source.isUptodate(); }
javascript
{ "resource": "" }
q37417
train
function (item, req, eachReq, res, next) { eachReq.item = item; eachReq[indexKey] = index; index++; next(); }
javascript
{ "resource": "" }
q37418
PancakesHapiPlugin
train
function PancakesHapiPlugin(opts) { this.pancakes = opts.pluginOptions.pancakes; this.jangular = opts.pluginOptions.jangular; }
javascript
{ "resource": "" }
q37419
_fetch
train
function _fetch() { vm.error = undefined; service.get({}, function (todos) { vm.todos = todos; }, function () { vm.todos = []; vm.error = 'An error occurred when fetching available todos'; }); }
javascript
{ "resource": "" }
q37420
add
train
function add() { vm.error = undefined; service.add({ description: vm.description }, function() { _fetch(); }, function() { vm.error = 'An error occurred when adding a todo'; }); vm.description = ''; }
javascript
{ "resource": "" }
q37421
complete
train
function complete(todo) { vm.error = undefined; service.complete(todo, function() { _fetch(); }, function() { vm.error = 'An error occurred when completing a todo'; }); }
javascript
{ "resource": "" }
q37422
archive
train
function archive() { vm.error = undefined; var promises = []; vm.todos.filter(function (todo) { return todo.completed; }).forEach(function (todo) { promises.push(_archive(todo)); }); $q.all(promises).then(function () { _fetch(); }).catch(function () { vm.error = 'An error occurred when archiving completed todos'; }); }
javascript
{ "resource": "" }
q37423
_archive
train
function _archive(todo) { var deferred = $q.defer(); service.archive(todo, function () { return deferred.resolve(); }, function () { return deferred.reject(); }); return deferred.promise; }
javascript
{ "resource": "" }
q37424
train
function (args) { if (false === (this instanceof Session)) throw new Error('new operator required'); args = args || {}; if (!args.attributes) { args.attributes = []; } var userModelID = new Attribute.ModelID(new User()); args.attributes.push(new Attribute({name: 'userID', type: 'Model', value: userModelID})); args.attributes.push(new Attribute({name: 'dateStarted', type: 'Date', value: new Date()})); args.attributes.push(new Attribute({name: 'passCode', type: 'String(20)'})); args.attributes.push(new Attribute({name: 'active', type: 'Boolean'})); args.attributes.push(new Attribute({name: 'ipAddress', type: 'String'})); Model.call(this, args); this.modelType = "Session"; this.set('active', false); }
javascript
{ "resource": "" }
q37425
train
function (args) { if (false === (this instanceof User)) throw new Error('new operator required'); args = args || {}; if (!args.attributes) { args.attributes = []; } args.attributes.push(new Attribute({name: 'name', type: 'String(20)'})); args.attributes.push(new Attribute({name: 'active', type: 'Boolean'})); args.attributes.push(new Attribute({name: 'password', type: 'String(20)'})); args.attributes.push(new Attribute({name: 'firstName', type: 'String(35)'})); args.attributes.push(new Attribute({name: 'lastName', type: 'String(35)'})); args.attributes.push(new Attribute({name: 'email', type: 'String(20)'})); Model.call(this, args); this.modelType = "User"; this.set('active', false); }
javascript
{ "resource": "" }
q37426
Workspace
train
function Workspace(args) { if (false === (this instanceof Workspace)) throw new Error('new operator required'); args = args || {}; if (!args.attributes) { args.attributes = []; } var userModelID = new Attribute.ModelID(new User()); args.attributes.push(new Attribute({name: 'user', type: 'Model', value: userModelID})); args.attributes.push(new Attribute({name: 'deltas', type: 'Object', value: {}})); // var delta // this.deltas = []; Model.call(this, args); this.modelType = "Workspace"; }
javascript
{ "resource": "" }
q37427
train
function (args) { if (false === (this instanceof MemoryStore)) throw new Error('new operator required'); args = args || {}; this.storeType = args.storeType || "MemoryStore"; this.name = args.name || 'a ' + this.storeType; this.storeProperty = { isReady: true, canGetModel: true, canPutModel: true, canDeleteModel: true, canGetList: true }; this.data = [];// Each ele is an array of model types and contents (which is an array of IDs and Model Value Store) this.idCounter = 0; var unusedProperties = getInvalidProperties(args, ['name', 'storeType']); var errorList = []; for (var i = 0; i < unusedProperties.length; i++) errorList.push('invalid property: ' + unusedProperties[i]); if (errorList.length > 1) throw new Error('error creating Store: multiple errors'); if (errorList.length) throw new Error('error creating Store: ' + errorList[0]); }
javascript
{ "resource": "" }
q37428
renderText
train
function renderText(text) { var textDiv = addEle(panel.panelForm, 'div', indent ? 'col-sm-offset-3' : ''); textDiv.innerHTML = marked(text.get()); text.onEvent('StateChange', function () { textDiv.innerHTML = marked(text.get()); }); panel.textListeners.push(text); // so we can avoid leakage on deleting panel }
javascript
{ "resource": "" }
q37429
train
function (event) { switch (attribute.type) { case 'Date': attribute.value = (input.value === '') ? null : attribute.coerce(input.value); if (attribute.value != null) { var mm = attribute.value.getMonth() + 1; var dd = attribute.value.getDate(); var yyyy = attribute.value.getFullYear(); if (mm < 10) mm = '0' + mm; if (dd < 10) dd = '0' + dd; input.value = mm + '/' + dd + '/' + yyyy; } else { input.value = ''; } break; default: attribute.value = (input.value === '') ? null : attribute.coerce(input.value); if (attribute.value != null) input.value = attribute.value; break; } attribute.validate(function () { }); }
javascript
{ "resource": "" }
q37430
renderHelpText
train
function renderHelpText(text) { if (text) { if (!helpTextDiv) { helpTextDiv = document.createElement("div"); helpTextDiv.className = 'col-sm-9 col-sm-offset-3 has-error'; formGroup.appendChild(helpTextDiv); } helpTextDiv.innerHTML = '<span style="display: block;" class="help-block">' + text + '</span>'; $(formGroup).addClass('has-error'); if (inputGroupButton) $(inputGroupButton).addClass('btn-danger'); } else { setTimeout(function () { if (helpTextDiv) { $(helpTextDiv).remove(); helpTextDiv = null; } }, 250); $(formGroup).removeClass('has-error'); if (inputGroupButton) $(inputGroupButton).removeClass('btn-danger'); } }
javascript
{ "resource": "" }
q37431
renderList
train
function renderList(list, theme) { var txtDiv = document.createElement("table"); txtDiv.className = 'table table-condensed table-bordered table-hover-' + theme; //bootstrapInterface.info(txtDiv.className); /** * Header */ var tHead = addEle(txtDiv, 'thead'); var tHeadRow = addEle(tHead, 'tr'); for (j = 1; j < list.model.attributes.length; j++) { // skip id (0)) var hAttribute = list.model.attributes[j]; if (hAttribute.hidden == undefined) addEle(tHeadRow, 'th').innerHTML = hAttribute.label; } /** * Now each row in list */ var gotData = list.moveFirst(); var tBody = addEle(txtDiv, 'tbody'); while (gotData) { var tBodyRow = addEle(tBody, 'tr'); var idAttribute = list.model.attributes[0]; $(tBodyRow).data("id", list.get(idAttribute.name)); $(tBodyRow).click(function (e) { // bootstrapInterface.dispatch(new Request({type: 'Command', command: action})); // bootstrapInterface.info('you picked #' + $(e.currentTarget).data("id")); if (list.pickKludge) list.pickKludge($(e.currentTarget).data("id")); // too shitty balls e.preventDefault(); }); for (j = 1; j < list.model.attributes.length; j++) { // skip id (0)) var dAttribute = list.model.attributes[j]; if (dAttribute.hidden == undefined) { var dValue = list.get(dAttribute.name); switch (dAttribute.type) { case 'Date': //console.log('dValue=' + dValue); // addEle(tBodyRow, 'td').innerHTML = left(dValue.toISOString(), 10); // addEle(tBodyRow, 'td').innerHTML = dValue.toString(); // todo use moment.js if (dValue) addEle(tBodyRow, 'td').innerHTML = left(dValue.toISOString(), 10); else addEle(tBodyRow, 'td').innerHTML = '&nbsp;'; break; case 'Boolean': if (dValue) addEle(tBodyRow, 'td').innerHTML = '<i class="fa fa-check-square-o"></i>'; else addEle(tBodyRow, 'td').innerHTML = '<i class="fa fa-square-o"></i>'; break; default: if (dValue && dValue.name) // todo instanceof Attribute.ModelID did not work so kludge here addEle(tBodyRow, 'td').innerHTML = dValue.name; else addEle(tBodyRow, 'td').innerHTML = dValue; } } } gotData = list.moveNext(); } panel.panelForm.appendChild(txtDiv); }
javascript
{ "resource": "" }
q37432
renderCommand
train
function renderCommand(command) { if (!panel.buttonDiv) { var formGroup = addEle(panel.panelForm, 'div', 'form-group'); panel.buttonDiv = addEle(formGroup, 'div', indent ? 'col-sm-offset-3 col-sm-9' : 'col-sm-9'); } var cmdTheme = command.theme || 'default'; var button = addEle(panel.buttonDiv, 'button', 'btn btn-' + cmdTheme + ' btn-presentation', {type: 'button'}); var icon = command.icon; if (icon) { if (left(icon, 2) == 'fa') icon = '<i class="fa ' + icon + '"></i>&nbsp;'; else icon = '<span class="glyphicon ' + icon + '"></span>&nbsp;'; button.innerHTML = icon + command.name; } else { button.innerHTML = command.name; } $(button).on('click', function (event) { event.preventDefault(); bootstrapInterface.dispatch(new Request({type: 'Command', command: command})); }); panel.listeners.push(button); // so we can avoid leakage on deleting panel }
javascript
{ "resource": "" }
q37433
setUnusableRecord
train
function setUnusableRecord(state, unusableRecord) { Object.defineProperty(state, 'unusableRecord', {value: unusableRecord, writable: true, configurable: true, enumerable: false}); }
javascript
{ "resource": "" }
q37434
setUserRecord
train
function setUserRecord(state, userRecord) { Object.defineProperty(state, 'userRecord', {value: userRecord, writable: true, configurable: true, enumerable: false}); }
javascript
{ "resource": "" }
q37435
setRecord
train
function setRecord(state, record) { Object.defineProperty(state, 'record', {value: record, writable: true, configurable: true, enumerable: false}); }
javascript
{ "resource": "" }
q37436
deleteLegacyState
train
function deleteLegacyState(trackedItem, context) { const taskTrackingName = Settings.getLegacyTaskTrackingName(context); return taskTrackingName && trackedItem ? delete trackedItem[taskTrackingName] : true; }
javascript
{ "resource": "" }
q37437
data
train
function data(app, file, key) { var o = has(app.options, key); var c = has(app.cache.data, key); var d = has(file.data, key); if (!c && !d && !o) { set(file.data, key, comment(key, 'property')); console.log(warning(' missing variable:')); } }
javascript
{ "resource": "" }
q37438
helper
train
function helper(app, file, key, re) { var h = get(app._.asyncHelpers, key); var a = get(app._.helpers, key); if (!h && !a) { set(file.data, key, function () { return comment(key, 'helper'); }); if (re.test(file.content)) { var message = 'MISSING helper: "' + key + '".\n'; // rethrow (or actually throw) the error var err = new SyntaxError(message); if (app.disabled('silent')) { rethrow(err, file.path, file.content, re); } } } }
javascript
{ "resource": "" }
q37439
rethrow
train
function rethrow(err, fp, str, re) { var lines = str.split('\n'); var len = lines.length, i = 0; var res = ''; while (len--) { var line = lines[i++]; if (re.test(line)) { error(err, fp, i, str); break; } } }
javascript
{ "resource": "" }
q37440
SQLite
train
function SQLite(config) { /*jshint bitwise: false */ var self = this; config = config || {}; config.mode = config.mode || (sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE); if (!config.filename) { // Exit if no filename provided throw new Error("No filename provided for SQLite Driver"); } else if (config.filename != ":memory:" && !fs.existsSync(config.filename)) { // Create file if it doesn't exist fs.writeFileSync(config.filename, '', 'binary'); } this.className = this.constructor.name; this.config = config; // Set client this.client = new sqlite3.Database(config.filename, config.mode); // Assign storage if (typeof config.storage == 'string') { this.storage = app.getResource('storages/' + config.storage); } else if (config.storage instanceof protos.lib.storage) { this.storage = config.storage; } // Set db this.db = config.filename; // Only set important properties enumerable protos.util.onlySetEnumerable(this, ['className', 'db']); }
javascript
{ "resource": "" }
q37441
createStacks
train
function createStacks (state) { const serviceErrors = state.config.service.errors || {} _.each(state.resources, function (resource) { const resourceErrors = resource.errors _.each(resource.actions, function (action, actionName) { action.name = actionName const actionErrors = action.errors var transform const key = [ resource.name, action.name ].join('!') if (state.config.middlewareStack) { const middleware = getStack(state, state.config.middlewareStack, resource, action) state.handlers[ middleware.name ] = middleware } if (state.config.transformStack) { transform = getStack(state, state.config.transformStack, resource, action) } else { transform = state.snap.stack(key) } transform.append(unit) state.transforms[ transform.name ] = transform const errors = Object.assign({}, serviceErrors, resourceErrors, actionErrors) state.errors[ key ] = handleError.bind(null, state, errors) }) }) }
javascript
{ "resource": "" }
q37442
defaultErrorStrategy
train
function defaultErrorStrategy (env, error) { return { status: 500, error: error, data: `An unhandled error of '${error.name}' occurred at ${env.resource} - ${env.action}` } }
javascript
{ "resource": "" }
q37443
getProperty
train
function getProperty (service, resource, action, propertySpec) { const parts = propertySpec.split('.') var target switch (parts[ 0 ]) { case 'action': target = action break case 'resource': target = resource break default: target = service } const property = parts[ 1 ] return { key: property, value: target ? target[ property ] : null } }
javascript
{ "resource": "" }
q37444
md5
train
function md5() { var string = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; return crypto.createHash('md5').update(new Buffer(string, 'utf-8')).digest("hex"); }
javascript
{ "resource": "" }
q37445
single
train
function single (url, options = {}) { let tries = 1 // Execute the request and retry if there are errors (and the // retry decider decided that we should try our luck again) const callRequest = () => request(url, options).catch(err => { if (internalRetry(++tries, err)) { return wait(callRequest, internalRetryWait(tries)) } throw err }) return callRequest() }
javascript
{ "resource": "" }
q37446
request
train
function request (url, options) { options = Object.assign({}, defaultOptions, options) let savedContent let savedResponse return new Promise((resolve, reject) => { fetch(url, options) .then(handleResponse) .then(handleBody) .catch(handleError) function handleResponse (response) { // Save the response for checking the status later savedResponse = response // Decode the response body switch (options.type) { case 'response': return response case 'json': return response.json() default: return response.text() } } function handleBody (content) { // Bubble an error if the response status is not okay if (savedResponse && savedResponse.status >= 400) { savedContent = content throw new Error(`Response status indicates error`) } // All is well! resolve(content) } function handleError (err) { // Overwrite potential decoding errors when the actual problem was the response if (savedResponse && savedResponse.status >= 400) { err = new Error(`Status ${savedResponse.status}`) } // Enrich the error message with the response and the content let error = new Error(err.message) error.response = savedResponse error.content = savedContent reject(error) } }) }
javascript
{ "resource": "" }
q37447
many
train
function many (urls, options = {}) { let flowMethod = (options.waitTime) ? flow.series : flow.parallel // Call the single method while respecting the wait time in between tasks const callSingle = (url) => single(url, options) .then(content => wait(() => content, options.waitTime)) // Map over the urls and call them using the method the user chose let promises = urls.map(url => () => callSingle(url)) return flowMethod(promises) }
javascript
{ "resource": "" }
q37448
generateForUser
train
function generateForUser(user, existingToken) { existingToken = existingToken || {}; var privateKey = config.security.token.privateKey; var decryptedToken = _.extend(existingToken, { _id: user._id, authToken: user.authToken }); return jsonwebtoken.sign(decryptedToken, privateKey); }
javascript
{ "resource": "" }
q37449
execute
train
function execute(req, res) { this.state.pubsub.psubscribe(req.conn, req.args); }
javascript
{ "resource": "" }
q37450
Channel
train
function Channel(server, opts) { this.server = server; opts = opts || {}; this.channelId = opts.channelId; this.timeserver = opts.timeserver || this.server.timeserverUrl(); this.clients = []; this.clientStates = {}; // Hackery this.setMaxListeners(150); this.clockClient = new ClockClient(this.timeserver); this.sync(); }
javascript
{ "resource": "" }
q37451
catchAsyncErrors
train
function catchAsyncErrors(fn) { return async (...args) => { try{ await Promise.resolve(fn(...args)).catch(args[2])} catch(e){ args[2](e) } } }
javascript
{ "resource": "" }
q37452
isLastLevel
train
function isLastLevel(arr){ //console.log("isLastLevel(" + arr + ")"); if(!arr){ return true; } for(var i = 0; i < arr.length; i++){ if(typeof arr[i] === 'number'); else if(arr[i].substring(0,1) === '-'){ //console.log("->false"); return false; } } //console.log("-> true"); return true; }
javascript
{ "resource": "" }
q37453
Message
train
function Message () { if (!(this instanceof Message)) { if (typeof arguments[0] === 'object' && arguments[0] instanceof Message) { debug('message is a message so return it'); return arguments[0]; } else { debug('creating new message and initializing with arguments'); var m = new Message(); Message.prototype.initialize.apply(m, slice.call(arguments)); return m; } } else { this.isMessage = true; if (arguments.length) { debug('initializing with arguments'); Message.prototype.initialize.apply(this, slice.call(arguments)); } } }
javascript
{ "resource": "" }
q37454
filterSchemas
train
function filterSchemas(schemas, tableNames, callback) { if (! (schemas || []).length || ! (tableNames || []).length) return process.nextTick(_.partial(callback, null, schemas || [])); var schemasMap = _.indexBy(schemas, 'tableName'); var filteredSchemas = _.chain(schemasMap).pick(tableNames).toArray().value(); resolveSchemasDeps(filteredSchemas, schemasMap, callback); }
javascript
{ "resource": "" }
q37455
resolveSchemasDeps
train
function resolveSchemasDeps(schemas, schemasMap, callback) { async.reduce(schemas, [], function (result, schema, next) { tryAndDelay(resolveSchemaDeps, result, schema, schemasMap, next); }, function (err, result) { return err ? callback(err) : callback(null, _.uniq(result)); }); }
javascript
{ "resource": "" }
q37456
resolveSchemaDeps
train
function resolveSchemaDeps(result, schema, schemasMap) { if (! (schema.deps || []).length) return result.concat([ schema ]); return schema.deps.reduce(function (result, tableName) { return (result.indexOf(schemasMap[tableName]) >= 0) ? result : result.concat(resolveSchemaDeps(result, schemasMap[tableName], schemasMap)); }, result).concat([ schema ]); }
javascript
{ "resource": "" }
q37457
tryAndDelay
train
function tryAndDelay(fn) { var args = _.chain(arguments).rest().initial().value(); var callback = _.last(arguments); try { process.nextTick(_.partial(callback, null, fn.apply(null, args))); } catch (err) { process.nextTick(_.partial(callback, err)); } }
javascript
{ "resource": "" }
q37458
genServiceMethod
train
function genServiceMethod(method) { return function (req) { return ajax.send(method.url, method.httpMethod, req, method.resourceName); }; }
javascript
{ "resource": "" }
q37459
genService
train
function genService(methods) { var service = {}; for (var methodName in methods) { if (methods.hasOwnProperty(methodName)) { service[methodName] = genServiceMethod(methods[methodName]); } } return service; }
javascript
{ "resource": "" }
q37460
reverse
train
function reverse() { var upperIndex, value, index = -1, object = Object(this), length = object.length >>> 0, middle = floor(length / 2); if (length > 1) { while (++index < middle) { upperIndex = length - index - 1; value = upperIndex in object ? object[upperIndex] : uid; if (index in object) { object[upperIndex] = object[index]; } else { delete object[upperIndex]; } if (value != uid) { object[index] = value; } else { delete object[index]; } } } return object; }
javascript
{ "resource": "" }
q37461
slice
train
function slice(start, end) { var index = -1, object = Object(this), length = object.length >>> 0, result = []; start = toInteger(start); start = start < 0 ? max(length + start, 0) : min(start, length); start--; end = end == null ? length : toInteger(end); end = end < 0 ? max(length + end, 0) : min(end, length); while ((++index, ++start) < end) { if (start in object) { result[index] = object[start]; } } return result; }
javascript
{ "resource": "" }
q37462
toInteger
train
function toInteger(value) { value = +value; return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1); }
javascript
{ "resource": "" }
q37463
isArguments
train
function isArguments() { // lazy define isArguments = function(value) { return toString.call(value) == '[object Arguments]'; }; if (noArgumentsClass) { isArguments = function(value) { return hasKey(value, 'callee') && !(propertyIsEnumerable && propertyIsEnumerable.call(value, 'callee')); }; } return isArguments(arguments[0]); }
javascript
{ "resource": "" }
q37464
isObject
train
function isObject(value) { var ctor, result = !!value && toString.call(value) == '[object Object]'; if (result && noArgumentsClass) { // avoid false positives for `arguments` objects in IE < 9 result = !isArguments(value); } if (result) { // IE < 9 presents nodes like `Object` objects: // IE < 8 are missing the node's constructor property // IE 8 node constructors are typeof "object" ctor = value.constructor; // check if the constructor is `Object` as `Object instanceof Object` is `true` if ((result = isClassOf(ctor, 'Function') && ctor instanceof ctor)) { // An object's own properties are iterated before inherited properties. // If the last iterated key belongs to an object's own property then // there are no inherited enumerable properties. forProps(value, function(subValue, subKey) { result = subKey; }); result = result === true || hasKey(value, result); } } return result; }
javascript
{ "resource": "" }
q37465
methodize
train
function methodize(fn) { return function() { var args = [this]; args.push.apply(args, arguments); return fn.apply(null, args); }; }
javascript
{ "resource": "" }
q37466
runScript
train
function runScript(code) { var anchor = freeDefine ? define.amd : Benchmark, script = doc.createElement('script'), sibling = doc.getElementsByTagName('script')[0], parent = sibling.parentNode, prop = uid + 'runScript', prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();'; // Firefox 2.0.0.2 cannot use script injection as intended because it executes // asynchronously, but that's OK because script injection is only used to avoid // the previously commented JaegerMonkey bug. try { // remove the inserted script *before* running the code to avoid differences // in the expected script element count/order of the document. script.appendChild(doc.createTextNode(prefix + code)); anchor[prop] = function() { destroyElement(script); }; } catch(e) { parent = parent.cloneNode(false); sibling = null; script.text = code; } parent.insertBefore(script, sibling); delete anchor[prop]; }
javascript
{ "resource": "" }
q37467
getMarkerKey
train
function getMarkerKey(object) { // avoid collisions with existing keys var result = uid; while (object[result] && object[result].constructor != Marker) { result += 1; } return result; }
javascript
{ "resource": "" }
q37468
each
train
function each(object, callback, thisArg) { var result = object; object = Object(object); var fn = callback, index = -1, length = object.length, isSnapshot = !!(object.snapshotItem && (length = object.snapshotLength)), isSplittable = (noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'), isConvertable = isSnapshot || isSplittable || 'item' in object, origObject = object; // in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists if (length === length >>> 0) { if (isConvertable) { // the third argument of the callback is the original non-array object callback = function(value, index) { return fn.call(this, value, index, origObject); }; // in IE < 9 strings don't support accessing characters by index if (isSplittable) { object = object.split(''); } else { object = []; while (++index < length) { // in Safari 2 `index in object` is always `false` for NodeLists object[index] = isSnapshot ? result.snapshotItem(index) : result[index]; } } } forEach(object, callback, thisArg); } else { forOwn(object, callback, thisArg); } return result; }
javascript
{ "resource": "" }
q37469
hasKey
train
function hasKey() { // lazy define for worst case fallback (not as accurate) hasKey = function(object, key) { var parent = object != null && (object.constructor || Object).prototype; return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]); }; // for modern browsers if (isClassOf(hasOwnProperty, 'Function')) { hasKey = function(object, key) { return object != null && hasOwnProperty.call(object, key); }; } // for Safari 2 else if ({}.__proto__ == Object.prototype) { hasKey = function(object, key) { var result = false; if (object != null) { object = Object(object); object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0]; } return result; }; } return hasKey.apply(this, arguments); }
javascript
{ "resource": "" }
q37470
interpolate
train
function interpolate(string, object) { forOwn(object, function(value, key) { // escape regexp special characters in `key` string = string.replace(RegExp('#\\{' + key.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') + '\\}', 'g'), value); }); return string; }
javascript
{ "resource": "" }
q37471
join
train
function join(object, separator1, separator2) { var result = [], length = (object = Object(object)).length, arrayLike = length === length >>> 0; separator2 || (separator2 = ': '); each(object, function(value, key) { result.push(arrayLike ? value : key + separator2 + value); }); return result.join(separator1 || ','); }
javascript
{ "resource": "" }
q37472
pluck
train
function pluck(array, property) { return map(array, function(object) { return object == null ? undefined : object[property]; }); }
javascript
{ "resource": "" }
q37473
enqueue
train
function enqueue(count) { while (count--) { queue.push(bench.clone({ '_original': bench, 'events': { 'abort': [update], 'cycle': [update], 'error': [update], 'start': [update] } })); } }
javascript
{ "resource": "" }
q37474
evaluate
train
function evaluate(event) { var critical, df, mean, moe, rme, sd, sem, variance, clone = event.target, done = bench.aborted, now = +new Date, size = sample.push(clone.times.period), maxedOut = size >= minSamples && (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime, times = bench.times, varOf = function(sum, x) { return sum + pow(x - mean, 2); }; // exit early for aborted or unclockable tests if (done || clone.hz == Infinity) { maxedOut = !(size = sample.length = queue.length = 0); } if (!done) { // sample mean (estimate of the population mean) mean = getMean(sample); // sample variance (estimate of the population variance) variance = reduce(sample, varOf, 0) / (size - 1) || 0; // sample standard deviation (estimate of the population standard deviation) sd = sqrt(variance); // standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean) sem = sd / sqrt(size); // degrees of freedom df = size - 1; // critical value critical = tTable[Math.round(df) || 1] || tTable.infinity; // margin of error moe = sem * critical; // relative margin of error rme = (moe / mean) * 100 || 0; extend(bench.stats, { 'deviation': sd, 'mean': mean, 'moe': moe, 'rme': rme, 'sem': sem, 'variance': variance }); // Abort the cycle loop when the minimum sample size has been collected // and the elapsed time exceeds the maximum time allowed per benchmark. // We don't count cycle delays toward the max time because delays may be // increased by browsers that clamp timeouts for inactive tabs. // https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs if (maxedOut) { // reset the `initCount` in case the benchmark is rerun bench.initCount = initCount; bench.running = false; done = true; times.elapsed = (now - times.timeStamp) / 1e3; } if (bench.hz != Infinity) { bench.hz = 1 / mean; times.cycle = mean * bench.count; times.period = mean; } } // if time permits, increase sample size to reduce the margin of error if (queue.length < 2 && !maxedOut) { enqueue(1); } // abort the invoke cycle when done event.aborted = done; }
javascript
{ "resource": "" }
q37475
isObjectObject
train
function isObjectObject(object) { return _.isObject(object) && !_.isArray(object) && !_.isFunction(object); }
javascript
{ "resource": "" }
q37476
getObjectSchema
train
function getObjectSchema(object) { var outputObject = {}; if (isObjectObject(object)) { Object.keys(object).forEach(function(key) { outputObject[key] = isObjectObject(object[key]) ? getObjectSchema(object[key]) : ''; }); } return outputObject; }
javascript
{ "resource": "" }
q37477
mergeObjectSchema
train
function mergeObjectSchema(object, other, options) { var settings = options || {}, prune = settings.prune || false, placeholder = settings.placeholder || false, source, sourceKeys, keysDiff, outputObject, i, value; // Don't bother doing anything with non-plain objects. if (!isObjectObject(object) || !isObjectObject(other)) { return object; } outputObject = {}; source = getObjectSchema(other); sourceKeys = Object.keys(source); i = -1; while (++i < sourceKeys.length) { // Original object already has property. if (object.hasOwnProperty(sourceKeys[i])) { // Recurse or copy defined property. if (isObjectObject(object[sourceKeys[i]])) { value = mergeObjectSchema(object[sourceKeys[i]], source[sourceKeys[i]], settings); } // Add placeholder for empty value. else if (placeholder && object[sourceKeys[i]].length === 0) { value = sourceKeys[i]; } // Copy value. else { value = object[sourceKeys[i]]; } } // Original object does not have property. else { // Recurse source property or add empty value. if (isObjectObject(source[sourceKeys[i]])) { value = mergeObjectSchema({}, source[sourceKeys[i]], settings); } else { value = placeholder ? sourceKeys[i] : ''; } } outputObject[sourceKeys[i]] = value; } // Add extra properties found in original object to the end of the object. if (!Boolean(prune)) { keysDiff = _.difference(Object.keys(object), sourceKeys); i = -1; while (++i < keysDiff.length) { outputObject[keysDiff[i]] = object[keysDiff[i]]; } } return outputObject; }
javascript
{ "resource": "" }
q37478
sortObjectSchema
train
function sortObjectSchema(object, options) { var sort = {asc: sortAsc, desc: sortDesc}, keys = Object.keys(object), outputObject = {}; if (options.sort) { keys.sort(sort[options.sort]); } keys.forEach(function(key, index) { if (isObjectObject(object[key])) { object[key] = sortObjectSchema(object[key], options); } outputObject[keys[index]] = object[keys[index]]; }); return outputObject; }
javascript
{ "resource": "" }
q37479
createOutputDirsAsync
train
function createOutputDirsAsync(buildOptions) { var outputDirs = new OutputDirs(buildOptions); var tasks = []; tasks.push(makeDirAndParents(outputDirs.tmp)); tasks.push(makeDirAndParents(outputDirs.gen)); tasks.push(makeDirAndParents(outputDirs.build)); return kew.all(tasks) .then(function() { return outputDirs; }); }
javascript
{ "resource": "" }
q37480
GFSuploadServer
train
function GFSuploadServer(mongoose, port, ssloptions, routes, listen, defaultcallback, authcallback) { this.port = port; this.ssloptions = ssloptions; this.routes = routes; this.listen = listen; this.authcallback = authcallback; this.mongoose = mongoose; if(defaultcallback) { this.defaultcallback = defaultcallback; } else { this.defaultcallback = function(err, result, type, user) { } } this.registerServer(routes); return this; }
javascript
{ "resource": "" }
q37481
validate
train
function validate(cmd, args, info) { AbstractCommand.prototype.validate.apply(this, arguments); var index = parseInt(args[1]) , value = info.db.getKey(args[0], info); if(value === undefined) { throw NoSuchKey; }else if(isNaN(index) || (index < 0 || index >= value.getLength())) { throw IndexRange; } args[1] = index; }
javascript
{ "resource": "" }
q37482
ConfigParser
train
function ConfigParser(path) { this.path = path; try { this.doc = xml.parseElementtreeSync(path); this.cdvNamespacePrefix = getCordovaNamespacePrefix(this.doc); et.register_namespace(this.cdvNamespacePrefix, 'http://cordova.apache.org/ns/1.0'); } catch (e) { console.error('Parsing '+path+' failed'); throw e; } var r = this.doc.getroot(); if (r.tag !== 'widget') { throw new CordovaError(path + ' has incorrect root node name (expected "widget", was "' + r.tag + '")'); } }
javascript
{ "resource": "" }
q37483
findElementAttributeValue
train
function findElementAttributeValue(attributeName, elems) { elems = Array.isArray(elems) ? elems : [ elems ]; var value = elems.filter(function (elem) { return elem.attrib.name.toLowerCase() === attributeName.toLowerCase(); }).map(function (filteredElems) { return filteredElems.attrib.value; }).pop(); return value ? value : ''; }
javascript
{ "resource": "" }
q37484
train
function(platform, resourceName) { var ret = [], staticResources = []; if (platform) { // platform specific icons this.doc.findall('platform[@name=\'' + platform + '\']/' + resourceName).forEach(function(elt){ elt.platform = platform; // mark as platform specific resource staticResources.push(elt); }); } // root level resources staticResources = staticResources.concat(this.doc.findall(resourceName)); // parse resource elements var that = this; staticResources.forEach(function (elt) { var res = {}; res.src = elt.attrib.src; res.target = elt.attrib.target || undefined; res.density = elt.attrib['density'] || elt.attrib[that.cdvNamespacePrefix+':density'] || elt.attrib['gap:density']; res.platform = elt.platform || null; // null means icon represents default icon (shared between platforms) res.width = +elt.attrib.width || undefined; res.height = +elt.attrib.height || undefined; // default icon if (!res.width && !res.height && !res.density) { ret.defaultResource = res; } ret.push(res); }); /** * Returns resource with specified width and/or height. * @param {number} width Width of resource. * @param {number} height Height of resource. * @return {Resource} Resource object or null if not found. */ ret.getBySize = function(width, height) { return ret.filter(function(res) { if (!res.width && !res.height) { return false; } return ((!res.width || (width == res.width)) && (!res.height || (height == res.height))); })[0] || null; }; /** * Returns resource with specified density. * @param {string} density Density of resource. * @return {Resource} Resource object or null if not found. */ ret.getByDensity = function(density) { return ret.filter(function(res) { return res.density == density; })[0] || null; }; /** Returns default icons */ ret.getDefault = function() { return ret.defaultResource; }; return ret; }
javascript
{ "resource": "" }
q37485
train
function (attributes, variables) { if (!attributes && !attributes.name) return; var el = new et.Element('plugin'); el.attrib.name = attributes.name; if (attributes.spec) { el.attrib.spec = attributes.spec; } // support arbitrary object as variables source if (variables && typeof variables === 'object' && !Array.isArray(variables)) { variables = Object.keys(variables) .map(function (variableName) { return {name: variableName, value: variables[variableName]}; }); } if (variables) { variables.forEach(function (variable) { el.append(new et.Element('variable', { name: variable.name, value: variable.value })); }); } this.doc.getroot().append(el); }
javascript
{ "resource": "" }
q37486
train
function(id){ if(!id){ return undefined; } var pluginElement = this.doc.find('./plugin/[@name="' + id + '"]'); if (null === pluginElement) { var legacyFeature = this.doc.find('./feature/param[@name="id"][@value="' + id + '"]/..'); if(legacyFeature){ events.emit('log', 'Found deprecated feature entry for ' + id +' in config.xml.'); return featureToPlugin(legacyFeature); } return undefined; } var plugin = {}; plugin.name = pluginElement.attrib.name; plugin.spec = pluginElement.attrib.spec || pluginElement.attrib.src || pluginElement.attrib.version; plugin.variables = {}; var variableElements = pluginElement.findall('variable'); variableElements.forEach(function(varElement){ var name = varElement.attrib.name; var value = varElement.attrib.value; if(name){ plugin.variables[name] = value; } }); return plugin; }
javascript
{ "resource": "" }
q37487
train
function(name, attributes) { var el = et.Element(name); for (var a in attributes) { el.attrib[a] = attributes[a]; } this.doc.getroot().append(el); }
javascript
{ "resource": "" }
q37488
train
function(name, spec){ if(!name) return; var el = et.Element('engine'); el.attrib.name = name; if(spec){ el.attrib.spec = spec; } this.doc.getroot().append(el); }
javascript
{ "resource": "" }
q37489
train
function(name){ var engines = this.doc.findall('./engine/[@name="' +name+'"]'); for(var i=0; i < engines.length; i++){ var children = this.doc.getroot().getchildren(); var idx = children.indexOf(engines[i]); if(idx > -1){ children.splice(idx,1); } } }
javascript
{ "resource": "" }
q37490
resolveFraction
train
function resolveFraction(frac) { frac = `${frac}`; if (Patterns.Percentage.test(frac)) { return parseFloat(frac) / 100; } else if (Patterns.Number.test(frac)) { return parseFloat(frac); } else throw new Error('Unknown fraction format: ', inp); }
javascript
{ "resource": "" }
q37491
train
function (name, data, origin, priority) { this.timestamp = Date.now(); this.name = name; this.data = data; this.origin = origin; this.priority = priority || 1; }
javascript
{ "resource": "" }
q37492
streamOn
train
function streamOn(name, fn) { var str, handle; if (typeof name === 'string') { str = name; name = { test: function (val) { return val === str; } }; } /** * @callback {EventStream.handle} * @param chunk * @type {function} */ handle = function (chunk) { if (name.test(chunk.name)) { fn(chunk.data); } }; this.eventStreamListeners.push(handle); return handle; }
javascript
{ "resource": "" }
q37493
train
function (handle) { var pos = this.eventStreamListeners.indexOf(handle); if (pos === -1) { return false; } this.eventStreamListeners.splice(this.eventStreamListeners.indexOf(handle), 1); return true; }
javascript
{ "resource": "" }
q37494
train
function (emitter, eventPrefix) { var self = this, oldEmit = emitter.emit; eventPrefix = eventPrefix || ''; emitter.emit = function (name, data) { oldEmit.apply(emitter, arguments); self.send(eventPrefix + name, data); }; return this; }
javascript
{ "resource": "" }
q37495
train
function (listener, eventPrefix) { var lastName; eventPrefix = eventPrefix || ''; this.receive({ test: function (val) { lastName = val; return true; } }, function (data) { listener.emit(eventPrefix + lastName, data); }); return this; }
javascript
{ "resource": "" }
q37496
captureLogs
train
function captureLogs() { 'use strict'; console.log('Now capturing logs'); var methods = [ 'debug', 'info', 'log', 'warn', 'error' ]; methods.forEach(function (mthd) { var realMethod = 'real' + mthd, report = captureLog.bind({}, mthd); console[realMethod] = console[mthd]; console[mthd] = function () { report(arguments); console.reallog.apply(console, arguments); }; }); }
javascript
{ "resource": "" }
q37497
saveItemController
train
function saveItemController(method, path) { restController.call(this, method, path); var ctrl = this; /** * Save item controller use this method to output a service as a rest * service * Output the saved document with the $outcome property * * @param {apiService} service * @param {object} [moreparams] optional additional parameters to give to the service * * @return {Promise} */ this.jsonService = function(service, moreparams) { var params = ctrl.getServiceParameters(ctrl.req); var promise = service.getResultPromise(params); ctrl.outputJsonFromPromise(service, promise); return promise; }; }
javascript
{ "resource": "" }
q37498
deleteItemController
train
function deleteItemController(path) { restController.call(this, 'delete', path); var ctrl = this; /** * Delete controller use this method to output a service as a rest * service * Output the deleted document with the $outcome property * * @param {apiService} service * * @return {Promise} */ this.jsonService = function(service) { var params = ctrl.getServiceParameters(ctrl.req); var promise = service.getResultPromise(params); ctrl.outputJsonFromPromise(service, promise); return promise; }; }
javascript
{ "resource": "" }
q37499
deleteOldFiles
train
function deleteOldFiles(path){ var deferred = Q.defer(); // Don't delete existing files & folders if overwrite is off if(options.overWrite !== false){ grunt.log.writeln('---> Deleting folder ==> '+path); rimraf(path, function(err){ if(err) { grunt.log.warn('---> There was an error deleting the existing repo folder : '+path+', error : '+err); deferred.reject(err); }else{ deferred.resolve(); } }); }else{ if(grunt.file.isDir(path)){ grunt.log.writeln('---> Folder exists so plugin will not overwrite ==> '+path); } deferred.resolve(); } return deferred.promise; }
javascript
{ "resource": "" }