_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q32200 | acornExtractComments | train | function acornExtractComments (input, opts) {
if (typeof input !== 'string') {
throw new TypeError('acorn-extract-comments expect `input` to be a string')
}
if (!input.length) return []
opts = extend({
ast: false,
line: false,
block: false,
preserve: false,
locations: false,
ecmaVersion: 6
}, opts)
var comments = opts.onComment = []
var ast = acorn.parse(stripShebang(input), opts)
if (!comments.length) return []
comments = filter(comments, function (comment) {
var line = (opts.line && comment.type === 'Line') || false
var block = (opts.block && comment.type === 'Block') || false
var ignore = false
if (typeof opts.preserve === 'boolean') {
ignore = opts.preserve && defaultIsIgnore(comment.value)
}
if (typeof opts.preserve === 'function') {
var preserve = opts.preserve(comment.value)
ignore = typeof preserve === 'boolean' ? preserve : ignore
}
if (!ignore && line) return true
if (!ignore && block) return true
return false
})
comments.ast = opts.ast && ast || undefined
return comments
} | javascript | {
"resource": ""
} |
q32201 | processComments | train | function processComments(file) {
let data = JSON.parse(file);
return data.map(x => ({
title: x.name,
subtitle: x.email,
arg: x.id,
valid: true
}));
} | javascript | {
"resource": ""
} |
q32202 | train | function(divisor) {
var coverage;
var percent = this.options.coverage.match(/(\d*)%$/);
if (percent) {
coverage = 100 - parseInt(percent[1]);
if (divisor) {
coverage = coverage / divisor;
}
}
return percent ? coverage + '%' : this.options.coverage;
} | javascript | {
"resource": ""
} | |
q32203 | train | function() {
// If lockup is already locked don't try to disable inputs again
if (this.$pinny.lockup('isLocked')) {
return;
}
var $focusableElements = $(FOCUSABLE_ELEMENTS).not(function() {
return $(this).isChildOf('.' + classes.PINNY);
});
$focusableElements.each(function(_, el) {
var $el = $(el);
var currentTabIndex = $el.attr('tabindex') || 0;
$el
.attr('data-orig-tabindex', currentTabIndex)
.attr('tabindex', '-1');
});
} | javascript | {
"resource": ""
} | |
q32204 | train | function() {
// At this point, this pinny has been closed and lockup has unlocked.
// If there are any other pinny's open we don't want to re-enable the
// inputs as they still require them to be disabled.
if (this._activePinnies()) {
return;
}
$('[data-orig-tabindex]').each(function(_, el) {
var $el = $(el);
var oldTabIndex = parseInt($el.attr('data-orig-tabindex'));
if (oldTabIndex) {
$el.attr('tabindex', oldTabIndex);
} else {
$el.removeAttr('tabindex');
}
$el.removeAttr('data-orig-tabindex');
});
} | javascript | {
"resource": ""
} | |
q32205 | basicParser | train | function basicParser(condition, str) {
let result = [];
for (let i = 0; i < str.length; ++i) {
if (condition(str[i])) {
result.push(str[i]);
}
}
return result;
} | javascript | {
"resource": ""
} |
q32206 | accumulativeParser | train | function accumulativeParser(condition, str) {
let accumulations = [];
let accumulator = "";
for (let i = 0; i < str.length; ++i) {
let ch = str[i];
if (condition(ch)) {
accumulator += ch;
} else if (accumulator !== "") {
accumulations.push(accumulator);
accumulator = "";
}
}
return accumulations;
} | javascript | {
"resource": ""
} |
q32207 | computeInitialValue | train | function computeInitialValue(propertyName) {
if (properties[propertyName] === undefined) return; // unknown property
if (initialValueMap[propertyName]) return; // value is cached.
let initialValue = properties[propertyName].initial;
if (Array.isArray(initialValue)) {
// it's a shorthand
initialValue.forEach(computeInitialValue);
initialValueMap[propertyName] =
canonicalShorthandInitialValues[propertyName]
|| initialValue.map(v => initialValueMap[v]).join(' ');
} else {
// it's a string with the initial value.
// the value may be nonsense though.
if (ILLEGAL_INITIAL_VALUES.test(initialValue)) {
initialValue = 'initial'; // safest legal value.
}
initialValueMap[propertyName] =
initialValueOverrides[propertyName] || initialValue;
}
const propertyNames = getShorthandComputedProperties(propertyName, true);
initialValueRecursiveMap[propertyName] = { [propertyName]: initialValueMap[propertyName] };
initialValueConcreteMap[propertyName] = { };
// In theory, the recursive calls to `computeInitialValue` above should be
// enough to populate the cache for these calls. However, in the case of data
// corruption of the initial property this could be a bad assumption.
propertyNames.forEach((prop) => {
initialValueRecursiveMap[propertyName][prop] = initialValueMap[prop];
if (!isShorthandProperty(prop)) {
initialValueConcreteMap[propertyName][prop] = initialValueMap[prop];
}
});
} | javascript | {
"resource": ""
} |
q32208 | initialValues | train | function initialValues(property, recursivelyResolve = false, includeShorthands = false) {
computeInitialValue(property);
if (recursivelyResolve) {
const initials = includeShorthands ? initialValueRecursiveMap[property] : initialValueConcreteMap[property];
if (!initials) {
// It's an unknown property, return initial and hope the caller knows what
// they are doing.
return { [property]: 'initial' };
}
// we make a copy here to prevent the caller from corrupting our cache.
return Object.assign({}, initials);
}
return { [property]: initialValueMap[property] || 'initial' };
} | javascript | {
"resource": ""
} |
q32209 | validateCaptcha | train | function validateCaptcha(captchaKey, captchaValue, callback) {
// callback = function(err, isValid) {...}
sweetcaptcha.api('check', {sckey: captchaKey, scvalue: captchaValue}, function(err, response){
if (err) return callback(err);
if (response === 'true') {
// valid captcha
return callback(null, true);
}
// invalid captcha
callback(null, false);
});
} | javascript | {
"resource": ""
} |
q32210 | train | function (depMap, parent) {
var mod = registry[depMap.id];
if (mod) {
getModule(depMap).enable();
}
} | javascript | {
"resource": ""
} | |
q32211 | skipComment | train | function skipComment() {
var ch, blockComment, lineComment;
blockComment = false;
lineComment = false;
while (index < length) {
ch = source[index];
if (lineComment) {
ch = nextChar();
if (isLineTerminator(ch)) {
lineComment = false;
if (ch === '\r' && source[index] === '\n') {
++index;
}
++lineNumber;
lineStart = index;
}
} else if (blockComment) {
if (isLineTerminator(ch)) {
if (ch === '\r' && source[index + 1] === '\n') {
++index;
}
++lineNumber;
++index;
lineStart = index;
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
ch = nextChar();
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
if (ch === '*') {
ch = source[index];
if (ch === '/') {
++index;
blockComment = false;
}
}
}
} else if (ch === '/') {
ch = source[index + 1];
if (ch === '/') {
index += 2;
lineComment = true;
} else if (ch === '*') {
index += 2;
blockComment = true;
if (index >= length) {
throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
}
} else {
break;
}
} else if (isWhiteSpace(ch)) {
++index;
} else if (isLineTerminator(ch)) {
++index;
if (ch === '\r' && source[index] === '\n') {
++index;
}
++lineNumber;
lineStart = index;
} else {
break;
}
}
} | javascript | {
"resource": ""
} |
q32212 | addComment | train | function addComment(start, end, type, value) {
assert(typeof start === 'number', 'Comment must have valid position');
// Because the way the actual token is scanned, often the comments
// (if any) are skipped twice during the lexical analysis.
// Thus, we need to skip adding a comment if the comment array already
// handled it.
if (extra.comments.length > 0) {
if (extra.comments[extra.comments.length - 1].range[1] > start) {
return;
}
}
extra.comments.push({
range: [start, end],
type: type,
value: value
});
} | javascript | {
"resource": ""
} |
q32213 | isInitialValue | train | function isInitialValue(property, value) {
const expanded = expandShorthandProperty(property, value, true, true);
return Object.entries(expanded).every(([prop, val]) => {
// eslint-disable-next-line no-param-reassign
val = val.toLowerCase();
if (isShorthandProperty(prop)) return true;
if (val === 'initial') return true;
const canonicalInitialValue = initialValue(prop).toLowerCase();
if (val === canonicalInitialValue) return true;
if (canonicalInitialValue === '0') { // all lengths
if (/^0(px|mm|cm|in|pt|pc|q|mozmm)$/.test(val)) {
return true;
}
}
return false;
});
} | javascript | {
"resource": ""
} |
q32214 | train | function (fragmentKey, cachePath, skipCache, callback) {
if (skipCache) {
debug(' cache is disabled so...');
callback(false);
} else {
fs.exists(cachePath + '/' + fragmentKey, callback);
}
} | javascript | {
"resource": ""
} | |
q32215 | train | function (data, fragmentKey, cachePath, callback) {
debug(' write content in file system');
var basePath = path.dirname(fragmentKey);
if (basePath){
mkdirp.sync(cachePath + '/' + basePath);
}
fs.writeFile(cachePath + '/' + fragmentKey, data, function (err) {
if (err) {
callback(err);
} else {
callback(null, data);
}
});
} | javascript | {
"resource": ""
} | |
q32216 | runHandler | train | function runHandler(plugin, handler, cancel) {
return function runHandlerDelegate(data) {
if (!data) {
return Promise.resolve();
}
return Promise
.resolve(handler.handler(data, plugin, cancel))
.then(function(result) {
return data.configure(result);
});
};
} | javascript | {
"resource": ""
} |
q32217 | submitFormData | train | function submitFormData(params, cb) {
var resourcePath = config.addURIParams("/appforms/forms/:id/submitFormData", params);
var method = "POST";
var data = params.submission;
params.resourcePath = resourcePath;
params.method = method;
params.data = data;
mbaasRequest.app(params, cb);
} | javascript | {
"resource": ""
} |
q32218 | search | train | function search(params, cb) {
var resourcePath = config.addURIParams("/appforms/forms/search", params);
var method = "POST";
var data = params.searchParams;
params.resourcePath = resourcePath;
params.method = method;
params.data = data;
mbaasRequest.app(params, cb);
} | javascript | {
"resource": ""
} |
q32219 | partial | train | function partial(fn) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
return function () {
return fn.apply(this, args.concat(toArray(arguments)));
};
} | javascript | {
"resource": ""
} |
q32220 | RedisTransport | train | function RedisTransport (opts) {
this._container = opts.container || 'logs';
this._length = opts.length || undefined;
this._client = opts.client || redis.createClient(opts.port, opts.host);
// Authorize cleint
if (opts.hasOwnProperty('password')) {
this._client.auth(opts.password);
}
// Set database index
if (opts.hasOwnProperty('db')) {
this._client.select(opts.db);
}
} | javascript | {
"resource": ""
} |
q32221 | findListLength | train | function findListLength (args, next) {
client.llen(self._container, function listLengthFound (err, length) {
if (err) {
return next(err);
}
args.length = length;
return next(null, length);
});
} | javascript | {
"resource": ""
} |
q32222 | trimList | train | function trimList (args, next) {
if (self._length === undefined || args.length <= self._length) {
return next();
}
client.ltrim(self._container, 0, self._length, function dataStored (err) {
if (err) {
return next(err);
}
return next();
});
} | javascript | {
"resource": ""
} |
q32223 | _transitionTo | train | function _transitionTo( nextState, action, data )
{
_cancelled = false;
_transitionCompleted = false;
if( isCancelled() ) { return false; }
if( _currentState ) {
let previousState = _currentState;
if(_options.history){ _history.push(previousState.name); }
}
_currentState = nextState;
if( action ) {
_stateChangedHandler( action, data );
} else {
_transitionCompleted = true;
FSM.log('State transition Completed! Current State :: ' + _currentState.name );
stateChanged.dispatch(_currentState);
}
} | javascript | {
"resource": ""
} |
q32224 | _processActionQueue | train | function _processActionQueue()
{
if( _actionQueue.length > 0 ) {
var stateEvent = _actionQueue.shift();
if(!_currentState.getTarget(stateEvent.action)) {
_processActionQueue();
}
else {
} FSM.action( stateEvent.action, stateEvent.data );
return false;
}
FSM.log('State transition Completed! Current State :: ' + _currentState.name );
stateChanged.dispatch(_currentState);
} | javascript | {
"resource": ""
} |
q32225 | train | function( action, target, actionIdnentifier ) {
if( this._transitions[ action ] ) { return false; }
this._transitions[ action ] = { target : target, _id : actionIdnentifier };
} | javascript | {
"resource": ""
} | |
q32226 | train | function (Class, descriptors, staticDescriptors) {
var castAll = Casting.forDescriptors(descriptors);
function cast (value) {
if (!(value instanceof this)) {
return new this(castAll(value));
}
else {
return castAll(value);
}
}
cast.isAutoGenerated = true;
return cast;
} | javascript | {
"resource": ""
} | |
q32227 | train | function (Class, descriptors, staticDescriptors) {
var validate = Validating.forDescriptors(descriptors);
validate.isAutoGenerated = true;
return validate;
} | javascript | {
"resource": ""
} | |
q32228 | train | function (Class, descriptors, staticDescriptors) {
var casters = {},
validators = {},
body = '"use strict";\n\
var valid = true,\n\
errors = {},\n\
result;\n\
if (values === undefined) {\n\
values = subject || {};\n\
subject = new this();\n\
}\n';
each(descriptors, function (descriptor, key) {
if (key === '[[state]]' ||
key === 'initialize' ||
(!descriptor.writable && typeof descriptor.set !== 'function') ||
typeof descriptor.value === 'function'
) {
return;
}
var accessor = createAccessor(key);
body += 'if (values'+accessor+' !== undefined) {\n';
if (descriptor.type) {
casters[key] = Casting.get(descriptor.type);
body += 'if (values'+accessor+' === null) {\n\
subject'+accessor+' = null;\n\
}\n\
else {\n\
result = tryCatch(casters'+accessor+', values'+accessor+');\n\
if (result.error) {\n\
valid = false;\n\
errors'+accessor+' = result.error.message;\n\
}\n\
else {\n\
subject'+accessor+' = result.value;\n\
}\n\
}\n';
}
else {
body += 'subject'+accessor+' = values'+accessor+';\n';
}
body += '}\n';
if (descriptor.rules) {
validators[key] = Validating.forDescriptor(key, descriptor);
body += 'if (!errors'+accessor+') {\n\
result = validators'+accessor+'(subject'+accessor+');\n\
if (!result.valid) {\n\
valid = false;\n\
errors'+accessor+' = result.error;\n\
}\n\
}\n';
}
});
body += 'return {\n\
valid: valid,\n\
value: subject,\n\
errors: errors\n\
};';
var input = this.createDynamicFunction('validators', 'casters', 'tryCatch', 'subject', 'values', body);
var fn = function (subject, values) {
return input.call(this, validators, casters, tryCatch1, subject, values);
};
fn.isAutoGenerated = true;
return fn;
} | javascript | {
"resource": ""
} | |
q32229 | train | function (Class, descriptors) {
var body = '"use strict";\n';
var casters = {};
each(descriptors, function (descriptor, name) {
if (descriptor.writable || typeof descriptor.set === 'function') {
var accessor = createAccessor(name);
if (descriptor.cast || descriptor.type) {
casters[name] = Casting.forDescriptor(descriptor);
body += 'if (config' + accessor + ' !== undefined) {\n\
this' + accessor + ' = casters' + accessor + '(config' + accessor + ');\n\
}\n';
}
else {
body += 'if (config' + accessor + ' !== undefined) {\n\
this' + accessor + ' = config' + accessor + ';\n\
}\n';
}
}
});
var configure = this.createDynamicFunction('casters', 'config', body);
var fn = function (config) {
return configure.call(this, casters, config);
};
fn.isAutoGenerated = true;
return fn;
} | javascript | {
"resource": ""
} | |
q32230 | train | function (Class, descriptors) {
ClassFactory.prototype.updateDynamicFunctions.call(this, Class, descriptors);
if (!Class.cast || Class.cast.isAutoGenerated) {
Class.cast = this.createStaticCast(Class, descriptors);
}
if (!Class.validate || Class.validate.isAutoGenerated) {
Class.validate = this.createStaticValidate(Class, descriptors);
}
if (!Class.input || Class.input.isAutoGenerated) {
Class.input = this.createStaticInput(Class, descriptors);
}
if (!Class.toJSON || Class.toJSON.isAutoGenerated) {
Class.toJSON = this.createStaticToJSON(Class, descriptors);
}
} | javascript | {
"resource": ""
} | |
q32231 | tryCatch1 | train | function tryCatch1 (fn, arg1) {
var errorObject = {};
try {
errorObject.value = fn(arg1);
}
catch (e) {
errorObject.error = e;
}
return errorObject;
} | javascript | {
"resource": ""
} |
q32232 | SuiteModel | train | function SuiteModel (name) {
this.className = 'js.' + name
this.scenarios = []
this.tagMap = {}
this.tagMap.JS = new TagModel('JS')
log('Creating new model ' + this.className)
} | javascript | {
"resource": ""
} |
q32233 | Slider | train | function Slider(elem) {
check(elem, 'elem').is.anInstanceOf(Element)();
var priv = {};
priv.elem = elem;
priv.transitions = [];
priv.phaser = phaser(elem);
priv.slides = [];
priv.upgrader = upgrader(elem);
priv.listeners = {};
priv.tempClasses = [];
priv.fromIndex = 1;
priv.toIndex = 0;
priv.started = false;
var pub = {};
/**
* Array containing all slide elements.
*
* @type Array
* @access read-only
*
* @fqn Slider.prototype.slides
*/
pub.slides = priv.slides;
/**
* Index of currently active slide.
*
* Set to `null` if ${link Slider.prototype.start} was not called on this slider.
*
* @type Number
* @access read-write
*
* @fqn Slider.prototype.currentIndex
*/
pub.currentIndex = null;
Object.defineProperty(pub, 'currentIndex', {
get: function() { return priv.slides.length !== 0? priv.toIndex: null; },
set: partial(moveTo, priv),
});
/**
* Currently active slide element.
*
* Set to `null` if ${link Slider.prototype.start} was not called on this slider.
*
* @type Element
* @access read-write
*
* @fqn Slider.prototype.currentSlide
*/
pub.currentSlide = null;
Object.defineProperty(pub, 'currentSlide', {
get: function() { return priv.slides.length !== 0? priv.slides[priv.toIndex]: null; },
set: function() { throw new Error('read only property! please use currentIndex instead'); },
});
bindMethods(pub, [
start,
moveTo,
moveToNext,
moveToPrevious,
on,
removeListener,
], priv);
priv.pub = pub;
return pub;
} | javascript | {
"resource": ""
} |
q32234 | start | train | function start(priv, callback) {
check(priv.started, 'slider.started').is.False();
check(callback, 'callback').is.aFunction.or.Undefined();
priv.startCallback = callback || noop;
window.addEventListener('keydown', partial(keyBasedMove, priv), false);
priv.elem.addEventListener('click', partial(clickBasedMove, priv), false);
priv.upgrader.onSlideUpgraded = acceptSlide.bind(null, priv);
priv.upgrader.start();
priv.phaser.addPhaseListener(partial(onPhaseChange, priv));
on(priv, 'slideChange', changeDot.bind(null, priv));
priv.started = true;
} | javascript | {
"resource": ""
} |
q32235 | moveToPrevious | train | function moveToPrevious(priv) {
moveTo(priv, (priv.toIndex - 1 + priv.slides.length) % priv.slides.length);
} | javascript | {
"resource": ""
} |
q32236 | moveTo | train | function moveTo(priv, index) {
check(priv.started, 'slider.started').is.True();
check(index, 'index').is.inRange(0, priv.slides.length)();
var toIndex = index <= priv.slides.length? index % priv.slides.length: index;
if (priv.toIndex === toIndex) {
return;
}
removeTempClasses(priv);
removeMarkers(priv);
priv.fromIndex = priv.toIndex;
priv.toIndex = toIndex;
addMarkers(priv);
addTempClasses(priv);
priv.phaser.startTransition();
emitEvent(priv, slidechange(priv.fromIndex, priv.toIndex));
} | javascript | {
"resource": ""
} |
q32237 | on | train | function on(priv, eventName, listener) {
check(eventName, 'eventName').is.aString.and.oneOf(EVENT_NAMES)();
check(listener, 'listener').is.aFunction();
getListeners(priv, eventName).push(listener);
} | javascript | {
"resource": ""
} |
q32238 | removeListener | train | function removeListener(priv, eventName, listener) {
check(eventName, 'eventName').is.aString.and.oneOf(EVENT_NAMES)();
var listeners = getListeners(priv, eventName);
check(listener, 'listener').is.aFunction.and.is.oneOf(listeners, 'registered listeners')();
listeners.splice(listeners.indexOf(listener), 1);
} | javascript | {
"resource": ""
} |
q32239 | acceptSlide | train | function acceptSlide(priv, slideElement) {
slideElement.classList.add(Flag.UPGRADED);
insertSlide(priv, slideElement);
priv.phaser.addPhaseTrigger(slideElement.querySelector('.'+ Layout.CONTENT));
if (priv.slides.length === 1) {
priv.startCallback.call(null, priv.pub);
// moving this to next tick is required in chromium for some reason
window.setTimeout(moveToFirstSlide.bind(null, priv), 1);
}
} | javascript | {
"resource": ""
} |
q32240 | onReady | train | function onReady( fn ) {
// Ensure we passed a function as the argument
if ( typeof fn !== 'function' ) {
return [];
}
// If the ready state is already complete, run the passed function,
// otherwise add it to our saved array.
if ( document.readyState === 'complete' ) {
fn();
} else {
_readyFunctions.push( fn );
}
// When the ready state changes to complete, run the passed function
document.onreadystatechange = function() {
if ( document.readyState === 'complete' ) {
for ( let i = 0, l = _readyFunctions.length; i < l; i++ ) {
_readyFunctions[i]();
}
_readyFunctions.length = 0;
}
};
return _readyFunctions;
} | javascript | {
"resource": ""
} |
q32241 | Hey | train | function Hey(options) {
// force the use of new
if (this.constructor !== Hey) {
throw "Hey must be instantiated with \"new\"!";
}
// we need some options, don't we?
if (!options || !options.path) {
throw "Option object must be set with a valid path to watch.";
}
// start EventEmitter
EventEmitter.call(this);
// folders and descriptors, just in case
this.__paths = [];
this.__descriptors = [];
// helpful boolean
this.__end_of_buffer = false;
// some filepath properties
this.__isDirectory = false;
this.__isFile = false;
Object.defineProperty(this, "isDirectory", {
enumerable: true,
get: function () {
return this.__isDirectory;
}
});
Object.defineProperty(this, "isFile", {
enumerable: true,
get: function () {
return this.__isFile;
}
});
// define options as "property"
this.__options = options;
Object.defineProperty(this, "options", {
enumerable: true,
get: function () {
return this.__options;
}
});
// default mask
Object.defineProperty(this, "defaultMask", {
enumerable: true,
get: function () {
return Hey.FLAGS.MODIFY | Hey.FLAGS.CREATE | Hey.FLAGS.DELETE
| Hey.FLAGS.SELF_DELETE | Hey.FLAGS.MOVE
| Hey.FLAGS.SELF_MOVE;
}
});
this.initialize();
} | javascript | {
"resource": ""
} |
q32242 | formatDeckAsFullCards | train | function formatDeckAsFullCards(deck, data) {
var newDeck = {
_id: deck._id,
name: deck.name,
username: deck.username,
lastUpdated: deck.lastUpdated,
faction: Object.assign({}, deck.faction)
};
if (data.factions) {
newDeck.faction = data.factions[deck.faction.value];
}
if (deck.agenda) {
newDeck.agenda = data.cards[deck.agenda.code];
}
newDeck.bannerCards = (deck.bannerCards || []).map(function (card) {
return data.cards[card.code];
});
newDeck.drawCards = processCardCounts(deck.drawCards || [], data.cards);
newDeck.plotCards = processCardCounts(deck.plotCards || [], data.cards);
newDeck.rookeryCards = processCardCounts(deck.rookeryCards || [], data.cards);
return newDeck;
} | javascript | {
"resource": ""
} |
q32243 | train | function (rawLine) {
// Maven on the Travis-CI Ubunty Trusty container makes the version line bold.
// Let's just say I'm pretty salty at this point. So we strip ANSI codes.
var line = stripAnsi(rawLine);
debug('Checking cmd output: ' + line);
var match = line.match(re);
if (match !== null) {
retv = match;
}
} | javascript | {
"resource": ""
} | |
q32244 | processWatches | train | function processWatches(items) {
// queue up matches
// { "member" : { "uri" : [ "match", "match" ] } }
var toSend = {};
GLOBAL.svc.indexer.retrieveWatches({}, function(err, res) {
if (res.hits) {
var watches = _.pluck(res.hits.hits, '_source');
// for each hit
items.forEach(function(item) {
var matches = watchLib.matches(item, watches);
if (matches.length) {
matches.forEach(function(match) {
toSend[match.member] = toSend[match.member] || {};
toSend[match.member][item.uri] = toSend[match.member][item.uri] || [];
toSend[match.member][item.uri].push(match.match);
});
}
});
send(toSend);
}
});
} | javascript | {
"resource": ""
} |
q32245 | createStore | train | function createStore(initialState, option) {
let $state = initialState;
let $listener = [];
const $enhancer = option && option.enhancer;
const $updater = (() => {
const f1 = option && option.updater;
const f2 = (s1, s2) => Object.assign({}, s1, s2);
return f1 || f2;
})();
return {
get listenerCount() {
return $listener.length;
},
getState,
setState,
dispatch: usecase,
usecase,
subscribe,
};
/**
* Get state
*
* @returns {S}
*/
function getState() {
return $state;
}
/**
* Set state
* this api depend on updater
*
* @param {Partial<S>} state
* @returns {S} state
*/
function setState(state) {
$state = $updater($state, state);
return $state;
}
/**
* Listen changing of state and exception of transition
*
* @param listener
* @returns {Function} unsubscribe
*/
function subscribe(listener) {
$listener.push(listener);
return function unsubscribe() {
$listener = $listener.filter(f => f !== listener);
};
}
/**
* Publish changing of state to listener
*
* @private
* @param {S} state
* @param {Error} [error]
* @returns {void}
*/
function publish(state, error) {
$listener.forEach(f => f(state, error));
}
/**
* Compose queue
*
* @param {string} [name]
* @returns {Use}
* @example
* usecase('name').use([f1, f2])(param)
* usecase('name').use(f1).use(f2)(param)
*/
function usecase(name) {
let $queue = [];
let $run;
return { use };
function use(arg) {
let q = [].concat(arg);
q = $enhancer ? q.map((t) => $enhancer(name, t)) : q;
q.forEach(t => $queue.push(t));
return $run || (() => {
$run = run;
$run.use = use;
return $run;
})();
}
function run() {
next($queue[Symbol.iterator](), arguments[0]);
}
;
}
/**
* Execute one task from iterator then
* mutation state and publishing
*
* @private
* @param {Iterator<Function>} i
* @param {*} p
* @param {Function} [task]
* @returns {void}
*/
function next(i, p, task) {
let iResult = task ? { value: task, done: false } : i.next();
try {
if (iResult.done) {
publish($state);
return;
}
const result = iResult.value($state, p);
/* Promise(Like) */
if (result && typeof result.then === 'function') {
result.then(resolved, rejected);
publish($state);
return;
function resolved(t) {
const _t = (typeof t === 'function') && t;
next(i, p, _t);
}
;
function rejected(err) {
publish($state, err);
}
}
if (!iResult.done) {
result && setState(result);
next(i, p);
return;
}
}
catch (e) {
publish($state, e);
}
}
} | javascript | {
"resource": ""
} |
q32246 | next | train | function next(i, p, task) {
let iResult = task ? { value: task, done: false } : i.next();
try {
if (iResult.done) {
publish($state);
return;
}
const result = iResult.value($state, p);
/* Promise(Like) */
if (result && typeof result.then === 'function') {
result.then(resolved, rejected);
publish($state);
return;
function resolved(t) {
const _t = (typeof t === 'function') && t;
next(i, p, _t);
}
;
function rejected(err) {
publish($state, err);
}
}
if (!iResult.done) {
result && setState(result);
next(i, p);
return;
}
}
catch (e) {
publish($state, e);
}
} | javascript | {
"resource": ""
} |
q32247 | dialog | train | function dialog(opts, cb) {
var $ = dialog.air
, el = opts.el.clone(true)
, container = opts.container || $('body')
, evt = opts.evt || 'click'
, res = {accepted: false, el: el};
opts.accept = opts.accept || '[href="#ok"]';
opts.reject = opts.reject || '[href="#cancel"]';
// pass function to remove element in result
// when we don't handle removing
if(opts.remove === false) {
res.remove = function() {
el.remove();
}
}
container.append(el);
function onReject(e) {
e.preventDefault();
if(opts.remove !== false) {
el.remove();
}
cb(res);
}
function onAccept(e) {
e.preventDefault();
if(opts.remove !== false) {
el.remove();
}
res.accepted = true;
cb(res);
}
var modal = el.find('.modal');
if(opts.modal !== false) {
modal.on(evt, onReject);
}else{
modal.css({cursor: 'auto'})
}
el.find(opts.reject).on(evt, onReject);
el.find(opts.accept).on(evt, onAccept);
return el;
} | javascript | {
"resource": ""
} |
q32248 | Delimiters | train | function Delimiters (delims, options) {
this.options = options || {};
this.delims = delims || [];
this.defaults = merge({}, {
beginning: '^', // '^' Matches beginning of input.
matter: '([\\s\\S]+?)', // The "content" between the delims
body: '([\\s\\S]+|\\s?)', // The "content" after the delims
end: '$', // '$' Matches end of input.
flags: '' // RegExp flags: g, m, i
}, options);
} | javascript | {
"resource": ""
} |
q32249 | safelyToExecutor | train | function safelyToExecutor(self, executor) {
let done = false;
try {
executor(
function(result) {
if (done) return;
done = true;
doResolve.call(self, result);
}, // doResolve
function(error) {
if (done) return;
done = true;
doReject.call(self, error);
} // doReject
);
} catch (error) {
if (done) return;
done = true;
doReject.call(self, error);
}
} | javascript | {
"resource": ""
} |
q32250 | doResolve | train | function doResolve(result) {
let self = this;
if (result === self) {
// Promise Standard 2.3.1
return doReject.call(
self,
new TypeError("Can not resolve 'Promise' itself")
);
}
// Promise Standard 2.3.3.2
try {
// Promise Standard 2.3.2 and 2.3.3 can be merge
// if result is a thenable(.then)
let then = safelyToThen(result);
if (then) {
// Promise Standard 2.3.3.3
safelyToExecutor(self, then.bind(result));
} else {
// [[ async ]]
setTimeout(function() {
// commonly case
if (self.currentState === Shared.PENDING) {
self.currentState = Shared.FULFILLED;
self.valOrErr = result;
for (let i = 0; i < self.onFulfilledCallback.length; i++) {
self.onFulfilledCallback[i](result);
}
self.onFulfilledCallback = [];
}
}, 0);
}
// case: when then(doResolve, doReject) -> asyncToResolveOrReject -> func(arg) -> return self
return self;
} catch (error) {
return doReject.call(self, error);
}
} | javascript | {
"resource": ""
} |
q32251 | text | train | function text (options) {
var opts = options || {}
var defaultCharset = opts.defaultCharset || 'utf-8'
var inflate = opts.inflate !== false
var limit = typeof opts.limit !== 'number'
? bytes.parse(opts.limit || '100kb')
: opts.limit
var type = opts.type || 'text/plain'
var verify = opts.verify || false
if (verify !== false && typeof verify !== 'function') {
throw new TypeError('option verify must be function')
}
// create the appropriate type checking function
var shouldParse = typeof type !== 'function'
? typeChecker(type)
: type
function parse (buf) {
return buf
}
return function textParser (req, res, next) {
if (req._body) {
debug('body already parsed')
next()
return
}
req.body = req.body || {}
// skip requests without bodies
if (!typeis.hasBody(req)) {
debug('skip empty body')
next()
return
}
debug('content-type %j', req.headers['content-type'])
// determine if request should be parsed
if (!shouldParse(req)) {
debug('skip parsing')
next()
return
}
// get charset
var charset = getCharset(req) || defaultCharset
// read
read(req, res, next, parse, debug, {
encoding: charset,
inflate: inflate,
limit: limit,
verify: verify
})
}
} | javascript | {
"resource": ""
} |
q32252 | getCharset | train | function getCharset (req) {
try {
return contentType.parse(req).parameters.charset.toLowerCase()
} catch (e) {
return undefined
}
} | javascript | {
"resource": ""
} |
q32253 | Fire | train | function Fire(opts) {
opts = opts || {};
opts.host = opts.host || '0.0.0.0';
opts.port = opts.port || 9998;
var self = this;
Socket.call(self);
self.n = 0;
self.buf_size = opts.buf_size || 100;
self.stream = opts.stream || 'off';
self.log_queue = [];
self.connect(opts.port, opts.host, function(){
debug('connected host %s port %s', opts.host, opts.port);
self.announce();
});
} | javascript | {
"resource": ""
} |
q32254 | train | function(name) {
if (name in props) {
// Check property descriptor
var desc = this.getOwnPropertyDescriptor(name);
if (props[name].nullable === false) {
throw name + ' is not allowd null or undefined';
}
return delete obj[name];
} else {
throw name + ' is not defined in this struct';
}
} | javascript | {
"resource": ""
} | |
q32255 | train | function(receiver, name, val) {
if (name in props) {
// Check property descriptor
var desc = this.getOwnPropertyDescriptor(name);
if (desc && !desc.writable) {
throw name + ' is not writable property';
}
if (props[name].nullable === false && isNullOrUndefined(val)) {
throw name + ' is not allowd null or undefined';
}
// Check type match
var type = props[name].type;
if (isNullOrUndefined(val) || Struct.isStructType(type, val) || Struct.util.isType(type, val)) {
// OK
} else {
throw name + ' must be ' + props[name].type + ' type';
}
if (props[name].cond && !props[name].cond(val)) {
throw 'Invalid value:' + name + '=' + String(val);
}
obj[name] = val;
return true;
} else {
throw name + ' is not defined in this struct';
}
} | javascript | {
"resource": ""
} | |
q32256 | createFake | train | function createFake(name, obj) {
obj = obj || {};
// Only add property for type check.
Object.defineProperty(obj, STRUCT_NAME_KEY, {
value: name,
wriatble: false,
enumerable: false
});
return obj;
} | javascript | {
"resource": ""
} |
q32257 | getUserDictionary | train | function getUserDictionary(){
const userDict = {};
if (!userId){
userDict['userId'] = deviceData.getDeviceId();
} else {
userDict['userId'] = userId;
}
for (let key in extraInfo){
userDict[key] = extraInfo[key];
}
return userDict;
} | javascript | {
"resource": ""
} |
q32258 | peekTransferables | train | function peekTransferables (data, result) {
if ( result === void 0 ) result = [];
if (isTransferable(data)) {
result.push(data);
} else if (isObject(data)) {
for (var i in data) {
peekTransferables(data[i], result);
}
}
return result
} | javascript | {
"resource": ""
} |
q32259 | train | function(service, credentials, accounts, keywords) {
Stream.call(this, service, credentials, accounts, keywords);
// Initialize FBGraph
fbgraph.setAccessToken(credentials.access_token);
// Set api endpoint URL for subscriber
this.api_endpoint = 'https://graph.facebook.com/'+ credentials.app_id +'/subscriptions/';
// Initialize subscriber object
this.subscriber = new Subscriber(credentials, this.callback_url(), this.api_endpoint);
// Initialize responder
this.responder = new Responder();
// Start listening for incoming
process.nextTick(function() {
this.delegateResponder();
}.bind(this));
} | javascript | {
"resource": ""
} | |
q32260 | train | function(key, value) {
const key2 = key.toLowerCase().replace(/[^a-z0-9]/ig, '');
res.serverassist.headers[key] = value;
res.serverassist.headers2[key2] = value;
} | javascript | {
"resource": ""
} | |
q32261 | setTimer | train | function setTimer(job){
clearTimeout(timer);
timer = setTimeout(excuteJob, job.excuteTime()-Date.now());
} | javascript | {
"resource": ""
} |
q32262 | excuteJob | train | function excuteJob(){
let job = peekNextJob();
let nextJob;
while(!!job && (job.excuteTime()-Date.now())<accuracy){
job.run();
queue.pop();
let nextTime = job.nextTime();
if(nextTime === null){
delete map[job.id];
}else{
queue.offer({id:job.id, time: nextTime});
}
job = peekNextJob();
}
//If all the job have been canceled
if(!job)
return;
//Run next schedule
setTimer(job);
} | javascript | {
"resource": ""
} |
q32263 | peekNextJob | train | function peekNextJob(){
if(queue.size() <= 0)
return null;
let job = null;
do{
job = map[queue.peek().id];
if(!job) queue.pop();
}while(!job && queue.size() > 0);
return (!!job)?job:null;
} | javascript | {
"resource": ""
} |
q32264 | getNextJob | train | function getNextJob(){
let job = null;
while(!job && queue.size() > 0){
let id = queue.pop().id;
job = map[id];
}
return (!!job)?job:null;
} | javascript | {
"resource": ""
} |
q32265 | _createProxy | train | function _createProxy(ids, workspaces) {
const _workspaces = makeArray(ids).map(id=>{
if (!workspaces.has(id)) workspaces.set(id, {});
return workspaces.get(id);
});
return new Proxy(global, {
get: function(target, property, receiver) {
if (property === 'global') return global;
for (let n=0; n<_workspaces.length; n++) {
if (property in _workspaces[n]) return Reflect.get(_workspaces[n], property, receiver);
}
return Reflect.get(target, property, receiver);
},
has: function(target, property) {
for (let n=0; n<_workspaces.length; n++) {
if (property in _workspaces[n]) return true;
}
return Reflect.has(target, property);
},
set: function(target, property, value, receiver) {
return Reflect.set(target, property, value, receiver);
}
});
} | javascript | {
"resource": ""
} |
q32266 | createLookup | train | function createLookup(ids) {
for (let value of lookup) {
if (ids.length === value.length) {
let match = true;
value.forEach(subItem=>{
if (ids[n] !== subItem) match = false;
});
if (match) return value;
}
}
return ids;
} | javascript | {
"resource": ""
} |
q32267 | bfsOrder | train | function bfsOrder(root) {
var inqueue = [root], outqueue = [];
root._bfs_parent = null;
while (inqueue.length > 0) {
var elem = inqueue.shift();
outqueue.push(elem);
var children = elem.childNodes;
var liParent = null;
for (var i=0 ; i<children.length; i++) {
if (children[i].nodeType == 1) {// element node
if (children[i].tagName === 'LI') {
liParent = children[i];
} else if ((children[i].tagName === 'UL' || children[i].tagName === 'OL') && liParent) {
liParent.appendChild(children[i]);
i--;
continue;
}
children[i]._bfs_parent = elem;
inqueue.push(children[i]);
}
}
}
outqueue.shift();
return outqueue;
} | javascript | {
"resource": ""
} |
q32268 | prefixBlock | train | function prefixBlock(prefix, block, skipEmpty) {
var lines = block.split('\n');
for (var i =0; i<lines.length; i++) {
// Do not prefix empty lines
if (lines[i].length === 0 && skipEmpty === true)
continue;
else
lines[i] = prefix + lines[i];
}
return lines.join('\n');
} | javascript | {
"resource": ""
} |
q32269 | setContent | train | function setContent(node, content, prefix, suffix) {
if (content.length > 0) {
if (prefix && suffix)
node._bfs_text = prefix + content + suffix;
else
node._bfs_text = content;
} else
node._bfs_text = '';
} | javascript | {
"resource": ""
} |
q32270 | getContent | train | function getContent(node) {
var text = '', atom;
for (var i = 0; i<node.childNodes.length; i++) {
if (node.childNodes[i].nodeType === 1) {
atom = node.childNodes[i]._bfs_text;
} else if (node.childNodes[i].nodeType === 3) {
atom = node.childNodes[i].data;
} else
continue;
if (text.match(/[\t ]+$/) && atom.match(/^[\t ]+/)) {
text = text.replace(/[\t ]+$/,'') + ' ' + atom.replace(/^[\t ]+/, '');
} else {
text = text + atom;
}
}
return text;
} | javascript | {
"resource": ""
} |
q32271 | processNode | train | function processNode(node) {
if (node.tagName === 'P' || node.tagName === 'DIV' || node.tagName === 'UL' || node.tagName === 'OL' || node.tagName === 'PRE')
setContent(node, getContent(node), '\n\n', '\n\n');
else if (node.tagName === 'BR')
setContent(node, '\n\n');
else if (node.tagName === 'HR')
setContent(node, '\n***\n');
else if (node.tagName === 'H1')
setContent(node, nltrim(getContent(node)), '\n# ', '\n');
else if (node.tagName === 'H2')
setContent(node, nltrim(getContent(node)), '\n## ', '\n');
else if (node.tagName === 'H3')
setContent(node, nltrim(getContent(node)), '\n### ', '\n');
else if (node.tagName === 'H4')
setContent(node, nltrim(getContent(node)), '\n#### ', '\n');
else if (node.tagName === 'H5')
setContent(node, nltrim(getContent(node)), '\n##### ', '\n');
else if (node.tagName === 'H6')
setContent(node, nltrim(getContent(node)), '\n###### ', '\n');
else if (node.tagName === 'B' || node.tagName === 'STRONG')
setContent(node, nltrim(getContent(node)), '**', '**');
else if (node.tagName === 'I' || node.tagName === 'EM')
setContent(node, nltrim(getContent(node)), '_', '_');
else if (node.tagName === 'A') {
var href = node.href ? nltrim(node.href) : '', text = nltrim(getContent(node)) || href, title = node.title ? nltrim(node.title) : '';
if (href.length > 0)
setContent(node, '[' + text + '](' + href + (title ? ' "' + title + '"' : '') + ')');
else
setContent(node, '');
} else if (node.tagName === 'IMG') {
var src = node.getAttribute('src') ? nltrim(node.getAttribute('src')) : '', alt = node.alt ? nltrim(node.alt) : '', caption = node.title ? nltrim(node.title) : '';
if (src.length > 0)
setContent(node, ' + ')');
else
setContent(node, '');
} else if (node.tagName === 'BLOCKQUOTE') {
var block_content = getContent(node);
if (block_content.length > 0)
setContent(node, prefixBlock('> ', block_content), '\n\n', '\n\n');
else
setContent(node, '');
} else if (node.tagName === 'CODE') {
if (node._bfs_parent.tagName === 'PRE' && node._bfs_parent._bfs_parent !== null)
setContent(node, prefixBlock(' ', getContent(node)));
else
setContent(node, nltrim(getContent(node)), '`', '`');
} else if (node.tagName === 'LI') {
var list_content = getContent(node);
if (list_content.length > 0)
if (node._bfs_parent.tagName === 'OL')
setContent(node, trim(prefixBlock(' ', list_content, true)), '1. ', '\n\n');
else
setContent(node, trim(prefixBlock(' ', list_content, true)), '- ', '\n\n');
else
setContent(node, '');
} else
setContent(node, getContent(node));
} | javascript | {
"resource": ""
} |
q32272 | initialize | train | function initialize() {
var hash = window.location.hash.match(/^\#?\/([^\/]+)?\/?$/)
, self = this;
//
// The login form is in the DOM by default so it can leverage
// browser password saving features.
//
this.content = $('section.modal').get('innerHTML');
if (hash && hash[1] === 'login') setTimeout(function check() {
if (Cortex.app('modal')) return self.render('login');
setTimeout(check, 100);
}, 100);
} | javascript | {
"resource": ""
} |
q32273 | modal | train | function modal(e) {
e.preventDefault();
// Remove the old listeners so we don't trigger the regular validation
Cortex.app('modal').off('done');
var self = this;
self.redirect = $(e.element).get('data-redirect');
if (!this.restore) this.restore = Cortex.app('modal').on('close', function () {
// The modal is closed, make sure that we still have a login state
// present or restore it with our cached content.
var modal = $('section.modal');
if (~modal.get('innerHTML').indexOf('type="password"')) return;
modal.set('innerHTML', self.content);
});
return this.render('login');
} | javascript | {
"resource": ""
} |
q32274 | forgotten | train | function forgotten() {
var self = this
, username = $('.modal input[name="username"]')
, button = $('.modal button[type="submit"]');
// Add an disabled state to the button as we are processing it
button.addClass('disabled loading')
.set('disabled', 'disabled')
.set('innerHTML', 'Submitting');
username = username.set('readOnly', true).get('value');
Cortex.request({
url: '/forgot'
, method: 'post'
, type: 'json'
, data: {
username: username
}
, success: function success(res) {
if (res.error) {
return self.render('forgot', {
error: 'Invalid user account'
, username: username
});
}
return self.render('forgot', {
success: 'We have sent an password reset request to your e-mail address'
, username: username
});
}
});
} | javascript | {
"resource": ""
} |
q32275 | validate | train | function validate(closed) {
if (closed) return;
var username = $('.modal input[name="username"]')
, password = $('.modal input[name="password"]')
, button = $('.modal button[type="submit"]')
, self = this;
// Add an disabled state to the button as we are processing it
button.addClass('disabled loading')
.set('disabled', 'disabled')
.set('innerHTML', 'Logging in');
username = username.set('readOnly', true).get('value');
password = password.set('readOnly', true).get('value');
// Show the spinner.
$('.modal .close').addClass('gone');
$('.modal .spinner').removeClass('gone');
Cortex.request({
url: '/signin/verify'
, method: 'post'
, type: 'json'
, data: {
username: username
, password: password
}
, success: function success(res) {
if (res.status === 'error') return self.render('login', {
error: res.message
, username: username
, password: password
});
$('.modal form').plain(0).submit();
}
});
return this;
} | javascript | {
"resource": ""
} |
q32276 | render | train | function render(name, data) {
var template;
if (name !== 'login') {
template = this.template(name, data || {});
template.where('name').is('username').use('username').as('value');
template.where('name').is('password').use('password').as('value');
if (data && data.error) {
template.className('error').use('error');
} else {
template.className('error').remove();
}
if (data && data.success) {
template.className('success').use('success');
} else {
template.className('success').remove();
}
} else if (data && data.error) {
// Hide the spinner and show the close button.
$('.modal .close').removeClass('gone');
$('.modal .spinner').addClass('gone');
// Login request, but with data.. so the login failed
$('.modal input[name="username"], .modal input[name="password"]').set(
'readOnly',
false
);
$('.modal button[type="submit"]')
.removeClass('disabled loading')
.set('innerHTML', 'Log in')
.set('disabled', '');
$('.modal .error').removeClass('gone').set('innerHTML', data.error);
}
Cortex.app('modal')
.render(template)
.once('done', this.close.bind(this, name));
//
// Check if we need to create a hidden input field with a redirect directive.
//
if (this.redirect) {
$('.modal form input[name="redirect"]').set('value', this.redirect);
}
return this;
} | javascript | {
"resource": ""
} |
q32277 | commandPluck | train | function commandPluck(context, componentIDs, attributes, options) {
// resolve the components to ids
let result;
let entitySet;
// if( true ){ log.debug('pluck> ' + stringify(_.rest(arguments))); }
attributes = context.valueOf(attributes, true);
attributes = Array.isArray(attributes) ? attributes : [attributes];
options = context.valueOf(options, true);
entitySet = context.resolveEntitySet();
// resolve the component ids
// componentIDs = context.valueOf(componentIDs,true);
// if( componentIDs ){
// componentIDs = context.registry.getIID( componentIDs, true );
// }
result = pluckEntitySet(
context.registry,
entitySet,
componentIDs,
attributes
);
if (options && options.unique) {
result = arrayUnique(result);
}
return context.last = [VALUE, result];
} | javascript | {
"resource": ""
} |
q32278 | expose | train | function expose(anchor, name, message) {
Object.defineProperty(errors[anchor], name, {
enumerable: true,
get: function() {
var err = new Error();
err.name = capitalize(anchor) + 'Error';
err.message = message;
Error.captureStackTrace(err, arguments.callee);
return err;
}
});
} | javascript | {
"resource": ""
} |
q32279 | Router | train | function Router() {
var self = this;
this.arr = [];
this.caseSensitive = true;
this.strict = false;
this.middleware = function router(msg, next) {
self._dispatch(msg, next);
};
} | javascript | {
"resource": ""
} |
q32280 | train | function(path, state) {
if (t.isStringLiteral(path.node.source, { value: 'react-dom' })) {
path.node.source = t.StringLiteral('react-native');
}
} | javascript | {
"resource": ""
} | |
q32281 | checkApiKey | train | function checkApiKey(key) {
if (!GLOBAL.config.apis || !GLOBAL.config.apis[key]) {
GLOBAL.error('no GLOBAL.config.apis.bing');
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q32282 | train | function(date, preventOnSelect)
{
if (!date) {
this._d = null;
return this.draw();
}
if (typeof date === 'string') {
date = new Date(Date.parse(date));
}
if (!isDate(date)) {
return;
}
var min = this._o.minDate,
max = this._o.maxDate;
if (isDate(min) && date < min) {
date = min;
} else if (isDate(max) && date > max) {
date = max;
}
this._d = new Date(date.getTime());
setToStartOfDay(this._d);
this.gotoDate(this._d);
if (this._o.field) {
this._o.field.value = this.toString();
fireEvent(this._o.field, 'change', { firedBy: this });
}
if (!preventOnSelect && typeof this._o.onSelect === 'function') {
this._o.onSelect.call(this, this.getDate());
}
} | javascript | {
"resource": ""
} | |
q32283 | train | function(date)
{
if (!isDate(date)) {
return;
}
this._y = date.getFullYear();
this._m = date.getMonth();
this.draw();
} | javascript | {
"resource": ""
} | |
q32284 | train | function(force)
{
if (!this._v && !force) {
return;
}
var opts = this._o,
minYear = opts.minYear,
maxYear = opts.maxYear,
minMonth = opts.minMonth,
maxMonth = opts.maxMonth;
if (this._y <= minYear) {
this._y = minYear;
if (!isNaN(minMonth) && this._m < minMonth) {
this._m = minMonth;
}
}
if (this._y >= maxYear) {
this._y = maxYear;
if (!isNaN(maxMonth) && this._m > maxMonth) {
this._m = maxMonth;
}
}
this.el.innerHTML = renderTitle(this) + this.render(this._y, this._m);
if (opts.bound) {
this.adjustPosition();
if(opts.field.type !== 'hidden') {
sto(function() {
opts.trigger.focus();
}, 1);
}
}
if (typeof this._o.onDraw === 'function') {
var self = this;
sto(function() {
self._o.onDraw.call(self);
}, 0);
}
} | javascript | {
"resource": ""
} | |
q32285 | train | function(year, month)
{
var opts = this._o,
now = new Date(),
days = getDaysInMonth(year, month),
before = new Date(year, month, 1).getDay(),
data = [],
row = [];
setToStartOfDay(now);
if (opts.firstDay > 0) {
before -= opts.firstDay;
if (before < 0) {
before += 7;
}
}
var cells = days + before,
after = cells;
while(after > 7) {
after -= 7;
}
cells += 7 - after;
for (var i = 0, r = 0; i < cells; i++)
{
var day = new Date(year, month, 1 + (i - before)),
isDisabled = (opts.minDate && day < opts.minDate) || (opts.maxDate && day > opts.maxDate),
isSelected = isDate(this._d) ? compareDates(day, this._d) : false,
isToday = compareDates(day, now),
isEmpty = i < before || i >= (days + before);
row.push(renderDay(1 + (i - before), isSelected, isToday, isDisabled, isEmpty));
if (++r === 7) {
data.push(renderRow(row, opts.isRTL));
row = [];
r = 0;
}
}
return renderTable(opts, data);
} | javascript | {
"resource": ""
} | |
q32286 | commandAlias | train | function commandAlias(context, name) {
let value;
context.alias = context.alias || {};
value = context.last;
name = context.valueOf(name, true);
value = context.valueOf(value, true);
if (context.debug) {
log.debug('cmd alias ' + stringify(name) + ' ' + stringify(value));
}
context.alias[name] = value;
return (context.last = [VALUE, value]);
} | javascript | {
"resource": ""
} |
q32287 | caller | train | function caller(instances, index, options) {
// at the moment we are only calling the first event,
// but lets start prepare the api for managin an array of events
return instances(options).then(function (_ref) {
var event = _ref.event,
eventName = _ref.eventName;
var shouldExit = typeof options.tick === 'function' ? options.tick(event, index) : false;
var newIndex = index + 1;
// if we havent reached the end of our cycle return a new caller
// otherwise just exit the recursive function
var eventObj = _eventProps2.default[eventName];
return newIndex >= options.steps || shouldExit ? event : caller(instances, newIndex, Object.assign({}, options, handlePathObj(options.path, event, eventObj, newIndex)));
});
} | javascript | {
"resource": ""
} |
q32288 | setContextPlugin | train | function setContextPlugin(options) {
var seneca = this;
var plugin = 'set-context';
options = seneca.util.deepextend({
createContext: createContext,
contextHeader: 'x-request-id'
}, options);
seneca.act({
role: 'web',
plugin: plugin,
use: processRequest.bind(null, options)
});
return {name: plugin};
} | javascript | {
"resource": ""
} |
q32289 | processRequest | train | function processRequest(options, req, res, next) {
debug('processing HTTP request');
var seneca = req.seneca;
options.createContext(req, res, createDefaultContext(options, req), function (error, context) {
if (error) {
next(error);
} else {
setContext(seneca, context);
next();
}
});
} | javascript | {
"resource": ""
} |
q32290 | createContext | train | function createContext(req, res, context, done) {
debug('default createContext - does nothing', context);
process.nextTick(done.bind(null, null, context));
} | javascript | {
"resource": ""
} |
q32291 | objectDeepFromEntries | train | function objectDeepFromEntries(entries) {
if (!isArray(entries)) {
throw new TypeError(
`Expected an array of entries. Received ${getTag(entries)}`
)
}
let res = {}
let isCollection = false
if (hasNumKey(entries)) {
res = []
isCollection = true
}
for (const entry of entries) {
let path = entry[0]
const value = entry[1]
if (!isArray(path)) {
path = [path]
}
const root = path.shift()
if (path.length === 0 && (isCollection && isNaN(root))) {
res.push({[root]: value})
} else if (path.length === 0) {
res[root] = value
} else if (isCollection && isNaN(root)) {
res.push({[root]: deepFromEntries(res[root], root, path, value)})
} else {
res[root] = deepFromEntries(res[root], root, path, value)
}
}
return res
} | javascript | {
"resource": ""
} |
q32292 | outerWidth | train | function outerWidth(margin) {
var s, style;
if(!this.length) {
return null;
}
s = this.dom[0].getClientRects()[0].width;
if(!margin) {
style = window.getComputedStyle(this.dom[0], null);
s -= parseInt(style.getPropertyValue('margin-top'));
s -= parseInt(style.getPropertyValue('margin-bottom'));
}
return s;
} | javascript | {
"resource": ""
} |
q32293 | outerHeight | train | function outerHeight(margin) {
var s, style;
if(!this.length) {
return null;
}
s = this.dom[0].getClientRects()[0].height;
if(!margin) {
style = window.getComputedStyle(this.dom[0], null);
s -= parseInt(style.getPropertyValue('margin-top'));
s -= parseInt(style.getPropertyValue('margin-bottom'));
}
return s;
} | javascript | {
"resource": ""
} |
q32294 | readDirStructure | train | async function readDirStructure(dirPath) {
if (!dirPath) {
throw new Error('Please specify a path to the directory')
}
const lstat = await makePromise(fs.lstat, dirPath)
if (!lstat.isDirectory()) {
const err = new Error('Path is not a directory')
err.code = 'ENOTDIR'
throw err
}
const dir = await makePromise(fs.readdir, dirPath)
const lstatRes = await lib.lstatFiles(dirPath, dir)
const directories = lstatRes.filter(isDirectory)
const notDirectories = lstatRes.filter(isNotDirectory)
const files = notDirectories.reduce((acc, lstatRes) => Object.assign(acc, {
[lstatRes.relativePath]: {
type: getType(lstatRes),
},
}), {})
const dirPromises = directories.map(async ({ path, relativePath }) => {
const structure = await readDirStructure(path)
return [relativePath, structure]
})
const dirsArray = await Promise.all(dirPromises)
const dirs = dirsArray.reduce(
(acc, [relativePath, structure]) => {
const d = { [relativePath]: structure }
return Object.assign(acc, d)
}, {}
)
const merged = Object.assign({}, files, dirs)
return {
type: 'Directory',
content: merged,
}
} | javascript | {
"resource": ""
} |
q32295 | fromEntries | train | function fromEntries(keys, values) {
return keys.reduce((obj, key, i) => {
obj[key] = values[i];
return obj;
}, {})
} | javascript | {
"resource": ""
} |
q32296 | isEmptyObj | train | function isEmptyObj(object) {
if(object === undefined)
return true;
var objToSend = JSON.parse(JSON.stringify(object));
var result = nestedEmptyCheck(objToSend);
if(JSON.stringify(result).indexOf('false') > -1)
return false;
return true;
} | javascript | {
"resource": ""
} |
q32297 | train | function(result) {
if (done) {
if (session.httpRequest && session.httpRequest.log) {
session.httpRequest.log.error("jsonrpc promise resolved after response sent:", req.method, "params:", req.params);
}
return;
}
return makeResult(req, result)
} | javascript | {
"resource": ""
} | |
q32298 | create | train | function create() {
function app(msg) { app.handle(msg); }
utils.merge(app, proto);
app.init();
for (var i = 0; i < arguments.length; ++i) {
app.use(arguments[i]);
}
return app;
} | javascript | {
"resource": ""
} |
q32299 | update | train | function update(app, target, source) {
for (var prop in source) {
if (!source.hasOwnProperty(prop)) continue;
var def = expandDefinition(app, prop, source[prop]);
if (prop in target) {
if (!def) {
delete target[prop];
} else if (def.route) {
debugger; //XXX
} else if (def.pathonly) {
target[prop].path = def.path;
} else {
//use defaults() instead of extends() so undefined are skipped
target[prop] = _.defaults({}, def, target[prop]);
}
} else if (!def.pathonly) {
if (typeof def.path === 'undefined')
def.path = prop; //use name as path
target[prop] = def;
}
}
return target;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.