_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q32100 | const_lookup_nesting | train | function const_lookup_nesting(nesting, name) {
var i, ii, result, constant;
if (nesting.length === 0) return;
// If the nesting is not empty the constant is looked up in its elements
// and in order. The ancestors of those elements are ignored.
for (i = 0, ii = nesting.length; i < ii; i++) {
constant = nesting[i].$$const[name];
if (constant != null) return constant;
}
} | javascript | {
"resource": ""
} |
q32101 | const_lookup_ancestors | train | function const_lookup_ancestors(cref, name) {
var i, ii, result, ancestors;
if (cref == null) return;
ancestors = Opal.ancestors(cref);
for (i = 0, ii = ancestors.length; i < ii; i++) {
if (ancestors[i].$$const && $hasOwn.call(ancestors[i].$$const, name)) {
return ancestors[i].$$const[name];
}
}
} | javascript | {
"resource": ""
} |
q32102 | create_dummy_iclass | train | function create_dummy_iclass(module) {
var iclass = {},
proto = module.$$prototype;
if (proto.hasOwnProperty('$$dummy')) {
proto = proto.$$define_methods_on;
}
var props = Object.getOwnPropertyNames(proto),
length = props.length, i;
for (i = 0; i < length; i++) {
var prop = props[i];
$defineProperty(iclass, prop, proto[prop]);
}
$defineProperty(iclass, '$$iclass', true);
$defineProperty(iclass, '$$module', module);
return iclass;
} | javascript | {
"resource": ""
} |
q32103 | descending_factorial | train | function descending_factorial(from, how_many) {
var count = how_many >= 0 ? 1 : 0;
while (how_many) {
count *= from;
from--;
how_many--;
}
return count;
} | javascript | {
"resource": ""
} |
q32104 | cutNumber | train | function cutNumber() {
if (isFloat()) {
var numerator = parseFloat(cutFloat());
if (str[0] === '/') {
// rational real part
str = str.slice(1);
if (isFloat()) {
var denominator = parseFloat(cutFloat());
return self.$Rational(numerator, denominator);
} else {
// reverting '/'
str = '/' + str;
return numerator;
}
} else {
// float real part, no denominator
return numerator;
}
} else {
return null;
}
} | javascript | {
"resource": ""
} |
q32105 | genrand_real | train | function genrand_real(mt) {
/* mt must be initialized */
var a = genrand_int32(mt), b = genrand_int32(mt);
return int_pair_to_real_exclusive(a, b);
} | javascript | {
"resource": ""
} |
q32106 | browserifySwap | train | function browserifySwap(file) {
var env = process.env.BROWSERIFYSWAP_ENV
, data = ''
, swapFile;
// no stubbing desired or we already determined that we can't find a swap config => just pipe it through
if (!env || cachedConfig === -1) return through();
if (cachedConfig) {
swapFile = swap(cachedConfig, env, file);
// early exit if we have config cached already and know we won't replace anything anyways
return swapFile ? through(write, end) : through();
} else {
return through(write, end)
}
function write(d, enc, cb) { data += d; cb(); }
function end(cb) {
/*jshint validthis:true */
var self = this;
// if config was cached we already resolved the swapFile if we got here
if (swapFile) {
swapFile = swapFile.replace(/\\/g, '/');
debug.inspect({ file: file, swapFile: swapFile });
self.push(requireSwap(swapFile));
return cb();
}
// we should only get here the very first time that this transform is invoked
resolveSwaps(root, function (err, config) {
if (config && config.packages) viralifyDeps(config.packages);
var swaps = config && config.swaps;
// signal with -1 that we already tried to resolve a swap config but didn't find any
cachedConfig = swaps || -1;
if (err) return cb(err);
debug.inspect({ swaps: swaps, env: env });
swapFile = swap(swaps, env, file);
debug.inspect({ file: file, swapFile: swapFile });
var src = swapFile ? requireSwap(swapFile.replace(/\\/g, '/')) : data;
self.push(src);
cb();
});
}
} | javascript | {
"resource": ""
} |
q32107 | prepareResponse | train | function prepareResponse(status, rootUrl, queryPath, data) {
var response = {};
prepareMeta(response, status);
if(rootUrl && queryPath) {
prepareLinks(response, rootUrl, queryPath);
}
if(data) {
prepareData(response, rootUrl, data);
}
return response;
} | javascript | {
"resource": ""
} |
q32108 | prepareMeta | train | function prepareMeta(response, status) {
switch(status) {
case CODE_OK:
response._meta = { "message": MESSAGE_OK,
"statusCode": CODE_OK };
break;
case CODE_NOTFOUND:
response._meta = { "message": MESSAGE_NOTFOUND,
"statusCode": CODE_NOTFOUND };
break;
case CODE_NOTIMPLEMENTED:
response._meta = { "message": MESSAGE_NOTIMPLEMENTED,
"statusCode": CODE_NOTIMPLEMENTED };
break;
case CODE_SERVICEUNAVAILABLE:
response._meta = { "message": MESSAGE_SERVICEUNAVAILABLE,
"statusCode": CODE_SERVICEUNAVAILABLE };
break;
default:
response._meta = { "message": MESSAGE_BADREQUEST,
"statusCode": CODE_BADREQUEST };
}
} | javascript | {
"resource": ""
} |
q32109 | prepareLinks | train | function prepareLinks(response, rootUrl, queryPath) {
var selfLink = { "href": rootUrl + queryPath };
response._links = {};
response._links.self = selfLink;
} | javascript | {
"resource": ""
} |
q32110 | cprModFunction | train | function cprModFunction (a, b) {
let res = a % b
if (res < 0) res += b
return res
} | javascript | {
"resource": ""
} |
q32111 | cprNLFunction | train | function cprNLFunction (lat) {
if (lat < 0) lat = -lat // Table is simmetric about the equator
if (lat < 10.47047130) return 59
if (lat < 14.82817437) return 58
if (lat < 18.18626357) return 57
if (lat < 21.02939493) return 56
if (lat < 23.54504487) return 55
if (lat < 25.82924707) return 54
if (lat < 27.93898710) return 53
if (lat < 29.91135686) return 52
if (lat < 31.77209708) return 51
if (lat < 33.53993436) return 50
if (lat < 35.22899598) return 49
if (lat < 36.85025108) return 48
if (lat < 38.41241892) return 47
if (lat < 39.92256684) return 46
if (lat < 41.38651832) return 45
if (lat < 42.80914012) return 44
if (lat < 44.19454951) return 43
if (lat < 45.54626723) return 42
if (lat < 46.86733252) return 41
if (lat < 48.16039128) return 40
if (lat < 49.42776439) return 39
if (lat < 50.67150166) return 38
if (lat < 51.89342469) return 37
if (lat < 53.09516153) return 36
if (lat < 54.27817472) return 35
if (lat < 55.44378444) return 34
if (lat < 56.59318756) return 33
if (lat < 57.72747354) return 32
if (lat < 58.84763776) return 31
if (lat < 59.95459277) return 30
if (lat < 61.04917774) return 29
if (lat < 62.13216659) return 28
if (lat < 63.20427479) return 27
if (lat < 64.26616523) return 26
if (lat < 65.31845310) return 25
if (lat < 66.36171008) return 24
if (lat < 67.39646774) return 23
if (lat < 68.42322022) return 22
if (lat < 69.44242631) return 21
if (lat < 70.45451075) return 20
if (lat < 71.45986473) return 19
if (lat < 72.45884545) return 18
if (lat < 73.45177442) return 17
if (lat < 74.43893416) return 16
if (lat < 75.42056257) return 15
if (lat < 76.39684391) return 14
if (lat < 77.36789461) return 13
if (lat < 78.33374083) return 12
if (lat < 79.29428225) return 11
if (lat < 80.24923213) return 10
if (lat < 81.19801349) return 9
if (lat < 82.13956981) return 8
if (lat < 83.07199445) return 7
if (lat < 83.99173563) return 6
if (lat < 84.89166191) return 5
if (lat < 85.75541621) return 4
if (lat < 86.53536998) return 3
if (lat < 87.00000000) return 2
else return 1
} | javascript | {
"resource": ""
} |
q32112 | glob | train | function glob(pattern, options, cb) {
if (typeof options === 'function') {
cb = options;
options = {};
}
if (Array.isArray(pattern)) {
return glob.each.apply(glob, arguments);
}
if (typeof cb !== 'function') {
if (typeof cb !== 'undefined') {
throw new TypeError('expected callback to be a function');
}
return glob.promise.apply(glob, arguments);
}
if (typeof pattern !== 'string') {
cb(new TypeError('expected glob to be a string or array'));
return;
}
var opts = createOptions(pattern, options);
bash(pattern, opts, function(err, files) {
if (err instanceof Error) {
cb(err);
return;
}
if (!files) {
files = err;
}
if (opts.nullglob === true && Array.isArray(files) && !files.length) {
files = [pattern];
}
glob.emit('files', files, opts.cwd);
if (!opts.each) {
glob.end(files);
}
cb(null, files);
});
return glob;
} | javascript | {
"resource": ""
} |
q32113 | bash | train | function bash(pattern, options, cb) {
if (!isGlob(pattern)) {
return nonGlob(pattern, options, cb);
}
if (typeof options === 'function') {
cb = options;
options = undefined;
}
var opts = extend({cwd: process.cwd()}, options);
fs.stat(opts.cwd, function(err, stat) {
if (err) {
cb(handleError(err, pattern, opts));
return;
}
if (!stat.isDirectory()) {
cb(new Error('cwd is not a directory: ' + opts.cwd));
return;
}
var cp = spawn(bashPath, cmd(pattern, options), options);
var buf = new Buffer(0);
cp.stdout.on('data', function(data) {
emitMatches(data.toString(), pattern, options);
buf = Buffer.concat([buf, data]);
});
cp.stderr.on('data', function(data) {
cb(handleError(data.toString(), pattern, options));
});
cp.on('close', function(code) {
cb(code, getFiles(buf.toString(), pattern, options));
});
});
} | javascript | {
"resource": ""
} |
q32114 | normalize | train | function normalize(val) {
if (Array.isArray(val)) {
val = val.join(' ');
}
return val.split(' ').join('\\ ');
} | javascript | {
"resource": ""
} |
q32115 | cmd | train | function cmd(patterns, options) {
var str = normalize(patterns);
var keys = Object.keys(options);
var args = [];
var valid = [
'dotglob',
'extglob',
'failglob',
'globstar',
'nocaseglob',
'nullglob'
];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
if (valid.indexOf(key) !== -1) {
args.push('-O', key);
}
}
args.push('-c', 'for i in ' + str + '; do echo $i; done');
return args;
} | javascript | {
"resource": ""
} |
q32116 | handleError | train | function handleError(err, pattern, options) {
var message = err;
if (typeof err === 'string') {
err = new Error(message.trim());
err.pattern = pattern;
err.options = options;
if (/invalid shell option/.test(err)) {
err.code = 'INVALID_SHELL_OPTION';
}
if (/no match:/.test(err)) {
err.code = 'NOMATCH';
}
return err;
}
if (err && (err.code === 'ENOENT' || err.code === 'NOMATCH')) {
if (options.nullglob === true) {
return [pattern];
}
if (options.failglob === true) {
return err;
}
return [];
}
return err;
} | javascript | {
"resource": ""
} |
q32117 | getFiles | train | function getFiles(res, pattern, options) {
var files = res.split(/\r?\n/).filter(Boolean);
if (files.length === 1 && files[0] === pattern) {
files = [];
} else if (options.realpath === true || options.follow === true) {
files = toAbsolute(files, options);
}
if (files.length === 0) {
if (options.nullglob === true) {
return [pattern];
}
if (options.failglob === true) {
return new Error('no matches:' + pattern);
}
}
return files.filter(function(filepath) {
return filepath !== '.' && filepath !== '..';
});
} | javascript | {
"resource": ""
} |
q32118 | toAbsolute | train | function toAbsolute(files, options) {
var len = files.length;
var idx = -1;
var arr = [];
while (++idx < len) {
var file = files[idx];
if (!file.trim()) continue;
if (file && options.cwd) {
file = path.resolve(options.cwd, file);
}
if (file && options.realpath === true) {
file = follow(file);
}
if (file) {
arr.push(file);
}
}
return arr;
} | javascript | {
"resource": ""
} |
q32119 | nonGlob | train | function nonGlob(pattern, options, cb) {
if (options.nullglob) {
cb(null, [pattern]);
return;
}
fs.stat(pattern, callback(null, pattern, options, cb));
return;
} | javascript | {
"resource": ""
} |
q32120 | emitMatches | train | function emitMatches(str, pattern, options) {
glob.emit('match', getFiles(str, pattern, options), options.cwd);
} | javascript | {
"resource": ""
} |
q32121 | Barterer | train | function Barterer(options) {
var self = this;
options = options || {};
self.routes = {
"/whereis": require('./routes/whereis'),
"/whatat": require('./routes/whatat'),
"/whatnear": require('./routes/whatnear'),
"/": express.static(path.resolve(__dirname + '/../web'))
};
console.log('reelyActive Barterer instance is exchanging data in an open IoT');
} | javascript | {
"resource": ""
} |
q32122 | isValidOptions | train | function isValidOptions(options) {
if(!options) {
return false;
}
if(options.hasOwnProperty('ids') && Array.isArray(options.ids)) {
for(var cId = 0; cId < options.ids.length; cId++) {
if(!reelib.identifier.isValid(options.ids[cId])) {
return false;
}
}
return true;
}
else {
return false;
}
} | javascript | {
"resource": ""
} |
q32123 | getComponentName | train | function getComponentName(target) {
if (target.displayName && typeof target.displayName === 'string') {
return target.displayName;
}
return target.name || 'Component';
} | javascript | {
"resource": ""
} |
q32124 | defaultWarningMessage | train | function defaultWarningMessage(_ref) {
var componentName = _ref.componentName,
prop = _ref.prop,
renamedProps = _ref.renamedProps;
return componentName + ' Warning: Prop "' + prop + '" is deprecated, use "' + renamedProps[prop] + '" instead.';
} | javascript | {
"resource": ""
} |
q32125 | componentDidMount | train | function componentDidMount() {
var _this2 = this;
Object.keys(renamedProps).forEach(function (prop) {
if (prop in _this2.props) {
console.warn(warningMessage({
componentName: getComponentName(WrappedComponent),
prop: prop,
renamedProps: renamedProps
}));
}
});
} | javascript | {
"resource": ""
} |
q32126 | harvester | train | function harvester (metricConsumer, agentList) {
var agentsToLoad = []
this.metricConsumer = metricConsumer
this.httpAgent = null
if (agentList) {
agentsToLoad = agentList
}
this.agents = []
for (var x in agentsToLoad) {
try {
var TmpAgentClass = require(agentsToLoad[x])
var tmpAgentInstance = new TmpAgentClass()
this.addAgent(tmpAgentInstance)
} catch (err) {
logger.error('Loading of agent failed:' + agentsToLoad[x])
logger.error(err)
}
}
process.on('exit', function () {
this.stop()
}.bind(this))
return this
} | javascript | {
"resource": ""
} |
q32127 | coerceRoot | train | function coerceRoot(root) {
var coerced = root.substring().trim();
var len = coerced.length;
if (len > 0 && coerced[len - 1] !== '/') {
coerced = coerced + '/';
}
return coerced;
} | javascript | {
"resource": ""
} |
q32128 | train | function(callable, root, isMaster) {
rfr = callable.bind(callable);
/**
* A read-only property tells whether this rfr instance is a master one.
* Call `require('rfr')` to get a master rfr instance.
* User created rfr instances, such as `require('rfr')({ root: '...' })` are
* not master ones.
* @type {Boolean}
*/
Object.defineProperty(rfr, 'isMaster', {
configurable: false,
enumerable: true,
value: !!isMaster,
writable: false
});
/**
* A read-only property tells whether this rfr instance is a global master.
* Call `require('rfr')` on a global rfr module to get a master rfr instance.
* Using the global master is error-prone.
* @type {Boolean}
*/
Object.defineProperty(rfr, 'isGlobalMaster', {
configurable: false,
enumerable: true,
value: constants.isGlobal && !!isMaster,
writable: false
});
/**
* The root of a rfr instance.
* @type {String}
*/
Object.defineProperty(rfr, 'root', {
configurable: false,
enumerable: true,
get: function() {
return callable.root;
},
set: function(root) {
callable.root = coerceRoot(root);
}
});
/**
* Set the root.
* @param {String} root The new root.
*/
rfr.setRoot = function(root) {
this.root = root;
};
/**
* Get the filename that will be loaded when this rfr is called.
* @returns {String} module filename.
*/
rfr.resolve = function(idFromRoot) {
return require.resolve(normalizeId(idFromRoot, this.root));
};
rfr.root = root;
return rfr;
} | javascript | {
"resource": ""
} | |
q32129 | createVersion | train | function createVersion(config) {
if (!(config && (typeof config.root === 'string'
|| config.root === null || config.root === undefined))) {
throw new Error('"config.root" is required and must be a string');
}
var root = config.root;
if (root === null || root === undefined) {
root = defaultRoot;
}
return createRfr(function(idFromRoot) {
if (typeof idFromRoot !== 'string') {
throw new Error('A string is required for the argument of ' +
'a user created RFR version.');
}
return require(normalizeId(idFromRoot, this.root));
}, root);
} | javascript | {
"resource": ""
} |
q32130 | parsePackageSpecifier | train | function parsePackageSpecifier(rawPackageSpecifier) {
rawPackageSpecifier = (rawPackageSpecifier || '').trim();
const separatorIndex = rawPackageSpecifier.lastIndexOf('@');
let name;
let version = undefined;
if (separatorIndex === 0) {
// The specifier starts with a scope and doesn't have a version specified
name = rawPackageSpecifier;
}
else if (separatorIndex === -1) {
// The specifier doesn't have a version
name = rawPackageSpecifier;
}
else {
name = rawPackageSpecifier.substring(0, separatorIndex);
version = rawPackageSpecifier.substring(separatorIndex + 1);
}
if (!name) {
throw new Error(`Invalid package specifier: ${rawPackageSpecifier}`);
}
return { name, version };
} | javascript | {
"resource": ""
} |
q32131 | resolvePackageVersion | train | function resolvePackageVersion(rushCommonFolder, { name, version }) {
if (!version) {
version = '*'; // If no version is specified, use the latest version
}
if (version.match(/^[a-zA-Z0-9\-\+\.]+$/)) {
// If the version contains only characters that we recognize to be used in static version specifiers,
// pass the version through
return version;
}
else {
// version resolves to
try {
const rushTempFolder = ensureAndJoinPath(rushCommonFolder, 'temp');
const sourceNpmrcFolder = path.join(rushCommonFolder, 'config', 'rush');
syncNpmrc(sourceNpmrcFolder, rushTempFolder);
const npmPath = getNpmPath();
// This returns something that looks like:
// @microsoft/rush@3.0.0 '3.0.0'
// @microsoft/rush@3.0.1 '3.0.1'
// ...
// @microsoft/rush@3.0.20 '3.0.20'
// <blank line>
const npmVersionSpawnResult = childProcess.spawnSync(npmPath, ['view', `${name}@${version}`, 'version', '--no-update-notifier'], {
cwd: rushTempFolder,
stdio: []
});
if (npmVersionSpawnResult.status !== 0) {
throw new Error(`"npm view" returned error code ${npmVersionSpawnResult.status}`);
}
const npmViewVersionOutput = npmVersionSpawnResult.stdout.toString();
const versionLines = npmViewVersionOutput.split('\n').filter((line) => !!line);
const latestVersion = versionLines[versionLines.length - 1];
if (!latestVersion) {
throw new Error('No versions found for the specified version range.');
}
const versionMatches = latestVersion.match(/^.+\s\'(.+)\'$/);
if (!versionMatches) {
throw new Error(`Invalid npm output ${latestVersion}`);
}
return versionMatches[1];
}
catch (e) {
throw new Error(`Unable to resolve version ${version} of package ${name}: ${e}`);
}
}
} | javascript | {
"resource": ""
} |
q32132 | getNpmPath | train | function getNpmPath() {
if (!_npmPath) {
try {
if (os.platform() === 'win32') {
// We're on Windows
const whereOutput = childProcess.execSync('where npm', { stdio: [] }).toString();
const lines = whereOutput.split(os.EOL).filter((line) => !!line);
// take the last result, we are looking for a .cmd command
// see https://github.com/Microsoft/web-build-tools/issues/759
_npmPath = lines[lines.length - 1];
}
else {
// We aren't on Windows - assume we're on *NIX or Darwin
_npmPath = childProcess.execSync('which npm', { stdio: [] }).toString();
}
}
catch (e) {
throw new Error(`Unable to determine the path to the NPM tool: ${e}`);
}
_npmPath = _npmPath.trim();
if (!fs.existsSync(_npmPath)) {
throw new Error('The NPM executable does not exist');
}
}
return _npmPath;
} | javascript | {
"resource": ""
} |
q32133 | rotatePoint | train | function rotatePoint(originX, originY, x, y, radiansX, radiansY) {
const v = {x: x - originX, y: y - originY};
const vx = (v.x * Math.cos(radiansX)) - (v.y * Math.sin(radiansX));
const vy = (v.x * Math.sin(radiansY)) + (v.y * Math.cos(radiansY));
return {x: vx + originX, y: vy + originY};
} | javascript | {
"resource": ""
} |
q32134 | isPointOnLineSegment | train | function isPointOnLineSegment(line1p1, line1p2, point) {
if (line1p2.lat <= Math.max(line1p1.lat, point.lat) && line1p2.lat >= Math.min(line1p1.lat, point.lat) &&
line1p2.lon <= Math.max(line1p1.lon, point.lon) && line1p2.lon >= Math.min(line1p1.lon, point.lon)) {
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q32135 | retrieveWhatAtTransmitter | train | function retrieveWhatAtTransmitter(req, res) {
if(redirect(req.params.id, '', '', res)) {
return;
}
switch(req.accepts(['json', 'html'])) {
case 'html':
res.sendFile(path.resolve(__dirname + '/../../web/response.html'));
break;
default:
var options = {
query: 'receivedBy',
req: req,
ids: [req.params.id]
};
var rootUrl = req.protocol + '://' + req.get('host');
var queryPath = req.originalUrl;
req.barterer.getDevicesState(options, rootUrl, queryPath,
function(response, status) {
res.status(status).json(response);
});
break;
}
} | javascript | {
"resource": ""
} |
q32136 | BartererServer | train | function BartererServer(options) {
options = options || {};
var specifiedHttpPort = options.httpPort || HTTP_PORT;
var httpPort = process.env.PORT || specifiedHttpPort;
var app = express();
var instance = new Barterer(options);
options.app = app;
instance.configureRoutes(options);
app.listen(httpPort, function() {
console.log('barterer is listening on port', httpPort);
});
return instance;
} | javascript | {
"resource": ""
} |
q32137 | ZeroServer | train | function ZeroServer (url, options, callback) {
EventEmitter.call(this);
this.id = null;
//this.streams = {};
if (url) {
this.listen(url, options, callback);
}
} | javascript | {
"resource": ""
} |
q32138 | D3Renderer | train | function D3Renderer(view, graphData, options) {
/**
* View stack
*
* @property view
* @param Array
*/
this.view = view;
/**
* graph Data
*
* @property graph
* @param Object
*/
this.graph = graphData;
/**
* (Default merged) option
*
* @property option
* @type Object
*/
this.option = mixin(defaultOptions, options || {});
/**
* Canvas container
*
* @property container
* @type d3-element-array
*/
this.container = null;
/**
* SVG container
*
* @property svg
* @type d3-element-array
*/
this.svg = null;
/**
* force reloader
*
* @property force
* @type d3-element-array
*/
this.force = null;
/**
* link elements
*
* @property link
* @type d3-element-array
*/
this.link = null;
/**
* Node elements
*
* @property node
* @type d3-element-array
*/
this.node = null;
/**
* test elements
*
* @property text
* @type d3-element-array
*/
this.text = null;
/**
* d3 color object
*
* @property color
* @type Object
*/
this.color = d3.scale.category20();
/**
* selected index
*
* @property selectedIdx
* @type Number
* @default -1
*/
this.selectedIdx = -1;
/**
* selected type
*
* @property selectedType
* @type String
* @default "normal"
*/
this.selectedType = 'normal';
/**
* selected object
*
* @property selectedObject
* @type Object
*/
this.selectedObject = {};
// Scope trick
this.radius = this.radius();
this.linkLine = this.linkLine();
} | javascript | {
"resource": ""
} |
q32139 | train | function (vinyl) {
return path.extname(vinyl.path) === ".lnxs" ? options.spec.dir : options.output;
} | javascript | {
"resource": ""
} | |
q32140 | validate | train | function validate () {
var env = state.env('NODE_ENV');
var uri = state.env('MONGO_URI');
var notTestEnv = env !== 'test';
if (notTestEnv) {
throw new Error('NODE_ENV must be set to "test".');
}
var notTestDb = word.test(uri) === false;
if (notTestDb) {
throw new Error('MONGO_URI must contain "test" word.');
}
} | javascript | {
"resource": ""
} |
q32141 | shipMetrics | train | function shipMetrics (metric) {
try {
this.emit('metric', metric)
this.spmSender.collectMetric(metric)
} catch (ex) {
logger.error('Error in shipMetrics' + ex.stack)
}
} | javascript | {
"resource": ""
} |
q32142 | train | function(view){
var viewCid = view.cid;
// delete model index
if (view.model){
delete this._indexByModel[view.model.cid];
}
// delete custom index
_.any(this._indexByCustom, function(cid, key) {
if (cid === viewCid) {
delete this._indexByCustom[key];
return true;
}
}, this);
// remove the view from the container
delete this._views[viewCid];
// update the length
this._updateLength();
} | javascript | {
"resource": ""
} | |
q32143 | train | function(method, args){
_.each(this._views, function(view){
if (_.isFunction(view[method])){
view[method].apply(view, args || []);
}
});
} | javascript | {
"resource": ""
} | |
q32144 | train | function(handlers){
_.each(handlers, function(handler, name){
var context = null;
if (_.isObject(handler) && !_.isFunction(handler)){
context = handler.context;
handler = handler.callback;
}
this.setHandler(name, handler, context);
}, this);
} | javascript | {
"resource": ""
} | |
q32145 | train | function(name, handler, context){
var config = {
callback: handler,
context: context
};
this._wreqrHandlers[name] = config;
this.trigger("handler:add", name, handler, context);
} | javascript | {
"resource": ""
} | |
q32146 | train | function(name){
var config = this._wreqrHandlers[name];
if (!config){
throw new Error("Handler not found for '" + name + "'");
}
return function(){
var args = Array.prototype.slice.apply(arguments);
return config.callback.apply(config.context, args);
};
} | javascript | {
"resource": ""
} | |
q32147 | train | function(commandName){
var commands = this._commands[commandName];
// we don't have it, so add it
if (!commands){
// build the configuration
commands = {
command: commandName,
instances: []
};
// store it
this._commands[commandName] = commands;
}
return commands;
} | javascript | {
"resource": ""
} | |
q32148 | train | function(name, args){
name = arguments[0];
args = Array.prototype.slice.call(arguments, 1);
if (this.hasHandler(name)){
this.getHandler(name).apply(this, args);
} else {
this.storage.addCommand(name, args);
}
} | javascript | {
"resource": ""
} | |
q32149 | train | function(name, handler, context){
var command = this.storage.getCommands(name);
// loop through and execute all the stored command instances
_.each(command.instances, function(args){
handler.apply(context, args);
});
this.storage.clearCommands(name);
} | javascript | {
"resource": ""
} | |
q32150 | train | function(options){
var storage;
var StorageType = options.storageType || this.storageType;
if (_.isFunction(StorageType)){
storage = new StorageType();
} else {
storage = StorageType;
}
this.storage = storage;
} | javascript | {
"resource": ""
} | |
q32151 | train | function(event) {
// get the method name from the event name
var methodName = 'on' + event.replace(splitter, getEventName);
var method = this[methodName];
// trigger the event, if a trigger method exists
if(_.isFunction(this.trigger)) {
this.trigger.apply(this, arguments);
}
// call the onMethodName if it exists
if (_.isFunction(method)) {
// pass all arguments, except the event name
return method.apply(this, _.tail(arguments));
}
} | javascript | {
"resource": ""
} | |
q32152 | iterateEvents | train | function iterateEvents(target, entity, bindings, functionCallback, stringCallback){
if (!entity || !bindings) { return; }
// allow the bindings to be a function
if (_.isFunction(bindings)){
bindings = bindings.call(target);
}
// iterate the bindings and bind them
_.each(bindings, function(methods, evt){
// allow for a function as the handler,
// or a list of event names as a string
if (_.isFunction(methods)){
functionCallback(target, entity, evt, methods);
} else {
stringCallback(target, entity, evt, methods);
}
});
} | javascript | {
"resource": ""
} |
q32153 | train | function(callback, contextOverride){
this._callbacks.push({cb: callback, ctx: contextOverride});
this._deferred.done(function(context, options){
if (contextOverride){ context = contextOverride; }
callback.call(context, options);
});
} | javascript | {
"resource": ""
} | |
q32154 | train | function(){
var callbacks = this._callbacks;
this._deferred = Marionette.$.Deferred();
this._callbacks = [];
_.each(callbacks, function(cb){
this.add(cb.cb, cb.ctx);
}, this);
} | javascript | {
"resource": ""
} | |
q32155 | train | function(view){
this.ensureEl();
var isViewClosed = view.isClosed || _.isUndefined(view.$el);
var isDifferentView = view !== this.currentView;
if (isDifferentView) {
this.close();
}
view.render();
if (isDifferentView || isViewClosed) {
this.open(view);
}
this.currentView = view;
Marionette.triggerMethod.call(this, "show", view);
Marionette.triggerMethod.call(view, "show");
} | javascript | {
"resource": ""
} | |
q32156 | train | function(){
var view = this.currentView;
if (!view || view.isClosed){ return; }
// call 'close' or 'remove', depending on which is found
if (view.close) { view.close(); }
else if (view.remove) { view.remove(); }
Marionette.triggerMethod.call(this, "close");
delete this.currentView;
} | javascript | {
"resource": ""
} | |
q32157 | train | function(regionDefinitions, defaults){
var regions = {};
_.each(regionDefinitions, function(definition, name){
if (typeof definition === "string"){
definition = { selector: definition };
}
if (definition.selector){
definition = _.defaults({}, definition, defaults);
}
var region = this.addRegion(name, definition);
regions[name] = region;
}, this);
return regions;
} | javascript | {
"resource": ""
} | |
q32158 | train | function(name, definition){
var region;
var isObject = _.isObject(definition);
var isString = _.isString(definition);
var hasSelector = !!definition.selector;
if (isString || (isObject && hasSelector)){
region = Marionette.Region.buildRegion(definition, Marionette.Region);
} else if (_.isFunction(definition)){
region = Marionette.Region.buildRegion(definition, Marionette.Region);
} else {
region = definition;
}
this._store(name, region);
this.triggerMethod("region:add", name, region);
return region;
} | javascript | {
"resource": ""
} | |
q32159 | train | function(){
this.removeRegions();
var args = Array.prototype.slice.call(arguments);
Marionette.Controller.prototype.close.apply(this, args);
} | javascript | {
"resource": ""
} | |
q32160 | train | function(name, region){
region.close();
delete this._regions[name];
this._setLength();
this.triggerMethod("region:remove", name, region);
} | javascript | {
"resource": ""
} | |
q32161 | train | function(template, data){
if (!template) {
var error = new Error("Cannot render the template since it's false, null or undefined.");
error.name = "TemplateNotFoundError";
throw error;
}
var templateFunc;
if (typeof template === "function"){
templateFunc = template;
} else {
templateFunc = Marionette.TemplateCache.get(template);
}
return templateFunc(data);
} | javascript | {
"resource": ""
} | |
q32162 | train | function(target){
target = target || {};
var templateHelpers = Marionette.getOption(this, "templateHelpers");
if (_.isFunction(templateHelpers)){
templateHelpers = templateHelpers.call(this);
}
return _.extend(target, templateHelpers);
} | javascript | {
"resource": ""
} | |
q32163 | train | function(events){
this._delegateDOMEvents(events);
Marionette.bindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
Marionette.bindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
} | javascript | {
"resource": ""
} | |
q32164 | train | function(events){
events = events || this.events;
if (_.isFunction(events)){ events = events.call(this); }
var combinedEvents = {};
var triggers = this.configureTriggers();
_.extend(combinedEvents, events, triggers);
Backbone.View.prototype.delegateEvents.call(this, combinedEvents);
} | javascript | {
"resource": ""
} | |
q32165 | train | function(){
var args = Array.prototype.slice.call(arguments);
Backbone.View.prototype.undelegateEvents.apply(this, args);
Marionette.unbindEntityEvents(this, this.model, Marionette.getOption(this, "modelEvents"));
Marionette.unbindEntityEvents(this, this.collection, Marionette.getOption(this, "collectionEvents"));
} | javascript | {
"resource": ""
} | |
q32166 | train | function(){
if (this.isClosed) { return; }
// allow the close to be stopped by returning `false`
// from the `onBeforeClose` method
var shouldClose = this.triggerMethod("before:close");
if (shouldClose === false){
return;
}
// mark as closed before doing the actual close, to
// prevent infinite loops within "close" event handlers
// that are trying to close other views
this.isClosed = true;
this.triggerMethod("close");
// unbind UI elements
this.unbindUIElements();
// remove the view from the DOM
this.remove();
} | javascript | {
"resource": ""
} | |
q32167 | train | function(){
if (!this.ui || !this._uiBindings){ return; }
// delete all of the existing ui bindings
_.each(this.ui, function($el, name){
delete this.ui[name];
}, this);
// reset the ui element to the original bindings configuration
this.ui = this._uiBindings;
delete this._uiBindings;
} | javascript | {
"resource": ""
} | |
q32168 | train | function(){
this.isClosed = false;
this.triggerMethod("before:render", this);
this.triggerMethod("item:before:render", this);
var data = this.serializeData();
data = this.mixinTemplateHelpers(data);
var template = this.getTemplate();
var html = Marionette.Renderer.render(template, data);
this.$el.html(html);
this.bindUIElements();
this.triggerMethod("render", this);
this.triggerMethod("item:rendered", this);
return this;
} | javascript | {
"resource": ""
} | |
q32169 | train | function(){
if (this.isClosed){ return; }
this.triggerMethod('item:before:close');
Marionette.View.prototype.close.apply(this, slice(arguments));
this.triggerMethod('item:closed');
} | javascript | {
"resource": ""
} | |
q32170 | train | function(){
if (this.collection){
this.listenTo(this.collection, "add", this.addChildView, this);
this.listenTo(this.collection, "remove", this.removeItemView, this);
this.listenTo(this.collection, "reset", this.render, this);
}
} | javascript | {
"resource": ""
} | |
q32171 | train | function(item, collection, options){
this.closeEmptyView();
var ItemView = this.getItemView(item);
var index = this.collection.indexOf(item);
this.addItemView(item, ItemView, index);
} | javascript | {
"resource": ""
} | |
q32172 | train | function(){
var ItemView;
this.collection.each(function(item, index){
ItemView = this.getItemView(item);
this.addItemView(item, ItemView, index);
}, this);
} | javascript | {
"resource": ""
} | |
q32173 | train | function(){
var EmptyView = Marionette.getOption(this, "emptyView");
if (EmptyView && !this._showingEmptyView){
this._showingEmptyView = true;
var model = new Backbone.Model();
this.addItemView(model, EmptyView, 0);
}
} | javascript | {
"resource": ""
} | |
q32174 | train | function(item, ItemView, index){
// get the itemViewOptions if any were specified
var itemViewOptions = Marionette.getOption(this, "itemViewOptions");
if (_.isFunction(itemViewOptions)){
itemViewOptions = itemViewOptions.call(this, item, index);
}
// build the view
var view = this.buildItemView(item, ItemView, itemViewOptions);
// set up the child view event forwarding
this.addChildViewEventForwarding(view);
// this view is about to be added
this.triggerMethod("before:item:added", view);
// Store the child view itself so we can properly
// remove and/or close it later
this.children.add(view);
// Render it and show it
this.renderItemView(view, index);
// call the "show" method if the collection view
// has already been shown
if (this._isShown){
Marionette.triggerMethod.call(view, "show");
}
// this view was added
this.triggerMethod("after:item:added", view);
} | javascript | {
"resource": ""
} | |
q32175 | train | function(item, ItemViewType, itemViewOptions){
var options = _.extend({model: item}, itemViewOptions);
return new ItemViewType(options);
} | javascript | {
"resource": ""
} | |
q32176 | train | function(view){
// shut down the child view properly,
// including events that the collection has from it
if (view){
this.stopListening(view);
// call 'close' or 'remove', depending on which is found
if (view.close) { view.close(); }
else if (view.remove) { view.remove(); }
this.children.remove(view);
}
this.triggerMethod("item:removed", view);
} | javascript | {
"resource": ""
} | |
q32177 | train | function(){
if (this.collection){
this.listenTo(this.collection, "add", this.addChildView, this);
this.listenTo(this.collection, "remove", this.removeItemView, this);
this.listenTo(this.collection, "reset", this._renderChildren, this);
}
} | javascript | {
"resource": ""
} | |
q32178 | train | function(){
this.isRendered = true;
this.isClosed = false;
this.resetItemViewContainer();
this.triggerBeforeRender();
var html = this.renderModel();
this.$el.html(html);
// the ui bindings is done here and not at the end of render since they
// will not be available until after the model is rendered, but should be
// available before the collection is rendered.
this.bindUIElements();
this.triggerMethod("composite:model:rendered");
this._renderChildren();
this.triggerMethod("composite:rendered");
this.triggerRendered();
return this;
} | javascript | {
"resource": ""
} | |
q32179 | train | function (options) {
options = options || {};
this._firstRender = true;
this._initializeRegions(options);
Marionette.ItemView.prototype.constructor.call(this, options);
} | javascript | {
"resource": ""
} | |
q32180 | train | function(){
if (this.isClosed){
// a previously closed layout means we need to
// completely re-initialize the regions
this._initializeRegions();
}
if (this._firstRender) {
// if this is the first render, don't do anything to
// reset the regions
this._firstRender = false;
} else if (!this.isClosed){
// If this is not the first render call, then we need to
// re-initializing the `el` for each region
this._reInitializeRegions();
}
var args = Array.prototype.slice.apply(arguments);
var result = Marionette.ItemView.prototype.render.apply(this, args);
return result;
} | javascript | {
"resource": ""
} | |
q32181 | train | function () {
if (this.isClosed){ return; }
this.regionManager.close();
var args = Array.prototype.slice.apply(arguments);
Marionette.ItemView.prototype.close.apply(this, args);
} | javascript | {
"resource": ""
} | |
q32182 | train | function(regions){
var that = this;
var defaults = {
regionType: Marionette.getOption(this, "regionType"),
parentEl: function(){ return that.$el; }
};
return this.regionManager.addRegions(regions, defaults);
} | javascript | {
"resource": ""
} | |
q32183 | train | function (options) {
var regions;
this._initRegionManager();
if (_.isFunction(this.regions)) {
regions = this.regions(options);
} else {
regions = this.regions || {};
}
this.addRegions(regions);
} | javascript | {
"resource": ""
} | |
q32184 | train | function(){
this.regionManager = new Marionette.RegionManager();
this.listenTo(this.regionManager, "region:add", function(name, region){
this[name] = region;
this.trigger("region:add", name, region);
});
this.listenTo(this.regionManager, "region:remove", function(name, region){
delete this[name];
this.trigger("region:remove", name, region);
});
} | javascript | {
"resource": ""
} | |
q32185 | train | function(controller, appRoutes) {
if (!appRoutes){ return; }
var routeNames = _.keys(appRoutes).reverse(); // Backbone requires reverted order of routes
_.each(routeNames, function(route) {
this._addAppRoute(controller, route, appRoutes[route]);
}, this);
} | javascript | {
"resource": ""
} | |
q32186 | train | function(){
var args = Array.prototype.slice.apply(arguments);
this.commands.execute.apply(this.commands, args);
} | javascript | {
"resource": ""
} | |
q32187 | train | function(options){
this.triggerMethod("initialize:before", options);
this._initCallbacks.run(options, this);
this.triggerMethod("initialize:after", options);
this.triggerMethod("start", options);
} | javascript | {
"resource": ""
} | |
q32188 | train | function(moduleNames, moduleDefinition){
// slice the args, and add this application object as the
// first argument of the array
var args = slice(arguments);
args.unshift(this);
// see the Marionette.Module object for more information
return Marionette.Module.create.apply(Marionette.Module, args);
} | javascript | {
"resource": ""
} | |
q32189 | train | function(){
this._regionManager = new Marionette.RegionManager();
this.listenTo(this._regionManager, "region:add", function(name, region){
this[name] = region;
});
this.listenTo(this._regionManager, "region:remove", function(name, region){
delete this[name];
});
} | javascript | {
"resource": ""
} | |
q32190 | train | function(options){
// Prevent re-starting a module that is already started
if (this._isInitialized){ return; }
// start the sub-modules (depth-first hierarchy)
_.each(this.submodules, function(mod){
// check to see if we should start the sub-module with this parent
if (mod.startWithParent){
mod.start(options);
}
});
// run the callbacks to "start" the current module
this.triggerMethod("before:start", options);
this._initializerCallbacks.run(options, this);
this._isInitialized = true;
this.triggerMethod("start", options);
} | javascript | {
"resource": ""
} | |
q32191 | train | function(){
// if we are not initialized, don't bother finalizing
if (!this._isInitialized){ return; }
this._isInitialized = false;
Marionette.triggerMethod.call(this, "before:stop");
// stop the sub-modules; depth-first, to make sure the
// sub-modules are stopped / finalized before parents
_.each(this.submodules, function(mod){ mod.stop(); });
// run the finalizers
this._finalizerCallbacks.run(undefined,this);
// reset the initializers and finalizers
this._initializerCallbacks.reset();
this._finalizerCallbacks.reset();
Marionette.triggerMethod.call(this, "stop");
} | javascript | {
"resource": ""
} | |
q32192 | divide | train | function divide(bit) {
var bitString = ((zeros + zeros) + (Number(bit).toString(2))).slice(-64);
return [
parseInt(bitString.slice(0, 32), 2), // hi
parseInt(bitString.slice(-32), 2) // lo
];
} | javascript | {
"resource": ""
} |
q32193 | setGetter | train | function setGetter(obj, prop, getter) {
var key = toPath(arguments);
return define(obj, key, getter);
} | javascript | {
"resource": ""
} |
q32194 | define | train | function define(obj, prop, getter) {
if (!~prop.indexOf('.')) {
defineProperty(obj, prop, getter);
return obj;
}
var keys = prop.split('.');
var last = keys.pop();
var target = obj;
var key;
while ((key = keys.shift())) {
while (key.slice(-1) === '\\') {
key = key.slice(0, -1) + '.' + keys.shift();
}
target = target[key] || (target[key] = {});
}
defineProperty(target, last, getter);
return obj;
} | javascript | {
"resource": ""
} |
q32195 | defineProperty | train | function defineProperty(obj, prop, getter) {
Object.defineProperty(obj, prop, {
configurable: true,
enumerable: true,
get: getter
});
} | javascript | {
"resource": ""
} |
q32196 | train | function(model) {
for (var i = 0; i < filterFunctions.length; i++) {
if (!filterFunctions[i](model)) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} | |
q32197 | isKyouikuKanji | train | function isKyouikuKanji(ch) {
return includes(kyouikuKanji.grade1, ch) ||
includes(kyouikuKanji.grade2, ch) ||
includes(kyouikuKanji.grade3, ch) ||
includes(kyouikuKanji.grade4, ch) ||
includes(kyouikuKanji.grade5, ch) ||
includes(kyouikuKanji.grade6, ch);
} | javascript | {
"resource": ""
} |
q32198 | getKyouikuGrade | train | function getKyouikuGrade(ch) {
let grade;
if (includes(kyouikuKanji.grade1, ch)) {
grade = 1;
}
else if (includes(kyouikuKanji.grade2, ch)) {
grade = 2;
}
else if (includes(kyouikuKanji.grade3, ch)) {
grade = 3;
}
else if (includes(kyouikuKanji.grade4, ch)) {
grade = 4;
}
else if (includes(kyouikuKanji.grade5, ch)) {
grade = 5;
}
else if (includes(kyouikuKanji.grade6, ch)) {
grade = 6;
}
return grade;
} | javascript | {
"resource": ""
} |
q32199 | contains | train | function contains(str) {
return {
hiragana: hasHiragana(str),
katakana: hasKatakana(str),
kanji: hasKanji(str)
};
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.