_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q29600 | train | function(options, callback) {
if(typeof options === 'function') {
callback = options;
options = {};
}
if(options.items) {
options.users = options.users || [];
for(var i = 0; i < options.items.length ; i++){
options.users.push(options.items[i]._key);
}
delete options.items;
}
if(options.title) {
options.label = options.title;
delete options.title;
}
if (!self.context.player || !options.users || options.users.length === 0 ) {
callback.apply(self);
} else {
UT.Expression._callAPI('dialog.users', [options], function(){
callback.apply(self);
});
}
} | javascript | {
"resource": ""
} | |
q29601 | F1 | train | function F1 (config) {
var valErrors = jjv.validate(configSchema, config)
if (valErrors && valErrors.validation) {
throw new Error('Validation errors: ' +
JSON.stringify(valErrors.validation, null, 3))
}
this.config = config
} | javascript | {
"resource": ""
} |
q29602 | train | function (optionCollection, key, model, collection) {
if (optionCollection) {
return strTo(optionCollection, model, Collection) || collection;
}
return strTo(key, model, Collection) || null;
} | javascript | {
"resource": ""
} | |
q29603 | train | function (alias, construct) {
var aliases = {};
var currAliases = Backbone.FormView.prototype.fieldAlias;
if (construct) {
aliases[alias] = construct;
} else { aliases = alias; }
defaults(currAliases, aliases);
} | javascript | {
"resource": ""
} | |
q29604 | train | function (schema) {
if (!this.rowConfig.options) { this.rowConfig.options = {}; }
this.rowConfig.options.schema = schema || this.options.rowSchema || this.rowSchema;
return this;
} | javascript | {
"resource": ""
} | |
q29605 | train | function () {
this.subs.detachElems();
this.$el.html(this.template(this._getTemplateVars()));
if (!this.getRows() || !this.getRows().length) {
this.setupRows();
}
this.subs.renderByKey('row', { appendTo: this.getRowWrapper() });
return this;
} | javascript | {
"resource": ""
} | |
q29606 | train | function (obj) {
var model = (obj instanceof Model) ? obj : null;
var view = (!model && obj instanceof Backbone.View) ? obj : null;
var arr = (!model && !view && isArray(obj)) ? obj : null;
if (arr) {
each(arr, this.deleteRow, this);
return this;
}
if (!view) {
view = this.subs.get(model);
} else if (!model) {
model = view.model;
}
this.subs.remove(view);
this.collection.remove(model);
return this;
} | javascript | {
"resource": ""
} | |
q29607 | train | function () {
var $input;
var id = this.inputId;
var attrs = this.addId ? { id : id, name: id } : {};
var valForInput = this.getValueForInput();
$input = Backbone.$('<' + this.elementType + '>');
if (this.elementType === 'input') { attrs.type = 'text'; }
if (this.placeholder) { attrs.placeholder = this.placeholder; }
$input.attr(extend(attrs, this.inputAttrs));
if (this.inputClass) { $input.attr('class', this.inputClass); }
this.getInputWrapper().html($input);
if (this._shouldSetValueOnInput(valForInput)) { $input.val(valForInput); }
this.isDisabled = null;
return this;
} | javascript | {
"resource": ""
} | |
q29608 | train | function () {
var possibleVals = result(this, 'possibleVals');
var key;
var i = 0;
var possibleVal;
var $checkbox;
var isSelected;
var $inputWrapper = this.getInputWrapper().empty();
for (key in possibleVals) {
if (possibleVals.hasOwnProperty(key)) {
possibleVal = this._parsePossibleVal(possibleVals, key);
isSelected = this.isSelected(possibleVal.value);
$checkbox = this._renderInput(possibleVal, isSelected, i);
$inputWrapper.append($checkbox);
i++;
}
}
return this;
} | javascript | {
"resource": ""
} | |
q29609 | train | function (key) {
var modelVal = this.getModelVal();
modelVal = this.multiple ? modelVal : [modelVal];
return (_.indexOf(_.map(modelVal, toStr), toStr(key)) > -1);
} | javascript | {
"resource": ""
} | |
q29610 | train | function () {
var possibleVals = result(this, 'possibleVals');
var id = this.inputId;
var $select = Backbone.$('<' + this.elementType + '>')
.attr(extend((this.addId ? { id: id, name: id } : {}), this.inputAttrs));
this.getInputWrapper().html($select);
if (this.multiple) { $select.attr('multiple', 'multiple'); }
if (this.inputClass) { $select.addClass(this.inputClass); }
if (this.placeholder) {
$select.append('<option value="">' + this.placeholder + '</option>');
}
return this._renderInput($select, possibleVals);
} | javascript | {
"resource": ""
} | |
q29611 | train | function (possibleVal, isChecked, index) {
var $listItem;
var $label;
var id = this.inputId;
var attributes = { type: 'checkbox', value: possibleVal.value};
if (this.addId) { extend(attributes, { name: id, id: (id + '-' + index) }); }
attributes = extend(attributes, this.inputAttrs);
if (this.inputClass) { attributes.class = this.inputClass; }
if (isChecked) { attributes.checked = 'checked'; }
$listItem = Backbone.$('<input>').attr(attributes);
$label = Backbone.$('<label>').attr(defaults(this.labelAttrs || {}, { 'class': 'checkbox' }));
return $label.append($listItem).append(possibleVal.display);
} | javascript | {
"resource": ""
} | |
q29612 | RedisClient | train | function RedisClient(opts) {
opts = opts || {};
BaseClient.apply(this, arguments);
this.recordsToKeep = opts.recordsToKeep || 1000;
this.namespace = opts.namespace || 'stats';
this.client = opts.redisClient;
} | javascript | {
"resource": ""
} |
q29613 | train | function(_options){
// bugfix for ie title with flash
_title = document.title;
var _parent = _e._$get(_options.parent)||document.body,
_html = _t0._$get(_seed_html,_options);
_parent.insertAdjacentHTML(
!_options.hidden?'beforeEnd':'afterBegin',_html
);
} | javascript | {
"resource": ""
} | |
q29614 | train | function(_id,_event){
var _type = _event.type.toLowerCase();
_t1.requestAnimationFrame(function(){
_v._$dispatchEvent(_id,_type);
});
} | javascript | {
"resource": ""
} | |
q29615 | train | function(_options){
// init flash vars
var _id = _options.id,
_params = _options.params;
if (!_params){
_params = {};
_options.params = _params;
}
var _vars = _params.flashvars||'';
_vars += (!_vars?'':'&')+('id='+_id);
// delegate mouse event bubble
if (!_options.hidden&&(!!_options.target||
_h.__canFlashEventBubble(_params.wmode))){
var _tid = _e._$id(_options.target)||
_e._$id(_options.parent);
_cache[_id+'-tgt'] = _tid;
}
_params.flashvars = _vars;
// check event callback
_u._$loop(_options,function(_value,_key){
if (_u._$isFunction(_value)&&_key!='onready'){
_cache[_id+'-'+_key] = _value;
}
});
} | javascript | {
"resource": ""
} | |
q29616 | EntityProvider | train | function EntityProvider(storage, location) {
EntityProvider.super_.call(this, storage);
Object.defineProperties(this, {
/**
* The location of the entities in the storage.
*
* @property location
* @type String
* @final
*/
location: {value: location}
});
if (Object.prototype.toString.call(this.location) !== '[object String]')
throw new TypeError('location must be a string');
} | javascript | {
"resource": ""
} |
q29617 | getEntities | train | function getEntities(callback) {
self.get(filter, fields, null, page, sort, function(error, entities, pagination) {
if (error) return callback(error);
allEntities = allEntities.concat(entities);
if (page < pagination.pages - 1) {
// There are other pages
// Get next page
page++;
getEntities(callback);
} else {
// No more pages
// End it
callback(null);
}
});
} | javascript | {
"resource": ""
} |
q29618 | registerHelper | train | function registerHelper(name, helper) {
var s = this;
s.helpers = s.helpers || {};
s.helpers[name] = helper;
return s;
} | javascript | {
"resource": ""
} |
q29619 | registerHelpers | train | function registerHelpers(helpers) {
var s = this;
var names = Object.keys(helpers || {});
for (var i = 0, len = names.length; i < len; i++) {
var name = names[i];
s.registerHelper(name, helpers[name]);
}
return s;
} | javascript | {
"resource": ""
} |
q29620 | SocketNamespace | train | function SocketNamespace() {
var self = this;
var namespace = null;
Object.defineProperties(this, {
/**
* The list of messages' handlers.
*
* @property handlers
* @type Object
*/
handlers: {value: {}},
/**
* The list of middlewares.
*
* @property middlewares
* @type Array
*/
middlewares: {value: []},
/**
* The socket namespace.
*
* @property namespace
* @type Namespace
*/
namespace: {
get: function() {
return namespace;
},
set: function(newNamespace) {
namespace = newNamespace;
mountHandlers.call(self);
mountMiddlewares.call(self);
}
}
});
} | javascript | {
"resource": ""
} |
q29621 | train | function (params) {
var element = document.createElement('script'),
headElement = document.getElementsByTagName('head')[0],
load = params.load,
error = params.error,
jsonpCallback = params.jsonpCallback,
timeout = params.timeout || 10000,
timeoutId,
handleError = function (err) {
window.clearTimeout(timeoutId);
delete window[jsonpCallback];
headElement.removeChild(element);
if (error) {
error("500", {message: err});
}
};
window[jsonpCallback] = function (data) {
window.clearTimeout(timeoutId);
// TODO: add response validation here
load("200", data);
delete window[jsonpCallback];
headElement.removeChild(element);
};
// Error handlers fall back to timeout.
element.onerror = handleError;
element.onreadystatechange = function () {
var readyState = element.readyState;
if (readyState !== 'loaded') {
handleError({type: 'error'});
}
};
timeoutId = window.setTimeout(handleError, timeout, 'timeout');
element.type = 'text/javascript';
element.src = this.updateQueryString(params.jsonpUrl, params.callbackName, jsonpCallback);
element.id = jsonpCallback;
element.async = true;
element.charset = 'utf-8';
headElement.appendChild(element);
} | javascript | {
"resource": ""
} | |
q29622 | train | function (url, key, value) {
var regex = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi"),
separator,
hash;
if (regex.test(url)) {
url = url.replace(regex, '$1' + key + "=" + value + '$2$3');
} else {
separator = url.indexOf('?') !== -1 ? '&' : '?';
hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
}
return url;
} | javascript | {
"resource": ""
} | |
q29623 | norender | train | function norender(app, ext, file, locals) {
return !app.engines.hasOwnProperty(ext)
|| app.isTrue('norender') || app.isFalse('render')
|| file.norender === true || file.render === false
|| locals.norender === true || locals.render === false;
} | javascript | {
"resource": ""
} |
q29624 | validateProperty | train | function validateProperty(property, validator) {
let isValid;
if (!validator) {
return void 0;
}
if (!property) {
return void 0;
}
const {value} = property;
const {options} = validator;
const isValueNullOrUndefined = isNull(value) || isUndefined(value );
isValid = (() => {
switch (validator.type) {
case 'required':
const prevalidString = '' === property.value ? false : true;
const prevalidDate = true;
return true === validator.value ? (!isNull(value) && !isUndefined(value) && prevalidString && prevalidDate) : true;
case 'regex':
if (isValueNullOrUndefined) {
return true;
}
return validator.value.test(value);
case 'email':
if (isValueNullOrUndefined) {
return true;
}
return emailValidation(value, options);
case 'number':
return numberValidation(value, options);
case 'string':
const stringToValidate = value || '';
return stringLength(stringToValidate, options);
case 'date':
return dateValidation(value, options);
case 'function':
return validator.value(value, options);
case 'checkbox':
return (isUndefined(value) || isNull(value)) ? false : true;
default:
return void 0;
}
})();
if (isUndefined(isValid) || isNull(isValid)) {
console.warn(`The validator of type: ${validator.type} is not defined`);
} else if (false === isValid) {
//Add the name of the property.
return getErrorLabel(validator.type, property.modelName + '.' + property.name, options); //"The property " + property.name + " is invalid.";
}
} | javascript | {
"resource": ""
} |
q29625 | train | function (evt,stopBubble) {
'use strict';
//console.log('fidjBlockMove');
// All but scrollable element = .c4p-container-scroll-y
//if (evt.preventDefault) evt.preventDefault() ;
//if (evt.preventDefault && !$(evt.target).parents('.c4p-container-scroll-y')[0]) {
// evt.preventDefault();
//}
if (evt.preventDefault && !$('.c4p-container-scroll-y').has($(evt.target)).length) {
evt.preventDefault();
}
if (stopBubble && evt.stopPropagation) evt.stopPropagation();
if (stopBubble && !evt.cancelBubble) evt.cancelBubble = true;
} | javascript | {
"resource": ""
} | |
q29626 | fidjDateParse | train | function fidjDateParse(date) {
if (!date || typeof date != 'string' || date == '') return false;
// Date (choose 0 in date to force an error if parseInt fails)
var yearS = parseInt(date.substr(0,4), 10) || 0;
var monthS = parseInt(date.substr(5,2), 10) || 0;
var dayS = parseInt(date.substr(8,2), 10) || 0;
var hourS = parseInt(date.substr(11,2), 10) || 0;
var minuteS = parseInt(date.substr(14,2),10) || 0;
var secS = parseInt(date.substr(17,2),10) || 0;
/*
BEWARE : here are the ONLY formats supported by all browsers in creating a Date object
var d = new Date(2011, 01, 07); // yyyy, mm-1, dd
var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss
var d = new Date("02/07/2011"); // "mm/dd/yyyy"
var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss"
var d = new Date(1297076700000); // milliseconds
var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC
*/
var newDate = new Date(yearS, monthS-1, dayS, hourS, minuteS, secS, 0);
if ((newDate.getFullYear() !== yearS) || (newDate.getMonth() !== (monthS-1)) || (newDate.getDate() !== dayS)) {
// Invalid date
return false;
}
return newDate;
} | javascript | {
"resource": ""
} |
q29627 | train | function (position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
geo_codeLatLng(lat, lng);
} | javascript | {
"resource": ""
} | |
q29628 | train | function (name) {
var filters = ltl.filters
var filter = filters[name]
if (!filter) {
try {
filter = filters[name] = ltl.scope[name] || (typeof require !== 'undefined' ? require(name) : null)
} catch (ignore) {
}
}
if (!filter) {
var todo = 'Set window.ltl.filters.' + name + ' to function that accepts a state object and returns a string of HTML.'
todo += 'Or run the following:\n cd ' + process.cwd() + '\n npm install --save ' + name
throw new Error('[Ltl] Unknown filter: "' + name + '". ' + todo)
}
return filter
} | javascript | {
"resource": ""
} | |
q29629 | Courier | train | function Courier(opts) {
stream.Transform.call(this, { objectMode: true });
this.options = merge(Object.create(Courier.DEFAULTS), opts || {});
} | javascript | {
"resource": ""
} |
q29630 | SmartRelay | train | function SmartRelay(socket, options) {
stream.Transform.call(this, {});
this.options = merge(Object.create(SmartRelay.DEFAULTS), options || {});
this.socket = socket;
this.recentData = [];
this.peers = function () {
return [];
};
} | javascript | {
"resource": ""
} |
q29631 | save | train | function save() {
var res = this;
res.$created = true;
return this.$loc.$save(this.$toObject()).then(function() {
emitter.emit('updated', res);
if (!res.$resolved) {
res.$deferred.resolve(res);
res.$resolved = true;
}
return res;
});
} | javascript | {
"resource": ""
} |
q29632 | updateOrCreate | train | function updateOrCreate(val) {
var res = _resources[val._id];
if (!res) {
res = new Resource(val, false, new Date().getTime());
} else {
res.$updateServer(val);
}
return res;
} | javascript | {
"resource": ""
} |
q29633 | train | function (modelName, plugins) {
logger.debug("Getting service for model: " + modelName);
var smd = this.config.resolverByModel(modelName);
return this.getService(smd, plugins);
} | javascript | {
"resource": ""
} | |
q29634 | train | function (serviceName, plugins) {
logger.debug("Getting service: " + serviceName);
var smd = this.config.resolver(serviceName);
return this.getService(smd, plugins);
} | javascript | {
"resource": ""
} | |
q29635 | train | function (smd, plugins) {
var reader = this.newReader(smd),
provider = this.config.provider,
matcher = this.pluginMatcher,
sentPlugins = plugins || [],
mixinPlugins = [],
pertinentMethods,
service;
mixinPlugins = mixinPlugins.concat(
this.pluginMatcher.listForServiceOnly(util.serviceName(reader.getSchemaId()),
reader.getMethodNames(), "mixin", this.config.plugins),
this.pluginMatcher.listForServiceOnly(util.serviceName(reader.getSchemaId()),
reader.getMethodNames(), "mixin", sentPlugins)
);
service = new Service(reader, provider, this.config.plugins, sentPlugins);
logger.debug("Mixin plugins for " + service.name, mixinPlugins);
util.executePluginChain(mixinPlugins, function (plugin) {
// get method names to pass to mixin plugin.
pertinentMethods = matcher.matchingMethodNames(service.name, reader.getMethodNames(), plugin);
plugin.fn.call(plugin.scope || plugin, service, pertinentMethods);
});
return service;
} | javascript | {
"resource": ""
} | |
q29636 | train | function (smd) {
// zyp format by default.
var ret = new ZypSMDReader(smd, this.config.resolver);
if (!smd.SMDVersion) {
//not zyp then fail.
throw new Error("Argument is not an SMD.");
}
return ret;
} | javascript | {
"resource": ""
} | |
q29637 | createPromiseWithTimeout | train | async function createPromiseWithTimeout(promise, timeout, desc) {
if (!(promise instanceof Promise))
throw new Error('Promise expected')
if (!timeout)
throw new Error('Timeout must be a number')
if (timeout < 0)
throw new Error('Timeout cannot be negative')
const { promise: toPromise, timeout: to } = makeTimeoutPromise(desc, timeout)
try {
return await Promise.race([
promise,
toPromise,
])
} finally {
clearTimeout(to)
}
} | javascript | {
"resource": ""
} |
q29638 | ancestry | train | function ancestry(input) {
const proto = input && typeof input === 'object' ? Object.getPrototypeOf(input) : null;
return proto ? ancestry(proto).concat(proto) : [];
} | javascript | {
"resource": ""
} |
q29639 | typeInAncestry | train | function typeInAncestry(type, input) {
return ancestry(input)
.reduce((carry, obj) => carry || Type.objectName(obj) === type, false);
} | javascript | {
"resource": ""
} |
q29640 | isType | train | function isType(type, input) {
if (input === null) {
return type.toLowerCase() === 'null';
}
return typeof input === type.toLowerCase() || Type.is(type, input);
} | javascript | {
"resource": ""
} |
q29641 | cachedTypeDetector | train | function cachedTypeDetector(type) {
if (!cache.has(type)) {
cache.set(type, (input) => isType(type, input) || typeInAncestry(type, input));
}
return cache.get(type);
} | javascript | {
"resource": ""
} |
q29642 | mapFiles | train | async function mapFiles (customizeResult, targetDir, callback) {
const files = mergeEngineResults(customizeResult)
const results = mapValues(files, (file, filename) => {
// Write each file
const fullpath = path.join(targetDir, filename)
return callback(fullpath, file.contents)
})
return deep(results)
} | javascript | {
"resource": ""
} |
q29643 | mapValues | train | function mapValues (obj, fn) {
return Object.keys(obj).reduce(function (subresult, key) {
subresult[key] = fn(obj[key], key)
return subresult
}, {})
} | javascript | {
"resource": ""
} |
q29644 | train | function (elem, func) {
var elt = new TeardownCallback(func);
var propName = DOMBackend.Teardown._CB_PROP;
if (! elem[propName]) {
// create an empty node that is never unlinked
elem[propName] = new TeardownCallback;
// Set up the event, only the first time.
$jq(elem).on(DOMBackend.Teardown._JQUERY_EVENT_NAME, NOOP);
}
elt.linkBefore(elem[propName]);
return elt; // so caller can call stop()
} | javascript | {
"resource": ""
} | |
q29645 | train | function (elem) {
var elems = [];
// Array.prototype.slice.call doesn't work when given a NodeList in
// IE8 ("JScript object expected").
var nodeList = elem.getElementsByTagName('*');
for (var i = 0; i < nodeList.length; i++) {
elems.push(nodeList[i]);
}
elems.push(elem);
$jq.cleanData(elems);
} | javascript | {
"resource": ""
} | |
q29646 | train | function () {
var eventDict = element.$blaze_events;
if (! eventDict)
return;
// newHandlerRecs has only one item unless you specify multiple
// event types. If this code is slow, it's because we have to
// iterate over handlerList here. Clearing a whole handlerList
// via stop() methods is O(N^2) in the number of handlers on
// an element.
for (var i = 0; i < newHandlerRecs.length; i++) {
var handlerToRemove = newHandlerRecs[i];
var info = eventDict[handlerToRemove.type];
if (! info)
continue;
var handlerList = info.handlers;
for (var j = handlerList.length - 1; j >= 0; j--) {
if (handlerList[j] === handlerToRemove) {
handlerToRemove.unbind();
handlerList.splice(j, 1); // remove handlerList[j]
}
}
}
newHandlerRecs.length = 0;
} | javascript | {
"resource": ""
} | |
q29647 | train | function (content) {
checkRenderContent(content);
if (content instanceof Blaze.Template) {
return content.constructView();
} else if (content instanceof Blaze.View) {
return content;
} else {
var func = content;
if (typeof func !== 'function') {
func = function () {
return content;
};
}
return Blaze.View('render', func);
}
} | javascript | {
"resource": ""
} | |
q29648 | train | function (x) {
if (typeof x === 'function') {
return function () {
var data = Blaze.getData();
if (data == null)
data = {};
return x.apply(data, arguments);
};
}
return x;
} | javascript | {
"resource": ""
} | |
q29649 | isResourceClass | train | function isResourceClass(Class) {
const hitByClass =
Class.prototype instanceof TheResource || Class === TheResource
if (hitByClass) {
return true
}
let named = Class
while (!!named) {
const hit = named.name && named.name.startsWith('TheResource')
if (hit) {
return true
}
named = named.__proto__
}
return false
} | javascript | {
"resource": ""
} |
q29650 | Probe | train | function Probe(connection, done) {
if (!(this instanceof Probe)) {
return new Probe(connection, done);
}
if (typeof connection === 'string') {
connection = Connection.from(
Deployment.getId(connection));
}
debug('connection is `%j`', connection);
this.deployment = new Deployment({
_id: Instance.getId(connection.getId()),
name: connection.name
});
this.connection = connection;
this.db = null;
this.metadata = null;
if (typeof done === 'function') {
this.exec(done);
}
} | javascript | {
"resource": ""
} |
q29651 | train | function(_dest, _src){
var _nodeName, _attr;
if (_dest.nodeType !== 1) {
return;
}
// lt ie9 才有
if (_dest.clearAttributes) {
_dest.clearAttributes();
_dest.mergeAttributes(_src);
}
// 判断是否有需要处理属性的节点
_nodeName = _dest.nodeName.toLowerCase();
if(_prop = _definitions.fixProps[_nodeName]){
_dest[_prop] = _src[_prop];
}
//移除节点标示
_dest.removeAttribute($._$signal);
// 移除ID: TODO? 是否允许有重复ID?
_dest.removeAttribute("id");
} | javascript | {
"resource": ""
} | |
q29652 | PersonAddresses | train | function PersonAddresses (f1, personID) {
if (!personID) {
throw new Error('PersonAddresses requires a person ID!')
}
Addresses.call(this, f1, {
path: '/People/' + personID + '/Addresses'
})
} | javascript | {
"resource": ""
} |
q29653 | TheHtmlStyle | train | function TheHtmlStyle(_ref) {
var className = _ref.className,
id = _ref.id,
options = _ref.options;
return _react.default.createElement(_theStyle.TheStyle, (0, _extends2.default)({
id: id
}, {
className: (0, _classnames.default)('the-html-style', className),
styles: TheHtmlStyle.data(options)
}));
} | javascript | {
"resource": ""
} |
q29654 | initFileLogger | train | function initFileLogger(filepath) {
currentFilePath = filepath || currentFilePath;
var logDir = path.dirname(currentFilePath);
appenders.push(logToFile);
if(!fs.existsSync(logDir)) fs.mkdirSync(logDir);
} | javascript | {
"resource": ""
} |
q29655 | writeLog | train | function writeLog(level, msg) {
var line;
if(showSourceInfo) {
var si = getSourceInfo();
if (includeDate) {
line = util.format("[%s] <%s>\t[%s:%s] %s", moment().format(), level, si.file, si.lineNumber, msg);
} else {
line = util.format("<%s>\t[%s:%s] %s", level, si.file, si.lineNumber, msg);
}
} else {
if (includeDate) {
line = util.format("[%s] <%s>\t%s", moment().format(), level, msg);
} else {
line = util.format("<%s>\t%s", level, msg);
}
}
line += '\n';
appenders.forEach(function(appender) {
appender(level, line);
});
} | javascript | {
"resource": ""
} |
q29656 | getSourceInfo | train | function getSourceInfo() {
var exec = getStack()[3];
var pos = exec.getFileName().lastIndexOf('\\');
if(pos < 0) exec.getFileName().lastIndexOf('/');
return {
methodName: exec.getFunctionName() || 'anonymous',
file: exec.getFileName().substring(pos + 1),
lineNumber: exec.getLineNumber()
};
} | javascript | {
"resource": ""
} |
q29657 | train | function ($scope, element, attrs) {
var opts = {};
if (attrs.uiAnimate) {
opts = $scope.$eval(attrs.uiAnimate);
if (angular.isString(opts)) {
opts = {'class': opts};
}
}
opts = angular.extend({'class': 'ui-animate'}, options, opts);
element.addClass(opts['class']);
$timeout(function () {
element.removeClass(opts['class']);
}, 20, false);
} | javascript | {
"resource": ""
} | |
q29658 | bindMapEvents | train | function bindMapEvents(scope, eventsStr, googleObject, element) {
angular.forEach(eventsStr.split(' '), function (eventName) {
//Prefix all googlemap events with 'map-', so eg 'click'
//for the googlemap doesn't interfere with a normal 'click' event
var $event = { type: 'map-' + eventName };
google.maps.event.addListener(googleObject, eventName, function (evt) {
element.trigger(angular.extend({}, $event, evt));
//We create an $apply if it isn't happening. we need better support for this
//We don't want to use timeout because tons of these events fire at once,
//and we only need one $apply
if (!scope.$$phase) scope.$apply();
});
});
} | javascript | {
"resource": ""
} |
q29659 | resolveIncludeDirectives | train | function resolveIncludeDirectives(text, fileItem) {
var result = [];
// parse source code with esprima
try {
var srcParsed = esprima.parse(text);
} catch (e) {
logger.error(buildErrMsg(fileItem.ancestor, 'Failed to parse a [%s] JavaScript file. Reason : [%s]', fileItem.filePath, e));
throw buildShortErrMsg(fileItem.ancestor, 'Failed to parse a [%s] JavaScript file. Reason : [%s]', path.basename(fileItem.filePath), e)
}
// iterating over and looking for include directives
for (var key in srcParsed.body) {
var item = srcParsed.body[key];
// resolve include directive from dom item
var includeDirective = resolveIncludeDirectiveDom(item);
if (includeDirective != null) {
result.push(includeDirective);
}
}
return result;
} | javascript | {
"resource": ""
} |
q29660 | train | function(){
var _body,_text;
try{
var _body = this.__frame.contentWindow.document.body,
_text = (_body.innerText||_body.textContent||'').trim();
// check result for same domain with upload proxy html
if (_text.indexOf(_xflag)>=0||
_body.innerHTML.indexOf(_xflag)>=0){
// use post message path
return;
}
}catch(ex){
// ignore if not same domain
return;
}
this.__onLoadRequest(_text);
} | javascript | {
"resource": ""
} | |
q29661 | train | function(_url,_mode,_cookie){
_j0._$request(_url,{
type:'json',
method:'POST',
cookie:_cookie,
mode:parseInt(_mode)||0,
onload:function(_data){
if (!this.__timer) return;
this._$dispatchEvent('onuploading',_data);
this.__timer = window.setTimeout(
_doProgress._$bind(
this,_url,_mode,_cookie
),1000
);
}._$bind(this),
onerror:function(_error){
if (!this.__timer) return;
this.__timer = window.setTimeout(
_doProgress._$bind(
this,_url,_mode,_cookie
),1000
);
}._$bind(this)
});
} | javascript | {
"resource": ""
} | |
q29662 | Cli | train | function Cli(hydro, argv) {
if (!(this instanceof Cli)) {
return new Cli(hydro, argv);
}
this.hydro = hydro;
this.argv = argv;
this.options = {};
this.conf = [];
this.commands = [ 'help', 'version' ];
this.arrayParams = { plugins: true };
} | javascript | {
"resource": ""
} |
q29663 | followEntryRefs | train | function followEntryRefs( key, callback ) {
return function( entry ) {
const refs = entry[ key ] || [];
return Promise.all( refs.map( callback ) ).then( flatten );
};
} | javascript | {
"resource": ""
} |
q29664 | MongoDatabase | train | function MongoDatabase(configuration) {
MongoDatabase.super_.call(this, configuration);
Object.defineProperties(this, {
/**
* The name of the replica set.
*
* @property replicaSet
* @type String
* @final
*/
replicaSet: {value: configuration.replicaSet},
/**
* A comma separated list of secondary servers.
*
* @property seedlist
* @type String
* @final
*/
seedlist: {value: configuration.seedlist},
/**
* The connected database.
*
* @property database
* @type Db
* @final
*/
db: {
value: null,
writable: true
}
});
} | javascript | {
"resource": ""
} |
q29665 | buildFilters | train | function buildFilters(filters) {
var builtFilters = [];
filters.forEach(function(filter) {
builtFilters.push(MongoDatabase.buildFilter(filter));
});
return builtFilters;
} | javascript | {
"resource": ""
} |
q29666 | isValidType | train | function isValidType(value, authorizedTypes) {
var valueToString = Object.prototype.toString.call(value);
for (var i = 0; i < authorizedTypes.length; i++)
if (valueToString === '[object ' + authorizedTypes[i] + ']') return true;
return false;
} | javascript | {
"resource": ""
} |
q29667 | addComparisonOperation | train | function addComparisonOperation(field, value, operator, authorizedTypes) {
if (!isValidType(field, ['String'])) throw new TypeError('Invalid field');
if (!isValidType(value, authorizedTypes)) throw new TypeError('Invalid value');
this.operations.push({
type: operator,
field: field,
value: value
});
return this;
} | javascript | {
"resource": ""
} |
q29668 | addLogicalOperation | train | function addLogicalOperation(filters, operator) {
for (var i = 0; i < filters.length; i++)
if (!(filters[i] instanceof ResourceFilter)) throw new TypeError('Invalid filters');
if (this.hasOperation(operator)) {
// This logical operator already exists in the list of operations
// Just add the new filters to the operator
for (var operation of this.operations) {
if (operation.type === operator)
operation.filters = operation.filters.concat(filters);
}
} else {
// This logical operator does not exist yet in the list of operations
this.operations.push({
type: operator,
filters: filters
});
}
return this;
} | javascript | {
"resource": ""
} |
q29669 | hashFile | train | function hashFile(filename, callback) {
var calledBack = false,
md5sum = crypto.createHash('md5'),
stream = fs.ReadStream(filename);
stream.on('data', function (data) {
md5sum.update(data);
});
stream.on('end', function () {
var hash = md5sum.digest('hex');
callback(null, hash);
});
stream.on('error', function(err) {
handleResponse(err);
});
function handleResponse(err, hash) {
if (calledBack) {
return;
}
calledBack = true;
callback(err, hash);
}
} | javascript | {
"resource": ""
} |
q29670 | train | function (state, cli) {
var name = cli['<name>'];
var chains = Object.keys(state.state.pointers);
if(chains.indexOf(name) > -1) {
console.log(`Error: Chain ${name} is already known, please choose another name.`);
process.exit();
}
newChain({name}, state, (err, chaindata) => {
if(typeof chaindata === 'string') return true;
state.state.pointers[chaindata.name] = chaindata.chainenv;
state.state.head = chaindata.name;
state.saveState(true);
});
} | javascript | {
"resource": ""
} | |
q29671 | hasOwnProperties | train | function hasOwnProperties(exclude) {
const arg = this;
if (!isObjectLike(arg)) return false;
if (!isValid(exclude)) {
const keys = Object.keys(arg);
return keys.length > 0;
}
return !!eachProp.call(arg, resolveTestFunc(exclude, objectHasNotOwnPropertyBreakTrue, arrayContainsNotKeyBreakTrue, testFuncNotBreakTrue, alwaysBreakTrue, keyNotEqualsBreakTrue), exclude);
} | javascript | {
"resource": ""
} |
q29672 | objFiltered | train | function objFiltered(filter, thisArg) {
const dst = isArray(this) ? [] : {};
copyFiltered.call(dst, this, filter, thisArg);
return dst;
} | javascript | {
"resource": ""
} |
q29673 | objMapped | train | function objMapped(callback, thisArg = UNDEFINED) {
const dst = isArray(this) ? [] : {};
eachProp.call(this, (value, key, src) => {
const result = callback.call(thisArg, value, key, src);
if (result === BREAK) return BREAK;
if (result !== UNDEFINED) {
dst[key] = result;
}
});
return dst;
} | javascript | {
"resource": ""
} |
q29674 | objMap | train | function objMap(callback, thisArg = UNDEFINED) {
const dst = [];
each.call(this, (value, key, src) => {
const result = callback.call(thisArg, value, key, src);
if (result === BREAK) return BREAK;
if (result !== UNDEFINED) {
dst.push(result);
}
});
return dst;
} | javascript | {
"resource": ""
} |
q29675 | objSome | train | function objSome(callback, thisArg = UNDEFINED) {
return !!each.call(this, (value, key, src) => {
BREAK.setDefault(true);
const result = callback.call(thisArg, value, key, src);
if (result === BREAK) return BREAK;
if (result) return BREAK(true);
});
} | javascript | {
"resource": ""
} |
q29676 | objReduceLeft | train | function objReduceLeft(callback/*, initialValue = UNDEFINED*/) {
const args = Array.prototype.slice.call(arguments, 0);
args.unshift(each);
return objReduceIterated.apply(this, args);
} | javascript | {
"resource": ""
} |
q29677 | objReduceRight | train | function objReduceRight(callback/*, initialValue = UNDEFINED*/) {
const args = Array.prototype.slice.call(arguments, 0);
args.unshift(eachRight);
return objReduceIterated.apply(this, args);
} | javascript | {
"resource": ""
} |
q29678 | encodeParams | train | function encodeParams(params) {
var queryString;
if (params && Object.keys(params)) {
queryString = [].slice.call(arguments).reduce(function (a, b) {
return a.concat(b instanceof Array ? b : [b]);
}, []).filter(function (c) {
return "object" === typeof c;
}).reduce(function (p, c) {
!(c instanceof Array) ? p = p.concat(Object.keys(c).map(function (key) {
return [key, c[key]];
})) : p.push(c);
return p;
}, []).reduce(function (p, c) {
c.length === 2 ? p.push(c) : p = p.concat(c);
return p;
}, []).reduce(function (p, c) {
c[1] instanceof Array ? c[1].forEach(function (v) {
p.push([c[0], v]);
}) : p.push(c);
return p;
}, []).map(function (c) {
c[1] = encodeURIComponent(c[1]);
return c.join("=");
}).join("&");
}
return queryString;
} | javascript | {
"resource": ""
} |
q29679 | train | function (e) {
var keyCode = e.keyCode || e.which;
// If the user pressed enter
if (keyCode === 13) {
this.addRow();
// Get the last row viewEvents, then get the title field, then have jQuery
// find the input and trigger a focus event.
_.last(this.subs.get('row')).subs.get('title').$('input').trigger('focus');
}
} | javascript | {
"resource": ""
} | |
q29680 | getAssertQueueOptions | train | function getAssertQueueOptions() {
const aliases ={
queueLimit: 'maxLength',
deadLetter: 'deadLetterExchange',
deadLetterRoutingKey: 'deadLetterRoutingKey'
};
const itemsToOmit = ['limit', 'noBatch'];
let aliased = _.transform(options, function(result, value, key) {
let alias = aliases[key];
result[alias || key] = value;
});
return _.omit(aliased, itemsToOmit);
} | javascript | {
"resource": ""
} |
q29681 | purge | train | function purge() {
qLog.info(`Purging queue ${channelName} - ${connectionName}`);
return channel.purgeQueue(channelName).then(function(){
qLog.debug(`Successfully purged queue ${channelName} - ${connectionName}`);
});
} | javascript | {
"resource": ""
} |
q29682 | getNoBatchOps | train | function getNoBatchOps(raw) {
messages.receivedCount += 1;
return {
ack: function() {
qLog.debug(`Acking tag ${raw.fields.deliveryTag} on ${messages.name} - ${messages.connectionName}`);
channel.ack({ fields: { deliveryTag: raw.fields.deliveryTag } }, false);
},
nack: function() {
qLog.debug(`Nacking tag ${raw.fields.deliveryTag} on ${messages.name} - ${messages.connectionName}`);
channel.nack({ fields: { deliveryTag: raw.fields.deliveryTag } }, false);
},
reject: function() {
qLog.debug(`Rejecting tag ${raw.fields.deliveryTag} on ${messages.name} - ${messages.connectionName}`);
channel.nack({ fields: { deliveryTag: raw.fields.deliveryTag } }, false, false);
}
};
} | javascript | {
"resource": ""
} |
q29683 | getResolutionOperations | train | function getResolutionOperations(raw, consumeOptions) {
if (consumeOptions.noAck) {
return getUntrackedOps(raw);
}
if (consumeOptions.noBatch) {
return getNoBatchOps(raw);
}
return getTrackedOps(raw);
} | javascript | {
"resource": ""
} |
q29684 | subscribe | train | function subscribe(callback, subscribeOptions) {
let consumeOptions = {};
_.assign(consumeOptions, options, subscribeOptions);
consumeOptions = _.pick(consumeOptions, ['consumerTag', 'noAck', 'noBatch', 'limit', 'exclusive', 'priority', 'arguments']);
let shouldAck = !consumeOptions.noAck;
let shouldBatch = !consumeOptions.noBatch;
if (shouldAck && shouldBatch) {
messages.listenForSignal();
}
qLog.info(`Starting subscription ${channelName} - ${connectionName} with ${JSON.stringify(consumeOptions)}`);
return (consumeOptions.limit !== false ? channel.prefetch(consumeOptions.limit || 500) : Promise.resolve())
.then(() => {
function handler(raw) {
let ops = getResolutionOperations(raw, consumeOptions);
qLog.silly(`Received message on queue ${channelName} - ${connectionName}`);
if (shouldAck && shouldBatch) {
messages.addMessage(ops.message);
}
try {
callback(raw, ops);
} catch(e) {
qLog.error(`Error handing message on queue ${channelName} - ${connectionName}`, e);
ops.reject();
}
}
return channel.consume(channelName, handler, _.omit(consumeOptions, ['noBatch', 'limit']));
}).then(function(result) {
channel.tag = result.consumerTag;
return result;
});
} | javascript | {
"resource": ""
} |
q29685 | define | train | function define() {
let aqOptions = getAssertQueueOptions();
topLog.info(`Declaring queue \'${channelName}\' on connection \'${connectionName}\' with the options: ${JSON.stringify(_.omit(aqOptions, ['name']))}`);
return channel.assertQueue(channelName, aqOptions);
} | javascript | {
"resource": ""
} |
q29686 | train | function(_map,_index,_list){
if (_u._$indexOf(_checklist,_map.w)<0){
_checklist.push(_map.w);
_list.splice(_index,1);
_map.w.name = _map.d;
}
} | javascript | {
"resource": ""
} | |
q29687 | train | function(_data){
var _result = {};
_data = _data||_o;
_result.origin = _data.origin||'';
_result.ref = location.href;
_result.self = _data.source;
_result.data = JSON.stringify(_data.data);
return _key+_u._$object2string(_result,'|',!0);
} | javascript | {
"resource": ""
} | |
q29688 | OnSwipe | train | function OnSwipe(element, fn) {
var axis = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : OdoPointer.Axis.X;
classCallCheck(this, OnSwipe);
this.fn = fn;
this.pointer = new OdoPointer(element, {
axis: axis
});
this._onEnd = this._handlePointerEnd.bind(this);
this.pointer.on(OdoPointer.EventType.END, this._onEnd);
} | javascript | {
"resource": ""
} |
q29689 | swiped | train | function swiped(event) {
console.log(event);
event.currentTarget.querySelector('span').textContent = 'Swiped ' + event.direction;
} | javascript | {
"resource": ""
} |
q29690 | getTransitionEndEvent | train | function getTransitionEndEvent() {
const div = document.createElement('div');
div.style.transitionProperty = 'width';
// Test the value which was just set. If it wasn't able to be set,
// then it shouldn't use unprefixed transitions.
/* istanbul ignore next */
if (div.style.transitionProperty !== 'width' && 'webkitTransition' in div.style) {
return 'webkitTransitionEnd';
}
return {
// Saf < 7, Android Browser < 4.4
WebkitTransition: 'webkitTransitionEnd',
transition: 'transitionend',
}[OdoDevice.Dom.TRANSITION];
} | javascript | {
"resource": ""
} |
q29691 | aggregateParams | train | function aggregateParams(_, pulse) {
var key = _.field,
value = _.value,
op = (_.op === 'count' ? '__count__' : _.op) || 'sum',
fields = accessorFields(key).concat(accessorFields(value)),
keys = pivotKeys(key, _.limit || 0, pulse);
return {
key: _.key,
groupby: _.groupby,
ops: keys.map(function() { return op; }),
fields: keys.map(function(k) { return get(k, key, value, fields); }),
as: keys.map(function(k) { return k + ''; }),
modified: _.modified.bind(_)
};
} | javascript | {
"resource": ""
} |
q29692 | get | train | function get(k, key, value, fields) {
return accessor(
function(d) { return key(d) === k ? value(d) : NaN; },
fields,
k + ''
);
} | javascript | {
"resource": ""
} |
q29693 | ViewportItem | train | function ViewportItem(options, parent) {
classCallCheck(this, ViewportItem);
this.parent = parent;
this.id = Math.random().toString(36).substring(7);
this.triggered = false;
this.threshold = 200;
this.isThresholdPercentage = false;
// Override defaults with options.
Object.assign(this, options);
// The whole point is to have a callback function. Don't do anything if it's not given.
if (typeof this.enter !== 'function') {
throw new TypeError('Viewport.add :: No `enter` function provided in Viewport options.');
}
this.parseThreshold();
this.hasExitCallback = typeof this.exit === 'function';
// Cache element's offsets and dimensions.
this.update();
} | javascript | {
"resource": ""
} |
q29694 | Viewport | train | function Viewport() {
classCallCheck(this, Viewport);
this.addId = null;
this.hasActiveHandlers = false;
this.items = new Map();
// Assume there is no horizontal scrollbar. documentElement.clientHeight
// is incorrect on iOS 8 because it includes toolbars.
this.viewportHeight = window.innerHeight;
this.viewportWidth = document.documentElement.clientWidth;
this.viewportTop = 0;
// What's nice here is that rAF won't execute until the user is on this tab,
// so if they open the page in a new tab which they aren't looking at,
// this will execute when they come back to that tab.
requestAnimationFrame(this.handleScroll.bind(this));
} | javascript | {
"resource": ""
} |
q29695 | resolveEntry | train | function resolveEntry(options) {
const cwd = options.cwd;
const pkg = options.pkg;
let entries = [];
if (is.array(options.entry)) entries = options.entry;
if (is.string(options.entry)) entries.push(options.entry);
const result = new Set();
try {
// set the entry that module exports
result.add(require.resolve(cwd));
} catch (_) {
// ignore
}
for (let entry of entries) {
const dir = path.join(cwd, entry);
// if entry is directory, find all js in the directory
if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) {
entry = path.join(entry, '**/*.js');
}
const files = glob.sync(entry, { cwd });
for (const file of files) {
result.add(path.join(cwd, file));
}
}
if (pkg.bin) {
const keys = Object.keys(pkg.bin);
for (const key of keys) {
result.add(path.join(cwd, pkg.bin[key]));
}
}
const dts = path.join(cwd, 'index.d.ts');
if (fs.existsSync(dts)) {
result.add(dts);
}
return Array.from(result);
} | javascript | {
"resource": ""
} |
q29696 | train | function () {
var data = this.data;
var targetEl = this.data.target;
// Only set up once.
if (targetEl.dataset.setImageFadeSetup) { return; }
targetEl.dataset.setImageFadeSetup = true;
// Create animation.
targetEl.setAttribute('animation__fade', {
property: 'material.color',
startEvents: 'set-image-fade',
dir: 'alternate',
dur: data.dur,
from: '#FFF',
to: '#000'
});
} | javascript | {
"resource": ""
} | |
q29697 | arrayGroup | train | function arrayGroup (set, get, reduce) {
//we can use a different lookup path on the right hand object
//is always the "needle"
function _compare (hay, needle) {
for(var i in set) {
var x = u.get(hay, set[i]), y = needle[i]
if(x !== y) return compare(x, y)
}
return 0
}
return function (a, b) {
if(a && !Array.isArray(a)) a = reduce([], a)
var A = a = a || []
var i = search(A, get.map(function (fn) { return fn(b) }), _compare)
if(i >= 0) A[i] = reduce(A[i], b)
else A.splice(~i, 0, reduce(undefined, b))
return a
}
} | javascript | {
"resource": ""
} |
q29698 | _compare | train | function _compare (hay, needle) {
for(var i in set) {
var x = u.get(hay, set[i]), y = needle[i]
if(x !== y) return compare(x, y)
}
return 0
} | javascript | {
"resource": ""
} |
q29699 | getTallest | train | function getTallest(elements) {
let tallest = 0;
for (let i = elements.length - 1; i >= 0; i--) {
if (elements[i].offsetHeight > tallest) {
tallest = elements[i].offsetHeight;
}
}
return tallest;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.