_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q33600 | train | function(options, callback) {
var that = this;
var data = that._searchInBbox(options.bbox);
callback(null, data);
} | javascript | {
"resource": ""
} | |
q33601 | train | function(data) {
// Data indexing
this._rtree = rbush(9);
data = data || [];
var array = [];
var that = this;
function index(d) {
var bbox = that._getBoundingBox(d);
if (bbox) {
var key = that._toIndexKey(bbox);
key.data = d;
array.push(key);
}
}
if (typeof data === 'function') {
data = data();
}
if (typeof data.forEach === 'function') {
data.forEach(index);
} else if (data.length) {
for (var i = 0; i < data.length; i++) {
index(data[i]);
}
}
this._rtree.load(array);
} | javascript | {
"resource": ""
} | |
q33602 | train | function(bbox) {
var coords = this._toIndexKey(bbox);
var array = this._rtree.search(coords);
array = this._sortByDistance(array, bbox);
var result = [];
var filterMultiPoints = !!this.options.filterPoints;
for (var i = 0; i < array.length; i++) {
var arr = array[i];
var r = arr.data;
var geometry = this.getGeometry(r);
var handled = false;
GeoJsonUtils.forEachGeometry(geometry, {
onPoints : function(points) {
if (!handled
&& (!filterMultiPoints || GeometryUtils
.bboxContainsPoints(points, bbox))) {
result.push(r);
handled = true;
}
},
onLines : function(lines) {
if (!handled
&& GeometryUtils.bboxIntersectsLines(lines, bbox)) {
result.push(r);
handled = true;
}
},
onPolygons : function(polygons) {
if (!handled
&& GeometryUtils.bboxIntersectsPolygonsWithHoles(
polygons, bbox)) {
result.push(r);
handled = true;
}
}
});
}
return result;
} | javascript | {
"resource": ""
} | |
q33603 | train | function(array, bbox) {
if (typeof this.options.sort === 'function') {
this._sortByDistance = this.options.sort;
} else {
this._sortByDistance = function(array, bbox) {
var p = bbox[0];
array.sort(function(a, b) {
var d = (a[1] - p[1]) - (b[1] - p[1]);
if (d === 0) {
d = (a[0] - p[0]) - (b[0] - p[0]);
}
return d;
});
return array;
}
}
return this._sortByDistance(array, bbox);
} | javascript | {
"resource": ""
} | |
q33604 | train | function(bbox) {
var a = +bbox[0][0], b = +bbox[0][1], c = +bbox[1][0], d = +bbox[1][1];
return [ Math.min(a, c), Math.min(b, d), Math.max(a, c), Math.max(b, d) ];
} | javascript | {
"resource": ""
} | |
q33605 | parseText | train | function parseText(text) {
text = text.replace(/\n/g, '')
/* istanbul ignore if */
if (!tagRE.test(text)) {
return null
}
var tokens = []
var lastIndex = tagRE.lastIndex = 0
var match, index, html, value, first, oneTime
/* eslint-disable no-cond-assign */
while (match = tagRE.exec(text)) {
/* eslint-enable no-cond-assign */
index = match.index
// push text token
if (index > lastIndex) {
tokens.push({
value: text.slice(lastIndex, index)
})
}
// tag token
html = htmlRE.test(match[0])
value = html ? match[1] : match[2]
first = value.charCodeAt(0)
oneTime = first === 42 // *
value = oneTime
? value.slice(1)
: value
tokens.push({
tag: true,
value: value.trim(),
html: html,
oneTime: oneTime
})
lastIndex = index + match[0].length
}
if (lastIndex < text.length) {
tokens.push({
value: text.slice(lastIndex)
})
}
return tokens
} | javascript | {
"resource": ""
} |
q33606 | makeViewportGetter_ | train | function makeViewportGetter_(dimension, inner, client) {
if (testMQ('(min-' + dimension + ':' + window[inner] + 'px)')) {
return function getWindowDimension_() {
return window[inner];
};
} else {
var docElem = document.documentElement;
return function getDocumentDimension_() {
return docElem[client];
};
}
} | javascript | {
"resource": ""
} |
q33607 | documentScrollY | train | function documentScrollY(targetElement) {
if (targetElement && (targetElement !== window)) {
return targetElement.scrollTop;
}
if (detectedIE10_ && (window.pageYOffset != document.documentElement.scrollTop)) {
return document.documentElement.scrollTop;
}
return window.pageYOffset || document.documentElement.scrollTop;
} | javascript | {
"resource": ""
} |
q33608 | getRect | train | function getRect(elem) {
if (elem && !elem.nodeType) {
elem = elem[0];
}
if (!elem || 1 !== elem.nodeType) {
return false;
}
var bounds = elem.getBoundingClientRect();
return {
height: bounds.bottom - bounds.top,
width: bounds.right - bounds.left,
top: bounds.top,
left: bounds.left
};
} | javascript | {
"resource": ""
} |
q33609 | dto | train | function dto(opts, cb) {
opts = 'string' == typeof opts
? {path: opts}
: opts
const path = opts.path || process.cwd()
cb = cb || function(){}
assert.equal(typeof path, 'string')
assert.equal(typeof cb, 'function')
saveDirs(path, {}, function(err, res) {
if (err) return cb(err)
saveFiles(path, opts, res, cb)
})
} | javascript | {
"resource": ""
} |
q33610 | saveDirs | train | function saveDirs(path, obj, cb) {
var currDir = ''
var root = ''
walk.walk(path, walkFn, function(err) {
if (err) return cb(err)
cb(null, obj)
})
function walkFn(baseDir, filename, stat, next) {
if (!root) root = baseDir
baseDir = stripLeadingSlash(baseDir.split(root)[1])
if (!baseDir) return next()
if (obj[baseDir]) return next()
if (baseDir != currDir) currDir = baseDir
if (stat.isDirectory()) {
setObject(baseDir, obj, {})
return next()
}
setObject(baseDir, obj, [])
next()
}
} | javascript | {
"resource": ""
} |
q33611 | saveFiles | train | function saveFiles(path, opts, obj, cb) {
const noDot = opts.noDot
var root = ''
walk.walk(path, walkFn, function (err) {
if (err) cb(err)
cb(null, obj)
})
function walkFn(baseDir, filename, stat, next) {
if (!root) root = baseDir
baseDir = stripLeadingSlash(baseDir.split(root)[1])
if (stat.isDirectory()) return next()
if (noDot) {
if (/^\./.test(filename)) return next()
}
pushArr(baseDir, obj, filename)
next()
}
} | javascript | {
"resource": ""
} |
q33612 | setObject | train | function setObject(path, obj, val) {
path = path.split('/')
path.forEach(function(subPath) {
obj = obj[subPath] = obj[subPath] || val
})
} | javascript | {
"resource": ""
} |
q33613 | pushArr | train | function pushArr(path, obj, val) {
path = path.split('/')
path.forEach(function(subPath) {
if (Array.isArray(obj[subPath])) return obj[subPath].push(val)
obj = obj[subPath]
})
} | javascript | {
"resource": ""
} |
q33614 | ScrollPositionController | train | function ScrollPositionController(targetScrollY) {
if (!(this instanceof ScrollPositionController)) {
return new ScrollPositionController(targetScrollY);
}
Emitter.mixin(this);
var trackerStream = ScrollTrackerStream.create(targetScrollY);
Stream.onValue(trackerStream, Util.partial(this.trigger, 'both'));
var beforeStream = Stream.filterFirst('before', trackerStream);
Stream.onValue(beforeStream, Util.partial(this.trigger, 'before'));
var afterStream = Stream.filterFirst('after', trackerStream);
Stream.onValue(afterStream, Util.partial(this.trigger, 'after'));
} | javascript | {
"resource": ""
} |
q33615 | create | train | function create(targetScrollY) {
var scrollPositionStream = ScrollStream.create();
var overTheLineStream = Stream.create();
var pastScrollY = false;
var firstRun = true;
Stream.onValue(scrollPositionStream, function onScrollTrackPosition_(currentScrollY) {
if ((firstRun || pastScrollY) && (currentScrollY < targetScrollY)) {
pastScrollY = false;
Stream.emit(overTheLineStream, ['before', targetScrollY]);
} else if ((firstRun || !pastScrollY) && (currentScrollY >= targetScrollY)) {
pastScrollY = true;
Stream.emit(overTheLineStream, ['after', targetScrollY]);
}
firstRun = false;
});
return overTheLineStream;
} | javascript | {
"resource": ""
} |
q33616 | train | function(type) {
var _this = this;
JobSvfOutputPayload.call(_this, type);
JobThumbnailOutputPayload.call(_this, type);
JobStlOutputPayload.call(_this, type);
JobStepOutputPayload.call(_this, type);
JobIgesOutputPayload.call(_this, type);
JobObjOutputPayload.call(_this, type);
} | javascript | {
"resource": ""
} | |
q33617 | ResizeController | train | function ResizeController(options) {
if (!(this instanceof ResizeController)) {
return new ResizeController(options);
}
Emitter.mixin(this);
options = options || {};
var resizeStream = ResizeStream.create(options);
Stream.onValue(resizeStream, Util.partial(this.trigger, 'resize'));
var debounceMs = Util.getOption(options.debounceMs, 200);
var resizeEndStream = debounceMs <= 0 ? resizeStream : Stream.debounce(
debounceMs,
resizeStream
);
Stream.onValue(resizeEndStream, Util.partial(this.trigger, 'resizeEnd'));
this.destroy = function() {
Stream.close(resizeStream);
this.off('resize');
this.off('resizeEnd');
};
} | javascript | {
"resource": ""
} |
q33618 | maybeTriggerImageLoad | train | function maybeTriggerImageLoad(image, event) {
if (!image.getAttribute('data-loaded') && isElementVisible(image)) {
image.dispatchEvent(event);
return true;
}
return false;
} | javascript | {
"resource": ""
} |
q33619 | loadImage | train | function loadImage(event) {
var image = event.target;
// Swap in the srcset info and add an attribute to prevent duplicate loads.
image.srcset = image.getAttribute('data-lazyload');
image.setAttribute('data-loaded', true);
} | javascript | {
"resource": ""
} |
q33620 | removeLoadingClass | train | function removeLoadingClass(image, loadingClass) {
var element = image;
var shouldReturn = false;
/*
* Since there may be additional elements wrapping the image (e.g. a link),
* we run a loop to check the image’s ancestors until we either find the
* element with the loading class or hit the `body` element.
*/
while (element.tagName.toLowerCase() !== 'body') {
if (element.classList.contains(loadingClass)) {
element.classList.remove(loadingClass);
shouldReturn = true;
} else {
element = element.parentNode;
}
if (shouldReturn) {
return;
}
}
} | javascript | {
"resource": ""
} |
q33621 | initialize | train | function initialize(_ref) {
var _ref$containerClass = _ref.containerClass,
containerClass = _ref$containerClass === undefined ? 'js--lazyload' : _ref$containerClass,
_ref$loadingClass = _ref.loadingClass,
loadingClass = _ref$loadingClass === undefined ? 'js--lazyload--loading' : _ref$loadingClass,
_ref$callback = _ref.callback,
callback = _ref$callback === undefined ? function (e) {
return e;
} : _ref$callback;
// Find all the containers and add the loading class.
var containers = document.getElementsByClassName(containerClass);
[].forEach.call(containers, function (container) {
container.classList.add(loadingClass);
});
// If we get here, `srcset` is supported and we can start processing things.
var images = [].map.call(containers, findImageElement);
// Create a custom event to trigger the event load.
var lazyLoadEvent = new Event('lazyload-init');
// Attach an onload handler to each image.
images.forEach(function (image) {
/*
* Once the image is loaded, we want to remove the loading class so any
* loading animations or other effects can be disabled.
*/
image.addEventListener('load', function (event) {
removeLoadingClass(event.target, loadingClass);
callback(event);
});
/*
* Set up a listener for the custom event that triggers the image load
* handler (which loads the image).
*/
image.addEventListener('lazyload-init', loadImage);
/*
* Check if the image is already in the viewport. If so, load it.
*/
maybeTriggerImageLoad(image, lazyLoadEvent);
});
var loadVisibleImages = checkForImagesToLazyLoad.bind(null, lazyLoadEvent, images);
/*
* Add an event listener when the page is scrolled. To avoid bogging down the
* page, we throttle this call to only run every 100ms.
*/
var scrollHandler = throttle(loadVisibleImages, 100);
window.addEventListener('scroll', scrollHandler);
// Return a function to allow manual checks for images to lazy load.
return loadVisibleImages;
} | javascript | {
"resource": ""
} |
q33622 | lazyLoadImages | train | function lazyLoadImages() {
var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// If we have `srcset` support, initialize the lazyloader.
/* istanbul ignore else: unreasonable to test browser support just for a no-op */
if ('srcset' in document.createElement('img')) {
return initialize(config);
}
// If there’s no support, return a no-op.
/* istanbul ignore next: unreasonable to test browser support just for a no-op */
return function () {
/* no-op */
};
} | javascript | {
"resource": ""
} |
q33623 | FeedJett | train | function FeedJett (options) {
if (!(this instanceof FeedJett)) {
return new FeedJett(options);
}
TransformStream.call(this);
this._readableState.objectMode = true;
this._readableState.highWaterMark = 16; // max. # of output nodes buffered
this.init();
this.parseOptions(options);
sax.MAX_BUFFER_LENGTH = this.options.MAX_BUFFER_LENGTH;
this.stream = sax.createStream(this.options.strict, {lowercase: true, xmlns: true });
this.stream.on('processinginstruction', this.onProcessingInstruction.bind(this));
this.stream.on('attribute', this.onAttribute.bind(this));
this.stream.on('opentag', this.onOpenTag.bind(this));
this.stream.on('closetag',this.onCloseTag.bind(this));
this.stream.on('text', this.onText.bind(this));
this.stream.on('cdata', this.onText.bind(this));
this.stream.on('end', this.onEnd.bind(this));
this.stream.on('error', this.onSaxError.bind(this));
} | javascript | {
"resource": ""
} |
q33624 | Console | train | function Console(game, messageHistoryCount, elClassName) {
this.el = document.createElement('div');
this.el.className = elClassName || 'console';
this.messageHistoryCount = messageHistoryCount || this.messageHistoryCount;
this.game = game;
} | javascript | {
"resource": ""
} |
q33625 | train | function(message){
if(this.el.children.length > this.messageHistoryCount - 1){
var childEl = this.el.childNodes[0];
childEl.remove();
}
var messageEl = document.createElement('div');
messageEl.innerHTML = message;
this.el.appendChild(messageEl);
} | javascript | {
"resource": ""
} | |
q33626 | Log | train | function Log (name, opts) {
if (!(this instanceof Log)) return new Log(name, opts)
Object.assign(options,
inspectOpts(process.env),
inspectNamespaces(process.env)
)
LogBase.call(this, name, Object.assign({}, options, opts))
const colorFn = (n) => chalk.hex(n)
this.color = selectColor(name, colorFn)
this.levColors = levelColors(colorFn)
if (!this.opts.json) {
this._log = this._logOneLine
}
} | javascript | {
"resource": ""
} |
q33627 | ClientSession | train | function ClientSession(request, socket, head, client) {
Session.call(this, request, socket, head);
/**
* The client instance of this session.
* @type {Client}
*/
this.client = client;
this.state = Session.STATE_OPEN;
this._init();
} | javascript | {
"resource": ""
} |
q33628 | coolors | train | function coolors(msg, config){
if(supportsColor) {
switch (typeof config) {
case 'string':
if(plugins[config]){
msg = plugins[config](msg);
}
break;
case 'object':
var decorators = Object.keys(styles.decorators);
decorators.forEach(function (decorator) {
if (config[decorator]) {
msg = styles.decorators[decorator](msg);
}
});
['text', 'background'].forEach(function (option) {
if (config[option] && styles[option][config[option]]) {
msg = styles[option][config[option]](msg);
}
});
break;
}
}
return msg;
} | javascript | {
"resource": ""
} |
q33629 | add | train | function add(locales, rule) {
var i;
rule.c = rule.c ? rule.c.map(unpack) : [ 'other' ];
rule.o = rule.o ? rule.o.map(unpack) : [ 'other' ];
for (i = 0; i < locales.length; i++) {
s[locales[i]] = rule;
}
} | javascript | {
"resource": ""
} |
q33630 | extract | train | function extract(selectorText) {
var attr = 0,
sels = [],
sel = '',
i,
c,
l = selectorText.length;
for (i = 0; i < l; i++) {
c = selectorText.charAt(i);
if (attr) {
if (c === '[' || c === '(') {
attr--;
}
sel += c;
} else if (c === ',') {
sels.push(sel);
sel = '';
} else {
if (c === '[' || c === '(') {
attr++;
}
if (sel.length || (c !== ',' && c !== '\n' && c !== ' ')) {
sel += c;
}
}
}
if (sel.length) {
sels.push(sel);
}
return sels;
} | javascript | {
"resource": ""
} |
q33631 | MultiObjectManager | train | function MultiObjectManager(game, ObjectConstructor, width, height) {
this.game = game;
this.ObjectConstructor = ObjectConstructor;
this.objects = [];
this.map = new RL.Array2d();
this.setSize(width, height);
var map = this.map;
this.map.each(function(val, x, y){
map.set(x, y, []);
});
} | javascript | {
"resource": ""
} |
q33632 | train | function(x, y, filter) {
if(filter){
var result = this.map.get(x, y);
if(result){
return result.filter(filter);
}
}
return this.map.get(x, y);
} | javascript | {
"resource": ""
} | |
q33633 | train | function(x, y, filter){
var arr = this.map.get(x, y);
if(arr){
if(filter){
for(var i = arr.length - 1; i >= 0; i--){
var item = arr[i];
if(filter(item)){
return item;
}
}
} else {
return arr[arr.length - 1];
}
}
} | javascript | {
"resource": ""
} | |
q33634 | train | function(x, y, obj) {
if(typeof obj === 'string'){
obj = this.makeNewObjectFromType(obj);
}
obj.game = this.game;
obj.x = x;
obj.y = y;
this.objects.push(obj);
var arr = this.map.get(x, y);
arr.push(obj);
if(obj.onAdd){
obj.onAdd();
}
return obj;
} | javascript | {
"resource": ""
} | |
q33635 | train | function(obj) {
var arr = this.map.get(obj.x, obj.y);
var index = arr.indexOf(obj);
arr.splice(index, 1);
index = this.objects.indexOf(obj);
this.objects.splice(index, 1);
if(obj.onRemove){
obj.onRemove();
}
} | javascript | {
"resource": ""
} | |
q33636 | train | function(x, y, filter){
var arr = this.get(x, y, filter);
for(var i = arr.length - 1; i >= 0; i--){
this.remove(arr[i]);
}
} | javascript | {
"resource": ""
} | |
q33637 | train | function(x, y, object) {
this.remove(object);
object.x = x;
object.y = y;
this.add(x, y, object);
} | javascript | {
"resource": ""
} | |
q33638 | train | function() {
this.objects = [];
this.map.reset();
var map = this.map;
this.map.each(function(val, x, y){
map.set(x, y, []);
});
} | javascript | {
"resource": ""
} | |
q33639 | train | function(width, height){
this.map.setSize(width, height);
var map = this.map;
this.map.each(function(val, x, y){
if(val === void 0){
map.set(x, y, []);
}
});
} | javascript | {
"resource": ""
} | |
q33640 | train | function(x, y, settings){
settings = settings || {};
if(settings.filter){
var filter = settings.filter;
settings.filter = function(objects){
return objects.filter(filter);
};
}
var results = this.map.getAdjacent(x, y, settings);
var out = [];
// merge all arrays
return out.concat.apply(out, results);
} | javascript | {
"resource": ""
} | |
q33641 | Player | train | function Player(game) {
this.game = game;
this.fov = new RL.FovROT(game);
// modify fov to set tiles as explored
this.fov.setMapTileVisible = function(x, y, range, visibility){
RL.FovROT.prototype.setMapTileVisible.call(this, x, y, range, visibility);
if(visibility){
var tile = this.game.map.get(x, y);
if(tile){
tile.explored = true;
}
}
};
if(this.init){
this.init(game);
}
} | javascript | {
"resource": ""
} |
q33642 | train | function(){
var x = this.x,
y = this.y,
fieldRange = this.fovFieldRange,
direction = this.fovDirection,
maxViewDistance = this.fovMaxViewDistance;
this.fov.update(x, y, fieldRange, direction, maxViewDistance, this);
} | javascript | {
"resource": ""
} | |
q33643 | train | function(action) {
// if the action is a direction
if(RL.Util.DIRECTIONS_4.indexOf(action) !== -1){
var offsetCoord = RL.Util.getOffsetCoordsFromDirection(action),
moveToX = this.x + offsetCoord.x,
moveToY = this.y + offsetCoord.y;
return this.move(moveToX, moveToY);
}
if(action === 'wait'){
this.wait();
return true;
}
return false;
} | javascript | {
"resource": ""
} | |
q33644 | train | function(x, y){
if(this.canMoveTo(x, y)){
this.moveTo(x, y);
return true;
} else {
// entity occupying target tile (if any)
var targetTileEnt = this.game.entityManager.get(x, y);
// if already occupied
if(targetTileEnt){
this.game.console.log('Excuse me <strong>Mr.' + targetTileEnt.name + '</strong>, you appear to be in the way.');
return targetTileEnt.bump(this);
} else {
// targeted tile (attempting to move into)
var targetTile = this.game.map.get(x, y);
return targetTile.bump(this);
}
}
return false;
} | javascript | {
"resource": ""
} | |
q33645 | train | function(cells, asText)
{
graph.getModel().beginUpdate();
try
{
// Applies only basic text styles
if (asText)
{
var edge = graph.getModel().isEdge(cell);
var current = (edge) ? graph.currentEdgeStyle : graph.currentVertexStyle;
var textStyles = ['fontSize', 'fontFamily', 'fontColor'];
for (var j = 0; j < textStyles.length; j++)
{
var value = current[textStyles[j]];
if (value != null)
{
graph.setCellStyles(textStyles[j], value, cells);
}
}
}
else
{
for (var i = 0; i < cells.length; i++)
{
var cell = cells[i];
// Removes styles defined in the cell style from the styles to be applied
var cellStyle = graph.getModel().getStyle(cell);
var tokens = (cellStyle != null) ? cellStyle.split(';') : [];
var appliedStyles = styles.slice();
for (var j = 0; j < tokens.length; j++)
{
var tmp = tokens[j];
var pos = tmp.indexOf('=');
if (pos >= 0)
{
var key = tmp.substring(0, pos);
var index = mxUtils.indexOf(appliedStyles, key);
if (index >= 0)
{
appliedStyles.splice(index, 1);
}
// Handles special cases where one defined style ignores other styles
for (var k = 0; k < keyGroups.length; k++)
{
var group = keyGroups[k];
if (mxUtils.indexOf(group, key) >= 0)
{
for (var l = 0; l < group.length; l++)
{
var index2 = mxUtils.indexOf(appliedStyles, group[l]);
if (index2 >= 0)
{
appliedStyles.splice(index2, 1);
}
}
}
}
}
}
// Applies the current style to the cell
var edge = graph.getModel().isEdge(cell);
var current = (edge) ? graph.currentEdgeStyle : graph.currentVertexStyle;
for (var j = 0; j < appliedStyles.length; j++)
{
var key = appliedStyles[j];
var styleValue = current[key];
if (styleValue != null && (key != 'shape' || edge))
{
// Special case: Connect styles are not applied here but in the connection handler
if (!edge || mxUtils.indexOf(connectStyles, key) < 0)
{
graph.setCellStyles(key, styleValue, [cell]);
}
}
}
}
}
}
finally
{
graph.getModel().endUpdate();
}
} | javascript | {
"resource": ""
} | |
q33646 | train | function(direction){
var coord = RL.Util.getOffsetCoordsFromDirection(direction);
return [coord.x, coord.y];
} | javascript | {
"resource": ""
} | |
q33647 | train | function(x, y, fieldRange, direction, maxViewDistance, entity){
if(fieldRange === void 0){
fieldRange = this.fieldRange;
}
if(direction === void 0){
direction = this.direction;
}
if(fieldRange !== 360 && typeof direction === 'string'){
direction = this.directionStringToArray(direction);
}
this.direction = direction;
if(maxViewDistance === void 0){
maxViewDistance = this.maxViewDistance;
}
this.validateFieldRange(fieldRange);
this.visibleTiles = [];
this.visibleTileKeys = [];
this.fovMap.reset();
var entityCanSeeThrough = this.getEntityCanSeeThroughCallback(entity);
var fov = new ROT.FOV.RecursiveShadowcasting(entityCanSeeThrough);
var setMapTileVisible = this.setMapTileVisible.bind(this);
if(fieldRange === 360){
fov.compute(x, y, maxViewDistance, setMapTileVisible);
}
else {
if(fieldRange === 180){
fov.compute180(x, y, maxViewDistance, direction, setMapTileVisible);
}
else if(fieldRange === 90){
fov.compute90(x, y, maxViewDistance, direction, setMapTileVisible);
}
}
} | javascript | {
"resource": ""
} | |
q33648 | train | function(x, y, range, visibility){
this.fovMap.set(x, y, visibility);
if(visibility){
var tile = this.game.map.get(x, y);
if(tile){
var key = x + ',' + y;
// check for duplicates
if(this.visibleTileKeys.indexOf(key) === -1){
this.visibleTiles.push({
x: x,
y: y,
value: tile,
range: range
});
this.visibleTileKeys.push(key);
}
}
}
} | javascript | {
"resource": ""
} | |
q33649 | train | function(files, metalsmith, done){
var yuiDocsData = require('../docs/data.json');
var makeUrl = function(docClass, method){
var out = '/docs/classes/' + docClass + '.html';
if(method){
out += '#method_' + method;
}
return out;
};
for(var key in files){
var file = files[key];
if(file.docs_class){
file.yui_class_data = yuiDocsData.classes[file.docs_class];
if(file.docs_method){
file.yui_method_url = makeUrl(file.docs_class) + '#method_' + file.docs_class;
}
}
var relatedDocs = file.related_methods;
var relatedDocsFormatted = [];
if(relatedDocs){
relatedDocs.forEach(function(doc){
if(doc.indexOf('.') !== -1){
var arr = doc.split('.');
relatedDocsFormatted.push({
name: arr[0] + '.prototype.' + arr[1] + '()',
class: arr[0],
method: arr[1],
url: makeUrl(arr[0], arr[1])
});
} else {
relatedDocsFormatted.push({
name: doc + '()',
class: doc,
url: makeUrl(doc)
});
}
});
file.related_docs = relatedDocsFormatted;
}
}
done();
} | javascript | {
"resource": ""
} | |
q33650 | train | function (file) {
var folder = path.dirname(file) + '/' + path.basename( file, '.json' );
return fs.existsSync(folder) && isDir(folder) ? folder : false;
} | javascript | {
"resource": ""
} | |
q33651 | train | function (parent) {
var elems = fs.readdirSync( parent ),
d = {
files : [],
folders : []
};
// get files and folders paths
elems.forEach( function (elem) {
var el = parent + '/' + elem;
if (!isDir( el )) {
d.files.push( el );
} else if (!fs.existsSync( el + '.json')) {
// add folder only if has no namesake json
d.folders.push( el );
}
});
return d;
} | javascript | {
"resource": ""
} | |
q33652 | train | function (file) {
var config = require( file ),
namesake = getNamesake( file );
return namesake ? extend( config, getData.folder( namesake )) : config;
} | javascript | {
"resource": ""
} | |
q33653 | train | function (folder) {
var elems = getFolderElements( folder ),
result = {};
// files
elems.files.forEach( function (route) {
// get object name
var fileName = path.basename( route, '.json' );
// assign object data from file
result[ fileName ] = getData.file( route );
});
// no namesake folders
elems.folders.forEach( function (route) {
// get object name
var fileName = path.basename( route );
// assign data from folder
result[ fileName ] = extend( result[ fileName ] || {}, getData.folder( route ));
});
return result;
} | javascript | {
"resource": ""
} | |
q33654 | Log | train | function Log (name, opts) {
if (!(this instanceof Log)) return new Log(name, opts)
const _storage = storage()
Object.assign(options,
inspectOpts(_storage),
inspectNamespaces(_storage)
)
options.colors = options.colors === false ? false : supportsColors()
LogBase.call(this, name, Object.assign({}, options, opts))
const colorFn = (c) => `color:${c}`
this.color = selectColor(name, colorFn)
this.levColors = levelColors(colorFn)
this.queue = new Queue(this._sendLog.bind(this), 3)
} | javascript | {
"resource": ""
} |
q33655 | ObjectManager | train | function ObjectManager(game, ObjectConstructor, width, height) {
this.game = game;
this.ObjectConstructor = ObjectConstructor;
this.objects = [];
this.map = new RL.Array2d(width, height);
} | javascript | {
"resource": ""
} |
q33656 | train | function(x, y, obj) {
if(typeof obj === 'string'){
obj = this.makeNewObjectFromType(obj);
}
var existing = this.get(x, y);
if(existing){
this.remove(existing);
}
obj.game = this.game;
obj.x = x;
obj.y = y;
this.objects.push(obj);
this.map.set(x, y, obj);
if(obj.onAdd){
obj.onAdd();
}
return obj;
} | javascript | {
"resource": ""
} | |
q33657 | train | function(object) {
this.map.remove(object.x, object.y);
var index = this.objects.indexOf(object);
this.objects.splice(index, 1);
if(object.onRemove){
object.onRemove();
}
} | javascript | {
"resource": ""
} | |
q33658 | train | function(x, y, object) {
var existing = this.get(object.x, object.y);
if(existing !== object){
throw new Error({error: 'Attempting to move object not in correct position in Object manager', x: x, y: y, object: object});
}
if(this.objects.indexOf(object) === -1){
throw new Error({error: 'Attempting to move object not in Object manager', x: x, y: y, object: object});
}
this.map.remove(object.x, object.y);
this.map.set(x, y, object);
object.x = x;
object.y = y;
} | javascript | {
"resource": ""
} | |
q33659 | toSingleRule | train | function toSingleRule(str) {
return str
// replace modulus with shortcuts
.replace(/([nivwft]) % (\d+)/g, '$1$2')
// replace ranges
.replace(/([nivwft]\d*) (=|\!=) (\d+[.,][.,\d]+)/g, function (match, v, cond, range) {
// range = 5,8,9 (simple set)
if (range.indexOf('..') < 0 && range.indexOf(',') >= 0) {
if (cond === '=') {
return format('IN([ %s ], %s)', range.split(',').join(', '), v);
}
return format('!IN([ %s ], %s)', range.split(',').join(', '), v);
}
// range = 0..5 or 0..5,8..20 or 0..5,8
var conditions = range.split(',').map(function (interval) {
// simple value
if (interval.indexOf('..') < 0) {
return format('%s %s %s', v, cond, interval);
}
// range
var start = interval.split('..')[0],
end = interval.split('..')[1];
if (cond === '=') {
return format('B(%s, %s, %s)', start, end, v);
}
return format('!B(%s, %s, %s)', start, end, v);
});
var joined;
if (conditions.length > 1) {
joined = '(' + conditions.join(cond === '=' ? ' || ' : ' && ') + ')';
} else {
joined = conditions[0];
}
return joined;
})
.replace(/ = /g, ' === ')
.replace(/ != /g, ' !== ')
.replace(/ or /g, ' || ')
.replace(/ and /g, ' && ');
} | javascript | {
"resource": ""
} |
q33660 | train | function(game, settings){
this.game = game;
settings = settings || {};
this.x = settings.x || this.x;
this.y = settings.y || this.y;
this.limitToFov = settings.limitToFov || this.limitToFov;
this.limitToNonDiagonalAdjacent = settings.limitToNonDiagonalAdjacent || this.limitToNonDiagonalAdjacent;
this.range = settings.range || this.range;
this.validTypes = settings.validTypes || [];
this.includeTiles = settings.includeTiles || this.includeTiles;
this.includeSelf = settings.includeSelf || this.includeSelf;
this.prepareValidTargets = settings.prepareValidTargets || this.prepareValidTargets;
this.filter = settings.filter || this.filter;
} | javascript | {
"resource": ""
} | |
q33661 | train | function(){
var tiles = this.getValidTargetTiles();
var result = [];
for (var i = 0; i < tiles.length; i++) {
var tile = tiles[i];
var targets = this.getValidTargetsAtPosition(tile.x, tile.y);
result = result.concat(targets);
if(this.includeTiles){
result.push(tile);
}
}
return result;
} | javascript | {
"resource": ""
} | |
q33662 | train | function(){
var tiles = [];
if(this.limitToFov){
var fovTiles = this.limitToFov.visibleTiles;
for (var i = 0; i < fovTiles.length; i++) {
var fovTile = fovTiles[i];
// if no max range, if there is a max range check it
if(!this.range || fovTile.range <= this.range){
// if including tile objects in result but not preparing them
if(this.includeTiles && !this.prepareValidTargets){
fovTile = fovTile.value;
}
tiles.push(fovTile);
}
}
} else {
var x = this.x,
y = this.y;
if(this.range === 1){
if(this.limitToNonDiagonalAdjacent){
tiles = this.game.map.getAdjacent(x, y, {withDiagonals: false});
}
else{
tiles = this.game.map.getAdjacent(x, y);
}
} else {
tiles = this.game.map.getWithinSquareRadius(x, y, {radius: this.range});
}
// if including tile objects, prepare them
if(this.includeTiles && this.prepareValidTargets){
var _this = this;
tiles = tiles.map(function(tile){
return _this.prepareTargetObject(tile);
});
}
}
return tiles;
} | javascript | {
"resource": ""
} | |
q33663 | train | function(x, y){
var objects = this.game.getObjectsAtPostion(x, y);
var range = RL.Util.getDistance(this.x, this.y, x, y);
var _this = this;
var filtered = objects.filter(function(target){
return _this.checkValidTarget(target);
});
return filtered.map(function(target){
return _this.prepareTargetObject(target, x, y, range);
});
} | javascript | {
"resource": ""
} | |
q33664 | train | function(target, x, y, range){
x = x || target.x;
y = y || target.y;
range = range || RL.Util.getDistance(this.x, this.y, x, y);
return {
x: x,
y: y,
range: range,
value: target
};
} | javascript | {
"resource": ""
} | |
q33665 | train | function(target){
// skip valid type check if value evaluating to false or empty array.
if(!this.validTypes || !this.validTypes.length){
return true;
}
for(var i = this.validTypes.length - 1; i >= 0; i--){
var type = this.validTypes[i];
if(target instanceof type){
return true;
}
}
// no valid type match found
return false;
} | javascript | {
"resource": ""
} | |
q33666 | train | function(target){
if(this.exclude){
if(target === this.exclude){
return false;
}
// if exclude is array and target is in it
if(Object.isArray(this.exclude) && this.exclude.indexOf(target) !== -1){
return false;
}
}
if(!this.checkValidType(target)){
return false;
}
if(this.filter && !this.filter(target)){
return false;
}
return true;
} | javascript | {
"resource": ""
} | |
q33667 | re | train | function re (opts) {
opts = opts || {}
return new RegExp(
format('\\b(?:%s)\\b', regexp.versioned.source + (opts.nil ? '|' + regexp.nil.source : '')),
'i' + (opts.flags || '')
)
} | javascript | {
"resource": ""
} |
q33668 | objectGet | train | function objectGet (object, expression) {
if (!(object && expression)) throw new Error('both object and expression args are required')
return expression.trim().split('.').reduce(function (prev, curr) {
var arr = curr.match(/(.*?)\[(.*?)\]/)
if (arr) {
return prev && prev[arr[1]][arr[2]]
} else {
return prev && prev[curr]
}
}, object)
} | javascript | {
"resource": ""
} |
q33669 | Input | train | function Input(onKeyAction, bindings) {
this.bindings = {};
if (onKeyAction !== void 0) {
this.onKeyAction = onKeyAction;
}
if (bindings !== void 0) {
this.addBindings(bindings);
}
this.startListening();
} | javascript | {
"resource": ""
} |
q33670 | train | function(bindings) {
for (var action in bindings) {
var keys = bindings[action];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
this.bindAction(action, key);
}
}
} | javascript | {
"resource": ""
} | |
q33671 | pump | train | function pump(reader, handler) {
reader.read().then(result => {
if (result.done) {
return;
}
if (handler(result.value) === false) {
// cancelling
return;
}
pump(reader, handler);
});
} | javascript | {
"resource": ""
} |
q33672 | _hook | train | function _hook(slf, name, handlerInfo, params) {
if (!slf.__hooks[name]) return;
slf.__hooks[name].forEach(function (hook) {
hook(handlerInfo, params);
});
} | javascript | {
"resource": ""
} |
q33673 | wrap_cb | train | function wrap_cb(fn, P) {
return function (params) {
return new P(function (resolve, reject) {
fn(params, function (err) { return !err ? resolve() : reject(err); });
});
};
} | javascript | {
"resource": ""
} |
q33674 | finalizeHandler | train | function finalizeHandler(p, hInfo) {
if (!p) return;
return p
.catch(storeErrOnce)
.then(function () {
if (errored && !hInfo.ensure) return null;
_hook(self, 'eachAfter', hInfo, params);
})
.catch(storeErrOnce);
} | javascript | {
"resource": ""
} |
q33675 | fetchStream | train | function fetchStream() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var callback = arguments[1];
var cb = callback;
var stream = null;
if (cb === undefined) {
stream = makeStream();
cb = stream.handler;
}
var url = typeof options === 'string' ? options : options.url || options.path;
if (supportFetch) {
// TODO support Request object?
var init = (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? options : {};
fetch(url, init).then(function (res) {
if (res.status >= 200 && res.status < 300) {
pump(res.body.getReader(), (0, _parser2.default)(cb));
} else {
// TODO read custom error payload
cb(null, { status: res.status, statusText: res.statusText });
}
}, function (err) {
cb(null, err);
});
} else {
(function () {
var parser = (0, _parser2.default)(cb, _parser.BUFFER);
var opts = (typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object' ? _extends({}, options) : {};
opts.path = url;
var req = _streamHttp2.default.get(opts, function (res) {
var status = res.status || res.statusCode;
if (!(status >= 200 && status < 300)) {
// TODO read custom error payload
cb(null, { status: status, statusText: res.statusText || res.statusMessage });
return;
}
res.on('data', function (buf) {
if (parser(buf) === false) {
// cancelling
req.abort();
}
});
res.on('error', function (err) {
req.abort();
cb(null, err);
});
});
})();
}
return stream;
} | javascript | {
"resource": ""
} |
q33676 | callApi | train | function callApi(method, parameters, callback) {
if (typeof parameters === 'undefined') {
throw new Error('undefined is not a valid parameters object.');
}
if( typeof parameters !== 'object' ){
throw new Error('valid parameters object required.');
}
var opts = this.options;
var noCallback = !callback || typeof callback !== 'function';
let noApiKey = typeof opts.API_KEY !== 'string' || opts.API_KEY.length === 0 || typeof opts.API_SECRET !== 'string' || opts.API_SECRET.length === 0;
if( noApiKey ){
if( noCallback ){
throw new Error('API key and API secret required.');
}
return callback(new Error("API key and API secret required."));
}
opts.method = method;
//
// final API url with hashes
//
let url = makeApiUrl(opts, parameters);
let reqOptions = {
uri: url,
json: true,
timeout: process.env.CF_TIMEOUT || opts.DEFAULT_TIMEOUT
};
//
// callback not exists, just return the request modules Request class instance for event
//
if( noCallback ){
return new Request(reqOptions);
}
//
// callback exists, return Request for streaming and handle callback for error handling and custom formatted data
//
return callRequest(reqOptions, handleCallback.bind(null,callback) );
} | javascript | {
"resource": ""
} |
q33677 | handleCallback | train | function handleCallback(callback, err, httpResponse, body) {
if(err){
return callback(err);
}
//
// API returns error
//
if( body.status !== 'OK' ){
return callback(new Error(body.comment));
}
return callback(null, body.result);
} | javascript | {
"resource": ""
} |
q33678 | makeApiUrl | train | function makeApiUrl(options,parameters) {
var query = parameters;
//
// If any parameter given in array, make it string separated by semicolon(;)
//
for(let key in query){
if( _.isArray(query[key]) ){
query[key] = _.join(query[key],';');
}
}
let curTime = Math.floor(Date.now() / 1000);
let randomToken = randomstring.generate(6);
query.time = curTime;
query.apiKey = options.API_KEY;
//
// Sort parameters according to codeforces API rules
//
query = _
.chain(query)
.map( (value, key) => {
return { key, value };
})
.orderBy(['key', 'value'], ['desc', 'desc'])
.reverse()
.keyBy('key')
.mapValues('value')
.value();
let qsFy = qs.stringify(query,{ encode: false });
let apiSig = `${randomToken}/${options.method}?${qsFy}#${options.API_SECRET}`;
apiSig = sha512(apiSig).toString();
query.apiSig = randomToken + apiSig;
qsFy = qs.stringify(query,{ encode: false });
let url = `${options.API_URL}/${options.method}?${qsFy}`;
return url;
} | javascript | {
"resource": ""
} |
q33679 | ServerSession | train | function ServerSession(request, socket, head, server) {
Session.call(this, request, socket, head);
this._resHeaders = {};
this._headerSent = false;
/**
* The server instance of this session.
* @type {Server}
*/
this.server = server;
/**
* The HTTP status code of handshake.
* @type {Number}
* @default 200
*/
this.statusCode = 200;
/**
* The HTTP status message of handshake.
* @type {String}
*/
this.statusMessage = '';
} | javascript | {
"resource": ""
} |
q33680 | train | function (job) {
if (job) {
if (arguments.length > 1) {
this.jobs = this.jobs.concat(Array.prototype.slice.call(arguments));
} else {
this.jobs.push(job);
}
}
return this;
} | javascript | {
"resource": ""
} | |
q33681 | train | function (err) {
if (this.jobs.length) {
var job = this.jobs.shift();
try {
job(err, this);
} catch (e) {
this.next(e);
}
} else {
this.running = false;
}
} | javascript | {
"resource": ""
} | |
q33682 | index_date | train | function index_date(timestamp, interval) {
function double_digitize(str) {
return (str.length === 1) ? ('0' + str) : str;
}
var year = timestamp.getUTCFullYear();
var month = (timestamp.getUTCMonth() + 1).toString();
switch (interval) {
case 'day':
var day = timestamp.getUTCDate().toString();
return [year, double_digitize(month), double_digitize(day)].join('.');
case 'week':
var week = current_week_number(timestamp);
return [year, double_digitize(week)].join('.');
case 'month':
return [year, double_digitize(month)].join('.');
case 'year':
return year;
case 'none':
return '';
default:
throw new Error('invalid interval: ' + interval + '; accepted intervals are "day", "week", "month", "year", and "none"');
}
} | javascript | {
"resource": ""
} |
q33683 | deleteHelper | train | function deleteHelper (data, node, nodeType, parentNode) {
if (node === null) {
return false;
}
// @TODO handle object comparisons -- doing a stringify is horrible dont do that
if (data === node.data) {
if (nodeType === Types.RIGHT) {
parentNode.right = null;
} else {
parentNode.left = null;
}
// Fix tree
if (node.left) {
var nodeRightSubtree = node.right;
parentNode[nodeType] = node.left;
parentNode[nodeType].right = nodeRightSubtree;
} else if (node.right) {
var nodeLeftSubtree = node.left;
parentNode[nodeType] = node.right;
parentNode[nodeType].left = nodeLeftSubtree;
}
return true;
}
if (safeCompare(data, node.data, this.compare)) {
return deleteHelper(data, node.left, Types.LEFT, node);
} else {
return deleteHelper(data, node.right, Types.RIGHT, node);
}
} | javascript | {
"resource": ""
} |
q33684 | train | function(direction){
var directionCoords = {
up: {x: 0, y:-1},
right: {x: 1, y: 0},
down: {x: 0, y: 1},
left: {x:-1, y: 0}
};
return directionCoords[direction];
} | javascript | {
"resource": ""
} | |
q33685 | train | function(currentDirection){
var directions = ['up', 'right', 'down', 'left'],
currentDirIndex = directions.indexOf(currentDirection),
newDirIndex;
// if currentDirection is not valid or is the last in the array use the first direction in the array
if(currentDirIndex === -1 || currentDirIndex === directions.length - 1){
newDirIndex = 0;
} else {
newDirIndex = currentDirIndex + 1;
}
return directions[newDirIndex];
} | javascript | {
"resource": ""
} | |
q33686 | train | function(x, y) {
// remove light from current position
if(this.game.lighting.get(this.x, this.y)){
this.game.lighting.remove(this.x, this.y);
}
// add to new position
this.game.lighting.set(x, y, this.light_r, this.light_g, this.light_b);
RL.Entity.prototype.moveTo.call(this, x, y);
} | javascript | {
"resource": ""
} | |
q33687 | extend | train | function extend() {
var src, copy, name, options, clone;
var target = arguments[0] || {};
var i = 1;
var length = arguments.length;
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( copy && typeof copy === "object" ) {
clone = src && typeof src === "object" ? src : {};
// Never move original objects, clone them
target[ name ] = extend( clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
} | javascript | {
"resource": ""
} |
q33688 | _explodeRules | train | function _explodeRules(rules) {
for (var i in rules) {
if (is_string(rules[i])) {
rules[i] = rules[i].split('|');
}
}
return rules;
} | javascript | {
"resource": ""
} |
q33689 | _parseRule | train | function _parseRule(rule) {
var parameters = [];
// The format for specifying validation rules and parameters follows an
// easy {rule}:{parameters} formatting convention. For instance the
// rule "Max:3" states that the value may only be three letters.
if (rule.indexOf(':')) {
var ruleInfo = rule.split(':');
parameters = _parseParameters(ruleInfo[0], ruleInfo[1]);
}
return { parameters: parameters, rule: ruleInfo[0]};
} | javascript | {
"resource": ""
} |
q33690 | _parseParameters | train | function _parseParameters(rule, parameter) {
if (rule.toLowerCase() == 'regex') return [parameter];
if (is_string(parameter)) {
return parameter.split(',');
};
return [];
} | javascript | {
"resource": ""
} |
q33691 | _addFailure | train | function _addFailure(attribute, rule, parameters) {
_addError(attribute, rule, parameters);
if (! _failedRules[attribute]) {
_failedRules[attribute] = {};
}
_failedRules[attribute][rule] = parameters;
} | javascript | {
"resource": ""
} |
q33692 | _addError | train | function _addError(attribute, rule, parameters) {
if (_errors[attribute]) {
return;
};
_errors[attribute] = _formatMessage(_getMessage(attribute, rule) || '', attribute, rule, parameters);
} | javascript | {
"resource": ""
} |
q33693 | _getMessage | train | function _getMessage(attribute, rule) {
var message = _messages[rule];
if (is_object(message)) {
var value = _getValue(attribute);
if (is_array(value) && message['array']) {
return message['array'];
} else if (_resolvers.numeric(value) && message['numeric']) {
return message['numeric'];
} else if (is_string(value) && message['string']){
return message['string'];
}
};
return message;
} | javascript | {
"resource": ""
} |
q33694 | _formatMessage | train | function _formatMessage(message, attribute, rule, parameters) {
parameters.unshift(_getAttribute(attribute));
for(i in parameters){
message = message.replace(/:[a-zA-z_][a-zA-z_0-9]+/, parameters[i]);
}
if (typeof _replacers[rule] === 'function') {
message = _replacers[rule](message, attribute, rule, parameters);
}
return message;
} | javascript | {
"resource": ""
} |
q33695 | _getAttribute | train | function _getAttribute(attribute) {
if (is_string(_attributes[attribute])) {
return _attributes[attribute];
}
if ((line = _translator.trans(attribute)) !== attribute) {
return line;
} else {
return attribute.replace('_', ' ');
}
} | javascript | {
"resource": ""
} |
q33696 | _getRule | train | function _getRule(attribute, rules) {
rules = rules || [];
if ( ! rules[attribute]) {
return;
}
for(var i in rules[attribute]) {
var value = rules[attribute][i];
parsedRule = _parseRule(rule);
if (in_array(parsedRule.rule, rules))
return [parsedRule.rule, parsedRule.parameters];
}
} | javascript | {
"resource": ""
} |
q33697 | _getSize | train | function _getSize(attribute, value) {
hasNumeric = _hasRule(attribute, _numericRules);
// This method will determine if the attribute is a number, string, or file and
// return the proper size accordingly. If it is a number, then number itself
// is the size. If it is a file, we take kilobytes, and for a string the
// entire length of the string will be considered the attribute size.
if (/^[0-9]+$/.test(value) && hasNumeric) {
return getValue(attribute);
} else if (value && is_string(value) || is_array(value)) {
return value.length;
}
return 0;
} | javascript | {
"resource": ""
} |
q33698 | _requireParameterCount | train | function _requireParameterCount(count, parameters, rule) {
if (parameters.length < count) {
throw Error('Validation rule"' + rule + '" requires at least ' + count + ' parameters.');
}
} | javascript | {
"resource": ""
} |
q33699 | _allFailingRequired | train | function _allFailingRequired(attributes) {
for (var i in attributes) {
var akey = attributes[i];
if (resolvers.validateRequired(key, self._getValue(key))) {
return false;
}
}
return true;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.