_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q14500
|
replaceTextWithMap
|
train
|
function replaceTextWithMap(string, map) {
// break the words into tokens using _ and words themselves
const tokens = XRegExp.match(string, /([a-z0-9_]+)/ig);
// for all the tokens replace it in string
for(let token of tokens) {
// try to replace only if the key exists in the map else skip over
if(map.hasOwnProperty(token)) {
string = replaceAll(token, map[token], string);
}
}
return string;
}
|
javascript
|
{
"resource": ""
}
|
q14501
|
loadClass
|
train
|
function loadClass(className) {
var Class = Classes[className];
if (Class !== undefined) {
return Class;
}
// This uses a switch for static require analysis
switch (className) {
case 'Connection':
Class = require('./lib/Connection');
break;
case 'ConnectionConfig':
Class = require('./lib/ConnectionConfig');
break;
case 'Pool':
Class = require('./lib/Pool');
break;
case 'PoolCluster':
Class = require('./lib/PoolCluster');
break;
case 'PoolConfig':
Class = require('./lib/PoolConfig');
break;
case 'SqlString':
Class = require('./lib/protocol/SqlString');
break;
case 'Types':
Class = require('./lib/protocol/constants/types');
break;
default:
throw new Error('Cannot find class \'' + className + '\'');
}
// Store to prevent invoking require()
Classes[className] = Class;
return Class;
}
|
javascript
|
{
"resource": ""
}
|
q14502
|
newGet
|
train
|
function newGet(endpoint, allowable) {
return function(params, callback) {
// allow options params
var args = utils.allowOptionalParams(params, callback);
// get and detach/remove the uri options
var uriOptions = utils.getURIOptions([utils.setup(), this, args.params]);
utils.removeURIOptions(args.params);
// create the URI
var uri = utils.url(endpoint, uriOptions);
// get the auth options
var authOptions = utils.getAuthOptions([utils.setup(), this, args.params]);
utils.removeAuthOptions(args.params);
// remove params that are not allowed
args.params = utils.pickParams(args.params, allowable);
// add the params as querystring to the URI
utils.addQueries(uri, args.params);
// sign the URI (automatically removes the secret param from the params)
try {
auth.sign(authOptions.key, authOptions.secret, uri);
} catch(err) {
return args.callback(err);
}
var url = uri.toString();
debug("[GET] /%s (%s)", endpoint, url);
return utils.request().get(url, utils.passResponse(args.callback));
};
}
|
javascript
|
{
"resource": ""
}
|
q14503
|
newGetOne
|
train
|
function newGetOne(endpoint, allowable) {
var get = newGet(endpoint, allowable);
return function(id, params, callback) {
var args = utils.allowOptionalParams(params, callback);
if (typeof id === "object") {
_.assign(args.params, id);
} else {
args.params.id = id;
}
return get.call(this, args.params, args.callback);
};
}
|
javascript
|
{
"resource": ""
}
|
q14504
|
newPostOne
|
train
|
function newPostOne(endpoint, options) {
// for backwards-compatibility <= 0.11.1
if (_.isArray(options)) {
options = { allowable: options };
}
options = _.defaultsDeep({}, options, {
allowable: [],
method: "post",
});
return function(body, callback) {
// get and remove/detach URI options
var uriOptions = utils.getURIOptions([utils.setup(), options, this, body]);
utils.removeURIOptions(body);
// create a URI
var uri = utils.url(endpoint, uriOptions);
// get auth options
var authOptions = utils.getAuthOptions([utils.setup(), this, body]);
utils.removeAuthOptions(body);
// remove params that are not allowed
body = utils.pickParams(body, options.allowable);
// sign the URI (automatically removes the secret param from body)
try {
auth.sign(authOptions.key, authOptions.secret, uri, body, {
apiVersion: uriOptions.apiVersion,
});
} catch(err) {
return callback(err);
}
var url = uri.toString();
var method;
var resOpts = {};
switch (options.method) {
case "put":
method = "put";
resOpts.put = true;
break;
case "post":
default:
method = "post";
resOpts.post = true;
}
debug("[%s] /%s (%s) [%j]", method.toUpperCase(), endpoint, url, body);
return utils.request()[method]({
url: url,
body: body,
}, utils.passResponse(callback, resOpts));
};
}
|
javascript
|
{
"resource": ""
}
|
q14505
|
newCustomPostOne
|
train
|
function newCustomPostOne(endpoint, initParams, allowable) {
var modify = newPostOne(endpoint, allowable);
return function(body, callback) {
_.assign(body, initParams);
return modify.call(this, body, callback);
};
}
|
javascript
|
{
"resource": ""
}
|
q14506
|
newPutOne
|
train
|
function newPutOne(endpoint, options) {
// for backwards-compatibility <= 0.11.1
if (_.isArray(options)) options = { allowable: options };
else options = options || {};
options.method = "put";
return newPostOne(endpoint, options);
}
|
javascript
|
{
"resource": ""
}
|
q14507
|
newSSEClientFactory
|
train
|
function newSSEClientFactory(endpoint) {
return function(initDict) {
initDict = initDict || { };
// get URI options
var uriOptions = utils.getURIOptions(initDict);
utils.removeURIOptions(initDict);
// create a new URI
var uri = utils.url(endpoint, uriOptions);
// get auth options
var authOptions = utils.getAuthOptions([utils.setup(), this, initDict]);
// sign the URI (automatically removes the secret param from initDict)
auth.sign(authOptions.key, authOptions.secret, uri);
// determine whether to use an eventsource or poll the endpoint
return new EventSource(uri.toString(), initDict);
};
}
|
javascript
|
{
"resource": ""
}
|
q14508
|
Compressor
|
train
|
function Compressor() {
var self = this;
var regexps = [/[\n\r\t]+/g, /\s{2,}/g];
/**
* Remover of the html comment blocks
* @param html
* @returns {*}
* @private
*/
function _clearHTMLComments(html) {
var cStart = '<!--',
cEnd = '-->',
beg = html.indexOf(cStart),
end = 0;
while (beg !== -1) {
end = html.indexOf(cEnd, beg + 4);
if (end === -1) {
break;
}
var comment = html.substring(beg, end + 3);
if (comment.indexOf("[if") !== -1 || comment.indexOf("![endif]") !== -1) { // skip
beg = html.indexOf(cStart, end + 3);
continue;
}
html = html.replace(comment, "");
beg = html.indexOf(cStart, end + 3);
}
return html;
}
// ---- ---- ---- ---- ----
/**
* Compressor of the html string
* @param {String} html
* @returns {*}
*/
self.compressHTML = function(html) {
if (html === null || html === "")
return html;
html = _clearHTMLComments(html);
var tags = ["script", "textarea", "pre", "code"],
id = new Date().getTime() + "#",
cache = {},
index = 0;
tags.forEach(function(tag, i) {
var tagS = '<' + tag,
tagE = '</' + tag + '>',
start = html.indexOf(tagS),
end = 0,
len = tagE.length;
while (start !== -1) {
end = html.indexOf(tagE, start);
if (end === -1) {
break;
}
var key = id + (index++),
value = html.substring(start, end + len);
if (i === 0) {
end = value.indexOf(">");
len = value.indexOf('type="text/template"');
if (len < end && len !== -1) {
break;
}
len = value.indexOf('type="text/html"');
if (len < end && len !== -1) {
break;
}
}
cache[key] = value;
html = html.replace(value, key);
start = html.indexOf(tagS, start + tagS.length);
}
});
regexps.forEach(function(regexp) {
html = html.replace(regexp, "");
});
Object.keys(cache).forEach(function(key) {
html = html.replace(key, cache[key]);
});
return html;
};
// api ----
return self;
}
|
javascript
|
{
"resource": ""
}
|
q14509
|
_clearHTMLComments
|
train
|
function _clearHTMLComments(html) {
var cStart = '<!--',
cEnd = '-->',
beg = html.indexOf(cStart),
end = 0;
while (beg !== -1) {
end = html.indexOf(cEnd, beg + 4);
if (end === -1) {
break;
}
var comment = html.substring(beg, end + 3);
if (comment.indexOf("[if") !== -1 || comment.indexOf("![endif]") !== -1) { // skip
beg = html.indexOf(cStart, end + 3);
continue;
}
html = html.replace(comment, "");
beg = html.indexOf(cStart, end + 3);
}
return html;
}
|
javascript
|
{
"resource": ""
}
|
q14510
|
train
|
function (ctx, next) {
var plugins = []
var config = process.cssy.config
ctx.imports = []
var parseImportPlugin = postcss.plugin('cssy-parse-imports', function () {
return function (styles) {
styles.walkAtRules(function (atRule) {
if (atRule.name !== 'import') {
return
}
if (/^url\(|:\/\//.test(atRule.params)) {
return // Absolute
}
ctx.imports.push(parseImport(atRule.params))
atRule.remove()
})
}
})
if (ctx.config.import) {
plugins.push(parseImportPlugin)
}
if (config.minify) {
plugins.push(cssnano(extend({}, (typeof config.minify === 'object')
? config.minify : DEFAULT_MINIFY_OPTIONS)))
}
postcss(plugins)
.process(ctx.src, {
from: ctx.filename,
to: ctx.filename + '.map',
map: {
prev: ctx.map,
inline: config.sourcemap
}
})
.then(function (result) {
ctx.src = result.css
if (config.sourcemap) {
// TODO: Dig sourcemap, dig more.
ctx.src += '\n/*# sourceURL=' + ctx.filename + '.output*/'
}
ctx.map = result.map
next(null, ctx)
})
next(null, ctx)
}
|
javascript
|
{
"resource": ""
}
|
|
q14511
|
parseCss
|
train
|
function parseCss (ctx, done) {
var result
try {
result = postcss()
.process(ctx.src, {
map: {
sourcesContent: true,
annotation: false,
prev: ctx.map
},
from: ctx.filename
})
ctx.src = result.css
ctx.map = result.map.toJSON()
done(null, ctx)
} catch (e) {
var msg = e.message
var ext = extname(ctx.filename).slice(1).toLowerCase()
if (ext !== 'css') {
msg += ' (Try to use appropriate parser for ' + ext + ')'
}
done(new Error(msg))
}
}
|
javascript
|
{
"resource": ""
}
|
q14512
|
Network
|
train
|
function Network(blogs) {
this.blogs = {};
this.loading = 0;
this.length = 1;
this.blog_names = [];
blogs = blogs || {};
for (var name in blogs) {
this.add(name, blogs[name]);
}
}
|
javascript
|
{
"resource": ""
}
|
q14513
|
getFromFileNameV1
|
train
|
function getFromFileNameV1 (filename) {
var result = mime.lookup(filename);
// Add charset just in case for some buggy browsers.
if (result === 'application/javascript' || result === 'application/json' || result === 'text/plain') {
result += '; charset=UTF-8';
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q14514
|
getFromFileNameV2
|
train
|
function getFromFileNameV2 (filename) {
var result = mime.getType(filename);
// Add charset just in case for some buggy browsers.
if (result === 'application/javascript' || result === 'application/json' || result === 'text/plain') {
result += '; charset=UTF-8';
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q14515
|
ListDirectoryContentRecursive
|
train
|
function ListDirectoryContentRecursive(directoryPath, callback) {
var fs = fs || require('fs');
var path = path || require('path');
var results = [];
fs.readdir(directoryPath, function(err, list) {
if (err) {
return callback(err);
}
var pending = list.length;
if (!pending) {
return callback(null, results);
}
list.forEach(function(file) {
file = path.join(directoryPath, file);
results.push(file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
ListDirectoryContentRecursive(file, function(err, res) {
results = results.concat(res);
if (!--pending) {
callback(null, results);
}
});
} else {
if (!--pending) {
callback(null, results);
}
}
});
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14516
|
ObjectDeepFind
|
train
|
function ObjectDeepFind(obj, propertyPath) {
// Divide todas as propriedades pelo .
var paths = propertyPath.split('.');
// Copia o objeto
var currentObj = obj;
// Para cada propriedade vou pegar a próxima até encontrar o valor do path inteiro da propriedade
for (var i = 0; i < paths.length; ++i) {
if (currentObj[paths[i]] == undefined) {
return undefined;
} else {
currentObj = currentObj[paths[i]];
}
}
return currentObj;
}
|
javascript
|
{
"resource": ""
}
|
q14517
|
curry
|
train
|
function curry (fn, ...args) {
if (args.length >= fn.length) {
return fn.apply(null, args)
} else {
return function (...rest) {
return curry(fn, ...args, ...rest)
}
}
}
|
javascript
|
{
"resource": ""
}
|
q14518
|
getRawRequest
|
train
|
function getRawRequest(context, excludedPreLoaders) {
excludedPreLoaders = excludedPreLoaders || /eslint-loader/;
return loaderUtils.getRemainingRequest({
resource: context.resource,
loaderIndex: context.loaderIndex,
loaders: context.loaders.filter(loader => !excludedPreLoaders.test(loader.path))
});
}
|
javascript
|
{
"resource": ""
}
|
q14519
|
findUserFromToken
|
train
|
function findUserFromToken(token, cb) {
var q = "SELECT * FROM users " +
"JOIN tokens t ON t.token = $1 " +
"JOIN users u ON u.id = t.user_id";
db.getClient(function(err, client, done) {
client.query(q, [token], function(err, r) {
var result = r && r.rows[0];
if(!result && !err) { err = new exceptions.NotFound(); }
if(err) {
cb(err);
done(err);
} else {
cb(null, result);
done();
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14520
|
create
|
train
|
function create(body, cb) {
var validates = Schema(body);
if(!validates) {
return cb(new exceptions.BadRequest());
}
body.expires_at = stampify(conf.session_maxage);
var q = qb.insert(body);
db.getClient(function(err, client, done) {
client.query(q[0], q[1], function(err, r) {
if(err) {
if(err.code == 23505) {
err = new exceptions.AlreadyExists();
}
cb(err);
done(err);
} else {
cb(null, r.rows[0]);
done();
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14521
|
harvest
|
train
|
function harvest() {
var q = "DELETE FROM tokens WHERE expires_at < now() AT TIME ZONE 'UTC'";
db.getClient(function(err, client, done) {
client.query(q, function(err) {
if(err) {
console.error(new Date);
console.error(err.stack);
}
done(err);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14522
|
filter
|
train
|
function filter(filterName, pattern, options) {
return function() {
options = options || {};
filters[filterName] = gFilter(pattern, options);
return filters[filterName];
};
}
|
javascript
|
{
"resource": ""
}
|
q14523
|
createBuffer
|
train
|
function createBuffer(str, encoding) {
if (BUFFER_FROM) {
return Buffer.from(str, encoding || ENCODING);
}
return new Buffer(str, encoding || ENCODING);
}
|
javascript
|
{
"resource": ""
}
|
q14524
|
convertValue
|
train
|
function convertValue(value, cast) {
var val;
if (value === null || value === undefined) {
return value;
}
val = Buffer.isBuffer(value) ? value.toString('utf8') : value;
if (cast !== false && typeof val === 'string') {
try {
return JSON.parse(val);
} catch (e) {}
}
return val;
}
|
javascript
|
{
"resource": ""
}
|
q14525
|
wrapData
|
train
|
function wrapData(target, name, value, rawBuffer, cast) {
var converted = false;
var val;
if (!target.hasOwnProperty(name)) {
if (value === null || value === undefined || (rawBuffer === true && Buffer.isBuffer(value))) {
converted = true;
val = value;
}
Object.defineProperty(target, name, {
get: function() {
if (!converted) {
val = convertValue(value, cast);
converted = true;
}
return val;
},
enumerable: true,
});
}
}
|
javascript
|
{
"resource": ""
}
|
q14526
|
sub
|
train
|
function sub (subURI, callback) {
var PING_TIMEOUT = process.env['PING_TIMEOUT']
if (!subURI) {
callback(new Error('uri is required'))
return
}
var domain = subURI.split('/')[2]
var wss = 'wss://' + domain + '/'
var Socket = new ws(wss, {
origin: 'http://websocket.org'
})
Socket.on('open', function open () {
debug('connected')
Socket.send('sub ' + subURI)
if (PING_TIMEOUT && parseInt(PING_TIMEOUT) && parseInt(PING_TIMEOUT) > 0 ) {
setInterval(function() {
debug('sending ping')
Socket.send('ping')
}, parseInt(PING_TIMEOUT * 1000))
}
})
Socket.on('close', function close () {
debug('disconnected')
})
Socket.on('message', function message (data, flags) {
debug(data)
callback(null, data)
})
}
|
javascript
|
{
"resource": ""
}
|
q14527
|
matchTabItem
|
train
|
function matchTabItem(tabItem, searchExp) {
var urlMatches = tabItem.url.match(searchExp);
var titleMatches = tabItem.title.match(searchExp);
if (urlMatches === null && titleMatches === null) {
return null;
}
return new FilteredTabItem({ tabItem: tabItem, urlMatches: urlMatches, titleMatches: titleMatches });
}
|
javascript
|
{
"resource": ""
}
|
q14528
|
matchTabWindow
|
train
|
function matchTabWindow(tabWindow, searchExp) {
var itemMatches = tabWindow.tabItems.map(function (ti) {
return matchTabItem(ti, searchExp);
}).filter(function (fti) {
return fti !== null;
});
var titleMatches = tabWindow.title.match(searchExp);
if (titleMatches === null && itemMatches.count() === 0) {
return null;
}
return FilteredTabWindow({ tabWindow: tabWindow, titleMatches: titleMatches, itemMatches: itemMatches });
}
|
javascript
|
{
"resource": ""
}
|
q14529
|
filterTabWindows
|
train
|
function filterTabWindows(tabWindows, searchExp) {
var res;
if (searchExp === null) {
res = _.map(tabWindows, function (tw) {
return new FilteredTabWindow({ tabWindow: tw });
});
} else {
var mappedWindows = _.map(tabWindows, function (tw) {
return matchTabWindow(tw, searchExp);
});
res = _.filter(mappedWindows, function (fw) {
return fw !== null;
});
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q14530
|
setICanGoHere
|
train
|
function setICanGoHere(positionsWhereCanIGo, position) {
return Object.assign({
iCanGoHere: containsXY(positionsWhereCanIGo, position)
}, position);
}
|
javascript
|
{
"resource": ""
}
|
q14531
|
printUnicodePosition
|
train
|
function printUnicodePosition(p) {
return isBackGroundBlack(p.x, p.y) ? printUnicodeBackgroundBlack(p) : printUnicodeBackgroundWhite(p);
}
|
javascript
|
{
"resource": ""
}
|
q14532
|
containsXY
|
train
|
function containsXY(positions, position) {
return positions ? positions.some(function (p) {
return hasSameXY(p, position);
}) : false;
}
|
javascript
|
{
"resource": ""
}
|
q14533
|
getJshintrc
|
train
|
function getJshintrc () {
var jshintrcPath = process.cwd() + '/.jshintrc';
try {
return JSON.parse(fs.readFileSync(jshintrcPath, 'utf8'));
}
catch (error) {
console.warn(`Expected to find JSHint configuration ${jshintrcPath}. Using default JSHint configuration`);
return undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q14534
|
returnData
|
train
|
function returnData (data, response) {
if (typeof (response) === 'function') {
return response(null, data)
}
if (!response.headersSent) {
return response.status(200).end(JSON.stringify(data))
}
}
|
javascript
|
{
"resource": ""
}
|
q14535
|
dispatchResult
|
train
|
function dispatchResult (error, data) {
if (_cb.beforeAll) { _cb.beforeAll() }
if (_cb.returnForAll) {
_cb.returnForAll(error, data)
} else if (!_isNullOrEmptyArray(error)) {
var _error = _normalizeError(error)
if (!_isNullOrEmptyArray(data)) {
processErrorAndData(_error, data)
} else {
processError(_error)
}
} else {
if (!_isNullOrEmptyArray(data)) {
processData(data)
} else {
processNotFound()
}
}
if (_cb.afterAll) { _cb.afterAll() }
}
|
javascript
|
{
"resource": ""
}
|
q14536
|
chars_to_bytes
|
train
|
function chars_to_bytes(ac) {
var retval = []
for (var i = 0; i < ac.length; i++) {
retval = retval.concat(str_to_bytes(ac[i]))
}
return retval
}
|
javascript
|
{
"resource": ""
}
|
q14537
|
int64_to_bytes
|
train
|
function int64_to_bytes(num) {
var retval = []
for (var i = 0; i < 8; i++) {
retval.push(num & 0xFF)
num = num >>> 8
}
return retval
}
|
javascript
|
{
"resource": ""
}
|
q14538
|
bytes_to_int32
|
train
|
function bytes_to_int32(arr, off) {
return (arr[off + 3] << 24) | (arr[off + 2] << 16) | (arr[off + 1] << 8) | (arr[off])
}
|
javascript
|
{
"resource": ""
}
|
q14539
|
typed_to_plain
|
train
|
function typed_to_plain(tarr) {
var retval = new Array(tarr.length)
for (var i = 0; i < tarr.length; i++) {
retval[i] = tarr[i]
}
return retval
}
|
javascript
|
{
"resource": ""
}
|
q14540
|
updateRun
|
train
|
function updateRun(nf, sin32, dw32, b32) {
var temp = d
d = c
c = b
//b = b + rol(a + (nf + (sin32 + dw32)), b32)
b = _add(b,
rol(
_add(a,
_add(nf, _add(sin32, dw32))
), b32
)
)
a = temp
}
|
javascript
|
{
"resource": ""
}
|
q14541
|
getUsageOptions
|
train
|
function getUsageOptions() {
var configData = this.config.data;
if (configData.usage && configData.usage.options) {
return configData.usage.options;
}
return {};
}
|
javascript
|
{
"resource": ""
}
|
q14542
|
formatDescription
|
train
|
function formatDescription(str, formattingOptions) {
var end = '.', endRe = new RegExp('[\\.\\!\\?]{1}[\\)\\]"\']*?$');
// Apply a fallback in case we're trying to format a null or undefined.
if (!str) {
str = 'N/A';
}
// Add a period in case no valid end-of-sentence marker is found.
if (formattingOptions.addPeriod) {
if (endRe.test(str) === false) {
str = str + end;
}
}
return str;
}
|
javascript
|
{
"resource": ""
}
|
q14543
|
formatUsageHeader
|
train
|
function formatUsageHeader(headerContent) {
var headerString = headerContent instanceof Array ?
headerContent.join(EOL) :
headerContent;
return headerString + EOL;
}
|
javascript
|
{
"resource": ""
}
|
q14544
|
formatUsage
|
train
|
function formatUsage(grunt, usageHeader, usageHelp) {
var usageString = '',
reUsage = [new RegExp('\\[-(.+?)\\]', 'g'), '[$1]'],
reTasks = [new RegExp('^[ ]{2}-([^\\s]*)', 'mg'), ' $1 '];
usageString += usageHeader;
usageHelp = usageHelp.replace(reUsage[0], reUsage[1]);
usageHelp = usageHelp.replace(reTasks[0], reTasks[1]);
usageString += usageHelp;
// One final pass to ensure linebreak normalization.
return grunt.util.normalizelf(usageString);
}
|
javascript
|
{
"resource": ""
}
|
q14545
|
addTaskGroup
|
train
|
function addTaskGroup(taskGroup, grunt, parser, descriptionOverrides,
formattingOptions) {
var parserGruntTasks;
var taskName, taskInfo;
var n;
// Create the parser for this group.
parserGruntTasks = parser.addArgumentGroup({
title: taskGroup.header ? taskGroup.header : 'Grunt tasks',
required: false
});
// Iterate through all tasks that we want to see in the output.
for (n = 0; n < taskGroup.tasks.length; ++n) {
taskName = taskGroup.tasks[n];
taskInfo = grunt.task._tasks[taskName];
// Add a task to the argument parser using either the user's
// description override or its package.json description.
parserGruntTasks.addArgument(['-' + taskName], {
'nargs': 0,
'required': false,
'help': formatDescription(
descriptionOverrides[taskName] ?
descriptionOverrides[taskName] :
taskInfo.info,
formattingOptions
)
}
);
}
}
|
javascript
|
{
"resource": ""
}
|
q14546
|
createReader
|
train
|
function createReader(db, options) {
if (options == null) options = {}
var iterator = db.iterator(options)
function _read(n) {
// ignore n for now
var self = this
iterator.next(function (err, key, value) {
if (err) {
iterator.end(noop)
self.emit("error", err)
return
}
if (key == null && value == null) {
iterator.end(noop)
self.push(null)
return
}
var record = multibuffer.pack([key, value])
self.push(record)
})
}
return spigot(_read)
}
|
javascript
|
{
"resource": ""
}
|
q14547
|
buildResolverOptions
|
train
|
function buildResolverOptions(options, base) {
var pathFilter = options.pathFilter;
options.basedir = base;
options.pathFilter = function(info, resvPath, relativePath) {
if (relativePath[0] !== '.') {
relativePath = './' + relativePath;
}
var mappedPath;
if (pathFilter) {
mappedPath = pathFilter.apply(this, [info, resvPath, path.normalize(relativePath)]);
}
if (mappedPath) {
return mappedPath;
}
return;
};
return options;
}
|
javascript
|
{
"resource": ""
}
|
q14548
|
parseError
|
train
|
function parseError(error) {
// If this file is at the root of your project
var pathRegexp = new RegExp(__dirname, 'g');
var display = '';
if (error.code) { display += 'Error code: ' + error.code + '\n\n' };
if (error.stack) { display += error.stack.replace(pathRegexp, ''); }
if (!display) { display = error.toString(); }
return display;
}
|
javascript
|
{
"resource": ""
}
|
q14549
|
openIssue
|
train
|
function openIssue(e) {
require('../lib/node.js')
.github('pauldijou/open-issue')
.title('Unexpected error')
.labels('bug', 'fatal')
.append('The following error occured:')
.appendCode(parseError(e))
.append('You can also add custom infos if necessary...')
.open();
}
|
javascript
|
{
"resource": ""
}
|
q14550
|
addSafely
|
train
|
function addSafely( collection, element, database ) {
// 1. IE doesn't support customData on text nodes;
// 2. Text nodes never get chance to appear twice;
if ( !element.is || !element.getCustomData( 'block_processed' ) ) {
element.is && CKEDITOR.dom.element.setMarker( database, element, 'block_processed', true );
collection.push( element );
}
}
|
javascript
|
{
"resource": ""
}
|
q14551
|
getDivContainer
|
train
|
function getDivContainer( element ) {
var container = editor.elementPath( element ).blockLimit;
// Never consider read-only (i.e. contenteditable=false) element as
// a first div limit (#11083).
if ( container.isReadOnly() )
container = container.getParent();
// Dont stop at 'td' and 'th' when div should wrap entire table.
if ( editor.config.div_wrapTable && container.is( [ 'td', 'th' ] ) ) {
var parentPath = editor.elementPath( container.getParent() );
container = parentPath.blockLimit;
}
return container;
}
|
javascript
|
{
"resource": ""
}
|
q14552
|
reject
|
train
|
function reject(err, async) {
err = toErr(err);
if (async) {
return Promise.reject(err);
} else {
throw err;
}
}
|
javascript
|
{
"resource": ""
}
|
q14553
|
copyFiles
|
train
|
function copyFiles(srcfile, dstfile, callback) {
var fs = require("fs");
var rs = fs.createReadStream(srcfile);
var ws = fs.createWriteStream(dstfile);
rs.on("data", function(d) {
ws.write(d);
});
rs.on("end", function() {
ws.end();
callback(true);
});
}
|
javascript
|
{
"resource": ""
}
|
q14554
|
train
|
function (db, index, term, field, cb) {
var url = host +
'databases/' + db +
'/suggest/' + index +
'?term=' + encodeURIComponent(term) +
'&field=' + field +
'&max=10&distance=Default&accuracy=0.5';
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(body);
cb(null, result);
}
else {
cb(error || new Error(response.statusCode), null);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14555
|
train
|
function (db, indexName, facetDoc, query, cb) {
var url = host + "databases/" + db + "/facets/" + indexName + "?facetDoc=" + facetDoc + "&query=" + encodeURIComponent(query);
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(body);
_.each(result.Results, function (v, k) {
if (_.filter(v.Values, function (x) {
return x.Hits > 0;
}).length < 2) {
delete result.Results[k];
return;
}
v.Values = _.chain(v.Values)
.map(function (x) {
var val = JSON.stringify(x.Range)
.replace(/^\"|\"$/gi, "")
.replace(/\:/gi, "\\:")
.replace(/\(/gi, "\\(")
.replace(/\)/gi, "\\)");
if (x.Range.indexOf(" TO ") <= 0 || x.Range.indexOf("[") !== 0) {
val = val.replace(/\ /gi, "\\ ");
}
val = encodeURIComponent(val);
x.q = k + ":" + val;
x.Range = x.Range
.replace(/^\[Dx/, "")
.replace(/ Dx/, " ")
.replace(/\]$/, "")
.replace(/ TO /, "-");
return x;
}).filter(function (x) {
return x.Hits > 0;
}).sortBy(function (x) {
return x.Range;
}).value();
});
cb(null, result.Results);
} else
cb(error || new Error(response.statusCode), null);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14556
|
train
|
function (db, indexName, whereClause, groupBy, fieldsToSum, cb) {
var url = host + 'databases/' + db + '/facets/' + indexName + '?';
url += whereClause ? '&query=' + encodeURIComponent(whereClause) : '';
url += '&facetStart=0&facetPageSize=1024';
var facets = fieldsToSum
.map(function (field) {
return {
"Mode": 0,
"Aggregation": 16,
"AggregationField": field,
"Name": groupBy,
"DisplayName": field,
"Ranges": [],
"MaxResults": null,
"TermSortMode": 0,
"IncludeRemainingTerms": false
};
});
url += '&facets=' + JSON.stringify(facets);
request(url, function (error, response, body) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(body);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14557
|
train
|
function (db, id, wantedPropsFromMetadata, cb) {
if(Object.prototype.toString.call(wantedPropsFromMetadata) == '[object Function]'){
cb = wantedPropsFromMetadata;
wantedPropsFromMetadata = [];
}
var url = host + 'databases/' + db + '/docs/' + id;
request(url, function (error, response, body) {
if(error || response.statusCode != 200)
return cb(error || new Error(response.statusCode));
var doc = JSON.parse(body);
var meta = _.reduce(response.headers
, function (memo, val, key) {
if (key.indexOf('raven') === 0 || wantedPropsFromMetadata.indexOf(key) != -1)
memo[key] = val;
return memo;
}, {});
meta['@id'] = response.headers['__document_id'];
meta.etag = response.headers['etag'];
meta.dateCreated = response.headers['DateCreated'] || response.headers['datecreated'];
doc['@metadata'] = meta;
cb(null, doc);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14558
|
train
|
function (db, id, doc, metadata, cb) {
var operations = [
{
Method: "PUT",
Document: doc,
Metadata: metadata,
Key: id
}
];
request.post({
url: host + 'databases/' + db + '/bulk_docs',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(operations)
}, function (error, response, resBody) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(resBody);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14559
|
train
|
function (db, id, operations, cb) {
request.patch({
url: host + 'databases/' + db + '/docs/' + id,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: JSON.stringify(operations)
}, function (error, response, resBody) {
if (!error && response.statusCode === 200) {
var result = JSON.parse(resBody);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14560
|
train
|
function (db, entityName, doc, cb) {
request.post({
url: host + 'databases/' + db + '/docs',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Raven-Entity-Name': entityName
},
body: JSON.stringify(doc)
}, function (error, response, resBody) {
if (!error && (response.statusCode === 201 || response.statusCode === 200)) {
var result = JSON.parse(resBody);
cb(null, result);
} else {
cb(error || new Error(response.statusCode), null);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14561
|
reinforceDistWeight
|
train
|
function reinforceDistWeight(dist, category) {
var abs = Math.abs(dist);
return 1.0 + (Algol.aReinforceDistWeight[abs] || 0);
}
|
javascript
|
{
"resource": ""
}
|
q14562
|
extractCategoryMap
|
train
|
function extractCategoryMap(oSentence) {
var res = {};
debuglog(debuglog.enabled ? ('extractCategoryMap ' + JSON.stringify(oSentence)) : '-');
oSentence.forEach(function (oWord, iIndex) {
if (oWord.category === IFMatch.CAT_CATEGORY) {
res[oWord.matchedString] = res[oWord.matchedString] || [];
res[oWord.matchedString].push({ pos: iIndex });
}
});
utils.deepFreeze(res);
return res;
}
|
javascript
|
{
"resource": ""
}
|
q14563
|
alias
|
train
|
function alias( name_current, name_alias ) {
if ( util.type( this ) != desc_class_type.value )
return null;
var name, proto = this.prototype;
if ( is_obj( name_current ) ) {
for ( name in name_current )
!util.has( name_current, name ) || alias.call( this, name, name_current[name] );
}
else if ( typeof proto[name_current] == 'function' )
util.def( proto, name_alias, get_method_descriptor( proto, name_current ), true );
return this;
}
|
javascript
|
{
"resource": ""
}
|
q14564
|
get_args
|
train
|
function get_args( args, fn_curr, fn_prev ) {
if ( args.length && OP.toString.call( args[0] ) === '[object Arguments]' ) {
if ( args.length < 2 && arguments.length > 1 ) {
if ( fn_curr in internal_method_names )
return get_args( args[0] );
if ( fn_prev && fn_curr === fn_prev )
return args[0];
}
}
return args;
}
|
javascript
|
{
"resource": ""
}
|
q14565
|
add
|
train
|
function add( key, value ) {
var desc;
switch ( typeof value ) {
case 'object' : desc = util.type( value ) == 'descriptor' ? value : util.describe( { value : value }, 'cw' ); break;
case 'function' : desc = util.describe( make_method( 'parent', value, get_method_descriptor( this, key ), key ), 'cw' ); break;
default : desc = util.describe( value, 'cew' );
}
util.def( this, key, desc, true );
return this.constructor;
}
|
javascript
|
{
"resource": ""
}
|
q14566
|
CrispHooks
|
train
|
function CrispHooks(options) {
if (options && options.eventEmitter) {
this.on = CrispHooks.prototype.hookSync;
this.emit = CrispHooks.prototype.triggerSync;
}
this._hooks = {};
}
|
javascript
|
{
"resource": ""
}
|
q14567
|
train
|
function(options) {
var constantsData = options.constantsData;
var location = options.location;
var index = options.index;
var name = options.name;
var bufferInfo;
var addData = false;
// Search for a buffer's info
array_registers.forEach(function(arrayRegister) {
if(name === arrayRegister.data) {
bufferInfo = {
'size': arrayRegister.size,
};
var importTypeData = true;
if(arrayRegister.type) {
if(arrayRegister.type !== 'raw') {
bufferInfo.type = arrayRegister.type;
importTypeData = false;
}
}
if(importTypeData) {
bufferInfo.type = constantsData[location][index].type;
}
addData = true;
}
});
if(addData) {
constantsData[location][index].bufferInfo = bufferInfo;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14568
|
train
|
function(constantsData) {
var i;
var registerName;
try {
for(i = 0; i < constantsData.registers.length; i++) {
registerName = constantsData.registers[i].name;
if(buffer_registers.indexOf(registerName) >= 0) {
constantsData.registers[i].isBuffer = true;
addMissingBufferRegisterInfoObject({
'constantsData': constantsData,
'location': 'registers',
'index': i,
'name': registerName,
});
}
}
for(i = 0; i < constantsData.registers_beta.length; i++) {
registerName = constantsData.registers_beta[i].name;
if(buffer_registers.indexOf(registerName) >= 0) {
constantsData.registers_beta[i].isBuffer = true;
addMissingBufferRegisterInfoObject({
'constantsData': constantsData,
'location': 'registers_beta',
'index': i,
'name': registerName,
});
}
}
} catch(err) {
console.log('Error adding missing buffer register flags', err, i);
}
return constantsData;
}
|
javascript
|
{
"resource": ""
}
|
|
q14569
|
train
|
function (checks) {
checks = checks || [];
this.checks = [];
for (var i = 0; i < checks.length; i = i + 1) {
this.add(checks[i]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14570
|
train
|
function (object) {
var values = [];
for (var i = 0; i < this.properties.length; i = i + 1) {
if (object == null) {
values.push(undefined);
} else {
values.push(object[this.properties[i]]);
}
}
return values;
}
|
javascript
|
{
"resource": ""
}
|
|
q14571
|
train
|
function (property, validation, required) {
if (required == null) {
required = true;
}
this.property = property;
this.validation = validation;
this.required = required;
}
|
javascript
|
{
"resource": ""
}
|
|
q14572
|
train
|
function (property, messager) {
this.base('initialize')([property], function (value) {
return value != null;
}, messager || function () {
return i18n['ch/maenulabs/validation/ExistenceCheck'].message();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14573
|
train
|
function (property, limit, messager) {
this.base('initialize')([property], function (value) {
return value > limit;
}, messager || function () {
return i18n['ch/maenulabs/validation/GreaterThanCheck'].message({
amount: limit
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q14574
|
train
|
function (property, minimum, maximum, required) {
this.base('initialize')(property, new Validation([
new AtLeastCheck('length', minimum, function () {
return i18n['ch/maenulabs/validation/StringLengthRangeCheck'].minimum({
amount: minimum
});
}),
new AtMostCheck('length', maximum, function () {
return i18n['ch/maenulabs/validation/StringLengthRangeCheck'].maximum({
amount: maximum
});
})
]), required);
}
|
javascript
|
{
"resource": ""
}
|
|
q14575
|
Typed
|
train
|
function Typed (config) {
const typed = this;
const hasDefault = config.hasOwnProperty('default');
// enum
if (config.hasOwnProperty('enum')) {
if (!Array.isArray(config.enum) || config.enum.length === 0) {
throw Error(util.propertyErrorMessage('enum', config.enum, 'Expected a non-empty array'));
}
const copy = [];
config.enum.forEach(function(v) {
if (copy.indexOf(v) === -1) copy.push(v);
});
config.enum = copy;
}
// transform
if (config.transform && typeof config.transform !== 'function') {
throw Error(util.propertyErrorMessage('transform', config.transform, 'Expected a function'));
}
// validate
if (config.validator && typeof config.validator !== 'function') {
throw Error(util.propertyErrorMessage('validator', config.validator, 'Expected a function'));
}
// define properties
Object.defineProperties(typed, {
default: {
/**
* @property
* @name Typed#default
* @type {function,*}
*/
value: config.default,
writable: false
},
enum: {
/**
* @property
* @name Typed#enum
* @readonly
* @type {function,*}
*/
value: config.enum,
writable: false
},
hasDefault: {
/**
* @property
* @name Typed#hasDefault
* @type {boolean}
*/
value: hasDefault,
writable: false
},
transform: {
/**
* @property
* @name Typed#transform
* @readonly
* @type {function}
*/
value: config.transform,
writable: false
},
type: {
/**
* @property
* @name Typed#type
* @readonly
* @type {string,function}
*/
value: config.type,
writable: false
},
validator: {
/**
* @property
* @name Typed#validator
* @readonly
* @type {function}
*/
value: config.validator,
writable: false
}
});
return typed;
}
|
javascript
|
{
"resource": ""
}
|
q14576
|
train
|
function() {
// Also fix all fucked up sizing
var elements = document.querySelectorAll(".fixheight");
for (var ii = 0; ii < elements.length; ++ii) {
var element = elements[ii];
var parent = element.parentNode;
if (parseInt(element.style.height) !== parent.clientHeight) {
element.style.height = parent.clientHeight + "px";
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14577
|
train
|
function() {
if (!document.body) {
setTimeout(stopSliding, 4);
} else {
document.body.addEventListener('touchmove', function(e) {
e.preventDefault();
}, false);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14578
|
train
|
function() {
// Note: This code is for games that require a certain orientation
// on phones only. I'm making the assuption that tablets don't need
// this.
//
// The issue I ran into is I tried to show several people games
// and they had their phone orientation locked to portrait. Having
// to go unlock just to play the game was frustrating. So, for
// controllers than require landscape just try to make the page
// show up in landscape. They'll understand they need to turn the phone.
//
// If the orientation is unlocked they'll turn and the page will
// switch to landscape. If the orientation is locked then turning
// the phone will not switch to landscape NOR will we get an orientation
// event.
var everything = $("hft-everything");
var detectPortrait = function() {
if (screen.width < screen.height) {
everything.className = "hft-portrait-to-landscape";
everything.style.width = window.innerHeight + "px";
everything.style.height = window.innerWidth + "px";
var viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-height, initial-scale=1.0, maximum-scale=1, user-scalable=no, minimal-ui');
} else {
everything.className = "";
}
};
detectPortrait();
window.addEventListener('resize', detectPortrait, false);
}
|
javascript
|
{
"resource": ""
}
|
|
q14579
|
createLogger
|
train
|
function createLogger(opt_level, opt_dir) {
var config = getLogConfig(opt_level, opt_dir);
var transports = getTransports(config);
// check logdir
if (!fs.existsSync(config.file.dir)) {
throw new Error(
util.format('The logdir does not exist: %s', config.file.dir));
}
// create instance
var logger = new (winston.Logger)({
transports: [
new winston.transports.Console(transports.console),
new winston.transports.File(transports.file)
],
exitOnError: false,
exceptionHandlers: [
new winston.transports.File(transports.error)
]
});
// use syslog's levels
logger.setLevels(winston.config.syslog.levels);
// if production env, remove console logger
if (process.env.NODE_ENV === 'production') {
logger.remove(winston.transports.Console);
}
return logger;
}
|
javascript
|
{
"resource": ""
}
|
q14580
|
getLogConfig
|
train
|
function getLogConfig(opt_level, opt_dir) {
var config = _.clone(defaultConfig);
if (opt_level) {
config.level = opt_level;
}
if (opt_dir) {
config.file.dir = opt_dir;
}
return config;
}
|
javascript
|
{
"resource": ""
}
|
q14581
|
getTransports
|
train
|
function getTransports(config) {
var transports = {
console: {
level: config.level,
handleExceptions: true,
colorize: true,
prettyPrint: true
},
file: {
level: config.level,
filename: path.join(config.file.dir, FILE_NAME),
maxsize: config.file.maxsize,
maxFiles: config.file.maxfiles,
json: false,
timestamp: true
}
};
transports.error = {
filename: path.join(config.file.dir, ERROR_FILE_NAME),
maxsize: config.file.maxsize,
maxFiles: config.file.maxfiles,
timestamp: true,
json: true,
prettyPrint: true
};
return transports;
}
|
javascript
|
{
"resource": ""
}
|
q14582
|
googAddDependency
|
train
|
function googAddDependency(file, provides, requires) {
provides.forEach(function(provided) {
symbolsFile[provided] = file;
deps[provided] = deps[provided] || [];
Array.prototype.push.apply(deps[provided], requires)
});
}
|
javascript
|
{
"resource": ""
}
|
q14583
|
generateManifest
|
train
|
function generateManifest(entryPoint) {
var added = new Set();
var manifest = [];
function addTransitiveDeps(symbol) {
added.add(symbol);
var symDeps = deps[symbol];
if (symDeps) {
symDeps.forEach(function(dependency) {
if (!added.has(dependency)) {
addTransitiveDeps(dependency);
}
});
} else {
gutil.log('No deps found for symbol', symbol, deps);
}
manifest.push(symbolsFile[symbol]);
}
addTransitiveDeps(entryPoint);
return manifest;
}
|
javascript
|
{
"resource": ""
}
|
q14584
|
generateManifestFile
|
train
|
function generateManifestFile() {
if (Object.keys(deps).length === 0) {
this.emit('end');
} else if (!entryPoint) {
this.emit('error',
new gutil.PluginError(PLUGIN_NAME, 'Closure entry point is not specified'));
} else {
var manifest = generateManifest(entryPoint);
var manifestFile = new gutil.File({
contents: new Buffer(manifest.join('\n')),
path: fileName
});
this.emit('data', manifestFile);
this.emit('end');
}
}
|
javascript
|
{
"resource": ""
}
|
q14585
|
connectNode
|
train
|
function connectNode (subscriptions, host, clientId) {
// Create client
var url = "tcp://" + host + ":1883";
var client = mqtt_lib.connect(url, {clientId : clientId});
// Register incoming message callback
client.on('message', function(channel, 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, channel);
if (cbs!==undefined) {
cbs.forEach(function(cb) {
if (Object.keys(subscriptions).indexOf(channel)!==-1) {
cb(message.toString());
} else {
cb(message.toString(), channel);
}
});
}
});
return client;
}
|
javascript
|
{
"resource": ""
}
|
q14586
|
subscribeNode
|
train
|
function subscribeNode (client, subscriptions, channel, callback, done_callback) {
if (subscriptions[channel]===undefined) {
subscriptions[channel] = [callback];
client.subscribe(channel, {qos: 0}, function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
});
} else {
subscriptions[channel].push(callback);
}
}
|
javascript
|
{
"resource": ""
}
|
q14587
|
train
|
function(client, subscriptions, channel, callback, done_callback) {
if (subscriptions[channel]===undefined)
return;
subscriptions[channel].splice(subscriptions[channel].indexOf(callback), 1);
if (subscriptions[channel].length===0) {
delete subscriptions[channel];
client.unsubscribe(channel, function() {
// If there is a done_callback defined, execute it
if (done_callback!==undefined) done_callback();
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q14588
|
replaceExt
|
train
|
function replaceExt(fpath, newExt) {
const oldExt = path.extname(fpath);
return _nativeExt.includes(oldExt) ? fpath :
path.join(path.dirname(fpath), path.basename(fpath, oldExt) + newExt);
}
|
javascript
|
{
"resource": ""
}
|
q14589
|
main
|
train
|
function main(args) {
return new Promise((resolve, reject) => {
let b = browserifyArgs(['--node', '--no-detect-globals'].concat(args));
let outdir = (b.argv.outdir || b.argv.o);
if (b.argv._[0] === 'help' || b.argv.h || b.argv.help ||
(process.argv.length <= 2 && process.stdin.isTTY)) {
reject(new Error('Usage: collect-js-deps --outdir <path> [--list] ' +
'{BROWSERIFY-OPTIONS} [entry files]'));
return;
}
if (!outdir && !b.argv.list) {
reject(new Error('collect-js-deps requires --outdir (-o) option for output directory, or --list'));
return;
}
collect_js_deps(b, { list: b.argv.list, outdir });
b.bundle((err, body) => err ? reject(err) : resolve());
});
}
|
javascript
|
{
"resource": ""
}
|
q14590
|
createDriver
|
train
|
function createDriver(opt_options, opt_service) {
var service = opt_service || getDefaultService();
var executor = executors.createExecutor(service.start());
var options = opt_options || new Options();
if (opt_options instanceof webdriver.Capabilities) {
// Extract the Chrome-specific options so we do not send unnecessary
// data across the wire.
options = Options.fromCapabilities(options);
}
return webdriver.WebDriver.createSession(
executor, options.toCapabilities());
}
|
javascript
|
{
"resource": ""
}
|
q14591
|
rectshift
|
train
|
function rectshift(a, b) {
if(a.x > b.x + b.width ||
a.x + a.width < b.x ||
a.y > b.y + b.height ||
a.y + a.height < b.y) {
return 0;
} else {
var overlap = b.x + b.width - a.x;
return overlap;
}
}
|
javascript
|
{
"resource": ""
}
|
q14592
|
train
|
function () {
this.isReady = false;
this._requestID = -1;
this._iframe = null;
this._initCallback = null;
this._requests = {};
this._options = {
iframeID: "pm-lib-iframe"
};
}
|
javascript
|
{
"resource": ""
}
|
|
q14593
|
long
|
train
|
function long(callback) {
var called = false
return function cbOnceLater() {
var args
if (called) {
return
}
called = true
args = Array.prototype.slice.call(arguments)
process.nextTick(function () {
callback.apply(null, args)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q14594
|
short
|
train
|
function short(callback) {
var called = false
return function cbOnceLater(err, data) {
if (called) {
return
}
called = true
process.nextTick(function () {
callback(err, data)
})
}
}
|
javascript
|
{
"resource": ""
}
|
q14595
|
constructor
|
train
|
function constructor(o) {
var f = main.bind(o);
o.current = o.states.initial || o.initial();
o.machine = f;
return f;
}
|
javascript
|
{
"resource": ""
}
|
q14596
|
log
|
train
|
function log(type, label, data) {
var typeLabel = type.charAt(0).toUpperCase() + type.slice(1);
var color;
if (typeLabel === 'Error') {
typeLabel = chalk.red(typeLabel);
color = 'red';
} else if (typeLabel === 'Warn') {
typeLabel = chalk.yellow(typeLabel);
color = 'yellow';
} else if (typeLabel === 'Info') {
typeLabel = chalk.green(typeLabel);
color = 'green';
} else if (typeLabel === 'Log') {
typeLabel = chalk.gray(typeLabel);
color = 'gray';
}
// used to avoid logging "undefined" in the console
if (useTypeLabels) {
label = typeLabel + ': ' + chalk.cyan(label);
} else {
label = chalk[color](label);
}
if (data) {
console[type](label, data);
} else {
console[type](label);
}
}
|
javascript
|
{
"resource": ""
}
|
q14597
|
syncChromeWindowById
|
train
|
function syncChromeWindowById(windowId, cb) {
chrome.windows.get(windowId, { populate: true }, function (chromeWindow) {
cb(function (state) {
return state.syncChromeWindow(chromeWindow);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q14598
|
train
|
function(owner, repo, params) {
return req.standardRequest(`${config.host}/repos/${owner}/${repo}/issues/comments?${req.assembleQueryParams(params,
['sort', 'direction', 'since'])}`);
}
|
javascript
|
{
"resource": ""
}
|
|
q14599
|
train
|
function(owner, repo, id) {
return req.standardRequest(`${config.host}/repos/${owner}/${repo}/issues/comments/${id}`);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.