_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q34900 | readTemplate | train | function readTemplate() {
return fs.readFileSync(path.resolve.apply(null, [__dirname, settings.paths.templates, ...arguments]), 'utf8');
} | javascript | {
"resource": ""
} |
q34901 | shouldBeStateless | train | function shouldBeStateless(definition, preferStateless) {
if (!preferStateless) {
return false;
}
if (runtime.isServer && (definition.getChildContext === undefined && definition.init === undefined)) {
return true;
}
// Not stateless if contains anything more than render and static properties
for (const prop in definition) {
if (prop !== 'render' && !~STATIC_KEYS.indexOf(prop)) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
q34902 | quit | train | function quit(m, l, ch) {
throw {
name: 'JSLintError',
line: l,
character: ch,
message: m + " (" + Math.floor((l / lines.length) * 100) +
"% scanned)."
};
} | javascript | {
"resource": ""
} |
q34903 | parse | train | function parse(rbp, initial) {
var left;
var o;
if (nexttoken.id === '(end)') {
error("Unexpected early end of program.", token);
}
advance();
if (option.adsafe && token.value === 'ADSAFE') {
if (nexttoken.id !== '.' || !(peek(0).identifier) ||
peek(1).id !== '(') {
warning('ADsafe violation.', token);
}
}
if (initial) {
anonname = 'anonymous';
funct['(verb)'] = token.value;
}
if (initial && token.fud) {
left = token.fud();
} else {
if (token.nud) {
o = token.exps;
left = token.nud();
} else {
if (nexttoken.type === '(number)' && token.id === '.') {
warning(
"A leading decimal point can be confused with a dot: '.{a}'.",
token, nexttoken.value);
advance();
return token;
} else {
error("Expected an identifier and instead saw '{a}'.",
token, token.id);
}
}
while (rbp < nexttoken.lbp) {
o = nexttoken.exps;
advance();
if (token.led) {
left = token.led(left);
} else {
error("Expected an operator and instead saw '{a}'.",
token, token.id);
}
}
if (initial && !o) {
warning(
"Expected an assignment or function call and instead saw an expression.",
token);
}
}
if (!option.evil && left && left.value === 'eval') {
warning("eval is evil.", left);
}
return left;
} | javascript | {
"resource": ""
} |
q34904 | symbol | train | function symbol(s, p) {
var x = syntax[s];
if (!x || typeof x !== 'object') {
syntax[s] = x = {
id: s,
lbp: p,
value: s
};
}
return x;
} | javascript | {
"resource": ""
} |
q34905 | train | function (s, o) {
if (o) {
if (o.adsafe) {
o.browser = false;
o.debug = false;
o.eqeqeq = true;
o.evil = false;
o.forin = false;
o.on = false;
o.rhino = false;
o.undef = true;
o.widget = false;
}
option = o;
} else {
option = {};
}
globals = option.adsafe ? {} : object(standard);
JSLINT.errors = [];
global = object(globals);
scope = global;
funct = {'(global)': true, '(name)': '(global)', '(scope)': scope};
functions = [];
src = false;
xmode = false;
xtype = '';
stack = null;
member = {};
membersOnly = null;
implied = {};
inblock = false;
lookahead = [];
indent = 0;
jsonmode = false;
warnings = 0;
lex.init(s);
prereg = true;
prevtoken = token = nexttoken = syntax['(begin)'];
populateGlobals();
try {
advance();
if (nexttoken.value.charAt(0) === '<') {
xml();
} else if (nexttoken.id === '{' || nexttoken.id === '[') {
option.laxbreak = true;
jsonmode = true;
jsonValue();
} else {
statements();
}
advance('(end)');
} catch (e) {
if (e) {
JSLINT.errors.push({
reason : e.message,
line : e.line || nexttoken.line,
character : e.character || nexttoken.from
}, null);
}
}
return JSLINT.errors.length === 0;
} | javascript | {
"resource": ""
} | |
q34906 | train | function (objSrc, objDest) {
if (_.isObject(objDest)) {
Object.getOwnPropertyNames(objDest).forEach(function (index) {
if (_.isObject(objDest[index])) {
objDest[index] = _recurseExtend(objSrc[index], objDest[index]);
}
else {
objDest[index] = objSrc && objSrc[index] ? objSrc[index] : '';
}
});
}
return _.cloneDeep(objDest);
} | javascript | {
"resource": ""
} | |
q34907 | sendStats | train | function sendStats(socket, stats, force) {
if (!socket || !stats) return;
if (!force && stats && stats.assets && stats.assets.every(function (asset) {
return !asset.emitted;
})) return;
socket.emit("hash", stats.hash);
if (stats.errors.length > 0)
socket.emit("errors", stats.errors);
else if (stats.warnings.length > 0)
socket.emit("warnings", stats.warnings);
else
socket.emit("ok");
} | javascript | {
"resource": ""
} |
q34908 | train | function (url) {
return new Promise(function (resolve, reject) {
middleware(new MockReq(url), new MockRes(url, resolve), reject);
});
} | javascript | {
"resource": ""
} | |
q34909 | SiteBuilder | train | function SiteBuilder(config, fileMap) {
this.config = config;
this.root = config.root;
var helperFile = path.join(this.root, '_lib', 'helpers.js');
if (existsSync(helperFile)) {
userHelpers = require(helperFile);
}
var filterFile = path.join(this.root, '_lib', 'filters.js');
if (existsSync(filterFile)) {
userFilters = require(filterFile);
}
var postFilterFile = path.join(this.root, '_lib', 'post-filters.js');
if (existsSync(postFilterFile)) {
userPostFilters = require(postFilterFile);
}
this.outputRoot = config.output;
this.fileMap = fileMap;
this.posts = [];
this.helpers = helpers;
this.events = new EventEmitter();
this.includes = {};
this.loadPlugins();
} | javascript | {
"resource": ""
} |
q34910 | API | train | function API (parameters) {
// Own API resource prefix (e.g. '/resource').
this.path = parameters.path || null;
// Own documentation.
this.title = parameters.title || null;
this.description = parameters.description || null;
// Own test setup functions.
this.beforeEachTest = parameters.beforeEachTest || null;
this.afterEachTest = parameters.afterEachTest || null;
// Parent API resource (or root server app).
this.parent = parameters.parent || null;
// API sub-resources (API instances) by relative path (e.g. '/subresource').
this.children = {};
// Own request handlers (handler parameters) by method (e.g. 'post').
this.handlers = {};
} | javascript | {
"resource": ""
} |
q34911 | train | function (method, path, parameters) {
if (!this.parent) {
return;
}
var fullPath = normalizePath(path, this.path);
this.parent.exportHandler(method, fullPath, parameters);
} | javascript | {
"resource": ""
} | |
q34912 | train | function (baseUrl, callback) {
var self = this;
var tests = [];
// Export own request handler examples as test functions.
for (var method in self.handlers) {
var handler = self.handlers[method];
if (!handler.examples) {
throw (
'Handler ' + method.toUpperCase() + ' ' + this.path +
' does not have examples!'
);
}
handler.examples.forEach(function (example) {
var test =
self.testHandlerExample.bind(self, baseUrl, method, handler, example);
tests.push(test);
});
}
// Don't hang when there are no children.
var pendingChildren = Object.keys(self.children).length;
if (pendingChildren === 0) {
callback(tests);
return;
}
// Export children's request handler test functions recursively.
var childBaseUrl = url.parse(String(baseUrl));
childBaseUrl.pathname = normalizePath(self.path, childBaseUrl.pathname);
childBaseUrl = url.format(childBaseUrl);
for (var path in self.children) {
self.children[path].exportAllTests(childBaseUrl, function (childTests) {
tests = tests.concat(childTests);
pendingChildren--;
if (pendingChildren === 0) {
callback(tests);
}
});
}
} | javascript | {
"resource": ""
} | |
q34913 | train | function (baseUrl) {
var fullUrl = url.parse(String(baseUrl || '/'));
fullUrl.pathname = normalizePath(this.path, fullUrl.pathname);
fullUrl = url.format(fullUrl);
var routes = {};
Object.keys(this.children).forEach(function (child) {
routes[child.replace(/^\//, '')] = nodepath.join(fullUrl, child);
});
return routes;
} | javascript | {
"resource": ""
} | |
q34914 | train | function (basePath, anchors) {
var fullPath = normalizePath(this.path, basePath) || '/';
anchors = anchors || [];
function getAnchor (title) {
var anchor = String(title).toLowerCase()
.replace(/[\s\-]+/g, ' ')
.replace(/[^a-z0-9 ]/g, '')
.trim()
.replace(/ /g, '-');
if (anchors.indexOf(anchor) > -1) {
var i = 2;
while (anchors.indexOf(anchor + '-' + i) > -1) {
i++;
}
anchor += '-' + i;
}
anchors.push(anchor);
return anchor;
}
var html = '';
if (this.title) {
html +=
'<h1 id="' + getAnchor(this.title) + '">' + this.title + '</h1>\n';
}
if (this.description) {
html += '<p>' + this.description.replace(/\n/g, '<br>') + '</p>\n';
}
// Export own request handlers.
for (var method in this.handlers) {
var handler = this.handlers[method];
var title = handler.title || '(no title)';
html += '<h2 id="' + getAnchor(title) + '">' + title + '</h2>\n';
html += '<pre>' + method.toUpperCase() + ' ' + fullPath + '</pre>\n';
if (handler.description) {
html += '<p>' + handler.description.replace(/\n/g, '<br>') + '</p>\n';
}
if (handler.examples && handler.examples.length > 0) {
var example = handler.examples[0];
var request = example.request || {};
if (request.urlParameters || request.headers || request.body) {
html += '<h3>Input</h3>\n<pre>';
var exampleURL = method.toUpperCase() + ' ' + fullPath;
if (request.urlParameters) {
exampleURL = replaceUrlParameters(exampleURL,
request.urlParameters);
}
html += exampleURL + '\n';
var requestHeaders = request.headers || {};
for (var header in requestHeaders) {
html += header + ': ' + requestHeaders[header] + '\n';
}
if (request.body) {
html += '\n' + jsonStringifyIfObject(request.body).trim() + '\n';
}
html += '</pre>\n';
}
var response = example.response || {};
var hasResponseStatus = isExplicitExample(response.status);
var hasResponseBody = isExplicitExample(response.body);
if (hasResponseStatus || response.headers || hasResponseBody) {
html += '<h3>Response</h3>\n<pre>';
if (hasResponseStatus) {
var message = http.STATUS_CODES[response.status];
html += 'Status: ' + response.status + ' ' + message + '\n';
}
var responseHeaders = response.headers || {};
for (var header in responseHeaders) {
var headerValue = responseHeaders[header];
if (isExplicitExample(headerValue)) {
html += header + ': ' + headerValue + '\n';
}
}
if (hasResponseBody) {
if (hasResponseStatus || Object.keys(responseHeaders).length > 0) {
html += '\n';
}
html += jsonStringifyIfObject(response.body).trim() + '\n';
}
html += '</pre>\n';
}
// TODO Document all unique possible status codes?
// TODO Document all request parameters?
}
}
// Export children's request handlers recursively.
for (var path in this.children) {
var child = this.children[path];
html += child.toHTML(fullPath, anchors);
}
return html;
} | javascript | {
"resource": ""
} | |
q34915 | train | function (basePath) {
var fullPath = normalizePath(this.path, basePath) || '/';
var markdown = '';
if (this.title) {
markdown += '# ' + this.title + '\n\n';
}
if (this.description) {
markdown += this.description + '\n\n';
}
// Export own request handlers.
for (var method in this.handlers) {
var handler = this.handlers[method];
markdown += '## ' + (handler.title || '(no title)') + '\n\n';
markdown += ' ' + method.toUpperCase() + ' ' + fullPath + '\n\n';
if (handler.description) {
markdown += handler.description + '\n\n';
}
if (handler.examples && handler.examples.length > 0) {
var example = handler.examples[0];
var request = example.request || {};
if (request.urlParameters || request.headers || request.body) {
markdown += '### Example input:\n\n';
var exampleURL = ' ' + method.toUpperCase() + ' ' + fullPath;
if (request.urlParameters) {
exampleURL = replaceUrlParameters(exampleURL,
request.urlParameters);
}
markdown += exampleURL + '\n';
var requestHeaders = request.headers || {};
for (var header in requestHeaders) {
markdown += ' ' + header + ': ' + requestHeaders[header] + '\n';
}
if (request.body) {
var requestBody = ' ' + jsonStringifyIfObject(request.body)
.trim().replace(/\n/g, '\n ');
markdown += ' \n' + requestBody + '\n';
}
markdown += '\n';
}
var response = example.response || {};
var hasResponseStatus = isExplicitExample(response.status);
var hasResponseBody = isExplicitExample(response.body);
if (hasResponseStatus || response.headers || hasResponseBody) {
markdown += '### Example response:\n\n';
if (hasResponseStatus) {
var message = http.STATUS_CODES[response.status];
markdown += ' Status: ' + response.status + ' ' + message + '\n';
}
var responseHeaders = response.headers || {};
for (var header in responseHeaders) {
var value = responseHeaders[header];
if (isExplicitExample(value)) {
markdown += ' ' + header + ': ' + value + '\n';
}
}
if (hasResponseBody) {
if (hasResponseStatus || Object.keys(responseHeaders).length > 0) {
markdown += ' \n';
}
markdown += ' ' + jsonStringifyIfObject(response.body).trim()
.replace(/\n/g, '\n ') + '\n';
}
markdown += '\n';
}
// TODO Document all unique possible status codes?
// TODO Document all request parameters?
}
}
// Export children's request handlers recursively.
for (var path in this.children) {
var child = this.children[path];
markdown += child.toMarkdown(fullPath);
}
return markdown;
} | javascript | {
"resource": ""
} | |
q34916 | isServerApp | train | function isServerApp (app) {
return !!(app && (app.use || app.handle) && app.get && app.post);
} | javascript | {
"resource": ""
} |
q34917 | getHandlerExporter | train | function getHandlerExporter (app) {
if (!isServerApp(app)) {
return null;
}
// `app` is an express-like server app.
return function (method, path, parameters) {
// Support restify.
if (method === 'del' && ('delete' in app)) {
method = 'delete';
}
app[method](path, parameters.handler);
};
} | javascript | {
"resource": ""
} |
q34918 | jsonStringifyWithFunctions | train | function jsonStringifyWithFunctions (value) {
function replacer (key, value) {
if (typeof value === 'function') {
// Stringify this function, and slightly minify it.
value = String(value).replace(/\s+/g, ' ');
}
return options.jsonStringifyReplacer(key, value);
}
return JSON.stringify(value, replacer, options.jsonStringifySpaces);
} | javascript | {
"resource": ""
} |
q34919 | Module | train | function Module(data, range, depth) {
this._id = data.name +'@'+ range; // An unique id that identifies this module.
this.released = data.released; // The date this version go released.
this.licenses = data.licenses; // The licensing.
this.version = data.version; // The version of the module.
this.author = data._npmUser || {}; // Author of the release.
this.latest = data.latest; // What the latest version is of the module.
this.required = range; // Which range we required to find this module.
this.name = data.name; // The name of the module.
this.parents = []; // Modules that depend on this version.
this.dependent = []; // Modules that depend on this version.
this.depth = depth; // The depth of the dependency nesting.
} | javascript | {
"resource": ""
} |
q34920 | checkOld | train | function checkOld (id, ts) {
return false
if(sources[id] && sources[id] >= ts) return true
sources[id] = ts
} | javascript | {
"resource": ""
} |
q34921 | onUpdate | train | function onUpdate (update) {
var value = update[0], ts = update[1], id = update[2]
insertBatch (id, key, ts, JSON.stringify(value), scuttlebutt)
} | javascript | {
"resource": ""
} |
q34922 | freeVariableWeight | train | function freeVariableWeight(sliced) {
return sliced.reduce(function(acc, part, i) {
// If is bound part
if (!/^:.+$/.test(part)) {
// Weight is positively correlated to indexes of bound parts
acc += Math.pow(i + 1, sliced.length)
}
return acc
}, 0)
} | javascript | {
"resource": ""
} |
q34923 | BasicConnection | train | function BasicConnection() {
var _this = this
this._disconnected = false
this._messageHandler = function() {
}
this._disconnectHandler = function() {
}
var childArgs = []
process.execArgv.forEach(function(arg) {
if (arg.indexOf('--debug-brk') !== -1) {
var _debugPort = parseInt(arg.substr(12)) + 1
debug('Child process debugger listening on port %d', _debugPort)
childArgs.push('--debug-brk=' + _debugPort)
}
})
this._process = child_process.fork(__dirname + '/../sandbox/sandbox.js', childArgs)
this._startHeartBeat()
this._process.on('message', function(data) {
var m = codec.decode(data);
debug('Recibing message: %j', m)
_this._messageHandler(m)
})
this._process.on('exit', function(m) {
debug('Exit process: %j', m)
_this._stopHeartBeat()
_this._disconnected = true
_this._disconnectHandler(m)
})
} | javascript | {
"resource": ""
} |
q34924 | decode2 | train | function decode2(s) {
assert.equal(s.length, 2)
const [ upper, lower ] = s
return (decode(upper) << 6) | decode(lower)
} | javascript | {
"resource": ""
} |
q34925 | decode3 | train | function decode3(s) {
assert.equal(s.length, 3)
const [ upper, mid, lower ] = s
return (decode(upper) << 12) | (decode(mid) << 6) | decode(lower)
} | javascript | {
"resource": ""
} |
q34926 | decode4 | train | function decode4(s) {
assert.equal(s.length, 4)
const [ upper, belowUpper, aboveLower, lower ] = s
return (decode(upper) << 18) | (decode(belowUpper) << 12)
| (decode(aboveLower) << 6) | decode(lower)
} | javascript | {
"resource": ""
} |
q34927 | decode5 | train | function decode5(s) {
assert.equal(s.length, 5)
const [ upper, belowUpper, mid, aboveLower, lower ] = s
return (decode(upper) << 24) | (decode(belowUpper) << 18)
| (decode(mid) << 12) | (decode(aboveLower) << 6) | decode(lower)
} | javascript | {
"resource": ""
} |
q34928 | encode2 | train | function encode2(n) {
assert(0 <= n && n <= 0xfff, ENCODE_OUTOFBOUNDS + n)
// 12 bits -> 2 digits
const lower = isolate(n, 0, 6)
const upper = isolate(n, 6, 6)
return encode(upper) + encode(lower)
} | javascript | {
"resource": ""
} |
q34929 | encode3 | train | function encode3(n) {
assert(0 <= n && n <= 0x3ffff, ENCODE_OUTOFBOUNDS + n)
// 18 bits -> 3 digits
const lower = isolate(n, 0, 6)
const mid = isolate(n, 6, 6)
const upper = isolate(n, 12, 6)
return encode(upper) + encode(mid) + encode(lower)
} | javascript | {
"resource": ""
} |
q34930 | encode4 | train | function encode4(n) {
assert(0 <= n && n <= 0xffffff, ENCODE_OUTOFBOUNDS + n)
// 24 bits -> 4 digits
const lower = isolate(n, 0, 6)
const aboveLower = isolate(n, 6, 6)
const belowUpper = isolate(n, 12, 6)
const upper = isolate(n, 18, 6)
return encode(upper) + encode(belowUpper)
+ encode(aboveLower) + encode(lower)
} | javascript | {
"resource": ""
} |
q34931 | encode5 | train | function encode5(n) {
assert(0 <= n && n <= 0x3fffffff, ENCODE_OUTOFBOUNDS + n)
// 30 bits -> 5 digits
const lower = isolate(n, 0, 6)
const aboveLower = isolate(n, 6, 6)
const mid = isolate(n, 12, 6)
const belowUpper = isolate(n, 18, 6)
const upper = isolate(n, 24, 6)
return encode(upper) + encode(belowUpper)
+ encode(mid) + encode(aboveLower) + encode(lower)
} | javascript | {
"resource": ""
} |
q34932 | decodeFor | train | function decodeFor(n) {
return (
n === 1 ? decode
: n === 2 ? decode2
: n === 3 ? decode3
: n === 4 ? decode4
: decode5
)
} | javascript | {
"resource": ""
} |
q34933 | train | function (selector, done) {
this.evaluate_now((selector) => {
let element = document.querySelector(selector)
if (!element) {
return false
}
for (let key in element) {
if (key.startsWith('__reactInternalInstance$')) {
return true
}
}
return false
}, done, selector)
} | javascript | {
"resource": ""
} | |
q34934 | train | function (selector, done) {
this.evaluate_now((selector) => {
let element = document.querySelector(selector)
if (!element) {
return null
}
for (let key in element) {
if (key.startsWith('__reactInternalInstance$')) {
const compInternals = element[key]._currentElement
const compWrapper = compInternals._owner
const {props, state, context} = compWrapper._instance
return {
props,
state,
context
}
}
}
return null
}, done, selector)
} | javascript | {
"resource": ""
} | |
q34935 | train | function (selector, done) {
this.evaluate_now((selector) => {
let elements = document.querySelectorAll(selector)
if (!elements.length) {
return []
}
elements = [].slice.call(elements) // Convert to array
return elements.map(element => {
for (let key in element) {
if (key.startsWith('__reactInternalInstance$')) {
const compInternals = element[key]._currentElement
const compWrapper = compInternals._owner
const {props, state, context} = compWrapper._instance
return {
props,
state,
context
}
}
}
}).filter(e => e != null)
}, done, selector)
} | javascript | {
"resource": ""
} | |
q34936 | waitfn | train | function waitfn () {
const softTimeout = this.timeout || null
const callback = this.callback
let executionTimer
let softTimeoutTimer
let self = arguments[0]
let args = sliced(arguments)
let done = args[args.length - 1]
let timeoutTimer = setTimeout(function () {
clearTimeout(executionTimer)
clearTimeout(softTimeoutTimer)
done(new Error(`.wait() timed out after ${self.options.waitTimeout}msec`))
}, self.options.waitTimeout)
return tick.apply(this, arguments)
function tick (self, fn) {
if (softTimeout) {
softTimeoutTimer = setTimeout(function () {
clearTimeout(executionTimer)
clearTimeout(timeoutTimer)
done()
}, softTimeout)
}
let waitDone = function (err, result) {
if (callback) {
result = callback(result)
}
if (result) {
clearTimeout(timeoutTimer)
clearTimeout(softTimeoutTimer)
return done()
} else if (err) {
clearTimeout(timeoutTimer)
clearTimeout(softTimeoutTimer)
return done(err)
} else {
executionTimer = setTimeout(function () {
tick.apply(self, args)
}, self.options.pollInterval)
}
}
let newArgs = [fn, waitDone].concat(args.slice(2, -1))
self.evaluate_now.apply(self, newArgs)
}
} | javascript | {
"resource": ""
} |
q34937 | waitelem | train | function waitelem (self, selector, done) {
let elementPresent
eval('elementPresent = function() {' + // eslint-disable-line
` var element = document.querySelector('${selector}');` +
' if (!element) { return null }' +
' for (let key in element) {' +
' if (key.startsWith(\'__reactInternalInstance$\')) {' +
' const compInternals = element[key]._currentElement;' +
' const compWrapper = compInternals._owner;' +
' const {props, state, context} = compWrapper._instance;' +
' return {props, state, context}' +
' }' +
' }' +
' return null;' +
'}')
waitfn.apply(this, [self, elementPresent, done])
} | javascript | {
"resource": ""
} |
q34938 | train | function(io) {
// chat routes
router.use('/chat', chatRoutes);
// ops routes
router.use('/ops', opsRoutes);
// ShareJS built-in REST routes
router.use('/docs', shareRoutes);
if(io) {
io.of('/chat').on('connection', chatHandler);
}
router.use('/lib', express.static(path.join(__dirname, '/node_modules')));
router.use(express.static(path.join(__dirname, '/public')));
return router;
} | javascript | {
"resource": ""
} | |
q34939 | decimal | train | function decimal(_num, _precision) {
// If _num is undefined, assing 0
if(_num === undefined) _num = 0;
// If _precision is undefined, assigned 2
if(_precision === undefined) _num = 2;
n = Math.abs(_num);
var sign = '';
if(_num < 0)
sign = '-';
return sign + n.toFixed(_precision);
} | javascript | {
"resource": ""
} |
q34940 | configureFetch | train | function configureFetch(init) {
// If the user only provided a query string
if (typeof init === 'string') {
var request = {
method: init.method || 'POST',
headers: init.headers || {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
query: init
})
};
// If the user provided an actual configuration object
} else {
var request = {
method: init.method || 'POST',
headers: init.headers || {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body:
init.body ||
JSON.stringify({
query: init.fields,
variables: init.variables
}),
mode: init.mode,
credentials: init.credentials,
cache: init.cache,
redirect: init.redirect,
referrer: init.referrer,
referrerPolicy: init.referrerPolicy,
integrity: init.integrity,
keepalive: init.keepalive,
signal: init.signal
};
}
return request;
} | javascript | {
"resource": ""
} |
q34941 | createGlobalManagerService | train | function createGlobalManagerService($http, authService) {
//Init the sync service
syncNetworkInit.initSync($http).catch(function(error) {
logger.getLogger().error("Failed to initialize sync", error);
});
var syncManager = new SyncManager();
authService.setLoginListener(function(profileData) {
syncManager.syncManagerMap(profileData);
});
authService.setLogoutListener(function() {
syncManager.removeManagers();
});
return syncManager;
} | javascript | {
"resource": ""
} |
q34942 | train | function(path) {
var loc = window.location;
if (path[path.length-1] === '/') {
path = path.slice(0, -1);
}
if (~path.indexOf('//')) {
return path;
}
var auth = /^[^:\/]+:\/\/[^\/]+/.exec(loc.href)[0];
if (path[0] === '/') {
path = auth + path;
} else {
path = path.replace(/^\.?\//, '');
loc = loc.pathname.replace(/^\/|\/$/g, '');
path = [auth, loc, path].join('/');
}
return path;
} | javascript | {
"resource": ""
} | |
q34943 | FileMap | train | function FileMap(config) {
this.config = config || {};
this.config.exclude = config && config.exclude ? config.exclude : [];
this.config.exclude.push('/_site');
this.ignoreDotFiles = true;
this.root = config.root;
this.files = [];
this.events = new EventEmitter();
this.filesLeft = 0;
this.dirsLeft = 1;
} | javascript | {
"resource": ""
} |
q34944 | dotFlatten | train | function dotFlatten(object, optSep) {
let flattenedMap = {};
if (!object) {
throw new Error('`object` should be a proper Object non null nor undefined.');
}
let sep = optSep || '.';
dotFlattenFn(object, sep, flattenedMap);
return flattenedMap;
} | javascript | {
"resource": ""
} |
q34945 | dotFlattenFn | train | function dotFlattenFn(object, sep, flattenedMap, optPathSoFar) {
let levelKeys = Object.keys(object);
for (let i = 0, j = levelKeys.length; i < j; i++) {
let key = levelKeys[i];
let value = object[key];
let pathSoFar = cloneDeep(optPathSoFar) || [];
pathSoFar.push(key);
if (isPlainObject(value)) {
dotFlattenFn(value, sep, flattenedMap, pathSoFar);
}
else {
flattenedMap[pathSoFar.join(sep)] = value;
}
}
} | javascript | {
"resource": ""
} |
q34946 | get | train | function get(url, opts){
opts = opts || {};
return requestp(_.extend(defaults, opts, {
url: url
}));
} | javascript | {
"resource": ""
} |
q34947 | normalizeFns | train | function normalizeFns(fns) {
Object.keys(fns).forEach(function(key) {
var handler = fns[key];
if (typeof handler === 'function') {
fns[key] = {
enter: handler,
leave: noop
};
}
});
} | javascript | {
"resource": ""
} |
q34948 | init | train | function init(options) {
options = options || {}
var port = options.port || 6466
global.client = global.client || socketIOClient(`http://localhost:${port}`)
client = global.client
log.debug(`Started global js socketIO client for ${process.env.ADAPTER} at ${port}`)
client.emit('join', ioid) // first join for serialization
client.on('disconnect', client.disconnect)
client.on('take', hasher.handle) // add listener
// add methods
client.pass = pass
client.clientPass = clientPass
return client
} | javascript | {
"resource": ""
} |
q34949 | pass | train | function pass(to, input) {
var defer = cdefer()
clientPass(defer.resolve, to, input)
return defer.promise.catch((err) => {
console.log(`global-client-js promise exception with input: ${input}, to: ${JSON.stringify(to)}`)
})
} | javascript | {
"resource": ""
} |
q34950 | cdefer | train | function cdefer() {
const maxWait = 20000
var resolve, reject
var promise = new Promise((...args) => {
resolve = args[0]
reject = args[1]
})
.timeout(maxWait)
return {
resolve: resolve,
reject: reject,
promise: promise
}
} | javascript | {
"resource": ""
} |
q34951 | getExcerptByMoreTag | train | function getExcerptByMoreTag(file, regExp) {
var excerpt = false,
contents = file.contents.toString();
contents = cheerio.load('<root>' + contents + '</root>', {decodeEntities: false})('root').html();
var match = contents.search(regExp);
if (match > -1) {
excerpt = contents.slice(0, match);
excerpt = v.unescapeHtml(excerpt);
}
return excerpt;
} | javascript | {
"resource": ""
} |
q34952 | getExcerptByFirstParagraph | train | function getExcerptByFirstParagraph(file) {
var $ = cheerio.load(file.contents.toString(), {decodeEntities: false}),
p = $('p').first(),
excerpt = p.length ? p.html().trim() : false;
if (excerpt) {
excerpt = v.unescapeHtml(excerpt);
}
return excerpt;
} | javascript | {
"resource": ""
} |
q34953 | is | train | function is(pattern, value) {
if (pattern == value) return true;
pattern = regexQuote(pattern);
// Asterisks are translated into zero-or-more regular expression wildcards
// to make it convenient to check if the strings starts with the given
// pattern such as "library/*", making any string check convenient.
pattern = pattern.replace(/\\\*/g, '.*');
pattern = new RegExp('^' + pattern + '$');
return pattern.test(value);
} | javascript | {
"resource": ""
} |
q34954 | quickRandom | train | function quickRandom(length) {
length = length || 16;
var pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
return str_shuffle(pool.repeat(5)).substr(0, length);
} | javascript | {
"resource": ""
} |
q34955 | WindowParam | train | function WindowParam(windowParamDict){
if(!(this instanceof WindowParam))
return new WindowParam(windowParamDict)
windowParamDict = windowParamDict || {}
// Check windowParamDict has the required fields
//
// checkType('int', 'windowParamDict.topRightCornerX', windowParamDict.topRightCornerX, {required: true});
//
// checkType('int', 'windowParamDict.topRightCornerY', windowParamDict.topRightCornerY, {required: true});
//
// checkType('int', 'windowParamDict.width', windowParamDict.width, {required: true});
//
// checkType('int', 'windowParamDict.height', windowParamDict.height, {required: true});
//
// Init parent class
WindowParam.super_.call(this, windowParamDict)
// Set object properties
Object.defineProperties(this, {
topRightCornerX: {
writable: true,
enumerable: true,
value: windowParamDict.topRightCornerX
},
topRightCornerY: {
writable: true,
enumerable: true,
value: windowParamDict.topRightCornerY
},
width: {
writable: true,
enumerable: true,
value: windowParamDict.width
},
height: {
writable: true,
enumerable: true,
value: windowParamDict.height
}
})
} | javascript | {
"resource": ""
} |
q34956 | train | function () {
// Create request options from parsed source URL
var options = url.parse(this.source, false);
// Add on some defaults
extend(options, {
method: 'get',
headers: {
host: options.host,
accept: 'image/*'
}
});
// Determine https/http from source URL
var library = options.protocol === 'https:' ? https : http;
// Setup the request and its event binds
this.request = library.request(options);
this.request.on('response', this.onResponse.bind(this));
this.request.on('error', this.onError.bind(this));
this.request.setTimeout(5000, this.onTimeout.bind(this));
// Start the download
this.startTime = new Date().getTime();
this.request.end();
} | javascript | {
"resource": ""
} | |
q34957 | normalizeRouteConfig | train | function normalizeRouteConfig(config, registry) {
if (config instanceof route_config_decorator_1.AsyncRoute) {
var wrappedLoader = wrapLoaderToReconfigureRegistry(config.loader, registry);
return new route_config_decorator_1.AsyncRoute({
path: config.path,
loader: wrappedLoader,
name: config.name,
data: config.data,
useAsDefault: config.useAsDefault
});
}
if (config instanceof route_config_decorator_1.Route || config instanceof route_config_decorator_1.Redirect || config instanceof route_config_decorator_1.AuxRoute) {
return config;
}
if ((+!!config.component) + (+!!config.redirectTo) + (+!!config.loader) != 1) {
throw new BaseException("Route config should contain exactly one \"component\", \"loader\", or \"redirectTo\" property.");
}
if (config.as && config.name) {
throw new BaseException("Route config should contain exactly one \"as\" or \"name\" property.");
}
if (config.as) {
config.name = config.as;
}
if (config.loader) {
var wrappedLoader = wrapLoaderToReconfigureRegistry(config.loader, registry);
return new route_config_decorator_1.AsyncRoute({
path: config.path,
loader: wrappedLoader,
name: config.name,
data: config.data,
useAsDefault: config.useAsDefault
});
}
if (config.aux) {
return new route_config_decorator_1.AuxRoute({ path: config.aux, component: config.component, name: config.name });
}
if (config.component) {
if (typeof config.component == 'object') {
var componentDefinitionObject = config.component;
if (componentDefinitionObject.type == 'constructor') {
return new route_config_decorator_1.Route({
path: config.path,
component: componentDefinitionObject.constructor,
name: config.name,
data: config.data,
useAsDefault: config.useAsDefault
});
}
else if (componentDefinitionObject.type == 'loader') {
return new route_config_decorator_1.AsyncRoute({
path: config.path,
loader: componentDefinitionObject.loader,
name: config.name,
data: config.data,
useAsDefault: config.useAsDefault
});
}
else {
throw new BaseException("Invalid component type \"" + componentDefinitionObject.type + "\". Valid types are \"constructor\" and \"loader\".");
}
}
return new route_config_decorator_1.Route(config);
}
if (config.redirectTo) {
return new route_config_decorator_1.Redirect({ path: config.path, redirectTo: config.redirectTo });
}
return config;
} | javascript | {
"resource": ""
} |
q34958 | ParamRoutePath | train | function ParamRoutePath(routePath) {
this.routePath = routePath;
this.terminal = true;
this._assertValidPath(routePath);
this._parsePathString(routePath);
this.specificity = this._calculateSpecificity();
this.hash = this._calculateHash();
var lastSegment = this._segments[this._segments.length - 1];
this.terminal = !(lastSegment instanceof ContinuationPathSegment);
} | javascript | {
"resource": ""
} |
q34959 | convertToJson | train | function convertToJson(callback) {
var output = new File(file);
output.contents = new Buffer(JSON.stringify(spritesheet, null, '\t'));
output.path = file;
this.push(output);
callback();
} | javascript | {
"resource": ""
} |
q34960 | train | function( callback ){
var tm = this;
setTimeout(function () {
var returnValue;
//check for template existance.
if (tm.template) {
tm._tokenize();
returnValue = tm._tokens;
// execute callback.
if (callback) {
callback( returnValue );
}
} else {
throw "ParseError: No template to parse.";
}
}, 0);
} | javascript | {
"resource": ""
} | |
q34961 | train | function () {
var i;
i = this._openPrints.indexOf(this._openBrackets);
// if print indicators where found
if (i >= 0) {
// close it
this._tokens.push({
type : "closePrintIndicator"
});
// remove the print from the stack
this._openPrints.splice(i, 1);
}
} | javascript | {
"resource": ""
} | |
q34962 | readSource | train | function readSource(src) {
var cwd = path.dirname(file.path);
if (options.assetsDirs && options.assetsDirs.length) {
var basename = path.basename(cwd);
if (options.assetsDirs.indexOf(basename) === -1) {
options.assetsDirs.unshift(path.basename(cwd));
}
src = path.join(options.assetsDirs.length > 1 ? '{' + options.assetsDirs.join(',') + '}' : options.assetsDirs[0], src);
cwd = path.dirname(cwd);
}
var match = glob.sync(src, {cwd: cwd});
if (!match.length) return next(new PluginError('gulp-nginclude', 'File "' + src + '" not found'));
return fs.readFileSync(path.join(cwd, match[0])).toString();
} | javascript | {
"resource": ""
} |
q34963 | normalizeResult | train | function normalizeResult(result){
if (!result || result._isResponseData !== true)
return ResponseData(result,{default:true})
return result
} | javascript | {
"resource": ""
} |
q34964 | defaultTransformSuccess | train | function defaultTransformSuccess(value,options){
if (options.default === true){
return {
status:true,
data:value
}
}
if (options.appendStatus !== false){
let obj = typeof value == 'object' ? value : {}
return Object.assign(obj,{status:true})
}
return value
} | javascript | {
"resource": ""
} |
q34965 | strictMode | train | function strictMode (callback) {
'use strict'
// The module api is in *Locked* state, so it will not change
// see http://nodejs.org/api/modules.html
// that is why I just copyed and pasted the orig module wrapper.
//
// By the way, in test.js there is a test that checks if the content of
// *origWrapper* needs an update.
const origWrapper = '(function (exports, require, module, __filename, __dirname) { '
const strictWrapper = origWrapper + '"use strict";'
if (typeof callback !== 'function') {
throw new TypeError('Argument *callback* must be a function')
}
const module = require('module')
if (typeof module.wrapper === 'undefined') {
// If you enter here, you are in a context other than server side Node.js.
// Since module.wrapper is not defined, do not switch strict mode on.
callback()
} else {
if (module.wrapper[0] === origWrapper) {
module.wrapper[0] = strictWrapper
// Every require in this callback will load modules in strict mode.
try {
callback()
} catch (err) {
console.error(err.stack)
}
// Restore orig module wrapper, play well with others.
module.wrapper[0] = origWrapper
} else {
// If module.wrapper[0] changed, do not switch strict mode on.
callback()
}
}
} | javascript | {
"resource": ""
} |
q34966 | getWords | train | function getWords(words) {
const defaults = loadJson('./words.json');
const extras = typeof words === 'string' ? loadJson(words) : words;
return defaults.concat(extras);
} | javascript | {
"resource": ""
} |
q34967 | loadJson | train | function loadJson(filepath) {
const json = fs.readFileSync(require.resolve(filepath), 'utf8');
return JSON.parse(stripJsonComments(json));
} | javascript | {
"resource": ""
} |
q34968 | getCorrection | train | function getCorrection(words, match) {
for (const word of words) {
const pattern = getPattern(word);
if (!getRegExp([pattern]).test(match)) {
continue;
}
const corrected = match.replace(new RegExp(`\\b${pattern}`, 'i'), word);
return matchCasing(corrected, match);
}
return false;
} | javascript | {
"resource": ""
} |
q34969 | train | function () {
// Determine https vs. http
this.server = this.ssl ?
https.createServer(this.ssl) :
http.createServer();
// Bind to the request
this.server.on('request', this.handle.bind(this));
} | javascript | {
"resource": ""
} | |
q34970 | train | function(folder, dest) {
try {
fs.mkdirSync(dest, '0755');
} catch (e) {}
var files = fs.readdirSync(folder);
var indexFile = templatesManager.getFolderIndex(files);
logger.debug('Index file for "%s": "%s"', folder, indexFile);
files.forEach(function(file) {
if (config.exclude.indexOf(file) === -1) {
var curPath = path.join(folder, file);
if (fs.statSync(curPath).isDirectory()) {
walk(curPath, path.join(dest, file));
} else {
if (['.md', '.markdown'].indexOf(path.extname(file).toLowerCase()) !== -1) {
var isIndex = (file === indexFile);
filesToRender[curPath] = {
filename: file,
path: curPath,
versions: templatesManager.getVersions(curPath, 'template', isIndex),
isIndex: isIndex
};
} else if (config.media.indexOf(path.extname(file).toLowerCase().substr(1)) !== -1) {
logger.log('Copy "%s" to "%s"', curPath, path.join(dest, path.basename(curPath)));
fs.copy(curPath, path.join(dest, path.basename(curPath)), {replace: true}, function(err) {
if (err) {
logger.error('Problem while copying media file "%s" to "%s": "%s"', curPath, path.join(dest, path.basename(curPath)), err);
}
});
}
}
} else {
logger.debug('Excluded:', file);
}
});
} | javascript | {
"resource": ""
} | |
q34971 | train | function(commands) {
if (!commands || (commands.length === 0)) {
return true;
}
if (typeof commands === 'string') {
commands = [commands];
}
return commands.every(function(command) {
logger.info('Starting command "%s"...', command);
var result = exec(
command,
{cwd: path.resolve('.')}
);
if (result.status !== 0) { // error
logger.error('Error: "%s" - "%s"', result.stdout, result.stderr.trim());
return false;
}
logger.success('Command successfully finished');
logger.log('Command result: "%s"', result.stdout);
return true;
});
} | javascript | {
"resource": ""
} | |
q34972 | rollClassic | train | function rollClassic( roll ) {
const data = roll instanceof Roll ? roll : convertToRoll( roll );
const { dice, count, modifier } = data;
const rolls = [ ...new Array( count ) ].map(() => randomRoll( dice ));
const summ = rolls.reduce(( prev, curr ) => prev + curr, 0 );
const result = normalizeRollResult( summ + modifier );
return new Result( data.toString(), result, rolls );
} | javascript | {
"resource": ""
} |
q34973 | rollWod | train | function rollWod( roll ) {
const data = roll instanceof WodRoll ? roll : convertToWodRoll( roll );
const { dice, count, again, success, fail } = data;
const rolls = [];
let i = count;
while ( i > 0 ) {
const value = randomRoll( dice );
rolls.push( value );
// Check for "10 Again" flag
// `repeatLimit` will prevent infinite loop, for cases like `d1!>1`
const repeatLimit = 100;
if ( value !== dice || !again || rolls.length > repeatLimit ) {
i -= 1;
}
}
const result = rolls.reduce(( suc, val ) => {
if ( val >= success ) {
return suc + 1;
} else if ( val <= fail ) {
return suc - 1;
}
return suc;
}, 0 );
return new Result( data.toString(), Math.max( result, 0 ), rolls );
} | javascript | {
"resource": ""
} |
q34974 | rollAny | train | function rollAny( roll ) {
if ( roll instanceof Roll ) {
return rollClassic( roll );
} else if ( roll instanceof WodRoll ) {
return rollWod( roll );
}
return isDefined( roll ) ? rollAny( convertToAnyRoll( roll )) : null;
} | javascript | {
"resource": ""
} |
q34975 | KoaRestMongoose | train | function KoaRestMongoose(options) {
if (!(this instanceof KoaRestMongoose)) {
return new KoaRestMongoose(options);
}
options = options || {};
debug('options: ', options);
// api url prefix
this.prefix = null;
if (options.prefix !== null && typeof options.prefix !== 'undefined') {
// add `/` if not exists
if (options.prefix.indexOf('/') === -1) {
this.prefix = '/';
}
this.prefix = (this.prefix || '') + options.prefix;
debug('prefix: ', this.prefix);
}
// get all mongoose models
this.models = mongoose.models;
const modelNames = Object.keys(this.models);
// generate controller by mongoose model
modelNames.map(modelName => {
const model = this.models[modelName];
debug('model: ', model);
const actions = generateActions(model);
// generate route and bind to router
generateRoutes(router, model.modelName, actions, this.prefix);
});
// router instance
this.router = router;
// get all routes
this.routes = () => {
return this.router.routes();
};
} | javascript | {
"resource": ""
} |
q34976 | train | function () {
var i, len;
// eval scripts.
if (data.scripts && data.scripts.length) {
for (i = 0, len = data.scripts.length; i < len; i++) {
Util.globalEval(data.scripts[i]);
}
}
callback && callback(data);
} | javascript | {
"resource": ""
} | |
q34977 | train | function (obj) {
if (!resourceChecked) {
Util.saveLoadedRes();
resourceChecked = true;
}
currReqID = obj.reqID;
// console.log('arrive', obj.id);
this.trigger('pageletarrive', obj);
var pagelet = new PageLet(obj, function () {
// console.log('dom ready', obj.id);
var item;
count--;
// enforce js executed after dom inserted.
if (count === 0) {
while ((item = pagelets.shift())) {
BigPipe.trigger('pageletinsert', pagelet, item.pageletData);
// console.log('pagelet exec js', item.pageletData.id);
item.loadJs((function (item) {
// console.log('pagelet exec done', item.pageletData.id);
BigPipe.trigger('pageletdone', pagelet, item.pageletData);
})(item));
}
}
});
pagelet.pageletData = obj;
pagelets.push(pagelet);
count++;
pagelet.loadCss();
} | javascript | {
"resource": ""
} | |
q34978 | checkCommonArgs | train | function checkCommonArgs(args) {
if (args.length < 2) throw new Error("File1, File2, and callback required");
if (typeof args.at(1) != "string") throw new Error("File2 required");
if (typeof args.at(0) != "string") throw new Error("File1 required");
if (!args.callbackGiven()) throw new Error("Callback required");
} | javascript | {
"resource": ""
} |
q34979 | computeHash | train | function computeHash(filename, algo, callback) {
var crypto = require('crypto');
var fs = require('fs');
var chksum = crypto.createHash(algo);
var s = fs.ReadStream(filename);
s.on('error', function (err) {
//no file, hash will be zero
callback(0, err);
});
s.on('data', function (d) {
chksum.update(d);
});
s.on('end', function () {
var d = chksum.digest('hex');
//util.debug(d + ' ' + filename);
callback(d);
});
} | javascript | {
"resource": ""
} |
q34980 | WodRoll | train | function WodRoll( dice = 10, count = 1, again = false, success = 6, fail ) {
this.dice = positiveInteger( dice );
this.count = positiveInteger( count );
this.again = !!again;
[ this.fail, this.success ] = normalizeWodBorders( fail, success, this.dice );
} | javascript | {
"resource": ""
} |
q34981 | Physics | train | function Physics(width, height, ballRadius) {
this._height = height;
this._width = width;
this._ballRadius = ballRadius || 0.2;
this._world = null;
this._ballScored = function () {
};
this._paddleFixtures = {};
this._init();
} | javascript | {
"resource": ""
} |
q34982 | deref | train | function deref(theSchema, optionalOptions, callbackFn) {
var root, loaders, error, options, callback;
options = optionalOptions || {};
if (typeof options === 'function') {
callback = options;
} else {
callback = callbackFn;
}
root = _.cloneDeep(theSchema);
loaders = _loaders(require('./loader/local'), options);
process.nextTick(function () {
traverse(root, _visit, _done);
});
function _visit(node, key, owner, next) {
if (node === root) {
next();
}
if (typeof node.$ref === 'string') {
_load(node.$ref, function (err, schema) {
if (err) {
error = err;
return false;
}
owner[key] = schema;
next();
});
} else {
next();
}
function _load($ref, resolve) {
if (!_evaluate(loaders, _try)) {
resolve({
message: 'no appropriate loader',
$ref: $ref
});
}
function _try(loader) {
return loader(root, $ref, resolve);
}
}
}
function _done() {
process.nextTick(function () {
if (error) {
callback(error);
} else {
callback(null, root);
}
});
}
} | javascript | {
"resource": ""
} |
q34983 | logAll | train | function logAll(files, cb) {
_walkAll(files, function(err, node) {
if (err) {
exports.log(err.name + ': ' + err.message + ' in ' + err.file + ':' + err.line + ':' + err.column);
if (cb) cb(err);
}
exports.log('Found console.' + node.type + ' at ' + node.file + ':' + node.line + ':' + node.column + ' with '
+ node.arguments.length + ' arg(s)');
}).then(function(allNodes) {
if (cb) cb(null, allNodes);
});
} | javascript | {
"resource": ""
} |
q34984 | getAll | train | function getAll(files, cb) {
walkAll(files)
.then(function(allNodes) {
if (cb) cb(null, allNodes);
})
.catch(function(err) {
if (cb) cb(err, []);
});
} | javascript | {
"resource": ""
} |
q34985 | App | train | function App() {
require('colors');
/**
* All of the developer defined middlewares.
*
* @var {Array}
* @protected
*/
this.__middlewares = [];
/**
* The filter instance
* @var {Object}
*/
this.filter;
/**
* The list of loaded service providers.
*
* @var {Object}
* @protected
*/
this.__loadedProviders = {};
/**
* Indicates if the application has "booted".
*
* @var {Boolean}
* @protected
*/
this.__booted = false;
/**
* The array of booting callbacks.
*
* @var {Array}
* @protected
*/
this.__bootingCallbacks = [];
/**
* The array of booted callbacks.
*
* @var {Array}
* @protected
*/
this.__bootedCallbacks = [];
/**
* Node HTTP server reference.
*
* @var {Object}
* @protected
*/
this.__server;
/**
* The application locals object.
*
* @var {Object}
*/
this.locals = {};
/**
* Aliases for internal Positron module
*
* @type {Object}
* @protected
*/
this.__aliases = {};
var self = this;
/**
* Run the application and send the response.
*
* @param request
* @param response
* @return {void}
*/
this.run = function (request, response) {
var reqDomain = domain.create();
reqDomain
.on('error', self.handleError.bind(self, request, response))
.run(function () {
self.__getStackedClient().handle(request, response);
});
};
} | javascript | {
"resource": ""
} |
q34986 | checkRequiredParameter | train | function checkRequiredParameter (param) {
return (
typeof param === 'function' || typeof param === 'undefined' || param === '' || param === null || (typeof param === 'number' && isNaN(param))
);
} | javascript | {
"resource": ""
} |
q34987 | checkIfOnlyOneRequired | train | function checkIfOnlyOneRequired (defaultParams) {
var keys = Object.keys(defaultParams);
var i, key;
var onlyOne = '';
for (i = 0; i < keys.length; i++){
key = keys[i];
if (defaultParams[key] === '') {
if (onlyOne !== '') return false;
onlyOne = key;
}
}
return onlyOne;
} | javascript | {
"resource": ""
} |
q34988 | normalizeRequestParameters | train | function normalizeRequestParameters (defaultsObject, paramsName, requestParams) {
var promise = new Promise(function (resolve, reject) {
var defaultParams;
var onlyOne;
// First check if we have a default parameters object with this name
if (typeof defaultsObject[paramsName] !== 'object') reject(new RequiredError(`No default parameters for '${paramsName}'`, paramsName, defaultsObject[paramsName]));
// Create an empty object with default parameters
defaultParams = extend(Object.create(null), defaultsObject[paramsName]);
// Check if there is only one required parameter in defaults
onlyOne = checkIfOnlyOneRequired(defaultParams);
// If checked parameters are not an object
if (typeof requestParams !== 'object') {
// If they are a string or a valid number and there is only one required parameter in default parameters
if ((typeof requestParams === 'string' || (typeof requestParams === 'number' && isNaN(requestParams))) && onlyOne !== false) {
// Provide this value as a value in the default params
defaultParams[onlyOne] = requestParams;
} else {
// Reject with error in other case
reject(new RequiredError('No request parameters provided', 'requestParams', requestParams));
}
}
for (var key in defaultParams) {
if (checkRequiredParameter(requestParams[key]) && defaultParams[key] === '') {
reject(new RequiredError(`Missing required parameter '${key}'`, key, requestParams[key]));
} else if (!checkRequiredParameter(requestParams[key])) {
defaultParams[key] = requestParams[key];
}
if (defaultParams[key] === '__optional') defaultParams[key] = '';
}
resolve(defaultParams);
});
return promise;
} | javascript | {
"resource": ""
} |
q34989 | signIn | train | function signIn (defOptions, credentials, callback) {
var promise = normalizeRequestParameters(defaults, 'SignIn', credentials).then(function (credentials) {
var options = {
method : 'POST',
uri : 'v1/SignIn',
json : credentials
};
extend(true, options, defOptions);
return options;
}).then(request).nodeify(callback);
return promise;
} | javascript | {
"resource": ""
} |
q34990 | requestWithTokenCheck | train | function requestWithTokenCheck (defOptions, credentials, token, options, callback) {
var returnedPromise;
options.headers = options.headers || {};
extend(true, options, defOptions);
if (Date.now() - token.Timestamp > tokenUpdateTime) {
returnedPromise = signIn(defOptions, credentials).then(function (data) {
if (data[0].statusCode !== 200) {
throw new Error(`${data[0].statusCode}: ${data[0].body.Message}`);
} else {
token.AuthenticationToken = data[0].body.AuthenticationToken;
token.Timestamp = Date.now();
options.headers.Authorization = `Basic ${token.AuthenticationToken}`;
return request(options);
}
});
} else {
options.headers.Authorization = `Basic ${token.AuthenticationToken}`;
returnedPromise = request(options);
}
returnedPromise.nodeify(callback);
return returnedPromise;
} | javascript | {
"resource": ""
} |
q34991 | removeSurveyLanguages | train | function removeSurveyLanguages (defOptions, credentials, token, requestParams, callback) {
var promise = normalizeRequestParameters(defaults, 'RemoveSurveyLanguages', requestParams).then(function (params) {
var options = {
method : 'DELETE',
uri : `v1/Surveys/${params.SurveyId}/Languages/${params.LanguageId}`,
};
return options;
}).then(options => requestWithTokenCheck(defOptions, credentials, token, options)).nodeify(callback);
return promise;
} | javascript | {
"resource": ""
} |
q34992 | getSurveySettings | train | function getSurveySettings (defOptions, credentials, token, surveyId, callback) {
if (typeof surveyId === 'function') callback = surveyId;
if (checkRequiredParameter(surveyId)) return Promise.reject(Error(`Missing required parameter 'SurveyId'`)).nodeify(callback);
var options = {
method : 'GET',
uri : `v1/Surveys/${surveyId}/Settings`
};
return requestWithTokenCheck(defOptions, credentials, token, options, callback);
} | javascript | {
"resource": ""
} |
q34993 | evaluatePromise | train | function evaluatePromise() {
var promise = kew.defer();
var args = utils.toArray(arguments);
args.push(promise.makeNodeResolver());
/*jshint validthis:true */
evaluate.apply(this, args);
return promise;
} | javascript | {
"resource": ""
} |
q34994 | makeLocation | train | function makeLocation(req, origin) {
var protocol = !!req.connection.verifyPeer ? 'https://' : 'http://',
reqOrigin = origin || (protocol + req.headers.host);
return url.parse(reqOrigin + req.originalUrl);
} | javascript | {
"resource": ""
} |
q34995 | servePage | train | function servePage(bundle, opts) {
opts = opts || {};
if (typeof bundle !== 'function') {
bundle = bundler.create(bundle, opts);
}
return function(req, res, next) {
var location = makeLocation(req, opts.origin);
var clientReq = request.createRequestFromLocation(location);
bundle()
.then(function(bundle) {
return evaluatePromise({
bundle: bundle,
code: renderComponentToString(clientReq),
debug: opts.debug,
location: location
});
})
.then(function(rendered) {
var init = renderComponent(rendered.request.data);
var markup = rendered.markup.replace(
'</head>',
'<script>' + init + '</script>'
);
res.setHeader('Content-type', 'text/html');
res.statusCode = rendered.isNotFoundErrorHandled ? 404 : 200;
res.write(markup);
res.end();
}, function(err) {
err.isNotFoundError ? res.send(404) : next(err);
});
}
} | javascript | {
"resource": ""
} |
q34996 | expandCombinedShortArg | train | function expandCombinedShortArg (arg) {
/* remove initial hypen */
arg = arg.slice(1)
return arg.split('').map(letter => '-' + letter)
} | javascript | {
"resource": ""
} |
q34997 | train | function( index )
{
if ( index == -1 )
return;
var links = this.element.getElementsByTag( 'a' );
var item = links.getItem( this._.focusIndex = index );
// Safari need focus on the iframe window first(#3389), but we need
// lock the blur to avoid hiding the panel.
if ( CKEDITOR.env.webkit || CKEDITOR.env.opera )
item.getDocument().getWindow().focus();
item.focus();
this.onMark && this.onMark( item );
} | javascript | {
"resource": ""
} | |
q34998 | subscribe | train | function subscribe (state, topic, subscription, options, context) {
assert(typeof topic, 'string', 'Arbiter.subscribe', 'strings', 'topics');
options = merge(state.options, options);
var
ancestor = addTopicLine(
topic, ancestorTopicSearch(topic, state._topics)
),
node = insert(
getPriority,
createSubscription(state, subscription, options, context),
ancestor.subscriptions
),
subscriptionToken = {
topic: topic,
id: node.id,
priority: node.priority
};
// Notify late subscribers of persisted messages
if (!options.ignorePersisted) {
var
persistedDescendents = map(getPersisted, descendents(ancestor)),
persistedMessages = mergeBy(getFingerArrayOrder, persistedDescendents),
persisted, i, n;
for (i = 0, n = persistedMessages.length; i < n; i++) {
persisted = persistedMessages[i];
!subscription.suspended // eslint-disable-line no-unused-expressions
&& subscription.call(
subscription.context, persisted.data, persisted.topic
);
}
}
return subscriptionToken;
} | javascript | {
"resource": ""
} |
q34999 | publish | train | function publish (state, topic, data, options) {
assert(typeof topic, 'string', 'Arbiter.publish', 'strings', 'topics');
options = merge(state.options, options);
var args = [state, topic, data, options];
if (options.sync) {
return hierarchicalTopicDispatcher(state, topic, data, options);
}
return async(hierarchicalTopicDispatcher, args);
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.