_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q14400
|
updateExistingItems
|
train
|
function updateExistingItems(groupUi) {
let itemUi = groupUi.firstElementChild
while (itemUi) {
updateItem(itemUi)
itemUi = itemUi.nextElementSibling
}
}
|
javascript
|
{
"resource": ""
}
|
q14401
|
addMissingItems
|
train
|
function addMissingItems(groupUi, options) {
let nextItemUi = groupUi.firstElementChild
let nextOption = options.firstElementChild
while (nextOption) {
if (!nextItemUi || nextItemUi._option !== nextOption) {
const newItemUi = document.createElement('szn-')
newItemUi._option = nextOption
newItemUi.setAttribute('data-szn-options--' + (nextOption.tagName === 'OPTGROUP' ? 'optgroup' : 'option'), '')
updateItem(newItemUi)
groupUi.insertBefore(newItemUi, nextItemUi)
} else {
nextItemUi = nextItemUi && nextItemUi.nextElementSibling
}
nextOption = nextOption.nextElementSibling
}
}
|
javascript
|
{
"resource": ""
}
|
q14402
|
_collectURLs
|
train
|
function _collectURLs ( token ) {
var elem, isArrayElem;
if ( Array.isArray( token ) ) {
for ( var i = 0; i < token.length; i++ ) {
elem = token[ i ];
isArrayElem = Array.isArray( elem );
if ( isArrayElem && ( elem[ 0 ] === 'uri' ) ) {
urls.push( elem );
} else if ( isArrayElem ) {
_collectURLs( elem );
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14403
|
train
|
function ( mask ) {
if ( mask && ( mask instanceof RegExp ) !== true ) {
throw { type: 'getURLs', message: 'First argument must be RegExp' };
}
return urls.map( function ( value ) {
return _getURLValue( value );
} ).filter( function ( value, pos, self ) {
var unique = self.indexOf( value ) === pos;
if ( mask && unique ) {
return mask.test( value );
} else {
return unique;
}
} );
}
|
javascript
|
{
"resource": ""
}
|
|
q14404
|
train
|
function ( from_value, to_value ) {
var type;
if ( from_value instanceof RegExp ) {
type = 'RegExp';
} else if ( typeof from_value === 'string' ) {
type = 'String';
} else {
throw { type: 'changeURLContent', message: 'First argument must be RegExp of String' };
}
if ( to_value === undefined ) {
to_value = "";
} else if( typeof to_value !== 'string' ) {
throw { type: 'changeURLContent', message: 'Second argument must be String' };
}
urls.filter( function ( value ) {
if ( type === "RegExp" ) {
return from_value.test( _getURLValue( value ) );
} else {
return _getURLValue( value ).indexOf( from_value ) !== -1;
}
} ).forEach( function ( value ) {
var new_value = _getURLValue( value ).replace( from_value, to_value );
_setURLValue( value, new_value );
} );
}
|
javascript
|
{
"resource": ""
}
|
|
q14405
|
Blog
|
train
|
function Blog(loader, options) {
this.slugs = {};
this.ids = {};
this.posts = [];
this.length = 0;
options = options || {};
if (typeof loader === 'string') {
loader = new FileSystemLoader(loader, options);
} else if (Array.isArray(loader)) {
loader = new ArrayLoader(loader);
}
var self = this;
loader.on('error', function (err) {
self.emit('error', err);
});
loader.on('load', this.onLoad.bind(this));
loader.on('new_post', this.onNewPost.bind(this));
loader.on('updated_post', this.onUpdatedPost.bind(this));
loader.on('removed_post', this.onRemovedPost.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q14406
|
train
|
function( offset ) {
// Saved the children count and text length beforehand.
var parent = this.$.parentNode,
count = parent.childNodes.length,
length = this.getLength();
var doc = this.getDocument();
var retval = new CKEDITOR.dom.text( this.$.splitText( offset ), doc );
if ( parent.childNodes.length == count )
{
// If the offset is after the last char, IE creates the text node
// on split, but don't include it into the DOM. So, we have to do
// that manually here.
if ( offset >= length )
{
retval = doc.createText( '' );
retval.insertAfter( this );
}
else
{
// IE BUG: IE8+ does not update the childNodes array in DOM after splitText(),
// we need to make some DOM changes to make it update. (#3436)
var workaround = doc.createText( '' );
workaround.insertAfter( retval );
workaround.remove();
}
}
return retval;
}
|
javascript
|
{
"resource": ""
}
|
|
q14407
|
train
|
function( indexA, indexB ) {
// We need the following check due to a Firefox bug
// https://bugzilla.mozilla.org/show_bug.cgi?id=458886
if ( typeof indexB != 'number' )
return this.$.nodeValue.substr( indexA );
else
return this.$.nodeValue.substring( indexA, indexB );
}
|
javascript
|
{
"resource": ""
}
|
|
q14408
|
setTypeValueFromInstance
|
train
|
function setTypeValueFromInstance(node)
{
var val = node.instance;
if(val === undefined)
{
node.type = "undefined";
node.value = "undefined";
}
else if(val === null)
{
node.type = "null";
node.value = "null";
}
else
{
var valType = typeof val;
if(valType === "boolean")
{
node.type = "boolean";
node.value = val.toString();
}
else if (valType === "number")
{
node.type = "number";
node.value = val.toString();
}
else if (valType === "string")
{
node.type = "string";
node.value = val;
}
else if (valType === "symbol")
{
node.type = "symbol";
node.value = val.toString();
}
else if(valType === "function")
{
node.type = "function";
node.value = val.toString();
}
else if(val instanceof Date)
{
node.type = "date";
node.value = val.getTime().toString();
}
else if(val instanceof Array)
{
node.type = "array";
}
else if(jsmeta.isEmpty(val))
{
node.type = "empty";
node.value = "empty";
}
else
{
node.type = "object";
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14409
|
setInstanceFromTypeValue
|
train
|
function setInstanceFromTypeValue(node)
{
if(node.type == "undefined")
{
node.instance = undefined;
}
else if(node.type === "boolean")
{
node.instance = Boolean(node.value);
}
else if (node.type === "number")
{
node.instance = Number(node.value);
}
else if (node.type === "string")
{
node.instance = node.value;
}
else if (node.type === "symbol")
{
node.instance = Symbol(node.value);
}
else if(node.type === "function")
{
var fn;
eval("fn = " + node.value);
node.instance = fn;
}
else if(node.type === "null")
{
node.instance = null;
}
else if(node.type === "date")
{
node.instance = new Date(Number(node.value))
}
else if(node.type === "array")
{
node.instance = [];
}
else if(node.type === "empty")
{
node.instance = {};
}
else
{
/* $lab:coverage:off$ */
if(node.type !== "object")
throw new Error("object expected");
/* $lab:coverage:on$ */
node.instance = {};
}
}
|
javascript
|
{
"resource": ""
}
|
q14410
|
ErroneousError
|
train
|
function ErroneousError(e, additional) {
additional = additional || {};
this.line = e.lineno || e.lineNumber || additional.lineno;
this.file = e.filename || e.fileName || additional.filename;
this.msg = e.message || additional.message;
this.time = e.timestamp || additional.timestamp || Date.now();
this.type = (this.parseMessage(this.msg) || e.type || e.name).toLowerCase();
// If it's a DOM node, let's figure out which
if (e.target) {
this.target = this.getTargetIdentifier(e.target);
if (e.target.nodeName) {
this.type = 'resource';
if (e.target.href) {
this.file = e.target.href;
} else if (e.target.src) {
this.file = e.target.src;
}
}
}
// Parse the stack if any
this.stack = e.stack;
this.parseStack(e.stack);
}
|
javascript
|
{
"resource": ""
}
|
q14411
|
_replaceMacros
|
train
|
function _replaceMacros(s, macros, obj) {
var regex = null;
for (var i = 0; i < macros.length; i++) {
var macro = macros[i];
regex = new RegExp(macro.macro, "g");
s = s.replace(regex, obj[macro.prop]);
}
return s;
}
|
javascript
|
{
"resource": ""
}
|
q14412
|
series
|
train
|
async function series(resolvers){
// buffer
const results = [];
// run resolvers in series
for (const r of resolvers){
results.push(await r.resolve());
}
// return results
return results;
}
|
javascript
|
{
"resource": ""
}
|
q14413
|
train
|
function (componentDescription) {
var i = components.length,
app;
// Old-school declaration
// > franky.Component.extend({
// id: 'hello',
// init: function () {
// console.log('hello');
// }
// });
if (franky.isObject(componentDescription)) {
app = franky.beget(franky.ComponentBase, componentDescription);
// Short form declaration
// > franky.Component.extend('hello', function () {
// console.log('hello');
// });
} else if (franky.isString(componentDescription) && franky.isFunction(arguments[1])) {
app = franky.beget(franky.ComponentBase, {
id: componentDescription,
init: arguments[1]
});
// Dependencies injection form declaration
// > franky.Component.extend('hello', ['$logger', function ($logger) {
// $logger.say('hello');
// }]);
} else if (franky.isString(componentDescription) && franky.isArray(arguments[1])) {
var args = arguments[1];
app = franky.beget(franky.ComponentBase, {
id: componentDescription,
init: function () {
var deps = franky.filter(args, function (item) {
return franky.isString(item);
});
deps = franky.map(deps, function (serviceName) {
if (!services[serviceName]) {
throw new Error('Service ' + serviceName + ' hasnt defined');
}
return services[serviceName]();
});
var defs = franky.filter(args, function (item) {
return franky.isFunction(item);
});
if (defs.length > 1) {
throw new Error('Too much declaration functions');
}
defs[0].apply(this, deps);
}
});
} else {
throw new Error('Unknown definition structure, try to use extend("yourName", function() { ... init code ... })');
}
if (!app.id) {
franky.error('extend method expects id field in description object');
}
components.push(app);
// fill index
componentsIndex[app.id] = i;
return components[i];
}
|
javascript
|
{
"resource": ""
}
|
|
q14414
|
getPRsForRepo
|
train
|
function getPRsForRepo(repo) {
print(['Fetching PRs for ', clc.yellow.bold(`${repo.owner.login}/${repo.name}`)], debug);
return new Promise((resolve, reject) => {
github.pullRequests.getAll({
user: repo.owner.login,
repo: repo.name,
state: 'open'
}, (err, prs) => {
if (err) {
return reject(err);
}
return resolve(prs.filter((pr) => {
return pr && pr.head;
}));
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14415
|
populateLabelsForPR
|
train
|
function populateLabelsForPR(pr) {
print(['Get labels for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
return new Promise((resolve) => {
github.issues.getIssueLabels({
user: pr.base.user.login,
repo: pr.base.repo.name,
number: pr.number
}, function (err, labels) {
if (err && debug) {
print(['Error fetching labels for PR ', clc.red.bold`${pr.base.user.login}/${pr.base.repo.name}#${pr.number}`], debug);
}
if (labels && labels.length > 0) {
pr.labels = labels.map((label) => {
return {
name: label.name,
color: label.color
};
});
}
return resolve(pr);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14416
|
getLabels
|
train
|
function getLabels(prs) {
return Promise.all(prs.reduce((flattenedPRs, pr) => {
if (pr) {
return flattenedPRs.concat(pr);
}
}, []).map(populateLabelsForPR));
}
|
javascript
|
{
"resource": ""
}
|
q14417
|
analyzePatch
|
train
|
function analyzePatch(patch) {
const patchLines = patch.split('\n').reduce((reducedPatch, currentLine) => {
if (currentLine.match(/^[-+]/)) {
return reducedPatch.concat(currentLine.replace(/^[-+]+\s*/, ''));
}
return reducedPatch;
}, []);
return {
lines: patchLines.length,
chars: patchLines.join('').length
};
}
|
javascript
|
{
"resource": ""
}
|
q14418
|
extractDiffData
|
train
|
function extractDiffData(diff) {
print(['Extract diff for ', clc.yellow.bold(`${diff.user}/${diff.repo}#${diff.number}`), clc.white.italic(` (${diff.title})`)], debug);
return {
user: diff.user,
repo: diff.repo,
title: diff.title,
number: diff.number,
link: diff.link,
createdAt: diff.createdAt,
updatedAt: diff.updatedAt,
labels: diff.labels,
aheadBy: diff.ahead_by,
behindBy: diff.behind_by,
status: diff.status,
totalCommits: diff.total_commits,
author: {
login: diff.merge_base_commit.author ? diff.merge_base_commit.author.login : 'Unknown',
avatarUrl: diff.merge_base_commit.author ? diff.merge_base_commit.author.avatar_url : '',
},
files: diff.files.map((file) => {
return {
filename: file.filename,
status: file.status,
additions: file.additions,
deletions: file.deletions,
changes: file.changes,
patch: analyzePatch(file.patch || '')
};
})
};
}
|
javascript
|
{
"resource": ""
}
|
q14419
|
getDiffForPR
|
train
|
function getDiffForPR(pr) {
print(['Get diff for PR ', clc.yellow.bold(`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`)], debug);
return new Promise((resolve) => {
github.repos.compareCommits({
user: pr.head.user.login,
repo: pr.head.repo.name,
head: pr.head.ref,
base: pr.base.ref
}, (err, diff) => {
if (err && debug) {
print(['Error fetching diffs for PR ', clc.red.bold`${pr.head.user.login}/${pr.head.repo.name}#${pr.number}`], debug);
}
diff.user = pr.head.user.login;
diff.repo = pr.head.repo.name;
diff.title = pr.title;
diff.number = pr.number;
diff.link = pr._links.html.href;
diff.createdAt = pr.created_at;
diff.createdAt = pr.updated_at;
diff.labels = pr.labels;
return resolve(extractDiffData(diff));
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14420
|
getDiffs
|
train
|
function getDiffs(prs) {
print('Fetching diffs', debug);
return Promise.all(prs.reduce((flattenedPRs, pr) => {
if (pr) {
return flattenedPRs.concat(pr);
}
}, []).map(getDiffForPR));
}
|
javascript
|
{
"resource": ""
}
|
q14421
|
getOpenPRs
|
train
|
function getOpenPRs(auth, repo, debugEnabled) {
setDebugMode(debugEnabled);
return authenticate(auth)
.then(function () {
return getPRsForRepo(repo)
.then(getLabels, handleError('getPRs'))
.then(getDiffs, handleError('getLabels'));
}, handleError('authenticate'));
}
|
javascript
|
{
"resource": ""
}
|
q14422
|
DoubleLast
|
train
|
function DoubleLast(input, letters) {
var last = LastChar(input);
if (!letters || ~letters.indexOf(last)) {
return input + last;
}
return input;
}
|
javascript
|
{
"resource": ""
}
|
q14423
|
train
|
function(err, data, response) {
// call the 'response' callback, if provided using 'node' style callback pattern
if (options.complete) {
options.complete.call(model, err, data, response, options);
}
// trigger any event listeners for "complete"
model.trigger('complete', err, data, response, options);
}
|
javascript
|
{
"resource": ""
}
|
|
q14424
|
handleMongoWriteConcernError
|
train
|
function handleMongoWriteConcernError(batch, bulkResult, ordered, err, callback) {
mergeBatchResults(ordered, batch, bulkResult, null, err.result);
const wrappedWriteConcernError = new WriteConcernError({
errmsg: err.result.writeConcernError.errmsg,
code: err.result.writeConcernError.result
});
return handleCallback(
callback,
new BulkWriteError(toError(wrappedWriteConcernError), new BulkWriteResult(bulkResult)),
null
);
}
|
javascript
|
{
"resource": ""
}
|
q14425
|
recordCursor
|
train
|
function recordCursor(records, id) {
var record;
id = coerceId(id);
for (var i = 0, len = records.length; i < len; i++) {
record = records[i];
if (coerceId(record.id) === id) {
return {record: record, index: i};
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14426
|
train
|
function (overlayName, modelName) {
var key = (overlayName || BASE_OVERLAY) + '#' + modelName;
if (!this.instances[key]) {
this.instances[key] = DevFixturesFixtures.create({
modelName: modelName,
overlayName: overlayName
});
}
return this.instances[key];
}
|
javascript
|
{
"resource": ""
}
|
|
q14427
|
Router
|
train
|
function Router(HandleConstructor) {
if (!(this instanceof Router)) return new Router(HandleConstructor);
this.Handle = DefaultHandle;
this.router = new HttpHash();
this.collections = new Map();
this.attachMethods = [];
}
|
javascript
|
{
"resource": ""
}
|
q14428
|
done
|
train
|
function done(err) {
if (err) return handle.error(err);
// Evaluate all the attach methods
for (const attachMethod of self.attachMethods) {
attachMethod.call(handle);
}
// No match found, send 404
if (match.handler === null) {
err = new Error('Not Found');
err.statusCode = 404;
return handle.error(err);
}
// match found, relay to HandlerCollection
match.handler(req.method, handle, match.params, match.splat);
}
|
javascript
|
{
"resource": ""
}
|
q14429
|
vsHash
|
train
|
function vsHash(text) {
let codes = [];
let pos = 0;
let partPos = 0;
for (let i = 0; i < text.length; i++) {
if (!codes[pos]) codes[pos]=[];
let code = decodeCharCode2Int36(text.charCodeAt(i));
if (code !== null) {
codes[pos][partPos] = code;
partPos += 1;
}
if (partPos === LEN) {
partPos = 0;
pos += 1;
}
}
if (partPos) {
for (let i = 0; i < LEN - partPos; i++) {
codes[pos].push(0);
}
}
return [codes.reduce((result, code) => {
result = result ^ code.reduce((r, v, i) => {
return r + v * Math.pow(36, i);
}, 0);
return result;
}, 0)];
}
|
javascript
|
{
"resource": ""
}
|
q14430
|
getResult
|
train
|
function getResult(matcherName, pass, ...messageWithPlaceholderValues) {
const formattedMessage = format.apply(this, messageWithPlaceholderValues);
messages[matcherName] = formattedMessage; // Save {not} message for later use
return {
pass,
message: formattedMessage.replace(' {not}', pass ? ' not' : '')
};
}
|
javascript
|
{
"resource": ""
}
|
q14431
|
createPromiseWith
|
train
|
function createPromiseWith(actual, expected, verb) {
assertPromise(actual);
const success = jasmine.createSpy('Promise success callback');
const failure = jasmine.createSpy('Promise failure callback');
actual.then(success, failure);
createScope().$digest();
const spy = verb === 'resolved' ? success : failure;
let pass = false;
let message = `Expected promise to have been ${verb} with ${jasmine.pp(expected)} but it was not ${verb} at all`;
if (isJasmine2 ? spy.calls.any() : spy.calls.length) {
const actualResult = isJasmine2 ? spy.calls.mostRecent().args[0] : spy.mostRecentCall.args[0];
if (angular.isFunction(expected)) {
expected(actualResult);
pass = true;
} else {
pass = angular.equals(actualResult, expected);
}
message = `Expected promise {not} to have been ${verb} with ${jasmine.pp(expected)} but was ${verb} with \
${jasmine.pp(actualResult)}`;
}
return getResult(`to${verb === 'resolved' ? 'Resolve' : 'Reject'}With`, pass, message);
}
|
javascript
|
{
"resource": ""
}
|
q14432
|
Bezierizer
|
train
|
function Bezierizer (container) {
this.$el = $(container);
this.$el.append($(HTML_TEMPLATE));
this._$canvasContainer = this.$el.find('.bezierizer-canvas-container');
this._$canvas = this._$canvasContainer.find('canvas');
this._$handleContainer = this.$el.find('.bezierizer-handle-container');
this._$handles = this._$handleContainer.find('.bezierizer-handle');
this._ctx = this._$canvas[0].getContext('2d');
this._$canvas[0].height = this._$canvas.height();
this._$canvas[0].width = this._$canvas.width();
this._$handles.dragon({
within: this._$handleContainer
});
this._points = {};
this.setHandlePositions({
x1: 0.25
,y1: 0.5
,x2: 0.75
,y2: 0.5
});
this._initBindings();
}
|
javascript
|
{
"resource": ""
}
|
q14433
|
train
|
function() {
if (cache.styles) {
return cache.styles;
}
cache.styles = {};
cache.styles[CONSTS.LOG] = chalk.white;
cache.styles[CONSTS.INFO] = chalk.cyan;
cache.styles[CONSTS.SUCCESS] = chalk.bold.green;
cache.styles[CONSTS.WARN] = chalk.yellow;
cache.styles[CONSTS.ERROR] = chalk.bold.red;
return cache.styles;
}
|
javascript
|
{
"resource": ""
}
|
|
q14434
|
train
|
function(type) {
var t = '[' + type.toUpperCase() + ']';
return utils.filler(t, utils.longestKey(CONSTS, 2));
}
|
javascript
|
{
"resource": ""
}
|
|
q14435
|
train
|
function(type, messages) {
if (type !== CONSTS.LOG) {
messages.unshift(tag(type));
}
return messages.map(styles.bind(null, type));
}
|
javascript
|
{
"resource": ""
}
|
|
q14436
|
detectErrors
|
train
|
function detectErrors (err, responseSpec, next) {
var callbackErr;
if (err) {
callbackErr = err;
}
else {
var status = responseSpec.statusCode;
if (status == 403) {
callbackErr = new Charon.RequestForbiddenError(responseSpec);
}
else if (status == 404) {
callbackErr = new Charon.ResourceNotFoundError(responseSpec);
}
else if (status == 409) {
callbackErr = new Charon.ResourceConflictError(responseSpec);
}
else if (status >= 400 && status <= 499) {
// 4xx error
callbackErr = new Charon.ConsumerError(responseSpec);
}
else if (status >= 500 && status <= 599) {
// 5xx error
callbackErr = new Charon.ServiceError(responseSpec);
}
else if (! (status >= 200 && status <= 299)) {
// not sure what this is, but it's not successful
callbackErr = new Charon.RuntimeError('Unrecognized HTTP status code', responseSpec);
}
}
this.invokeNext(callbackErr, responseSpec, next);
}
|
javascript
|
{
"resource": ""
}
|
q14437
|
parseResource
|
train
|
function parseResource (err, responseSpec, next) {
var resource = responseSpec ? responseSpec.body : undefined;
this.invokeNext(err, resource, next);
}
|
javascript
|
{
"resource": ""
}
|
q14438
|
train
|
function (propertyName) {
var value = this.client[propertyName];
if (! _.isUndefined(this[propertyName])) {
// pass, defer to resource manager prototype properties
}
else if (_.isFunction(value)) {
// copy functions (including the error ctors) by direct reference
this[propertyName] = value;
}
else if (_.contains(this.client.serviceCallParams, propertyName)) {
// default service call params which are not function values are proxied
// via getter functions
this[propertyName] = function () { return this.client[propertyName]; };
}
// all other properties are assumed to be client configuration, and
// should be accessed by referencing the ``client`` instance property.
}
|
javascript
|
{
"resource": ""
}
|
|
q14439
|
ls
|
train
|
function ls(uri, callback) {
if (!uri) {
callback(new Error('uri is required'))
}
util.getAll(uri, function(err, val) {
var res = {}
for (var i=0; i<val.length; i++) {
if (val[i].predicate.uri === 'http://www.w3.org/ns/ldp#contains') {
if (! res[val[i].object.uri]) res[val[i].object.uri] = {}
res[val[i].object.uri].contains = val[i].object.uri
}
if (val[i].predicate.uri === 'http://www.w3.org/ns/posix/stat#mtime') {
if (! res[val[i].subject.uri]) res[val[i].subject.uri] = {}
res[val[i].subject.uri].mtime = val[i].object.value
}
}
var arr =[]
for( var k in res ) {
if (res.hasOwnProperty(k)) {
if (k && res[k] && res[k].mtime && res[k].contains) {
arr.push({ file : res[k].contains, mtime : res[k].mtime })
}
}
}
arr = arr.sort(function(a, b){
if (a.mtime < b.mtime) return -1
if (a.mtime > b.mtime) return 1
return 0
})
var ret = []
for (i=0; i<arr.length; i++) {
ret.push(arr[i].file)
}
callback(null, ret)
})
}
|
javascript
|
{
"resource": ""
}
|
q14440
|
train
|
function (name) {
name = name || BASE_OVERLAY;
if (!this.instances[name]) {
this.instances[name] = DevFixturesOverlay.create({name: name});
}
return this.instances[name];
}
|
javascript
|
{
"resource": ""
}
|
|
q14441
|
train
|
function(json) {
var decoder = Parse.Op._opDecoderMap[json.__op];
if (decoder) {
return decoder(json);
} else {
return undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14442
|
train
|
function() {
var self = this;
return _.map(this.relationsToRemove, function(objectId) {
var object = Parse.Object._create(self._targetClassName);
object.id = objectId;
return object;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14443
|
train
|
function() {
var adds = null;
var removes = null;
var self = this;
var idToPointer = function(id) {
return { __type: 'Pointer',
className: self._targetClassName,
objectId: id };
};
var pointers = null;
if (this.relationsToAdd.length > 0) {
pointers = _.map(this.relationsToAdd, idToPointer);
adds = { "__op": "AddRelation", "objects": pointers };
}
if (this.relationsToRemove.length > 0) {
pointers = _.map(this.relationsToRemove, idToPointer);
removes = { "__op": "RemoveRelation", "objects": pointers };
}
if (adds && removes) {
return { "__op": "Batch", "ops": [adds, removes]};
}
return adds || removes || {};
}
|
javascript
|
{
"resource": ""
}
|
|
q14444
|
blobToString
|
train
|
function blobToString (blob) {
return blobUtil
.blobToArrayBuffer(blob)
.then(function (buffer) {
return String.fromCharCode.apply(null, new Uint16Array(buffer))
})
}
|
javascript
|
{
"resource": ""
}
|
q14445
|
remakeBody
|
train
|
function remakeBody (body, bodyType) {
return blobUtil
.base64StringToBlob(body)
.then(function (blob) {
switch (bodyType) {
case BodyTypes.ARRAY_BUFFER:
return blobUtil.blobToArrayBuffer(blob)
case BodyTypes.BLOB:
return blob
case BodyTypes.FORM_DATA:
throw new Error('Cannot make FormData from serialised Request')
case BodyTypes.JSON:
return blobToString(blob)
.then(function (str) {
return JSON.parse(str)
})
case BodyTypes.TEXT:
return blobToString(blob)
default:
throw new Error('Unknown requested body type "' + bodyType + '"')
}
})
}
|
javascript
|
{
"resource": ""
}
|
q14446
|
serialiseRequest
|
train
|
function serialiseRequest (request, toObject) {
if (!(request instanceof Request)) {
throw new Error('Expecting request to be instance of Request')
}
var headers = []
var headerNames = request.headers.keys()
for (var i = 0; i < headerNames.length; i++) {
var headerName = headerNames[i]
headers[headerName] = request.headers.get(headerName)
}
var serialised = {
method: request.method,
url: request.url,
headers: headers,
context: request.context,
referrer: request.referrer,
mode: request.mode,
credentials: request.credentials,
redirect: request.redirect,
integrity: request.integrity,
cache: request.cache,
bodyUsed: request.bodyUsed
}
return request
.blob()
.then(blobUtil.blobToBase64String)
.then(function (base64) {
serialised.__body = base64
return toObject
? serialised
: JSON.stringify(serialised)
})
}
|
javascript
|
{
"resource": ""
}
|
q14447
|
deserialiseRequest
|
train
|
function deserialiseRequest (serialised) {
var options
var url
if (typeof serialised === 'string') {
options = JSON.parse(serialised)
url = options.url
} else if (typeof serialised === 'object') {
options = serialised
url = options.url
} else {
throw new Error('Expecting serialised request to be a string or object')
}
const request = new Request(url, options)
const properties = {
context: {
enumerable: true,
value: options.context
}
}
const methods = Object.keys(BodyTypes).reduce(function (obj, key) {
const methodName = BodyMethods[key]
obj[methodName] = {
enumerable: true,
value: function () {
if (request.bodyUsed) {
return Promise.reject(new TypeError('Already used'))
}
request.bodyUsed = true
return Promise.resolve(remakeBody(options.__body, key))
}
}
return obj
}, properties)
Object.defineProperties(request, methods)
return request
}
|
javascript
|
{
"resource": ""
}
|
q14448
|
scrapePage
|
train
|
function scrapePage(cb, pages, links) {
links = links || [];
pages = pages || basePages.slice();
var url = pages.pop();
jsdom.env({
url: url,
scripts: ['http://code.jquery.com/jquery.js'],
done: function(err, window){
if (err) return cb(err);
_getLinks(window, links);
if (!pages.length) return cb(null, links);
scrapePage(cb, pages, links);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q14449
|
_getLinks
|
train
|
function _getLinks (window, links) {
var $ = window.$;
$('a.lede__link').each(function(){
var text = $(this).text().trim();
if (!text) return;
links.push(text);
});
}
|
javascript
|
{
"resource": ""
}
|
q14450
|
generateRandomClientId
|
train
|
function generateRandomClientId() {
var length = 22;
var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var result = '';
for (var i = length; i > 0; --i) {
result += chars[Math.round(Math.random() * (chars.length - 1))];
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q14451
|
connectBrowser
|
train
|
function connectBrowser (subscriptions, backlog, host, done_cb, secure) {
// Associate the right port
var websocket_uri;
if(secure == true) {
websocket_uri ='wss://' + host + ':1885/mqtt';
}
else {
websocket_uri ='ws://' + host + ':1884/mqtt';
}
// Create client
var client = new mqtt_lib.Client(websocket_uri, generateRandomClientId());
// Register callback for connection lost
client.onConnectionLost = function() {
// TODO try to reconnect
};
// Register callback for received message
client.onMessageArrived = function (message) {
// Execute all the appropriate callbacks:
// the ones specific to this channel with a single parameter (message)
// the ones associated to a wildcard channel, with two parameters (message and channel)
var cbs = findCallbacks(subscriptions, message.destinationName);
if (cbs!==undefined) {
cbs.forEach(function(cb) {
if (Object.keys(subscriptions).indexOf(message.destinationName)!==-1)
cb(message.payloadString);
else
cb(message.payloadString, message.destinationName);
});
}
};
// Connect
client.connect({onSuccess: function() {
// Execute optional done callback passing true
if (done_cb!==undefined)
done_cb(true);
// Execute the backlog of operations performed while the client wasn't connected
backlog.forEach(function(e) {
e.op.apply(this, e.params);
});
},
onFailure: function() {
// Execute optional done callback passing false
if (done_cb!==undefined)
done_cb(false);
else
console.error('There was a problem initializing nutella.');
}});
return client;
}
|
javascript
|
{
"resource": ""
}
|
q14452
|
subscribeBrowser
|
train
|
function subscribeBrowser (client, subscriptions, backlog, channel, callback, done_callback) {
if ( addToBacklog(client, backlog, subscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return;
if (subscriptions[channel]===undefined) {
subscriptions[channel] = [callback];
client.subscribe(channel, {qos: 0, onSuccess: function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
}});
} else {
subscriptions[channel].push(callback);
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
}
}
|
javascript
|
{
"resource": ""
}
|
q14453
|
train
|
function(client, subscriptions, backlog, channel, callback, done_callback) {
if ( addToBacklog(client, backlog, unsubscribeBrowser, [client, subscriptions, backlog, channel, callback, done_callback]) ) return;
if (subscriptions[channel]===undefined)
return;
subscriptions[channel].splice(subscriptions[channel].indexOf(callback), 1);
if (subscriptions[channel].length===0) {
delete subscriptions[channel];
client.unsubscribe(channel, {onSuccess : function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
}});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14454
|
train
|
function (client, backlog, channel, message) {
if ( addToBacklog(client, backlog, publishBrowser, [client, backlog, channel, message]) ) return;
message = new mqtt_lib.Message(message);
message.destinationName = channel;
client.send(message);
}
|
javascript
|
{
"resource": ""
}
|
|
q14455
|
findCallbacks
|
train
|
function findCallbacks (subscriptions, channel) {
// First try to see if a callback for the exact channel exists
if(Object.keys(subscriptions).indexOf(channel)!==-1)
return subscriptions[channel];
// If it doesn't then let's try to see if the channel matches a wildcard callback
var pattern = matchesWildcard(subscriptions, channel);
if (pattern!== undefined) {
return subscriptions[pattern];
}
// If there's no exact match or wildcard we have to return undefined
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q14456
|
matchesWildcard
|
train
|
function matchesWildcard (subscriptions, channel) {
var i;
var subs = Object.keys(subscriptions);
for (i=0; i < subs.length; i++) {
if (matchesFilter(subs[i], channel)) {
return subs[i];
}
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q14457
|
addToBacklog
|
train
|
function addToBacklog (client, backlog, method, parameters) {
if (!client.isConnected() ) {
backlog.push({
op : method,
params : parameters
});
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q14458
|
printParsableCode
|
train
|
function printParsableCode(snippets) {
// prints all lines, some of which were fixed to make them parsable
var lines = snippets
.map(function (x) { return '[ ' + x.code + ' ]'; });
console.log(lines.join('\n'));
}
|
javascript
|
{
"resource": ""
}
|
q14459
|
configure
|
train
|
function configure(cacheType, conf) {
// Check for custom logging functions on cache (debug)
if (conf && conf.logger) {
logger_1.configureLogger(conf.logger);
logger_1.logger.info('Custom cache logger configured');
}
if (cacheType)
exports.cache = cacheType;
}
|
javascript
|
{
"resource": ""
}
|
q14460
|
Tasks
|
train
|
function Tasks() {
this.tasks = [];
this.add = function(task) {
var commit = grunt.config.get('releasebot.commit');
if (commit.skipTaskCheck(task)) {
grunt.log.writeln('Skipping "' + task + '" task');
return false;
}
// grunt.log.writeln('Queuing "' + task + '" task');
return this.tasks.push(task);
};
}
|
javascript
|
{
"resource": ""
}
|
q14461
|
Args
|
train
|
function Args() {
if (argv._.length >= 1) {
try {
// Attempt to parse 1st argument as JSON string
_.extend(this, JSON.parse(argv._[0]));
} catch (err) {
// Pass, we must be in the console so don't worry about it
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14462
|
getLastResult
|
train
|
function getLastResult() {
if (argv._.length >= 2) {
try {
return JSON.parse(argv._[1]);
} catch (err) {
// pass
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q14463
|
EStoreScraper
|
train
|
function EStoreScraper() {
_.defaults(this, {
logger: new logging.Logger(),
cookieJar: new CookieJar(),
maxConcurrency: 10,
startPage: '',
agent: new http.Agent()
});
this.agent.maxSockets = this.maxConcurrency;
this.products = [];
this.waiting = 0;
}
|
javascript
|
{
"resource": ""
}
|
q14464
|
closestNumber
|
train
|
function closestNumber(arr, num) {
return arr.reduce((prev, curr) => (Math.abs(curr - num) < Math.abs(prev - num)) ? curr : prev);
}
|
javascript
|
{
"resource": ""
}
|
q14465
|
train
|
function(source, type) {
var out = null;
switch(type) {
case Augmented.Utility.TransformerType.xString:
if (typeof source === 'object') {
out = JSON.stringify(source);
} else {
out = String(source);
}
break;
case Augmented.Utility.TransformerType.xInteger:
out = parseInt(source);
break;
case Augmented.Utility.TransformerType.xNumber:
out = Number(source);
break;
case Augmented.Utility.TransformerType.xBoolean:
out = Boolean(source);
break;
case Augmented.Utility.TransformerType.xArray:
if (!Array.isArray(source)) {
out = [];
out[0] = source;
} else {
out = source;
}
break;
case Augmented.Utility.TransformerType.xObject:
if (typeof source !== 'object') {
out = {};
out[source] = source;
} else {
out = source;
}
break;
}
return out;
}
|
javascript
|
{
"resource": ""
}
|
|
q14466
|
train
|
function(source) {
if (source === null) {
return Augmented.Utility.TransformerType.xNull;
} else if (typeof source === 'string') {
return Augmented.Utility.TransformerType.xString;
} else if (typeof source === 'number') {
return Augmented.Utility.TransformerType.xNumber;
} else if (typeof source === 'boolean') {
return Augmented.Utility.TransformerType.xBoolean;
} else if (Array.isArray(source)) {
return Augmented.Utility.TransformerType.xArray;
} else if (typeof source === 'object') {
return Augmented.Utility.TransformerType.xObject;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14467
|
train
|
function(type, level) {
if (type === Augmented.Logger.Type.console) {
return new consoleLogger(level);
} else if (type === Augmented.Logger.Type.colorConsole) {
return new colorConsoleLogger(level);
} else if (type === Augmented.Logger.Type.rest) {
return new restLogger(level);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14468
|
train
|
function(username, password) {
var c = null;
Augmented.ajax({
url: this.uri,
method: "GET",
user: username,
password: password,
success: function(data, status) {
var p = new principal({
fullName: data.fullName,
id: data.id,
login: data.login,
email: data.email
});
c = new securityContext(p, data.permissions);
},
failure: function(data, status) {
// TODO: Bundle this perhaps
throw new Error("Failed to authenticate with response of - " + status);
}
});
return c;
}
|
javascript
|
{
"resource": ""
}
|
|
q14469
|
train
|
function(clientType) {
if (clientType === Augmented.Security.ClientType.OAUTH2) {
return new Augmented.Security.Client.OAUTH2Client();
} else if (clientType === Augmented.Security.ClientType.ACL) {
return new Augmented.Security.Client.ACLClient();
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q14470
|
train
|
function(message) {
var key = "";
if (message) {
var x = message.level &&
(key += message.level, message.kind &&
(key += this.delimiter + message.kind, message.rule &&
(key += this.delimiter + message.rule, message.values.title &&
(key += this.delimiter + message.values.title))));
}
return (key) ? key : "";
}
|
javascript
|
{
"resource": ""
}
|
|
q14471
|
train
|
function() {
var myValidator;
if (myValidator === undefined) {
myValidator = new Validator();
}
/**
* Returns if the framework supports validation
* @method supportsValidation
* @returns {boolean} Returns true if the framework supports validation
* @memberof Augmented.ValidationFramework
*/
this.supportsValidation = function() {
return (myValidator !== null);
};
/**
* Registers a schema to the Framework
* @method registerSchema
* @param {string} identity The identity of the schema
* @param {object} schema The JSON schema
* @memberof Augmented.ValidationFramework
*/
this.registerSchema = function(identity, schema) {
myValidator.addSchema(identity, schema);
};
/**
* Gets a schema
* @method getSchema
* @param {string} identity The identity of the schema
* @returns {object} The JSON schema
* @memberof Augmented.ValidationFramework
*/
this.getSchema = function(identity) {
return myValidator.getSchema(identity);
};
/**
* Gets all schemas
* @method getSchemas
* @returns {array} all JSON schemas
* @memberof Augmented.ValidationFramework
*/
this.getSchemas = function() {
return myValidator.getSchemaMap();
};
/**
* Clears all schemas
* @method clearSchemas
* @memberof Augmented.ValidationFramework
*/
this.clearSchemas = function() {
myValidator.dropSchemas();
};
/**
* Validates data via a schema
* @method validate
* @param {object} data The data to validate
* @param {object} The JSON schema
* @returns {object} Returns the validation object
* @memberof Augmented.ValidationFramework
*/
this.validate = function(data, schema) {
return myValidator.validateMultiple(data, schema);
};
/**
* Validates data via a schema
* @method getValidationMessages
* @returns {array} Returns the validation messages
* @memberof Augmented.ValidationFramework
*/
this.getValidationMessages = function() {
return myValidator.error;
};
this.generateSchema = function(model) {
if (model && model instanceof Augmented.Model) {
return Augmented.Utility.SchemaGenerator(model.toJSON());
}
return Augmented.Utility.SchemaGenerator(model);
};
}
|
javascript
|
{
"resource": ""
}
|
|
q14472
|
train
|
function() {
if (this.supportsValidation() && Augmented.ValidationFramework.supportsValidation()) {
// validate from Validator
this.validationMessages = Augmented.ValidationFramework.validate(this.toJSON(), this.schema);
} else {
this.validationMessages.valid = true;
}
return this.validationMessages;
}
|
javascript
|
{
"resource": ""
}
|
|
q14473
|
train
|
function() {
const messages = [];
if (this.validationMessages && this.validationMessages.errors) {
const l = this.validationMessages.errors.length;
var i = 0;
for (i = 0; i < l; i++) {
messages.push(this.validationMessages.errors[i].message + " from " + this.validationMessages.errors[i].dataPath);
}
}
return messages;
}
|
javascript
|
{
"resource": ""
}
|
|
q14474
|
train
|
function(method, model, options) {
if (!options) {
options = {};
}
if (this.crossOrigin === true) {
options.crossDomain = true;
}
if (!options.xhrFields) {
options.xhrFields = {
withCredentials: true
};
}
if (this.mock) {
options.mock = this.mock;
}
return Augmented.sync(method, model, options);
}
|
javascript
|
{
"resource": ""
}
|
|
q14475
|
train
|
function() {
if (this.supportsValidation() && Augmented.ValidationFramework.supportsValidation()) {
// validate from Validator
var messages = [];
this.validationMessages.messages = messages;
this.validationMessages.valid = true;
var a = this.toJSON(), i = 0, l = a.length;
//logger.debug("AUGMENTED: Collection Validate: Beginning with " + l + " models.");
for (i = 0; i < l; i++) {
messages[i] = Augmented.ValidationFramework.validate(a[i], this.schema);
if (!messages[i].valid) {
this.validationMessages.valid = false;
}
}
//logger.debug("AUGMENTED: Collection Validate: Completed isValid " + this.validationMessages.valid);
} else {
this.validationMessages.valid = true;
}
return this.validationMessages;
}
|
javascript
|
{
"resource": ""
}
|
|
q14476
|
train
|
function(key) {
if (key) {
var data = this.toJSON();
if (data) {
var sorted = Augmented.Utility.Sort(data, key);
this.reset(sorted);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14477
|
train
|
function(options) {
options = (options) ? options : {};
var data = (options.data || {});
var p = this.paginationConfiguration;
var d = {};
d[p.currentPageParam] = this.currentPage;
d[p.pageSizeParam] = this.pageSize;
options.data = d;
var xhr = Augmented.Collection.prototype.fetch.call(this, options);
// TODO: parse header links to sync up vars
return xhr;
}
|
javascript
|
{
"resource": ""
}
|
|
q14478
|
train
|
function(apiType, data) {
var arg = (data) ? data : {};
var collection = null;
if (!apiType) {
apiType = paginationAPIType.github;
}
if (apiType === paginationAPIType.github) {
collection = new paginatedCollection(arg);
collection.setPaginationConfiguration({
currentPageParam: "page",
pageSizeParam: "per_page"
});
} else if (apiType === paginationAPIType.solr) {
collection = new paginatedCollection(arg);
collection.setPaginationConfiguration({
currentPageParam: "start",
pageSizeParam: "rows"
});
} else if (apiType === paginationAPIType.database) {
collection = new paginatedCollection(arg);
collection.setPaginationConfiguration({
currentPageParam: "offset",
pageSizeParam: "limit"
});
}
return collection;
}
|
javascript
|
{
"resource": ""
}
|
|
q14479
|
train
|
function(permission, negative) {
if (!negative) {
negative = false;
}
if (permission !== null && !Array.isArray(permission)) {
var p = (negative) ? this.permissions.exclude : this.permissions.include;
p.push(permission);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14480
|
train
|
function(permission, negative) {
if (!negative) {
negative = false;
}
if (permission !== null && !Array.isArray(permission)) {
var p = (negative) ? this.permissions.exclude : this.permissions.include;
p.splice((p.indexOf(permission)), 1);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14481
|
train
|
function(permissions, negative) {
if (!negative) {
negative = false;
}
if (permissions !== null && Array.isArray(permissions)) {
if (negative) {
this.permissions.exclude = permissions;
} else {
this.permissions.include = permissions;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14482
|
train
|
function(match, negative) {
if (!negative) {
negative = false;
}
var p = (negative) ? this.permissions.exclude : this.permissions.include;
return (p.indexOf(match) !== -1);
}
|
javascript
|
{
"resource": ""
}
|
|
q14483
|
mix
|
train
|
function mix (r, s, or, cl) {
if (!s || !r) {
return r;
}
var i = 0,
c, len;
or = or || arguments.length === 2;
if (cl && (len = cl.length)) {
for (; i < len; i++) {
c = cl[i];
if ((c in s) && (or || !(c in r))) {
r[c] = s[c];
}
}
} else {
for (c in s) {
if (or || !(c in r)) {
r[c] = s[c];
}
}
}
return r;
}
|
javascript
|
{
"resource": ""
}
|
q14484
|
pyre
|
train
|
function pyre(pattern, namedCaptures) {
pattern = String(pattern || '').trim();
// populate namedCaptures array and removed named captures from the `pattern`
namedCaptures = namedCaptures == undefined ? [] : namedCaptures;
var numGroups = 0;
pattern = replaceCaptureGroups(pattern, function (group) {
if (/^\(\?P[<]/.test(group)) {
// Python-style "named capture"
// It is possible to name a subpattern using the syntax (?P<name>pattern).
// This subpattern will then be indexed in the matches array by its normal
// numeric position and also by name.
var match = /^\(\?P[<]([^>]+)[>]([^\)]+)\)$/.exec(group);
if (namedCaptures) namedCaptures[numGroups] = match[1];
numGroups++;
return '(' + match[2] + ')';
} else if ('(?:' === group.substring(0, 3)) {
// non-capture group, leave untouched
return group;
} else {
// regular capture, leave untouched
numGroups++;
return group;
}
});
var regexp = new RegExp(pattern);
regexp.pyreReplace = function(source, replacement) {
var jsReplacement = pyreReplacement(replacement, namedCaptures);
return source.replace(this, jsReplacement);
}
return regexp;
}
|
javascript
|
{
"resource": ""
}
|
q14485
|
unwrapAst
|
train
|
function unwrapAst (ast, prefix, suffix) {
let fake_code = `${prefix}\nlet ${LONG_AND_WEIRED_STRING}\n${suffix}`
let fake_ast = babylon.parse(fake_code, {
sourceType: 'module'
})
let selected_node
let selected_index
traverse(fake_ast, {
enter: function (node, parent) {
// removes the loc info of fake ast
if (node.loc) {
node.loc = null
}
if (node.type !== 'BlockStatement') {
return
}
// find the index of LONG_AND_WEIRED_STRING
let index = node.body.findIndex(n => {
if (node.type !== 'VariableDeclaration') {
return
}
if (
access(n, [
'declarations', 0,
'id',
'name'
]) === LONG_AND_WEIRED_STRING
) {
return true
}
})
if (!~index) {
return
}
selected_node = node
selected_index = index
}
})
if (selected_node) {
selected_node.body.splice(selected_index, 1)
selected_node.body.push(...ast.program.body)
}
return fake_ast
}
|
javascript
|
{
"resource": ""
}
|
q14486
|
train
|
function(datasetId) {
if (syncSubscribers && datasetId && syncSubscribers[datasetId]) {
syncSubscribers[datasetId].unsubscribeAll();
delete syncSubscribers[datasetId];
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14487
|
create_message
|
train
|
function create_message(req, data) {
debug.assert(data).is('object');
if(!is.uuid(data.$id)) {
data.$id = require('node-uuid').v4();
}
req.session.client.messages[data.$id] = data;
}
|
javascript
|
{
"resource": ""
}
|
q14488
|
hookStdout
|
train
|
function hookStdout(callback)
{
process.stdout._oWrite = process.stdout.write;
// take control
process.stdout.write = function(string, encoding, fd)
{
callback(string, encoding, fd);
};
// reverse it
return function()
{
process.stdout.write = process.stdout._oWrite;
};
}
|
javascript
|
{
"resource": ""
}
|
q14489
|
Fume
|
train
|
function Fume(sources, config) {
config = config || {};
config.nameTagPrefix = config.nameTagPrefix || NAME_TAG_PREFIX;
config.preferTagPrefix = config.preferTagPrefix || PREFER_TAG_PREFIX;
config.amdTagPrefix = config.amdTagPrefix || AMD_TAG_PREFIX;
config.cjsTagPrefix = config.cjsTagPrefix || CJS_TAG_PREFIX;
this.config = config;
var nameTagRe = new RegExp(
"^.*?" +
this.config.nameTagPrefix +
"\\s*(\\w+)\\W*$"
),
preferTagRe = new RegExp(
"^.*?" +
this.config.preferTagPrefix +
"\\s*(\\S+)\\s+(\\S+)\\W*$"
),
amdTagRe = new RegExp(
"^.*?" +
this.config.amdTagPrefix +
"\\s*(\\S+)\\s+(\\S+)\\W*$"
),
cjsTagRe = new RegExp(
"^.*?" +
this.config.cjsTagPrefix +
"\\s*(\\S+)\\s+(\\S+)\\W*$"
);
// parse the sources and get needed information
sources.forEach(function (source) {
source.dir = path.dirname(source.path);
source.tree = parse(source.code);
source.factory = source.tree.body[0];
source.amdMaps = {};
source.cjsMaps = {};
source.preferMaps = {};
if (source.factory.type !== 'FunctionDeclaration')
throw Error("Expected a factory function at '" +
source.path + "'");
source.args = source.factory.params;
// get comment lines before the factory function:
var m = source.code.match(cmtLinesRe);
// this RegExp should always match
if (!m) throw Error("Unable to parse pre-factory annotation");
var cLines = m[1].split(/[\n\r]/);
// extract annotation from the comment lines:
cLines.forEach(function (line) {
// attempt to detect the factory name:
// first try:
// the parse tree doesn't include comments, so we need to look
// at the source. a simple regex to detect the @name tag
// anywhere before the factory function:
var m = line.match(nameTagRe);
if (m) source.name = m[1];
// second try:
// if name tag isn't specified, take the function's name:
source.name = source.name || source.factory.id.name;
// check if this name is already taken by another factory:
if (sources.some(function (other) {
return other !== source &&
other.dir === source.dir &&
other.name === source.name;
}))
throw Error(
"Factory path '" +
path.join(source.dir, source.name) +
"' cannot be specified more than once"
);
// detect prefer mapping:
m = line.match(preferTagRe);
if (m) source.preferMaps[m[1]] = m[2];
// detect AMD mapping:
m = line.match(amdTagRe);
if (m) source.amdMaps[m[1]] = m[2];
// detect CJS mapping:
m = line.match(cjsTagRe);
if (m) source.cjsMaps[m[1]] = m[2];
});
});
// detect sibling dependencies
sources.forEach(function (source) {
source.factory.params.forEach(function (param) {
// find the siblings which can qualify as this dependency
param.candidatePaths = sources.filter(function (other) {
return other !== source && other.name === param.name;
}).map(function (other) {
return other.path;
});
});
});
return sources.reduce(function (p, e, i, o) {
p[e.path] = new Factory(e);
return p;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q14490
|
amdWrap
|
train
|
function amdWrap(factoryCode, deps) {
var deps = deps.map(function (dep) {
return "'" + dep + "'";
});
return AMD_TEMPLATE.START +
deps.join(',') +
AMD_TEMPLATE.MIDDLE +
factoryCode +
AMD_TEMPLATE.END;
}
|
javascript
|
{
"resource": ""
}
|
q14491
|
cjsWrap
|
train
|
function cjsWrap(factoryCode, deps) {
var requires = deps.map(function (dep) {
return "require('" + dep + "')";
});
return CJS_TEMPLATE.START +
factoryCode +
CJS_TEMPLATE.MIDDLE +
requires.join(',') +
CJS_TEMPLATE.END;
}
|
javascript
|
{
"resource": ""
}
|
q14492
|
ensureFolderExists
|
train
|
function ensureFolderExists(file) {
var folderName = path.dirname(file);
if (fs.existsSync(folderName)) {
return;
}
try {
mkdirp.sync(folderName);
}
catch (e) {
console.log(colors.red("Unable to create parent folders for: " + file), e);
}
}
|
javascript
|
{
"resource": ""
}
|
q14493
|
mergeTypes
|
train
|
function mergeTypes(env, types, conf, ENV, fn) {
fetch(conf, 'types', function(err, layout) {
if (err) return fn(err);
debug('# TYPES');
var batch = new Batch();
batch.concurrency(1);
types.forEach(function(type) {
batch.push(function(cb) {
debug(type);
mergeConf(env, layout, type, ENV, cb);
});
});
batch.end(fn);
});
}
|
javascript
|
{
"resource": ""
}
|
q14494
|
mergeApp
|
train
|
function mergeApp(env, app, conf, ENV, fn) {
fetch(conf, 'apps', function(err, apps) {
if (err) return fn(err);
debug('# APP');
debug(app);
mergeConf(env, apps, app, ENV, fn);
});
}
|
javascript
|
{
"resource": ""
}
|
q14495
|
mergeConf
|
train
|
function mergeConf(env, conf, key, ENV, fn) {
fetch(conf, key, function(err, layout) {
if (err) return fn(err);
fetch(layout, 'default', function(err, defaults) {
if (err) return fn(err);
debug(' default', defaults);
merge(ENV, defaults);
debug(' ', ENV);
fetch(layout, env, function(err, envs) {
if (err) return fn(err);
debug(' ' + env, envs);
merge(ENV, envs);
debug(' ', ENV);
fn();
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14496
|
fetch
|
train
|
function fetch(conf, key, fn) {
getKey(conf, key, function(err, layout) {
if (err) return fn(err);
get(layout, fn);
});
}
|
javascript
|
{
"resource": ""
}
|
q14497
|
get
|
train
|
function get(obj, fn) {
if (typeof obj === 'object') return fn(null, obj);
if (typeof obj === 'undefined') return fn(null, {});
if (typeof obj !== 'function') return fn(new Error('cannot read conf:\n' + obj));
if (obj.length === 1) return obj(fn);
var val;
try {
val = obj();
} catch(err) {
return fn(err);
}
fn(null, val);
}
|
javascript
|
{
"resource": ""
}
|
q14498
|
getIndexOf
|
train
|
function getIndexOf(string, find) {
// if regex then do it regex way
if(XRegExp.isRegExp(find)) {
return string.search(find);
} else {
// normal way
return string.indexOf(find);
}
}
|
javascript
|
{
"resource": ""
}
|
q14499
|
getStringWithLength
|
train
|
function getStringWithLength(string, find) {
let obj;
// if regex then do it regex way
if(XRegExp.isRegExp(find)) {
obj = {
textValue: XRegExp.replace(string, find, '$1', 'one'),
textLength: XRegExp.match(string, /class/g, 'one')
.length
};
return;
} else {
obj = {
textValue: find,
textLength: find.length
};
}
return obj;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.