_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q33100 | bubbleEvent | train | function bubbleEvent(eventName, toEmitter) {
this.on(eventName, (event) => {
toEmitter.emit(eventName, event.data, event);
});
} | javascript | {
"resource": ""
} |
q33101 | getListeners | train | function getListeners(eventName, handler, context, args) {
if (!this.__listeners || !this.__listeners[eventName]) {
return null;
}
return this.__listeners[eventName]
.map((config) => {
if (handler !== undefined && config.fn !== handler) {
return false;
}
if (context !== undefined && config.context !== context) {
return false;
}
if (args !== undefined && config.args !== args) {
return false;
}
return config;
})
.filter((result) => !!result);
} | javascript | {
"resource": ""
} |
q33102 | init | train | function init(shard, eid) { // {{{2
/**
* Entry constructor
*
* @param shard {Object} Entry owner shard instance
* @param eid {Number|String} Entry id
*
* @method constructor
*/
O.inherited(this)();
this.setMaxListeners(Consts.coreListeners);
this.subjectState = this.SUBJECT_STATE.INIT;
this.shard = shard; // {{{3
/**
* Reference to containing [shard]
*
* @property shard
* @type Object
*/
this.id = eid; // {{{3
/**
* Unique id of entry within containing [shard]
*
* @property id
* @type Integer
*/
// }}}3
if (eid in shard.cache) {
throw O.log.error(this, 'Duplicit eid', eid);
}
shard.cache[eid] = this;
} | javascript | {
"resource": ""
} |
q33103 | train | function(key) {
if (arguments.length === 0) {
// reset all values, including non-enumerable and readonly properties
this.key_list.forEach(function(key) {
this._reset(key);
}, this);
} else {
this._reset(key);
}
} | javascript | {
"resource": ""
} | |
q33104 | train | function(key) {
var attr = this.__attrs[key];
if (!attr) {
return;
}
var value = attr.value = attr._origin;
var setup = attr.type.setup;
if (setup) {
setup.call(this.host, value, key, this);
}
} | javascript | {
"resource": ""
} | |
q33105 | resolve | train | function resolve(ref, context) {
if (typeof ref !== 'string') return ref;
if (/^#/.test(ref)) { ref = (context._href || '/') + ref; }
return generator.fragment$[ref];
} | javascript | {
"resource": ""
} |
q33106 | pageLang | train | function pageLang(page) {
return page.lang ||
opts.lang ||
(opts.langDirs && !u.isRootLevel(page._href) && u.topLevel(page._href)) ||
'en';
} | javascript | {
"resource": ""
} |
q33107 | defaultFragmentHtml | train | function defaultFragmentHtml(fragmentName, faMarkdown, html, frame) {
var f = generator.fragment$[fragmentName];
if (f) return fragmentHtml(f);
if (faMarkdown && u.find(opts.pkgs, function(pkg) {
return ('pub-pkg-font-awesome' === pkg.pkgName);
})) {
return fragmentHtml( { _txt:faMarkdown, _href:'/#synthetic' }, {noWrap:1});
}
return /</.test(html) ? html :
fragmentHtml( {_txt:html, _href:'/#synthetic' }, {noWrap:1});
} | javascript | {
"resource": ""
} |
q33108 | el | train | function el(tag, attrs) {
var n = el.air(create(tag));
if(attrs && n.attr) {
return n.attr(attrs);
}
return n;
} | javascript | {
"resource": ""
} |
q33109 | Repo | train | function Repo(name, username) {
this.name = name;
this.username = username;
this.isLoaded = Deferred();
this.isCloned = Deferred();
this.isClonning = false;
this.branch = null;
} | javascript | {
"resource": ""
} |
q33110 | Route | train | function Route(topic, fns, options) {
options = options || {};
this.topic = topic;
this.fns = fns;
this.regexp = pattern.parse(topic
, this.keys = []
, options.sensitive
, options.strict);
} | javascript | {
"resource": ""
} |
q33111 | train | function() {
var current = $state.current();
if(current && current.url) {
var path;
path = current.url;
// Add parameters or use default parameters
var params = current.params || {};
var query = {};
for(var name in params) {
var re = new RegExp(':'+name, 'g');
if(path.match(re)) {
path = path.replace(re, params[name]);
} else {
query[name] = params[name];
}
}
$location.path(path);
$location.search(query);
_url = $location.url();
}
} | javascript | {
"resource": ""
} | |
q33112 | train | function (str) {
for (var bytes = [], i = 0; i < str.length; i++)
bytes.push(str.charCodeAt(i) & 0xFF);
return bytes;
} | javascript | {
"resource": ""
} | |
q33113 | train | function (bytes) {
for (var str = [], i = 0; i < bytes.length; i++)
str.push(String.fromCharCode(bytes[i]));
return str.join("");
} | javascript | {
"resource": ""
} | |
q33114 | train | function () {
// p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1
var p = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");
var a = BigInteger.ZERO;
var b = ec.fromHex("7");
var n = ec.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
var h = BigInteger.ONE;
var curve = new ec.CurveFp(p, a, b);
var G = curve.decodePointHex("04"
+ "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798"
+ "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8");
return new ec.X9Parameters(curve, G, n, h);
} | javascript | {
"resource": ""
} | |
q33115 | train | function (input) {
var bi = BigInteger.fromByteArrayUnsigned(input);
var chars = [];
while (bi.compareTo(B58.base) >= 0) {
var mod = bi.mod(B58.base);
chars.unshift(B58.alphabet[mod.intValue()]);
bi = bi.subtract(mod).divide(B58.base);
}
chars.unshift(B58.alphabet[bi.intValue()]);
// Convert leading zeros too.
for (var i = 0; i < input.length; i++) {
if (input[i] == 0x00) {
chars.unshift(B58.alphabet[0]);
} else break;
}
return chars.join('');
} | javascript | {
"resource": ""
} | |
q33116 | train | function (len, val) {
var array = [];
var i = 0;
while (i < len) {
array[i++] = val;
}
return array;
} | javascript | {
"resource": ""
} | |
q33117 | train | function (i) {
if (i < 0xfd) {
// unsigned char
return [i];
} else if (i <= 1 << 16) {
// unsigned short (LE)
return [0xfd, i >>> 8, i & 255];
} else if (i <= 1 << 32) {
// unsigned int (LE)
return [0xfe].concat(Crypto.util.wordsToBytes([i]));
} else {
// unsigned long long (LE)
return [0xff].concat(Crypto.util.wordsToBytes([i >>> 32, i]));
}
} | javascript | {
"resource": ""
} | |
q33118 | train | function (valueBuffer) {
var value = this.valueToBigInt(valueBuffer).toString();
var integerPart = value.length > 8 ? value.substr(0, value.length - 8) : '0';
var decimalPart = value.length > 8 ? value.substr(value.length - 8) : value;
while (decimalPart.length < 8) decimalPart = "0" + decimalPart;
decimalPart = decimalPart.replace(/0*$/, '');
while (decimalPart.length < 2) decimalPart += "0";
return integerPart + "." + decimalPart;
} | javascript | {
"resource": ""
} | |
q33119 | train | function (valueString) {
// TODO: Detect other number formats (e.g. comma as decimal separator)
var valueComp = valueString.split('.');
var integralPart = valueComp[0];
var fractionalPart = valueComp[1] || "0";
while (fractionalPart.length < 8) fractionalPart += "0";
fractionalPart = fractionalPart.replace(/^0+/g, '');
var value = BigInteger.valueOf(parseInt(integralPart));
value = value.multiply(BigInteger.valueOf(100000000));
value = value.add(BigInteger.valueOf(parseInt(fractionalPart)));
return value;
} | javascript | {
"resource": ""
} | |
q33120 | removeColon | train | function removeColon(protocol) {
return protocol && protocol.length && protocol[protocol.length - 1] === ':'
? protocol.substring(0, protocol.length - 1) : protocol;
} | javascript | {
"resource": ""
} |
q33121 | VegaWrapper | train | function VegaWrapper(wrapperOpts) {
var self = this;
// Copy all options into this object
self.objExtender = wrapperOpts.datalib.extend;
self.objExtender(self, wrapperOpts);
self.validators = {};
self.datalib.load.loader = function (opt, callback) {
var error = callback || function (e) { throw e; }, url;
try {
url = self.sanitizeUrl(opt); // enable override
} catch (err) {
error(err);
return;
}
// Process data response
var cb = function (error, data) {
return self.dataParser(error, data, opt, callback);
};
if (self.useXhr) {
return self.datalib.load.xhr(url, opt, cb);
} else {
return self.datalib.load.http(url, opt, cb);
}
};
self.datalib.load.sanitizeUrl = self.sanitizeUrl.bind(self);
// Prevent accidental use
self.datalib.load.file = alwaysFail;
if (self.useXhr) {
self.datalib.load.http = alwaysFail;
} else {
self.datalib.load.xhr = alwaysFail;
}
} | javascript | {
"resource": ""
} |
q33122 | _prepareViews | train | function _prepareViews( actionData, paramData )
{
let linkedTranssModules = actionData.linkedVTransModules, // look into slice speed over creating new array
ViewsModuleLength = linkedTranssModules.length,
promises = [],
preparedViews = [],
actionDataClone = null,
viewCache = {},
i = 0,
viewsModuleObject;
while( i < ViewsModuleLength ) {
viewsModuleObject = linkedTranssModules[i];
actionDataClone = _cloneViewState( actionData, viewsModuleObject, paramData );
preparedViews[ preparedViews.length ] = _fetchViews( viewsModuleObject.views, actionDataClone, promises, viewCache);
++i;
}
viewCache = null;
return { promises : promises, preparedViews : preparedViews };
} | javascript | {
"resource": ""
} |
q33123 | _fetchViews | train | function _fetchViews( viewsToPrepare, actionDataClone, promises, viewCache )
{
const views = viewsToPrepare,
viewManager = _options.viewManager,
length = views.length,
currentViewID = actionDataClone.currentViewID,
nextViewID = actionDataClone.nextViewID;
let i = 0,
_deferred,
view,
foundView,
parsedRef,
viewRef;
while( i < length )
{
viewRef = views[ i ];
if(viewRef)
{
foundView = viewCache[ viewRef ];
if(!foundView) { // cache the view instance for reuse if needed
foundView = viewCache[ viewRef ] = viewManager.fetchView( viewRef );
_deferred = Deferred();
promises[ promises.length ] = _deferred.promise;
if( !foundView ){ return TVM.error( viewRef+' is undefined' ); }
if( foundView.prepareView ){ foundView.prepareView( _deferred ); }
else { _deferred.resolve(); }
}
view = foundView;
/* change ref to current view or next view to allow general transitions */
parsedRef = _viewRef(viewRef, [ currentViewID, nextViewID ]);
if( parsedRef ) {
actionDataClone.views[ parsedRef ] = view;
}
actionDataClone.views[ viewRef ] = view;
}
++i;
}
return actionDataClone;
} | javascript | {
"resource": ""
} |
q33124 | _viewRef | train | function _viewRef( ref, comparisonViews ) {
var index = comparisonViews.indexOf( ref );
return (index === -1 )? null : ['currentView', 'nextView'][ index ];
} | javascript | {
"resource": ""
} |
q33125 | _getCached | train | function _getCached( cached, data )
{
if( !data ){ return cached; }
let i = -1, len = cached.length;
while (++i < len) {
cached[i].data = data;
}
return cached;
} | javascript | {
"resource": ""
} |
q33126 | _cloneViewState | train | function _cloneViewState( actionData, transitionObject, paramData ) {
return {
data : paramData,
currentViewID : actionData.currentView, // optional
nextViewID : actionData.nextView, // optional
views : {},
transitionType : transitionObject.transitionType
};
} | javascript | {
"resource": ""
} |
q33127 | parserOnHeaders | train | function parserOnHeaders(headers, url) {
// Once we exceeded headers limit - stop collecting them
if (this.maxHeaderPairs <= 0 ||
this._headers.length < this.maxHeaderPairs) {
this._headers = this._headers.concat(headers);
}
this._url += url;
} | javascript | {
"resource": ""
} |
q33128 | throwIf | train | function throwIf (target /*, illegal... */) {
Array.prototype.slice.call(arguments, 1).forEach(function (name) {
if (options[name]) {
throw new Error('Cannot set ' + name + ' and ' + target + 'together');
}
});
} | javascript | {
"resource": ""
} |
q33129 | train | function()
{
this.appendView
(
new ns.MyLoadedView(this.context.addTo({templateUrl:'template-2.html'})),
new ns.MyOtherView(this.context.addTo({template:'This is an internal template using <b>options.template</b> that hates <span cb-style="favoriteColor:color">{{favoriteColor}}</span>'}))
);
} | javascript | {
"resource": ""
} | |
q33130 | Log | train | function Log() {
var args = CopyArguments(arguments);
var level = args.shift();
args.unshift("[Thread] <"+threadId+">");
args.unshift(level);
process.send({name: "thread-log", args: SerializeForProcess(args)});
} | javascript | {
"resource": ""
} |
q33131 | ConvertArgs | train | function ConvertArgs(args, baseResponse) {
var baseResponse = Object.assign({}, baseResponse);
args.forEach(function(arg, i) {
if (typeof(arg) == "object" && arg._classname == "SerializedFunction") {
var idRemoteFunction = arg.id;
args[i] = function() {
process.send(Object.assign(baseResponse, {name: "thread-execute-remote-function", args: [{id: idRemoteFunction, args: SerializeForProcess(CopyArguments(arguments))}]}));
};
}
});
return args;
} | javascript | {
"resource": ""
} |
q33132 | finalizeRequestDone | train | function finalizeRequestDone() {
if (PendingRequests.length) {
// If we have queued requests, we execute the next one
currentRequest = PendingRequests.shift();
Log(3, "Executing request", currentRequest.id);
executeRequest(currentRequest);
} else {
// We set a timeout in case of other requests blocked in the process
executing = false;
PendingTimeout = setTimeout(() => {
if (Object.keys(PendingRequests).length == 0) {
// Telling main thread that he can kill us if he wants
Log(3, "Inactive thread");
process.send({name: "thread-no-pending-requests", args: [{threadId: threadId}]});
}
}, 1000);
}
} | javascript | {
"resource": ""
} |
q33133 | _includeCSSInternal | train | function _includeCSSInternal (css) {
var head,
style = document.getElementById(_stylesheetTagID);
if (!style) {
// there's no our styles tag - create
style = document.createElement('style');
style.setAttribute('id', _stylesheetTagID);
style.setAttribute('type', 'text/css');
head = document.getElementsByTagName('head')[0];
head.appendChild(style);
}
if (style.styleSheet) { // IE
style.styleSheet.cssText += css;
} else { // the others
style.appendChild(document.createTextNode(css));
}
} | javascript | {
"resource": ""
} |
q33134 | train | function (css, name) {
if (typeof css === "function") { css = css(); }
if (!css) { return; }
if (!name) {
_includeCSSInternal(css);
} else if (!_stylesheetFiles[name]) {
_includeCSSInternal(css);
_stylesheetFiles[name] = true;
}
} | javascript | {
"resource": ""
} | |
q33135 | clear | train | function clear() {
timeouts.forEach((callback, timeout) => {
clearTimeout(timeout);
// reject Promise or execute callback which returns Error
callback();
});
const length = size();
cache.clear();
return length;
} | javascript | {
"resource": ""
} |
q33136 | put | train | function put(key, value, timeout, callback) {
// key type is incorrect
if (typeof key !== 'string' && typeof key !== 'number' && typeof key !== 'boolean') {
throw new TypeError(`key can be only: string | number | boolean instead of ${typeof key}`);
}
// check if key is not NaN
if (typeof key === 'number' && isNaN(key)) {
throw new TypeError('key can be only: string | number | boolean instead of NaN');
}
// timeout type is incorrect and/or timeout is not positive number
if (timeout !== undefined && (typeof timeout !== 'number' || isNaN(timeout) || timeout <= 0)) {
throw new TypeError('timeout should be positive number');
}
// callback type is incorrect
if (callback !== undefined && typeof callback !== 'function') {
throw new TypeError(`callback should be function instead of ${typeof callback}`);
}
// key does exist
if (has(key)) {
return false;
}
cache.set(key, value);
// return Promise
if (timeout !== undefined && callback === undefined) {
return new Promise((resolve, reject) => {
const t = setTimeout(() => {
if (cache.delete(key)) {
resolve({ key, value, timeout });
} else {
reject(new Error(`${key} does not exist`));
}
}, timeout);
timeouts.set(t, () => reject(new Error(`${key} timeout was cleared`)));
});
}
// execute callback
if (timeout !== undefined && callback !== undefined) {
const t = setTimeout(() => {
if (cache.delete(key)) {
callback(null, key, value, timeout);
} else {
callback(new Error(`${key} does not exist`));
}
}, timeout);
timeouts.set(t, () => callback(new Error(`${key} timeout was cleared`)));
}
return true;
} | javascript | {
"resource": ""
} |
q33137 | Option | train | function Option(flags, description) {
this.flags = flags;
this.required = ~flags.indexOf('<');
this.optional = ~flags.indexOf('[');
this.bool = !~flags.indexOf('-no-');
flags = flags.split(/[ ,|]+/);
if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();
this.long = flags.shift();
this.description = description || '';
} | javascript | {
"resource": ""
} |
q33138 | train | function() {
// Reset views
var resetPromised = {};
angular.forEach(_activeSet, function(view, id) {
resetPromised[id] = $q.when(view.reset());
});
// Empty active set
_activeSet = {};
return $q.all(resetPromised);
} | javascript | {
"resource": ""
} | |
q33139 | train | function(id, view, data, controller) {
return _getTemplate(data).then(function(template) {
// Controller
if(controller) {
var current = $state.current();
return view.render(template, controller, current.locals);
// Template only
} else {
return view.render(template);
}
});
} | javascript | {
"resource": ""
} | |
q33140 | train | function(callback) {
// Activate current
var current = $state.current();
if(current) {
// Reset
_resetActive().then(function() {
// Render
var viewsPromised = {};
var templates = current.templates || {};
var controllers = current.controllers || {};
angular.forEach(templates, function(template, id) {
if(_viewHash[id]) {
var view = _viewHash[id];
var controller = controllers[id];
viewsPromised[id] = _renderView(id, view, template, controller);
_activeSet[id] = view;
}
});
$q.all(viewsPromised).then(function() {
callback();
}, callback);
}, callback);
// None
} else {
callback();
}
} | javascript | {
"resource": ""
} | |
q33141 | train | function(id, view) {
// No id
if(!id) {
throw new Error('View requires an id.');
// Require unique id
} else if(_viewHash[id]) {
throw new Error('View requires a unique id');
// Add
} else {
_viewHash[id] = view;
}
// Check if view is currently active
var current = $state.current() || {};
var templates = current.templates || {};
var controllers = current.controllers || {};
if(!!templates[id]) {
_renderView(id, view, templates[id], controllers[id]);
}
// Implement destroy method
view.destroy = function() {
_unregister(id);
};
return view;
} | javascript | {
"resource": ""
} | |
q33142 | read | train | function read (req, res, next, parse, debug, options) {
var length
var opts = options || {}
var stream
// flag as parsed
req._body = true
// read options
var encoding = opts.encoding !== null
? opts.encoding || 'utf-8'
: null
var verify = opts.verify
try {
// get the content stream
stream = contentstream(req, debug, opts.inflate)
length = stream.length
stream.length = undefined
} catch (err) {
return next(err)
}
// set raw-body options
opts.length = length
opts.encoding = verify
? null
: encoding
// assert charset is supported
if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase()
}))
}
// read body
debug('read body')
getBody(stream, opts, function (err, body) {
if (err) {
// default to 400
setErrorStatus(err, 400)
// echo back charset
if (err.type === 'encoding.unsupported') {
err = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
charset: encoding.toLowerCase()
})
}
// read off entire request
stream.resume()
onFinished(req, function onfinished () {
next(err)
})
return
}
// verify
if (verify) {
try {
debug('verify body')
verify(req, res, body, encoding)
} catch (err) {
// default to 403
setErrorStatus(err, 403)
next(err)
return
}
}
// parse
var str
try {
debug('parse body')
str = typeof body !== 'string' && encoding !== null
? iconv.decode(body, encoding)
: body
req.body = parse(str)
} catch (err) {
err.body = str === undefined
? body
: str
// default to 400
setErrorStatus(err, 400)
next(err)
return
}
next()
})
} | javascript | {
"resource": ""
} |
q33143 | contentstream | train | function contentstream (req, debug, inflate) {
var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
var length = req.headers['content-length']
var stream
debug('content-encoding "%s"', encoding)
if (inflate === false && encoding !== 'identity') {
throw createError(415, 'content encoding unsupported')
}
switch (encoding) {
case 'deflate':
stream = zlib.createInflate()
debug('inflate body')
req.pipe(stream)
break
case 'gzip':
stream = zlib.createGunzip()
debug('gunzip body')
req.pipe(stream)
break
case 'identity':
stream = req
stream.length = length
break
default:
throw createError(415, 'unsupported content encoding "' + encoding + '"', {
encoding: encoding
})
}
return stream
} | javascript | {
"resource": ""
} |
q33144 | setErrorStatus | train | function setErrorStatus (error, status) {
if (!error.status && !error.statusCode) {
error.status = status
error.statusCode = status
}
} | javascript | {
"resource": ""
} |
q33145 | syncContents | train | function syncContents(file, val) {
switch (utils.typeOf(val)) {
case 'buffer':
file._contents = val;
file._content = val.toString();
break;
case 'string':
file._contents = new Buffer(val);
file._content = val;
break;
case 'stream':
file._contents = val;
file._content = val;
break;
case 'undefined':
case 'null':
default: {
file._contents = null;
file._content = null;
break;
}
}
} | javascript | {
"resource": ""
} |
q33146 | createElement | train | function createElement(nodeName) {
var elem = document.createElement(nodeName);
elem.className = [].join.call(arguments, ' ');
return elem;
} | javascript | {
"resource": ""
} |
q33147 | createSliderElement | train | function createSliderElement(slidesCount) {
var sliderElement = createElement('div', Layout.SLIDER);
for (var i = 0; i < slidesCount; ++i) {
sliderElement.appendChild(createElement('div', Layout.SLIDE));
}
return sliderElement;
} | javascript | {
"resource": ""
} |
q33148 | OPTICS | train | function OPTICS(dataset, epsilon, minPts, distanceFunction) {
this.tree = null;
/** @type {number} */
this.epsilon = 1;
/** @type {number} */
this.minPts = 1;
/** @type {function} */
this.distance = this._euclideanDistance;
// temporary variables used during computation
/** @type {Array} */
this._reachability = [];
/** @type {Array} */
this._processed = [];
/** @type {number} */
this._coreDistance = 0;
/** @type {Array} */
this._orderedList = [];
this._init(dataset, epsilon, minPts, distanceFunction);
} | javascript | {
"resource": ""
} |
q33149 | createElement | train | function createElement(filePath, props) {
if (!filePath || typeof filePath !== 'string' || filePath.length === 0) {
throw new Error('Expected filePath to be a string');
}
// clear the require cache if we have already imported the file (if we are watching it)
if (require.cache[filePath]) {
delete require.cache[filePath];
}
var component = require(filePath); // eslint-disable-line global-require, import/no-dynamic-require
var element = _react2.default.createElement(component.default || component, props || {});
return element;
} | javascript | {
"resource": ""
} |
q33150 | transformForIn | train | function transformForIn(node, path) {
var label = node.$label;
delete node.$label;
var idx = ident(generateSymbol("idx"));
var inArray = ident(generateSymbol("in"));
var declVars = parsePart("var $0,$1 = [];for ($0 in $2) $1.push($0)", [idx,
inArray,node.right]).body;
var loop = parsePart("for ($0; $1.length;){ $2 = $1.shift(); $:3 ; }", [node.left,
inArray,node.left.type === 'VariableDeclaration' ? node.left.declarations[0].id : node.left,
node.body]).body[0];
loop.$label = label;
for (var b = 0;b < path.length; b++) {
if (examine(path[b].parent).isBlockStatement) {
path[b].parent[path[b].field].splice(path[b].index, 0, declVars[0], declVars[1]);
break;
}
}
coerce(node, loop);
} | javascript | {
"resource": ""
} |
q33151 | iterizeForOf | train | function iterizeForOf(node, path) {
if (node.body.type !== 'BlockStatement') {
node.body = {
type: 'BlockStatement',
body: [node.body]
};
}
var index, iterator, initIterator = parsePart("[$0[Symbol.iterator]()]", [node.right]).expr;
if (node.left.type === 'VariableDeclaration') {
if (node.left.kind === 'const')
node.left.kind = 'let';
if (node.left.kind === 'let') {
node.update = literal(null) ;
node.update.$EmptyExpression = true ;
}
index = node.left.declarations[0].id;
var decls = getDeclNames(node.left.declarations[0].id);
iterator = ident(generateSymbol("iterator_" + decls.join('_')));
node.left.declarations = decls.map(function (name) {
return {
type: "VariableDeclarator",
id: ident(name)
};
});
node.left.declarations.push({
type: "VariableDeclarator",
id: iterator,
init: initIterator
});
node.init = node.left;
} else {
index = node.left;
iterator = ident(generateSymbol("iterator_" + index.name));
var declaration = {
type: 'VariableDeclaration',
kind: 'var',
declarations: [{
type: "VariableDeclarator",
id: iterator,
init: initIterator
}]
};
node.init = declaration;
}
node.type = 'ForStatement';
node.test = parsePart("!($0[1] = $0[0].next()).done && (($1 = $0[1].value) || true)", [iterator,
index]).expr;
delete node.left;
delete node.right;
} | javascript | {
"resource": ""
} |
q33152 | mappableLoop | train | function mappableLoop(n) {
return n.type === 'AwaitExpression' && !n.$hidden || inAsyncLoop && (n.type === 'BreakStatement' || n.type === 'ContinueStatement') && n.label;
} | javascript | {
"resource": ""
} |
q33153 | train | function (label) {
return {
type: 'ReturnStatement',
argument: {
type: 'UnaryExpression',
operator: 'void',
prefix: true,
argument: {
type: 'CallExpression',
callee: ident(label || symExit),
arguments: []
}
}
};
} | javascript | {
"resource": ""
} | |
q33154 | checkRequiredFiles | train | function checkRequiredFiles() {
const indexHtmlExists = fse.existsSync(paths.indexHtml);
const indexJsExists = fse.existsSync(paths.indexJs);
if (!indexHtmlExists || !indexJsExists) {
logError('\nSome required files couldn\'t be found. Make sure these all exist:\n');
logError(`\t- ${paths.indexHtml}`);
logError(`\t- ${paths.indexJs}\n`);
process.exit(1);
}
} | javascript | {
"resource": ""
} |
q33155 | printErrors | train | function printErrors(summary, errors) {
logError(`${summary}\n`);
errors.forEach(err => {
logError(`\t- ${err.message || err}`);
});
console.log();
} | javascript | {
"resource": ""
} |
q33156 | changeAnnotationState | train | function changeAnnotationState(combo, username) {
combo.annotations.forEach(function(anno) {
anno.state = combo.state;
});
contentLib.indexContentItem({uri: combo.uri}, { member: username , annotations: combo.annotations} );
} | javascript | {
"resource": ""
} |
q33157 | publishUpdate | train | function publishUpdate(combo) {
GLOBAL.svc.indexer.retrieveByURI(combo.uri, function(err, res) {
if (!err && res && res._source) {
res = res._source;
combo.selector = 'body';
combo.text = res.text;
combo.content = res.content;
fayeClient.publish('/item/annotations/annotate' + (combo.member ? '/' + combo.member.replace(/ /g, '_') : ''), combo);
debounceUpdate(combo);
} else {
GLOBAL.error('not annotated', err, combo);
}
});
} | javascript | {
"resource": ""
} |
q33158 | debounceUpdate | train | function debounceUpdate(combo) {
bouncedUpdates[combo.uri] = combo;
if (Object.keys(bouncedUpdates).length < bounceHold) {
clearTimeout(bounceTimeout);
bounceTimeout = setTimeout(function() {
var toDebounce = Object.keys(bouncedUpdates).map(function(b) { return bouncedUpdates[b]; });
bouncedUpdates = {};
fayeClient.publish('/item/updated', toDebounce);
}, bounceDelay);
}
} | javascript | {
"resource": ""
} |
q33159 | adjureAnnotators | train | function adjureAnnotators(uris, annotators) {
GLOBAL.info('/item/annotations/adjure annotators'.yellow, uris, JSON.stringify(annotators));
uris.forEach(function(uri) {
annotators.forEach(function(member) {
publishUpdate({ uri: uri, member: member});
});
});
} | javascript | {
"resource": ""
} |
q33160 | adjureAnnotations | train | function adjureAnnotations(uris, annotations, username) {
GLOBAL.info('/item/annotations/adjure annotations'.yellow, username.blue, uris, annotations.length);
try {
var user = GLOBAL.svc.auth.getUserByUsername(username);
if (!user) {
throw new Error("no user " + username);
}
uris.forEach(function(uri) {
var annos = [];
// TODO apply validation state based on user
annotations.forEach(function(p) {
p.roots = p.roots || [username];
p.annotatedBy = username;
p.state = utils.states.annotations.unvalidated;
if (!user.needsValidation) {
p.state = utils.states.annotations.validated;
}
p.hasTarget = uri;
var a = annoLib.createAnnotation(p);
annos.push(a);
});
contentLib.saveAnnotations(uri, { member: username }, annos, function(err, res, cItem) {
if (cItem) {
debounceUpdate(cItem);
} else {
utils.passingError('missing cItem');
}
});
});
} catch (err) {
GLOBAL.error('saveAnnotations failed', err);
console.trace();
}
} | javascript | {
"resource": ""
} |
q33161 | publish | train | function publish(channel, data, clientID) {
if (clientID) {
channel += '/' + clientID;
}
fayeClient.publish(channel, data);
} | javascript | {
"resource": ""
} |
q33162 | MbaasClient | train | function MbaasClient(envId, mbaasConf) {
this.envId = envId;
this.mbaasConfig = mbaasConf;
this.setMbaasUrl();
this.app = {};
this.admin = {};
proxy(this.app, app, this.mbaasConfig);
proxy(this.admin, admin, this.mbaasConfig);
} | javascript | {
"resource": ""
} |
q33163 | roundRat | train | function roundRat (f) {
var a = f[0]
var b = f[1]
if (a.cmpn(0) === 0) {
return 0
}
var h = a.abs().divmod(b.abs())
var iv = h.div
var x = bn2num(iv)
var ir = h.mod
var sgn = (a.negative !== b.negative) ? -1 : 1
if (ir.cmpn(0) === 0) {
return sgn * x
}
if (x) {
var s = ctz(x) + 4
var y = bn2num(ir.ushln(s).divRound(b))
return sgn * (x + y * Math.pow(2, -s))
} else {
var ybits = b.bitLength() - ir.bitLength() + 53
var y = bn2num(ir.ushln(ybits).divRound(b))
if (ybits < 1023) {
return sgn * y * Math.pow(2, -ybits)
}
y *= Math.pow(2, -1023)
return sgn * y * Math.pow(2, 1023 - ybits)
}
} | javascript | {
"resource": ""
} |
q33164 | train | function(req, token, refreshToken, profile, done) {
// asynchronous
process.nextTick(function() {
var User = app.userModel;
// find the user in the database based on their facebook id
User.findOne({ 'facebook.id' : profile.id }, function(err, user) {
// if there is an error, stop everything and return that
// ie an error connecting to the database
if (err)
return done(err);
// if the user is found, then log them in
if (user) {
if (req.session.reauthenticate) {
delete req.session.reauthenticate;
req.session.loginTime = new Date();
}
return done(null, user); // user found, return that user
} else {
// if there is no user found with that facebook id, create them
var newUser = new User();
// set all of the facebook information in our user model
newUser.facebook.id = profile.id; // set the users facebook id
newUser.facebook.token = token; // we will save the token that facebook provides to the user
newUser.facebook.name = profile.name.givenName + ' ' + profile.name.familyName; // look at the passport user profile to see how names are returned
newUser.facebook.email = profile.emails[0].value; // facebook can return multiple emails so we'll take the first
//XXX if the user with that email already exists -- associate with facebook (prompt for password?)
//XXX need a way for a currently logged in user to login to facebook and associate accounts
// save our user to the database
newUser.save(function(err) {
if (err)
return done(err);
if (req.session.reauthenticate) {
delete req.session.reauthenticate;
req.session.loginTime = new Date();
}
// if successful, return the new user
return done(null, newUser);
});
}
});
});
} | javascript | {
"resource": ""
} | |
q33165 | listNotifications | train | function listNotifications(params, cb) {
params.resourcePath = config.addURIParams(constants.NOTIFICATIONS_BASE_PATH, params);
params.method = 'GET';
params.data = params.data || {};
mbaasRequest.admin(params, cb);
} | javascript | {
"resource": ""
} |
q33166 | boot | train | function boot(containerElement) {
check(containerElement, 'containerElement').is.anInstanceOf(Element)();
var containerOptions = getEnabledOptions(containerElement);
var sliderElems = concatUnique(
[].slice.call(containerElement.querySelectorAll('.'+ Layout.SLIDER)),
[].slice.call(containerElement.querySelectorAll('.'+ Common.SLIDER_SHORT))
);
var sliders = sliderElems.map(function(elem) {
containerOptions.forEach(function(option) {
if (elem.classList.contains(option)) {
return;
}
elem.classList.add(option);
});
return new Slider(elem);
});
sliders.forEach(function(slider) { slider.start(); });
return sliders;
} | javascript | {
"resource": ""
} |
q33167 | getEnabledOptions | train | function getEnabledOptions(element) {
var retVal = [];
Object.values(Option).forEach(function(option) {
if (element.classList.contains(option)) {
retVal.push(option);
}
});
return retVal;
} | javascript | {
"resource": ""
} |
q33168 | publisher | train | function publisher(port) {
var socket = zeromq.socket('pub');
socket.identity = 'pub' + process.pid;
socket.connect(port);
console.log('publisher connected to ' + port);
// lets count messages / sec
var totalMessages=0;
setInterval(function() {
console.log('total messages sent = '+totalMessages);
totalMessages=0;
// now fire messages
for(var i=0;i<5000;i++) {
var value = Math.random()*1000;
socket.send('log ' + value);
totalMessages++;
}
}, 1000);
} | javascript | {
"resource": ""
} |
q33169 | subscriber | train | function subscriber(port) {
var socket = zeromq.socket('sub');
socket.identity = 'sub' + process.pid;
// have to subscribe, otherwise nothing would show up
// subscribe to everything
socket.subscribe('');
var totalMessages=0;
// receive messages
socket.on('message', function(data) {
//console.log(socket.identity + ': received data ' + data.toString());
totalMessages++;
});
socket.connect(port);
console.log('connected to ' + port);
// lets count messages recvd
setInterval(function() {
console.log('messages received = ' + totalMessages);
totalMessages=0;
}, 1000);
} | javascript | {
"resource": ""
} |
q33170 | forwarder | train | function forwarder(frontPort, backPort) {
var frontSocket = zeromq.socket('sub'),
backSocket = zeromq.socket('pub');
frontSocket.identity = 'sub' + process.pid;
backSocket.identity = 'pub' + process.pid;
frontSocket.subscribe('');
frontSocket.bind(frontPort, function (err) {
console.log('bound', frontPort);
});
var totalMessages=0;
frontSocket.on('message', function() {
//pass to back
//console.log('forwarder: recasting', arguments[0].toString());
backSocket.send(Array.prototype.slice.call(arguments));
totalMessages++;
});
backSocket.bind(backPort, function (err) {
console.log('bound', backPort);
});
// lets count messages forwarded
setInterval(function() {
console.log('messages forwarded = ' + totalMessages);
totalMessages=0;
}, 1000);
} | javascript | {
"resource": ""
} |
q33171 | createComponent | train | function createComponent(loader, obj) {
const entitySet = loader.entitySet;
// determine whether any attributes are refering to marked pois
obj = resolveMarkReferences(loader, obj);
// the alternative form is to use @uri
if (obj[CMD_COMPONENT_URI]) {
obj[CMD_COMPONENT] = obj[CMD_COMPONENT_URI];
delete obj[CMD_COMPONENT_URI];
}
if( obj[CMD_COMPONENT] === undefined ){
throw new Error('invalid create component command');
}
const component = loader.registry.createComponent(obj);
return Promise.resolve(component)
.then(component => {
if (!loader.entity) {
return _createEntity(loader, null, { shadow: true });
}
// Log.debug('[createComponent]', 'adding to existing entity', loader.entity.id);
return component;
})
.then(() => loader.entity.addComponent(component))
.then(() => component);
// loader.entity.addComponent( component );
// return Promise.resolve(component);
} | javascript | {
"resource": ""
} |
q33172 | retrieveEntityByAttribute | train | async function retrieveEntityByAttribute(
entitySet,
componentID,
attribute,
value
) {
// Log.debug('[retrieveEntityByAttribute]', componentID, 'where', attribute, 'equals', value);
const query = Q => [
Q.all(componentID).where(Q.attr(attribute).equals(value)),
Q.limit(1)
];
if (entitySet.isAsync) {
const existing = await entitySet.query(query, { debug: false });
// Log.debug('[retrieveEntityByAttribute]', entityToString( existing));
if (existing.size() === 1) {
return existing.at(0);
}
return null;
} else {
return Promise.resolve(true).then(() => {
const existing = entitySet.query(query);
// Log.debug('[retrieveEntityByAttribute]', 'query result', existing.size(), entityToString(existing), componentID, attribute, value );
if (existing.size() === 1) {
return existing.at(0);
}
return null;
});
}
} | javascript | {
"resource": ""
} |
q33173 | train | function(apiClient) {
this.apiClient = apiClient || ApiClient.instance;
/**
* Callback function to receive the result of the closeSessions operation.
* @callback module:api/SessionApi~closeSessionsCallback
* @param {String} error Error message, if any.
* @param {module:model/RestOK} data The data returned by the service call.
* @param {String} response The complete HTTP response.
*/
/**
* Closes session with timeout. Targets are selected by same rule to findSessions() op. While targeting multiple sessions, this operation requires same access rights with findSessions(). Closing a single session requires 'same session id' or 'unrestricted workspace acceess'.
* @param {String} sessionId webida session id (usually different from socket id from sock.io)
* @param {String} workspaceId webida workspace id in query part
* @param {Integer} closeAfter Waiting time before actual closing, to let client save files and prevent reconnecting.
* @param {module:api/SessionApi~closeSessionsCallback} callback The callback function, accepting three arguments: error, data, response
* data is of type: {module:model/RestOK}
*/
this.closeSessions = function(sessionId, workspaceId, closeAfter, callback) {
var postBody = null;
// verify the required parameter 'sessionId' is set
if (sessionId == undefined || sessionId == null) {
throw "Missing the required parameter 'sessionId' when calling closeSessions";
}
// verify the required parameter 'workspaceId' is set
if (workspaceId == undefined || workspaceId == null) {
throw "Missing the required parameter 'workspaceId' when calling closeSessions";
}
// verify the required parameter 'closeAfter' is set
if (closeAfter == undefined || closeAfter == null) {
throw "Missing the required parameter 'closeAfter' when calling closeSessions";
}
var pathParams = {
'sessionId': sessionId
};
var queryParams = {
'workspaceId': workspaceId,
'closeAfter': closeAfter
};
var headerParams = {
};
var formParams = {
};
var authNames = ['webida-simple-auth'];
var contentTypes = ['application/json'];
var accepts = ['application/json', 'application/octet-stream'];
var returnType = RestOK;
return this.apiClient.callApi(
'/sessions/{sessionId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType, callback
);
}
/**
* Callback function to receive the result of the findSessions operation.
* @callback module:api/SessionApi~findSessionsCallback
* @param {String} error Error message, if any.
* @param {Array.<module:model/Session>} data The data returned by the service call.
* @param {String} response The complete HTTP response.
*/
/**
* Finds webida sessions established to server. if session id is given, matched session info will be returned and workspace id parameter will be ignored. To find all sessions of some workspace, set session id to '*' and specify workspace id. This operation requires proper accsss rights. 1) To find all sessions, an unrestricted token is required. 2) To find some workspace sesions, token should have proper access right on the workspace.
* @param {String} sessionId webida session id (usually different from socket id from sock.io)
* @param {String} workspaceId webida workspace id in query part
* @param {module:api/SessionApi~findSessionsCallback} callback The callback function, accepting three arguments: error, data, response
* data is of type: {Array.<module:model/Session>}
*/
this.findSessions = function(sessionId, workspaceId, callback) {
var postBody = null;
// verify the required parameter 'sessionId' is set
if (sessionId == undefined || sessionId == null) {
throw "Missing the required parameter 'sessionId' when calling findSessions";
}
// verify the required parameter 'workspaceId' is set
if (workspaceId == undefined || workspaceId == null) {
throw "Missing the required parameter 'workspaceId' when calling findSessions";
}
var pathParams = {
'sessionId': sessionId
};
var queryParams = {
'workspaceId': workspaceId
};
var headerParams = {
};
var formParams = {
};
var authNames = ['webida-simple-auth'];
var contentTypes = ['application/json'];
var accepts = ['application/json', 'application/octet-stream'];
var returnType = [Session];
return this.apiClient.callApi(
'/sessions/{sessionId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
authNames, contentTypes, accepts, returnType, callback
);
}
} | javascript | {
"resource": ""
} | |
q33174 | relativePathTo | train | function relativePathTo(from, to, strip) {
var relPath = path.relative(from.replace(path.basename(from), ''), to);
if (relPath.match(/^\.\.?(\/|\\)/) === null) { relPath = './' + relPath; }
if (strip) { return relPath.replace(/((\/|\\)index\.js|\.js)$/, ''); }
return relPath;
} | javascript | {
"resource": ""
} |
q33175 | filterFile | train | function filterFile(template) {
// Find matches for parans
var filterMatches = template.match(/\(([^)]+)\)/g);
var filters = [];
if (filterMatches) {
filterMatches.forEach(function(filter) {
filters.push(filter.replace('(', '').replace(')', ''));
template = template.replace(filter, '');
});
}
return { name: template, filters: filters };
} | javascript | {
"resource": ""
} |
q33176 | templateIsUsable | train | function templateIsUsable(self, filteredFile) {
var filters = self.config.get('filters');
var enabledFilters = [];
for (var key in filters) {
if (filters[key]) { enabledFilters.push(key); }
}
var matchedFilters = self._.intersection(filteredFile.filters, enabledFilters);
// check that all filters on file are matched
if (filteredFile.filters.length && matchedFilters.length !== filteredFile.filters.length) {
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q33177 | format | train | function format(obj) {
var parameters = obj.parameters
var type = obj.type
if (!type || typeof type !== 'string' || !tokenRegExp.test(type)) {
throw new TypeError('invalid type')
}
// start with normalized type
var string = String(type).toLowerCase()
// append parameters
if (parameters && typeof parameters === 'object') {
var param
var params = Object.keys(parameters).sort()
for (var i = 0; i < params.length; i++) {
param = params[i]
var val = param.substr(-1) === '*'
? ustring(parameters[param])
: qstring(parameters[param])
string += '; ' + param + '=' + val
}
}
return string
} | javascript | {
"resource": ""
} |
q33178 | pencode | train | function pencode(char) {
var hex = String(char)
.charCodeAt(0)
.toString(16)
.toUpperCase()
return hex.length === 1
? '%0' + hex
: '%' + hex
} | javascript | {
"resource": ""
} |
q33179 | Contour | train | function Contour(options) {
var contour = this
, assets;
this.fuse();
//
// Add the pagelets of the required framework.
//
options = options || {};
//
// Load and optimize the pagelets, extend contour but acknowledge external
// listeners when all pagelets have been fully initialized.
//
assets = new Assets(options.brand, options.mode || 'bigpipe');
assets.on('optimized', this.emits('init'));
this.mixin(this, assets);
} | javascript | {
"resource": ""
} |
q33180 | defaultGetCallingScript | train | function defaultGetCallingScript(offset = 0) {
const stack = (new Error).stack.split(/$/m);
const line = stack[(/^Error/).test(stack[0]) + 1 + offset];
const parts = line.split(/@(?![^/]*?\.xpi)|\(|\s+/g);
return parts[parts.length - 1].replace(/:\d+(?::\d+)?\)?$/, '');
} | javascript | {
"resource": ""
} |
q33181 | next | train | function next(exp) {
exp.lastIndex = index;
const match = exp.exec(code)[0];
index = exp.lastIndex;
return match;
} | javascript | {
"resource": ""
} |
q33182 | Assets | train | function Assets(brand, mode) {
var readable = Assets.predefine(this, Assets.predefine.READABLE)
, enumerable = Assets.predefine(this, { configurable: false })
, self = this
, i = 0
, files;
/**
* Callback to emit optimized event after all Pagelets have been optimized.
*
* @param {Error} error
* @api private
*/
function next(error) {
if (error) return self.emit('error', error);
if (++i === files.length) self.emit('optimized');
}
//
// Default framework to use with reference to the path to core.styl.
//
readable('brand', brand = brand || 'nodejitsu');
//
// Load all assets of the branch.
//
(files = fs.readdirSync(assets)).forEach(function include(file) {
if ('.js' !== path.extname(file) || ~file.indexOf('pagelet')) return;
//
// Create getter for each pagelet in assets.
//
var Pagelet = require(path.join(assets, file));
enumerable(path.basename(file, '.js'), {
enumerable: true,
value: Pagelet.brand(self.brand, mode === 'standalone', next)
}, true);
});
} | javascript | {
"resource": ""
} |
q33183 | next | train | function next(error) {
if (error) return self.emit('error', error);
if (++i === files.length) self.emit('optimized');
} | javascript | {
"resource": ""
} |
q33184 | getIn | train | function getIn (client, from, nodes, callback, remove) {
remove = remove || [];
const outNodes = [];
const nodeIndex = {};
const fromIndex = {};
if (from instanceof Array) {
from.forEach((node) => {fromIndex[node] = true});
} else {
from = null;
}
nodes.forEach((node) => {nodeIndex[node] = true});
client.g.V.apply(client.g, nodes).Tag('o').In(null, 'p').All((err, result) => {
if (err = error(err, result, true)) {
return callback(err);
}
if (result) {
result.forEach((triple) => {
// TODO collect subject (triple.id) for: subject > next > object
// escape quotes
let object = triple.o;
if (triple.o.indexOf('"') > -1) {
triple.o = triple.o.replace(/"/g, '\\"')
}
// remove from > p > node triples
if (!from || fromIndex[triple.id]) {
remove.push({
subject: triple.id,
predicate: triple.p,
object: triple.o
});
// don't delete nodes with more then one in connections
} else {
nodeIndex[object] = false;
}
});
for (let node in nodeIndex) {
if (nodeIndex[node]) {
if (node.indexOf('"') > -1) {
node = node.replace(/"/g, '\\"');
}
outNodes.push(node);
}
};
}
callback(null, outNodes, remove);
});
} | javascript | {
"resource": ""
} |
q33185 | createPayment | train | function createPayment(data, callback) {
var client = new this.clients.Payments();
client.create(data, callback);
} | javascript | {
"resource": ""
} |
q33186 | getPaymentById | train | function getPaymentById(id, callback) {
var client = new this.clients.Payments();
client.getById(id, callback);
} | javascript | {
"resource": ""
} |
q33187 | getPaymentByNotificationToken | train | function getPaymentByNotificationToken(token, callback) {
var client = new this.clients.Payments();
client.getByNotificationToken(token, callback);
} | javascript | {
"resource": ""
} |
q33188 | refundPayment | train | function refundPayment(id, callback) {
var client = new this.clients.Payments();
client.refund(id, callback);
} | javascript | {
"resource": ""
} |
q33189 | train | function(trigger, job){
this.trigger = this.decodeTrigger(trigger);
this.nextTime = this.nextExcuteTime(Date.now());
this.job = job;
} | javascript | {
"resource": ""
} | |
q33190 | timeMatch | train | function timeMatch(value, cronTime){
if(typeof(cronTime) == 'number'){
if(cronTime == -1)
return true;
if(value == cronTime)
return true;
return false;
}else if(typeof(cronTime) == 'object' && cronTime instanceof Array){
if(value < cronTime[0] || value > cronTime[cronTime.length -1])
return false;
for(let i = 0; i < cronTime.length; i++)
if(value == cronTime[i])
return true;
return false;
}
return null;
} | javascript | {
"resource": ""
} |
q33191 | decodeRangeTime | train | function decodeRangeTime(map, timeStr){
let times = timeStr.split('-');
times[0] = Number(times[0]);
times[1] = Number(times[1]);
if(times[0] > times[1]){
console.log("Error time range");
return null;
}
for(let i = times[0]; i <= times[1]; i++){
map[i] = i;
}
} | javascript | {
"resource": ""
} |
q33192 | decodePeriodTime | train | function decodePeriodTime(map, timeStr, type){
let times = timeStr.split('/');
let min = Limit[type][0];
let max = Limit[type][1];
let remind = Number(times[0]);
let period = Number(times[1]);
if(period==0)
return;
for(let i = min; i <= max; i++){
if(i%period == remind)
map[i] = i;
}
} | javascript | {
"resource": ""
} |
q33193 | checkNum | train | function checkNum(nums, min, max){
if(nums == null)
return false;
if(nums == -1)
return true;
for(let i = 0; i < nums.length; i++){
if(nums[i]<min || nums[i]>max)
return false;
}
return true;
} | javascript | {
"resource": ""
} |
q33194 | setupCronInput | train | function setupCronInput(val) {
$('input.cron').jqCron({
enabled_minute: true,
multiple_dom: true,
multiple_month: true,
multiple_mins: true,
multiple_dow: true,
multiple_time_hours: true,
multiple_time_minutes: true,
default_period: 'week',
default_value: val || '15 12 * * 7',
no_reset_button: true,
lang: 'en'
});
} | javascript | {
"resource": ""
} |
q33195 | getSearchInput | train | function getSearchInput() {
var cronValue = $('#scheduleSearch').prop('checked') ? $('input.cron').val() : null, searchName = $('#searchName').val(), targetResults = $('#targetResults').val(), input = $('#searchInput').val(), searchContinue = $('#searchContinue').val(), searchCategories = $('#searchCategories').val().split(',').map(function(t) { return t.trim(); }), searchTeam = $('select.searcher.team option:selected').map(function() { return this.value; }).get();
return { searchName: searchName, cron: cronValue, input: input, relevance: searchContinue, team: searchTeam, categories: searchCategories, targetResults: targetResults, valid: (input.length > 0 && searchContinue.length > 0 && searchTeam.length > 0 && searchCategories.length > 0 && targetResults.length > 0 )};
} | javascript | {
"resource": ""
} |
q33196 | submitSearch | train | function submitSearch() {
var searchInput = getSearchInput();
// FIXME: SUI validation for select2 field
if (!searchInput.valid) {
alert('Please select team members');
return;
}
console.log('publishing', searchInput);
$('.search.message').html('Search results:');
$('.search.message').removeClass('hidden');
context.pubsub.status('queued', function(res) {
console.log(res);
var message = '';
if (res.err) {
message = res.err;
} else {
message = 'found <a target="_searchresult" href="' + res.status.uri + '">' + res.status.uri + '</a> from ' + res.status.source;
}
$('.search.message').append('<div>' + message + '</div>');
});
context.pubsub.search.queue(searchInput);
context.queryLib.setAnnotationTags($('#searchCategories').val().split(','));
context.queryLib.submitQuery();
} | javascript | {
"resource": ""
} |
q33197 | Loader | train | function Loader(options) {
if (!(this instanceof Loader)) {
return new Loader(options);
}
this.options = options || {};
this.cache = this.options.helpers || {};
} | javascript | {
"resource": ""
} |
q33198 | deepClone | train | function deepClone(inputDict){
if (!inputDict)
return null;
const clonedDict = {};
for (let key in inputDict){
if (typeof(inputDict[key]) == 'object'){
clonedDict[key] = deepClone(inputDict[key]);
}
else{
clonedDict[key] = inputDict[key];
}
}
return clonedDict;
} | javascript | {
"resource": ""
} |
q33199 | setCookie | train | function setCookie(cookieName, value, validity, useAppPrefix = true){
const appPrefix = useAppPrefix ? _getAppPrefix() : '';
const cookieString = appPrefix + cookieName + '=' + value + ';' + 'expires=' +
validity.toUTCString();
document.cookie = cookieString;
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.