_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q55900
|
_fnBindAction
|
train
|
function _fnBindAction( n, oData, fn )
{
$(n)
.bind( 'click.DT', oData, function (e) {
n.blur(); // Remove focus outline for mouse users
fn(e);
} )
.bind( 'keypress.DT', oData, function (e){
if ( e.which === 13 ) {
fn(e);
} } )
.bind( 'selectstart.DT', function () {
/* Take the brutal approach to cancelling text selection */
return false;
} );
}
|
javascript
|
{
"resource": ""
}
|
q55901
|
_fnCallbackReg
|
train
|
function _fnCallbackReg( oSettings, sStore, fn, sName )
{
if ( fn )
{
oSettings[sStore].push( {
"fn": fn,
"sName": sName
} );
}
}
|
javascript
|
{
"resource": ""
}
|
q55902
|
train
|
function ()
{
if ( this.oFeatures.bServerSide ) {
if ( this.oFeatures.bPaginate === false || this._iDisplayLength == -1 ) {
return this._iDisplayStart+this.aiDisplay.length;
} else {
return Math.min( this._iDisplayStart+this._iDisplayLength,
this._iRecordsDisplay );
}
} else {
return this._iDisplayEnd;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55903
|
validateSentence
|
train
|
function validateSentence(parsed) {
const sentences = parsed.sentences();
return [
!isSingleSentence(sentences) ? 'Must be one and only one sentence.' : null,
!isNotTooShort(parsed) ? 'Must be at least two words long.' : null,
!isNotPunctuated(sentences) ? 'Must not have any end punctuation.' : null,
].filter(Boolean);
}
|
javascript
|
{
"resource": ""
}
|
q55904
|
validateFirstTerm
|
train
|
function validateFirstTerm(parsed) {
const term = parsed.terms().data()[0];
return [
!isValidVerb(term) ? 'First word must be imperative verb.' : null,
!isCapitalized(term) ? 'First word must be capitalized.' : null,
].filter(Boolean);
}
|
javascript
|
{
"resource": ""
}
|
q55905
|
destroy
|
train
|
function destroy (stream) {
if (stream instanceof ReadStream) {
return destroyReadStream(stream)
}
if (!(stream instanceof Stream)) {
return stream
}
if (typeof stream.destroy === 'function') {
stream.destroy()
}
return stream
}
|
javascript
|
{
"resource": ""
}
|
q55906
|
destroyReadStream
|
train
|
function destroyReadStream (stream) {
stream.destroy()
if (typeof stream.close === 'function') {
// node.js core bug work-around
stream.on('open', onOpenClose)
}
return stream
}
|
javascript
|
{
"resource": ""
}
|
q55907
|
LiveConnectAPIError
|
train
|
function LiveConnectAPIError(message, code) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = 'LiveConnectAPIError';
this.message = message;
this.code = code;
}
|
javascript
|
{
"resource": ""
}
|
q55908
|
train
|
function(observable, value, callback) {
var subscription = observable.subscribe(function() {
subscription.dispose();
setTimeout(function() {
callback();
}, 50);
});
observable(value);
}
|
javascript
|
{
"resource": ""
}
|
|
q55909
|
countdown
|
train
|
function countdown (howMany, lambda, completed) {
var result;
return function () {
if (--howMany >= 0 && lambda) result = lambda.apply(undef, arguments);
// we want ==, not <=, since some callers expect call-once functionality
if (howMany == 0 && completed) completed(result);
return result;
}
}
|
javascript
|
{
"resource": ""
}
|
q55910
|
convertPathMatcher
|
train
|
function convertPathMatcher (cfg) {
var pathMap = cfg.pathMap;
cfg.pathRx = new RegExp('^(' +
cfg.pathList.sort(function (a, b) { return pathMap[b].specificity - pathMap[a].specificity; } )
.join('|')
.replace(/\/|\./g, '\\$&') +
')(?=\\/|$)'
);
delete cfg.pathList;
}
|
javascript
|
{
"resource": ""
}
|
q55911
|
process
|
train
|
function process (ev) {
ev = ev || global.event;
// detect when it's done loading
// ev.type == 'load' is for all browsers except IE6-9
// IE6-9 need to use onreadystatechange and look for
// el.readyState in {loaded, complete} (yes, we need both)
if (ev.type == 'load' || readyStates[el.readyState]) {
delete activeScripts[def.id];
// release event listeners
el.onload = el.onreadystatechange = el.onerror = ''; // ie cries if we use undefined
success();
}
}
|
javascript
|
{
"resource": ""
}
|
q55912
|
CurlApi
|
train
|
function CurlApi (ids, callback, errback, waitFor) {
var then, ctx;
ctx = core.createContext(userCfg, undef, [].concat(ids));
this['then'] = then = function (resolved, rejected) {
when(ctx,
// return the dependencies as arguments, not an array
function (deps) {
if (resolved) resolved.apply(undef, deps);
},
// just throw if the dev didn't specify an error handler
function (ex) {
if (rejected) rejected(ex); else throw ex;
}
);
return this;
};
this['next'] = function (ids, cb, eb) {
// chain api
return new CurlApi(ids, cb, eb, ctx);
};
this['config'] = _config;
if (callback || errback) then(callback, errback);
when(waitFor, function () { core.getDeps(ctx); });
}
|
javascript
|
{
"resource": ""
}
|
q55913
|
train
|
function (arg) {
var args = Array.isArray(arg) ? arg : [].slice.call(arguments);
var channel = options.taskChannelPrefix + '.' + args[0];
args[0] = channel;
fs.write(tmpfile, JSON.stringify(args) + "\n", "a");
}
|
javascript
|
{
"resource": ""
}
|
|
q55914
|
train
|
function(contextObj, options) {
options = options ? mergeDeep(this.options, options, true) : this.options;
var context = this._parseContext(contextObj);
var subKey = options.applySubstitutions !== false ? 'subbed': 'unsubbed';
var collector = this.masterDelta ? cloneDeep(this.masterDelta[subKey]) : {};
this._readHelper(this.tree, 0, context, collector, subKey);
if(collector.__ycb_source__) {
return omit(collector, '__ycb_source__');
}
return collector;
}
|
javascript
|
{
"resource": ""
}
|
|
q55915
|
train
|
function(cur, depth, context, collector, subKey) {
if(depth === context.length) {
mergeDeep(cur[subKey], collector, false);
return;
}
var value = context[depth];
if(value.constructor !== Array) {
var keys = this.precedenceMap[value];
var n = keys.length;
for(var j=0; j<n; j++) {
if(cur[keys[j]] !== undefined) {
this._readHelper(cur[keys[j]], depth+1, context, collector, subKey);
}
}
} else {
var seen = {};
var i = value.length;
while(i--) {
keys = this.precedenceMap[value[i]];
n = keys.length;
for(j=0; j<n; j++) {
if(cur[keys[j]] !== undefined && seen[keys[j]] === undefined) {
this._readHelper(cur[keys[j]], depth+1, context, collector, subKey);
seen[keys[j]] = true;
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55916
|
train
|
function(contextObj, options) {
var context = this._parseContext(contextObj);
var subKey = options.applySubstitutions !== false ? 'subbed': 'unsubbed';
var collector = this.masterDelta ? [this.masterDelta[subKey]] : [];
this._readNoMergeHelper(this.tree, 0, context, collector, subKey);
return cloneDeep(collector);
}
|
javascript
|
{
"resource": ""
}
|
|
q55917
|
train
|
function(cur, depth, context, collector, subKey) {
if(depth === context.length) {
collector.push(cur[subKey]);
return;
}
var value = context[depth];
if(value.constructor !== Array) {
var keys = this.precedenceMap[value];
var n = keys.length;
for(var j=0; j<n; j++) {
if(cur[keys[j]] !== undefined) {
this._readNoMergeHelper(cur[keys[j]], depth+1, context, collector, subKey);
}
}
} else {
var seen = {};
var i = value.length;
while(i--) {
keys = this.precedenceMap[value[i]];
n = keys.length;
for(j=0; j<n; j++) {
if(cur[keys[j]] !== undefined && seen[keys[j]] === undefined) {
this._readNoMergeHelper(cur[keys[j]], depth+1, context, collector, subKey);
seen[keys[j]] = true;
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55918
|
train
|
function(contextObj) {
if(contextObj === undefined) {
contextObj = {};
}
var context = new Array(this.dimensionsList.length);
for(var i=0; i<this.dimensionsList.length; i++) {
var dimension = this.dimensionsList[i];
if(contextObj.hasOwnProperty(dimension)) {
var value = contextObj[dimension];
if(value.constructor === Array) {
var newValue = [];
for(var j=0; j<value.length; j++) {
var numValue = this.valueToNumber[dimension][value[j]];
if(numValue !== undefined) {
newValue.push(numValue);
}
}
if(newValue.length) {
context[i] = newValue;
continue;
}
} else {
numValue = this.valueToNumber[dimension][value];
if(numValue !== undefined) {
context[i] = numValue;
continue;
}
}
}
context[i] = 0;
}
return context;
}
|
javascript
|
{
"resource": ""
}
|
|
q55919
|
train
|
function(context) {
var contextObj = {};
for(var i=0; i<context.length; i++) {
if(context[i] !== '0') {
contextObj[this.dimensionsList[i]] = this.numberToValue[context[i]];
}
}
return contextObj;
}
|
javascript
|
{
"resource": ""
}
|
|
q55920
|
train
|
function(config) {
for(var i=0; i<config.length; i++) {
if(config[i].dimensions) {
var dimensions = config[i].dimensions;
this.dimensions = dimensions;
var allDimensions = {};
for(var j=0; j<dimensions.length; j++) {
var name;
for(name in dimensions[j]) {
allDimensions[name] = j;
break;
}
}
return [dimensions, allDimensions];
}
}
return [[], {}];
}
|
javascript
|
{
"resource": ""
}
|
|
q55921
|
train
|
function(config, allDimensions, height) {
var usedDimensions = {};
var usedValues = {};
var contexts = {};
configLoop:
for(var i=0; i<config.length; i++) {
if (config[i].settings) {
var setting = config[i].settings;
if(setting.length === 0 ) {
continue;
}
if(setting[0] === 'master') {
if(this.masterDelta !== undefined) {
this.masterDelta = mergeDeep(this._buildDelta(config[i]), this.masterDelta, true);
} else {
this.masterDelta = this._buildDelta(config[i]);
}
continue;
}
var context = new Array(height);
for(var q=0; q<height; q++) {
context[q] = DEFAULT;
}
for(var j=0; j<setting.length; j++) {
var kv = setting[j].split(':');
var dim = kv[0];
var index = allDimensions[dim];
if(index === undefined) {
console.log('WARNING: invalid dimension "' + dim +
'" in settings ' + JSON.stringify(setting));
continue configLoop;
}
usedDimensions[dim] = 1;
usedValues[dim] = usedValues[dim] || {};
if(kv[1].indexOf(',') === -1) {
usedValues[dim][kv[1]] = 1;
context[index] = kv[1];
} else {
var vals = kv[1].split(',');
context[index] = vals;
for(var k=0; k<vals.length; k++) {
usedValues[dim][vals[k]] = 1;
}
}
}
contexts[i] = context;
}
}
return [usedDimensions, usedValues, contexts];
}
|
javascript
|
{
"resource": ""
}
|
|
q55922
|
train
|
function(config) {
config = omit(config, 'settings');
var subbed = cloneDeep(config);
var subFlag = this._applySubstitutions(subbed, null, null);
var unsubbed = subFlag ? config : subbed;
return {subbed:subbed, unsubbed:unsubbed};
}
|
javascript
|
{
"resource": ""
}
|
|
q55923
|
train
|
function(dimensions, usedDimensions, usedValues) {
var activeDimensions = new Array(dimensions.length);
var valueCounter = 1;
for(var i=0; i<dimensions.length; i++) {
var dimensionName;
for(dimensionName in dimensions[i]){break}
if(usedDimensions[dimensionName] === undefined) {
activeDimensions[i] = 0;
continue;
}
activeDimensions[i] = 1;
this.dimensionsList.push(dimensionName);
var labelCollector = {};
valueCounter = this._dimensionWalk(dimensions[i][dimensionName], usedValues[dimensionName],
valueCounter, [0], this.precedenceMap, labelCollector, this.numberToValue);
this.valueToNumber[dimensionName] = labelCollector;
}
return activeDimensions;
}
|
javascript
|
{
"resource": ""
}
|
|
q55924
|
train
|
function(fullContext, activeDimensions, usedValues, setting) {
var height = this.dimensionsList.length;
var newContext = new Array(height);
for(var i=0; i<height; i++) {
newContext[i] = 0;
}
var activeIndex = 0;
for(i=0; i<fullContext.length; i++) {
if(activeDimensions[i]) {
var dimensionName = this.dimensionsList[activeIndex];
var contextValue = fullContext[i];
if(contextValue.constructor === Array) {
var newValue = [];
for(var k=0; k<contextValue.length; k++) {
var valueChunk = contextValue[k];
if(usedValues[dimensionName][valueChunk] === 2) {
newValue.push(this.valueToNumber[dimensionName][valueChunk]);
} else {
console.log('WARNING: invalid value "' + valueChunk + '" for dimension "' +
dimensionName + '" in settings ' + JSON.stringify(setting));
}
}
if(newValue.length === 0) {
return;
}
newContext[activeIndex] = newValue;
} else {
if(usedValues[dimensionName][contextValue] === 2) {
newContext[activeIndex] = this.valueToNumber[dimensionName][contextValue];
} else if(contextValue !== DEFAULT) {
console.log('WARNING: invalid value "' + contextValue + '" for dimension "' +
dimensionName + '" in settings ' + JSON.stringify(setting));
return;
}
}
activeIndex++;
}
}
return newContext;
}
|
javascript
|
{
"resource": ""
}
|
|
q55925
|
train
|
function(root, depth, context, delta) {
var i;
var currentValue = context[depth];
var isMulti = currentValue.constructor === Array;
if(depth === context.length-1) {
if(isMulti) {
for(i=0; i<currentValue.length; i++) {
var curDelta = delta;
if(root[currentValue[i]] !== undefined) {
curDelta = mergeDeep(delta, root[currentValue[i]], true);
}
root[currentValue[i]] = curDelta;
}
} else {
curDelta = delta;
if(root[currentValue] !== undefined) {
curDelta = mergeDeep(delta, root[currentValue], true);
}
root[currentValue] = curDelta;
}
return;
}
if(isMulti){
for(i=0; i<currentValue.length; i++) {
if(root[currentValue[i]] === undefined) {
root[currentValue[i]] = {};
}
this._buildTreeHelper(root[currentValue[i]], depth+1, context, delta);
}
} else {
if(root[currentValue] === undefined) {
root[currentValue] = {};
}
this._buildTreeHelper(root[currentValue], depth+1, context, delta);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55926
|
train
|
function (config, base, parent) {
var key,
sub,
find,
item;
base = base || config;
parent = parent || {ref: config, key: null};
var subFlag = false;
for (key in config) {
if (config.hasOwnProperty(key)) {
// If the value is an "Object" or an "Array" drill into it
if (isIterable(config[key])) {
// parent param {ref: config, key: key} is a recursion
// pointer that needed only when replacing "keys"
subFlag = this._applySubstitutions(config[key], base, {ref: config, key: key}) || subFlag;
} else {
// Test if the key is a "substitution" key
sub = SUBMATCH.exec(key);
if (sub && (sub[0] === key)) {
subFlag = true;
// Pull out the key to "find"
find = extract(base, sub[1], null);
if (isA(find, Object)) {
// Remove the "substitution" key
delete config[key];
// Add the keys founds
// This should be inline at the point where the "substitution" key was.
// Currently they will be added out of order on the end of the map.
for (item in find) {
if (find.hasOwnProperty(item)) {
if (!parent.ref[parent.key]) {
parent.ref[item] = find[item];
} else {
parent.ref[parent.key][item] = find[item];
}
}
}
} else {
config[key] = '--YCB-SUBSTITUTION-ERROR--';
}
} else if (SUBMATCH.test(config[key])) {
subFlag = true;
// Test if the value is a "substitution" value
// We have a match so lets use it
sub = SUBMATCH.exec(config[key]);
// Pull out the key to "find"
find = sub[1];
// First see if it is the whole value
if (sub[0] === config[key]) {
// Replace the whole value with the value found by the sub string
find = extract(base, find, null);
// If we have an array in an array do it "special like"
if (isA(find, Array) && isA(config, Array)) {
// This has to be done on the parent or the reference is lost
// The whole {ref: config, key: key} is needed only when replacing "keys"
parent.ref[parent.key] = config.slice(0, parseInt(key, 10))
.concat(find)
.concat(config.slice(parseInt(key, 10) + 1));
} else {
config[key] = find;
}
} else {
// If not it's just part of the whole value
config[key] = config[key]
.replace(SUBMATCHES, replacer(base));
}
}
}
}
}
return subFlag;
}
|
javascript
|
{
"resource": ""
}
|
|
q55927
|
train
|
function (callback) {
if(this.masterDelta && !callback({}, cloneDeep(this.masterDelta))) {
return undefined;
}
this._walkSettingsHelper(this.tree, 0, [], callback, [false]);
}
|
javascript
|
{
"resource": ""
}
|
|
q55928
|
train
|
function(cur, depth, context, callback, stop) {
if(stop[0]) {
return true;
}
if(depth === this.dimensionsList.length) {
stop[0] = !callback(this._contextToObject(context), cloneDeep(cur));
return stop[0];
}
var key;
for(key in cur) {
if(this._walkSettingsHelper(cur[key], depth+1, context.concat(key), callback, stop)) {
return true;
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55929
|
round
|
train
|
function round(value) {
var d = Math.pow(10, decimals);
return Math.round(value * d) / d;
}
|
javascript
|
{
"resource": ""
}
|
q55930
|
numberWithCommas
|
train
|
function numberWithCommas(value) {
if (formatting) {
var parts = (""+value).split(decimalSeparator);
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator);
return parts.join(decimalSeparator);
}
else {
// No formatting applies.
return value;
}
}
|
javascript
|
{
"resource": ""
}
|
q55931
|
formatPrecision
|
train
|
function formatPrecision(value) {
if (!(value || value === 0)) {
return '';
}
var formattedValue = parseFloat(value).toFixed(decimals);
formattedValue = formattedValue.replace('.', decimalSeparator);
return numberWithCommas(formattedValue);
}
|
javascript
|
{
"resource": ""
}
|
q55932
|
parseViewValue
|
train
|
function parseViewValue(value) {
if (angular.isUndefined(value)) {
value = '';
}
value = (""+value).replace(decimalSeparator, '.');
// Handle leading decimal point, like ".5"
if (value.indexOf('.') === 0) {
value = '0' + value;
}
// Allow "-" inputs only when min < 0
if (value.indexOf('-') === 0) {
if (min >= 0) {
value = null;
ngModelCtrl.$setViewValue(formatViewValue(lastValidValue));
ngModelCtrl.$render();
}
else if (value === '-') {
value = '';
}
}
var empty = ngModelCtrl.$isEmpty(value);
if (empty) {
lastValidValue = '';
//ngModelCtrl.$modelValue = undefined;
}
else {
if (regex.test(value) && (value.length <= maxInputLength)) {
if ((value > max) && limitMax) {
lastValidValue = max;
}
else if ((value < min) && limitMin) {
lastValidValue = min;
}
else {
lastValidValue = (value === '') ? null : parseFloat(value);
}
}
else {
// Render the last valid input in the field
ngModelCtrl.$setViewValue(formatViewValue(lastValidValue));
ngModelCtrl.$render();
}
}
return lastValidValue;
}
|
javascript
|
{
"resource": ""
}
|
q55933
|
calculateMaxLength
|
train
|
function calculateMaxLength(value) {
var length = 16;
if (!angular.isUndefined(value)) {
length = Math.floor(value).toString().length;
}
if (decimals > 0) {
// Add extra length for the decimals plus one for the decimal separator.
length += decimals + 1;
}
if (min < 0) {
// Add extra length for the - sign.
length++;
}
return length;
}
|
javascript
|
{
"resource": ""
}
|
q55934
|
minmaxValidator
|
train
|
function minmaxValidator(value, testValue, validityName, limit, compareFunction) {
if (!angular.isUndefined(testValue) && limit) {
if (!ngModelCtrl.$isEmpty(value) && compareFunction) {
return testValue;
} else {
return value;
}
}
else {
if (!limit) {
ngModelCtrl.$setValidity(validityName, !compareFunction);
}
return value;
}
}
|
javascript
|
{
"resource": ""
}
|
q55935
|
train
|
function(url) {
return new Promise(function (resolve) {
self.roptions.url = url;
request(self.roptions, function (err, response, body) {
if (!err && response.statusCode === 200) {
var $ = cheerio.load(body);
// no results
if (!$('.result').length) {
return resolve(result);
}
$('.result').each(function() {
var href = $(this).find('a').attr('href');
if(href.toString().indexOf("http") !== 0) {
result.push(base + href);
} else {
result.push(href);
}
});
if (num && result.length > num) {
return resolve(result.slice(0,num));
}
// search for current page and select next one
var page = $('#nextPage').attr('href');
if (page) {
resolve(nextPage(base + page));
}
else {
resolve(result);
}
} else {
resolve(result)
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55936
|
train
|
function(target, options) {
var poller = findPoller(target);
if (!poller) {
poller = new Poller(target, options);
pollers.push(poller);
poller.start();
} else {
poller.set(options);
poller.restart();
}
return poller;
}
|
javascript
|
{
"resource": ""
}
|
|
q55937
|
train
|
function() {
angular.forEach(pollers, function(p) {
p.delay = p.idleDelay;
if (angular.isDefined(p.interval)) {
p.restart();
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q55938
|
runTimerGatheringTimeout
|
train
|
function runTimerGatheringTimeout() {
if (typeof self.options.gatheringTimeout !== 'number') {
return;
}
// If setLocalDescription was already called, it may happen that
// ICE gathering is not needed, so don't run this timer.
if (self.pc.iceGatheringState === 'complete') {
return;
}
debug('setLocalDescription() | ending gathering in %d ms (gatheringTimeout option)',
self.options.gatheringTimeout);
self.timerGatheringTimeout = setTimeout(function () {
if (isClosed.call(self)) {
return;
}
debug('forced end of candidates after gatheringTimeout timeout');
// Clear gathering timers.
delete self.timerGatheringTimeout;
clearTimeout(self.timerGatheringTimeoutAfterRelay);
delete self.timerGatheringTimeoutAfterRelay;
// Ignore new candidates.
self.ignoreIceGathering = true;
if (self.onicecandidate) {
self.onicecandidate({ candidate: null }, null);
}
}, self.options.gatheringTimeout);
}
|
javascript
|
{
"resource": ""
}
|
q55939
|
setConfigurationAndOptions
|
train
|
function setConfigurationAndOptions(pcConfig) {
// Clone pcConfig.
this.pcConfig = merge(true, pcConfig);
// Fix pcConfig.
Adapter.fixPeerConnectionConfig(this.pcConfig);
this.options = {
iceTransportsRelay: (this.pcConfig.iceTransports === 'relay'),
iceTransportsNone: (this.pcConfig.iceTransports === 'none'),
gatheringTimeout: this.pcConfig.gatheringTimeout,
gatheringTimeoutAfterRelay: this.pcConfig.gatheringTimeoutAfterRelay
};
// Remove custom rtcninja.RTCPeerConnection options from pcConfig.
delete this.pcConfig.gatheringTimeout;
delete this.pcConfig.gatheringTimeoutAfterRelay;
debug('setConfigurationAndOptions | processed pcConfig: %o', this.pcConfig);
}
|
javascript
|
{
"resource": ""
}
|
q55940
|
train
|
function (height, options) {
if (numberIsInteger(height) && height < 1) {
throw VideomailError.create('Passed limit-height argument cannot be less than 1!', options)
} else {
const limitedHeight = Math.min(
height,
// document.body.scrollHeight,
document.documentElement.clientHeight
)
if (limitedHeight < 1) {
throw VideomailError.create('Limited height cannot be less than 1!', options)
} else {
return limitedHeight
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55941
|
train
|
function (callback) {
var cb = this.lambda(callback)
// iterate from chain
if (this.__results) {
for (var i = 0, l = this.__results.length; i < l; i++) cb.call(this, this.__results[i], i)
}
// otherwise iterate the entire collection
else {
this.all(function(r) {
for (var i = 0, l = r.length; i < l; i++) cb.call(this, r[i], i)
})
}
return this
}
|
javascript
|
{
"resource": ""
}
|
|
q55942
|
train
|
function(name) {
return {
// the key
key: name + '._index_',
// returns the index
all: function() {
var a = storage.getItem(this.key)
if (a) {
a = JSON.parse(a)
}
if (a === null) storage.setItem(this.key, JSON.stringify([])) // lazy init
return JSON.parse(storage.getItem(this.key))
},
// adds a key to the index
add: function (key) {
var a = this.all()
a.push(key)
storage.setItem(this.key, JSON.stringify(a))
},
// deletes a key from the index
del: function (key) {
var a = this.all(), r = []
// FIXME this is crazy inefficient but I'm in a strata meeting and half concentrating
for (var i = 0, l = a.length; i < l; i++) {
if (a[i] != key) r.push(a[i])
}
storage.setItem(this.key, JSON.stringify(r))
},
// returns index for a key
find: function (key) {
var a = this.all()
for (var i = 0, l = a.length; i < l; i++) {
if (key === a[i]) return i
}
return false
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55943
|
train
|
function(obj, callback, error) {
var that = this
objs = (this.isArray(obj) ? obj : [obj]).map(function(o) {
if (!o.key) {
o.key = that.uuid()
}
return o
}),
ins = "INSERT OR REPLACE INTO " + this.record + " (value, timestamp, id) VALUES (?,?,?)",
win = function() {
if (callback) {
that.lambda(callback).call(that, that.isArray(obj) ? objs : objs[0])
}
}, error = error || function() {}, insvals = [],
ts = now()
try {
for (var i = 0, l = objs.length; i < l; i++) {
insvals[i] = [JSON.stringify(objs[i]), ts, objs[i].key];
}
} catch (e) {
fail(e)
throw e;
}
that.db.transaction(function(t) {
for (var i = 0, l = objs.length; i < l; i++)
t.executeSql(ins, insvals[i])
}, function(e, i) {
fail(e, i)
}, win)
return this
}
|
javascript
|
{
"resource": ""
}
|
|
q55944
|
train
|
function(options) {
self.consoleLog('sync - init called');
self.config = JSON.parse(JSON.stringify(self.defaults));
for (var i in options) {
self.config[i] = options[i];
}
//prevent multiple monitors from created if init is called multiple times
if(!self.init_is_called){
self.init_is_called = true;
self.datasetMonitor();
}
defaultCloudHandler.init(self.config.cloudUrl, self.config.cloudPath);
}
|
javascript
|
{
"resource": ""
}
|
|
q55945
|
train
|
function(config, options) {
// Make sure config is initialised
if( ! config ) {
config = JSON.parse(JSON.stringify(self.defaults));
}
var datasetConfig = JSON.parse(JSON.stringify(config));
var optionsIn = JSON.parse(JSON.stringify(options));
for (var k in optionsIn) {
datasetConfig[k] = optionsIn[k];
}
return datasetConfig;
}
|
javascript
|
{
"resource": ""
}
|
|
q55946
|
train
|
function(callback) {
var online = true;
// first, check if navigator.online is available
if(typeof navigator.onLine !== "undefined"){
online = navigator.onLine;
}
// second, check if Phonegap is available and has online info
if(online){
//use phonegap to determin if the network is available
if(typeof navigator.network !== "undefined" && typeof navigator.network.connection !== "undefined"){
var networkType = navigator.network.connection.type;
if(networkType === "none" || networkType === null) {
online = false;
}
}
}
return callback(online);
}
|
javascript
|
{
"resource": ""
}
|
|
q55947
|
train
|
function (type, args) {
this.type = type;
this.single = false;
// Message is a 'multiple attribute message'.
if (typeof args === 'object' || typeof args === 'undefined') {
this.args = args || {};
}
// Message is a 'single attribute message'.
else {
this.single = true;
this.args = args;
}
if (!this.single) {
if (this.args.flowId) {
this.arg('flowId', this.args.flowId);
}
else if (index.autoFlowId) {
this.arg('flowId', Message.flowId);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55948
|
stage_01
|
train
|
function stage_01(gp_accs){
// Ready logging.
var logger = new bbop.logger();
logger.DEBUG = true;
function ll(str){ logger.kvetch('JSM01: ' + str); }
ll('');
ll('Stage 01 start...');
// Helpers.
var each = bbop.core.each;
var dump = bbop.core.dump;
// Prep the progress bar and hide the order selector until we're
// done.
jQuery("#progress-text").empty();
jQuery("#progress-text").append('<b>Loading...</b>');
//jQuery("#progress-bar").empty();
jQuery("#progress-widget").show();
// Next, setup the manager environment.
ll('Setting up manager.');
var server_meta = new amigo.data.server();
//var gloc = server_meta.golr_base();
var gloc = 'http://golr.berkeleybop.org/solr/';
var gconf = new bbop.golr.conf(amigo.data.golr);
var go = new bbop.golr.manager.jquery(gloc, gconf);
go.set_personality('annotation'); // always this
//go.debug(false);
// Now, cycle though all of the gps to collect info on.
ll('Gathering batch URLs for annotation data...');
var gp_user_order = {};
each(gp_accs, function(acc, index){
// Set/reset for the next query.
go.reset_query_filters(); // reset from the last iteration
//
go.add_query_filter('document_category', 'annotation', ['*']);
go.add_query_filter('bioentity', acc);
//go.add_query_filter('taxon', taxon_filter, ['*']); }
go.set('rows', 0); // we don't need any actual rows returned
go.set_facet_limit(-1); // we are only interested in facet counts
go.facets(['regulates_closure']);
go.add_to_batch();
gp_user_order[acc] = index;
});
var gp_info = {};
// Fetch the data and grab the number we want.
var accumulator_fun = function(resp){
// Who was this?
var acc = null;
var fqs = resp.parameter('fq');
//console.log(fqs);
//console.log(resp);
each(fqs, function(fq){
//console.log(fq);
//console.log(fq.substr(0, 9));
if( fq.substr(0, 9) === 'bioentity' ){
acc = fq.substr(10, fq.length-1);
ll('Looking at info for: ' + acc);
}
});
if( acc ){
//ll('Looking at info for: ' + acc);
console.log(resp);
var ffs = resp.facet_field('regulates_closure');
each(ffs, function(pair){
console.log(pair);
// Ensure existance.
if( ! gp_info[acc] ){
gp_info[acc] = {};
}
//
gp_info[acc][pair[0]] = pair[1];
});
}
};
// The final function is the data renderer.
var final_fun = function(){
ll('Starting final in stage 01...');
ll('gp_info: ' + dump(gp_info));
stage_02(gp_info, gp_accs);
ll('Completed stage 01!');
};
go.run_batch(accumulator_fun, final_fun);
}
|
javascript
|
{
"resource": ""
}
|
q55949
|
_prep_download_url
|
train
|
function _prep_download_url(){
var engine = new impl_engine(golr_response);
//engine.method('GET');
//engine.use_jsonp(true);
var gman = new golr_manager(gserv, gconf, engine, 'async');
gman.set_personality('annotation');
gman.add_query_filter('document_category', 'annotation', ['*']);
// gman.set_results_count(download_count);
var field_list = [ // from GAF
'source', // c1
'bioentity_internal_id', // c2; not bioentity
'bioentity_label', // c3
'qualifier', // c4
'annotation_class', // c5
'reference', // c6
'evidence_type', // c7
'evidence_with', // c8
'aspect', // c9
'bioentity_name', // c10
'synonym', // c11
'type', // c12
'taxon', // c13
'date', // c14
'assigned_by', // c15
'annotation_extension_class', // c16
'bioentity_isoform' // c17
];
// gman.set('fl', field_list.join(','));
// //manager.set('rows', arg_hash['rows']);
// gman.set('csv.encapsulator', '');
// gman.set('csv.separator', '%09');
// gman.set('csv.header', 'false');
// gman.set('csv.mv.separator', '|');
// gman.set('start', _random_number(5));
//gman.set('start', _random_number(5));
gman.set_extra('&start=' + _random_number(4));
//console.log(gman.get_download_url(field_list, { 'rows': lines }));
return gman.get_download_url(field_list, { 'rows': lines });
}
|
javascript
|
{
"resource": ""
}
|
q55950
|
train
|
function(identifiers, search_fields){
ll('run search');
search.set_targets(identifiers, search_fields);
//
search.search();
// Scroll to results.
jQuery('html, body').animate({
scrollTop: jQuery('#' + 'results-area').offset().top
}, 500);
}
|
javascript
|
{
"resource": ""
}
|
|
q55951
|
train
|
function (element) {
if(!element[0]) return false;
//short-circuit most common case
if(IS_FA.test(element[0].tagName)) return true;
//otherwise loop through attributes
var ret = false;
angular.forEach(element[0].attributes, function(attr){
ret = ret || IS_FA.test(attr);
});
return ret;
}
|
javascript
|
{
"resource": ""
}
|
|
q55952
|
train
|
function(a, b) {
if (typeof a === "number") {
return a - b;
}
else {
return a.map(function(x, i) { return x - b[i]; });
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55953
|
train
|
function(A, b) {
// b is a scalar, A is a scalar or a vector
if (typeof A === "number") {
return A * b;
}
else {
return A.map(function(x) { return x * b; });
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55954
|
onTouchStart
|
train
|
function onTouchStart(event) {
var touches = event.touches && event.touches.length ? event.touches : [event];
var x = touches[0].clientX;
var y = touches[0].clientY;
touchCoordinates.push(x, y);
$timeout(function() {
// Remove the allowable region.
for (var i = 0; i < touchCoordinates.length; i += 2) {
if (touchCoordinates[i] === x && touchCoordinates[i+1] === y) {
touchCoordinates.splice(i, i + 2);
return;
}
}
}, PREVENT_DURATION, false);
}
|
javascript
|
{
"resource": ""
}
|
q55955
|
_shrink_wrap
|
train
|
function _shrink_wrap(elt_id){
// Now take what we have, and wrap around some expansion code if
// it looks like it is too long.
var _trim_hash = {};
var _trimit = 100;
// Only want to compile once.
var ea_regexp = new RegExp("\<\/a\>", "i"); // detect an <a>
var br_regexp = new RegExp("\<br\ \/\>", "i"); // detect a <br />
function _trim_and_store( in_str ){
var retval = in_str;
// Let there be tests.
var list_p = br_regexp.test(retval);
var anchors_p = ea_regexp.test(retval);
// Try and break without breaking anchors, etc.
var tease = null;
if( ! anchors_p && ! list_p ){
// A normal string then...trim it!
//ll("\tT&S: easy normal text, go nuts!");
tease = new html.span(bbop.crop(retval, _trimit, '...'),
{'generate_id': true});
}else if( anchors_p && ! list_p ){
// It looks like it is a link without a break, so not
// a list. We cannot trim this safely.
//ll("\tT&S: single link so cannot work on!");
}else{
//ll("\tT&S: we have a list to deal with");
var new_str_list = retval.split(br_regexp);
if( new_str_list.length <= 3 ){
// Let's just ignore lists that are only three
// items.
//ll("\tT&S: pass thru list length <= 3");
}else{
//ll("\tT&S: contruct into 2 plus tag");
var new_str = '';
new_str = new_str + new_str_list.shift();
new_str = new_str + '<br />';
new_str = new_str + new_str_list.shift();
tease = new html.span(new_str, {'generate_id': true});
}
}
// If we have a tease (able to break down incoming string),
// assemble the rest of the packet to create the UI.
if( tease ){
// Setup the text for tease and full versions.
var bgen = function(lbl, dsc){
var b = new html.button(lbl, {
'generate_id': true,
'type': 'button',
'title': dsc || lbl,
//'class': 'btn btn-default btn-xs'
'class': 'btn btn-primary btn-xs'
});
return b;
};
var more_b = new bgen('more', 'Display the complete list');
var full = new html.span(retval, {'generate_id': true});
var less_b = new bgen('less', 'Display the truncated list');
// Store the different parts for later activation.
var tease_id = tease.get_id();
var more_b_id = more_b.get_id();
var full_id = full.get_id();
var less_b_id = less_b.get_id();
_trim_hash[tease_id] = [tease_id, more_b_id, full_id, less_b_id];
// New final string.
retval = tease.to_string() + " " +
more_b.to_string() + " " +
full.to_string() + " " +
less_b.to_string();
}
return retval;
}
var pre_html = jQuery('#' + elt_id).html();
if( pre_html && pre_html.length && (pre_html.length > _trimit * 2) ){
// Get the new value into the wild.
var new_str = _trim_and_store(pre_html);
if( new_str !== pre_html ){
jQuery('#' + elt_id).html(new_str);
// Bind the jQuery events to it.
// Add the roll-up/down events to the doc.
us.each(_trim_hash, function(val, key){
var tease_id = val[0];
var more_b_id = val[1];
var full_id = val[2];
var less_b_id = val[3];
// Initial state.
jQuery('#' + full_id ).hide();
jQuery('#' + less_b_id ).hide();
// Click actions to go back and forth.
jQuery('#' + more_b_id ).click(function(){
jQuery('#' + tease_id ).hide();
jQuery('#' + more_b_id ).hide();
jQuery('#' + full_id ).show('fast');
jQuery('#' + less_b_id ).show('fast');
});
jQuery('#' + less_b_id ).click(function(){
jQuery('#' + full_id ).hide();
jQuery('#' + less_b_id ).hide();
jQuery('#' + tease_id ).show('fast');
jQuery('#' + more_b_id ).show('fast');
});
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q55956
|
train
|
function (user, next) {
if (!user.hasOwnProperty('password') || !user.password || this.isHashed(user.password)) {
next(null, user);
} else {
bcrypt.hash(user.password, 10, function (err, hash) {
user.password = hash;
next(err, user);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55957
|
create_request_function
|
train
|
function create_request_function(personality, doc_type,
id_field, label_field, link_type){
return function(request, query) {
// Declare a delayed response.
var response = new Deferred();
//response.wait(5000); // 5s wait for resolution
// New agent on every call.
var go = new bbop.golr.manager.ringo(server_loc, gconf);
go.set_personality(personality); // profile in gconf
go.add_query_filter('document_category', doc_type);
// Define what we do when our GOlr (async) information
// comes back within the scope of the deferred response
// variable.
function golr_callback_action(resp){
// Return caches for the values we'll collect.
var ret_terms = [];
var ret_descs = [];
var ret_links = [];
// Gather document info if available.
//var found_docs = resp.documents();
bbop.core.each(resp.documents(),
function(doc){
var id = doc[id_field];
var label = doc[label_field];
ret_terms.push(label);
ret_descs.push(id);
ret_links.push(linker.url(id, link_type));
});
// Assemble final answer into the OpenSearch JSON
// form.
var ret_body = [query];
ret_body.push(ret_terms);
ret_body.push(ret_descs);
ret_body.push(ret_links);
var ans = {
status: 200,
headers: {'Content-Type': 'application/json'},
body: [bbop.core.to_string(ret_body)]
};
response.resolve(ans);
}
// Run the agent action.
//go.set_query(query);
go.set_comfy_query(query);
go.register('search', 'do', golr_callback_action);
go.update('search');
return response.promise;
};
}
|
javascript
|
{
"resource": ""
}
|
q55958
|
_doc_to_tree_node
|
train
|
function _doc_to_tree_node(doc, parent_id){
var retnode = {};
// ID.
var raw_id = doc['id'];
var safe_id = raw_id; // need to process?
retnode['attr'] = { "id" : safe_id };
// Label (with fallback).
var label = doc['label'];
if( ! label || label == '' ){
label = raw_id;
}else{
label = label + ' (' + raw_id + ')';
}
// Set anchor title and href.
var detlink = linker.url(raw_id, 'term');
retnode['data'] = {"title" : label,
"attr": {"href": detlink}};
// Turn to graph, get kids.
var graph = new bbop.model.graph();
graph.load_json(jQuery.parseJSON(doc['topology_graph']));
var kids = graph.get_child_nodes(doc['id']);
// Add state and kid_query.
if( ! kids || kids.length == 0 ){
// No kids...
}else{
// No kids, make sure the node is closed.
retnode['state'] = 'closed';
// Collect kid info for the query to get them later.
var qbuff = [];
bbop.core.each(kids,
function(kid){
qbuff.push('id:"' + kid.id() + '"');
});
retnode['attr']['kid_query'] = qbuff.join(' OR ');
}
// If the parent_id is defined, use that to pull the relationship
// out of the graph and get a more appropriate icon.
if( parent_id ){
// Try and dig out the rel to display.
var edges = graph.get_edges(raw_id, parent_id);
if( edges && edges.length ){
var weight = {
'is_a': 3,
'part_of': 2
};
var unknown_rel_weight = 1;
edges.sort(
function(a, b){
var aw = weight[a.predicate_id()];
if( ! aw ){ aw = unknown_rel_weight; }
var bw = weight[b.predicate_id()];
if( ! bw ){ bw = unknown_rel_weight; }
return bw - aw;
});
// Add it in a brittle way.
var prime_rel = edges[0].predicate_id();
retnode['data']['icon'] =
server_meta.image_base() + '/' + prime_rel + '.gif';
}
}
return retnode;
}
|
javascript
|
{
"resource": ""
}
|
q55959
|
_new_manager
|
train
|
function _new_manager(){
var engine = new jquery_engine(golr_response);
engine.method('GET');
engine.use_jsonp(true);
var manager = new golr_manager(gserv_bulk, gconf, engine, 'async');
return manager;
}
|
javascript
|
{
"resource": ""
}
|
q55960
|
_get_filters
|
train
|
function _get_filters(filter_manager){
var lstate = filter_manager.get_filter_query_string();
var lparams = bbop.url_parameters(decodeURIComponent(lstate));
var filters_as_strings = [];
us.each(lparams, function(lparam){
if( lparam[0] === 'fq' && lparam[1] ){
filters_as_strings.push(lparam[1]);
}
});
//console.log('pass filter state: ', filters_as_strings);
return filters_as_strings;
}
|
javascript
|
{
"resource": ""
}
|
q55961
|
TermInfoStage
|
train
|
function TermInfoStage(term_accs){
// Ready logging.
var logger = new bbop.logger();
logger.DEBUG = true;
function ll(str){ logger.kvetch('JSM01: ' + str); }
ll('TermInfoStage start...');
// Prep the progress bar and hide the order selector until we're
// done.
jQuery("#progress-text").empty();
jQuery("#progress-text").append('<b>Loading...</b>');
//jQuery("#progress-bar").empty();
jQuery("#progress-widget").show();
jQuery("#order-selector").hide();
// Now, cycle though all of the terms to collect info on.
ll('Gathering batch functions for term info...');
var run_funs = [];
var term_user_order = {};
us.each(term_accs, function(r, r_i){
// Remember the incoming order.
term_user_order[r] = r_i;
// Create runner function.
run_funs.push(function(){
// Manager settings.
var go = _new_manager();
go.set_personality('ontology');
// Set the next query and go.
go.set_id(r);
return go.search();
});
});
var term_info = {};
// Fetch the data and grab the number we want.
var accumulator_fun = function(resp){
// Who was this?
var qval = resp.parameter('q');
var two_part = bbop.first_split(':', qval);
var acc = bbop.dequote(two_part[1]);
ll(' Looking at info for: ' + acc);
term_info[acc] = {
id : acc,
name: acc,
source : 'n/a',
index : term_user_order[acc]
};
// Dig out names and the like.
var doc = resp.get_doc(0);
if( doc ){
term_info[acc]['name'] = doc['annotation_class_label'];
term_info[acc]['source'] = doc['source'];
}
};
// The final function is the data renderer.
var final_fun = function(){
ll('Starting final in TermInfoStage...');
ll(' term_info: ' + bbop.dump(term_info));
TermDataStage(term_info, term_accs);
ll('Completed TermInfoStage!');
};
// Create and run coordinating manager.
var manager = _new_manager();
manager.run_promise_functions(
run_funs,
accumulator_fun,
final_fun,
function(err){
alert(err.toString());
});
}
|
javascript
|
{
"resource": ""
}
|
q55962
|
_abstract_solr_filter_template
|
train
|
function _abstract_solr_filter_template(filters){
var allbuf = new Array();
for( var filter_key in filters ){
var filter_val = filters[filter_key];
// If the value looks like an array, iterate over it and
// collect.
if( filter_val &&
filter_val != null &&
typeof filter_val == 'object' &&
filter_val.length ){
for( var i = 0; i < filter_val.length; i++ ){
var minibuffer = new Array();
var try_val = filter_val[i];
if( typeof(try_val) != 'undefined' &&
try_val != '' ){
minibuffer.push('fq=');
minibuffer.push(filter_key);
minibuffer.push(':');
minibuffer.push('"');
minibuffer.push(filter_val[i]);
minibuffer.push('"');
allbuf.push(minibuffer.join(''));
}
}
}else{
var minibuf = new Array();
if( typeof(filter_val) != 'undefined' &&
filter_val != '' ){
minibuf.push('fq=');
minibuf.push(filter_key);
minibuf.push(':');
minibuf.push('"');
minibuf.push(filter_val);
minibuf.push('"');
allbuf.push(minibuf.join(''));
}
}
}
return allbuf.join('&');
}
|
javascript
|
{
"resource": ""
}
|
q55963
|
_roots2json
|
train
|
function _roots2json(doc){
var root_id = doc['annotation_class'];
console.log("_roots2json: " +
doc + ', ' +
root_id + ', ' +
entity_counts[root_id]);
// Extract the intersting graphs.
var topo_graph_field = 'topology_graph_json';
var trans_graph_field = 'regulates_transitivity_graph_json';
var topo_graph = new model.graph();
topo_graph.load_base_json(JSON.parse(doc[topo_graph_field]));
var trans_graph = new model.graph();
trans_graph.load_base_json(JSON.parse(doc[trans_graph_field]));
//
var kids_p = false;
var kids = [];
us.each(topo_graph.get_child_nodes(root_id), function(kid){
kids.push({
'id': kid.id(),
'text': kid.label() || kid.id()
});
});
if( kids.length > 0 ){
kids_p = true;
}
// Using the badge template, get the spans for the IDs.
var ac_badges = new CountBadges(filter_manager);
var id_to_badge_text =
ac_badges.make_badge(root_id, entity_counts[root_id]);
var lbl_txt = doc['annotation_class_label'] || root_id;
var tmpl = {
'id': root_id,
'icon': 'glyphicon glyphicon-record',
'text': lbl_txt + id_to_badge_text,
//'icon': "string",
'state': {
'opened': false,
'disabled': false,
'selected': false
},
'children': kids_p,
'li_attr': {},
'a_attr': {}
};
return tmpl;
}
|
javascript
|
{
"resource": ""
}
|
q55964
|
_resp2json
|
train
|
function _resp2json(doc){
console.log("_resp2json: " + doc);
var kids = []; // ret
// Extract the intersting graphs.
var topo_graph_field = 'topology_graph_json';
var trans_graph_field = 'regulates_transitivity_graph_json';
var topo_graph = new model.graph();
topo_graph.load_base_json(JSON.parse(doc[topo_graph_field]));
var trans_graph = new model.graph();
trans_graph.load_base_json(JSON.parse(doc[trans_graph_field]));
//console.log('topo: ' + doc[topo_graph_field]);
// Collect child ids.
var child_ids = [];
us.each(topo_graph.get_child_nodes(doc['id']), function(kid){
child_ids.push(kid.id());
});
// Using the badger, get the spans for the IDs.
var ac_badges = new CountBadges(filter_manager);
var ids_to_badge_text = ac_badges.get_future_badges(child_ids);
//
us.each(topo_graph.get_child_nodes(doc['id']), function(kid){
// Extract some info.
var oid = doc['id'];
var sid = kid.id();
var preds = topo_graph.get_predicates(sid, oid);
var imgsrc = bbop.resourcify(sd.image_base, preds[0], 'gif');
var lbl_txt = kid.label() || sid;
// Push template.
kids.push({
'id': sid,
'text': lbl_txt + ids_to_badge_text[sid],
'icon': imgsrc,
'state': {
'opened': false,
'disabled': false,
'selected': false
},
'children': true, // unknowable w/o lookahead
'li_attr': {},
'a_attr': {}
});
});
return kids;
}
|
javascript
|
{
"resource": ""
}
|
q55965
|
train
|
function(term_id){
return function(){
// Create manager.
var engine = new jquery_engine(golr_response);
engine.method('GET');
engine.use_jsonp(true);
var manager = new golr_manager(gserv, gconf, engine, 'async');
// Manager settings.
var personality = 'bioentity';
var confc = gconf.get_class(personality);
manager.set_personality(personality);
manager.add_query_filter('document_category',
confc.document_category());
manager.set_results_count(0); // don't need any actual rows returned
manager.set_facet_limit(0); // care not about facets
manager.add_query_filter('regulates_closure', term_id);
//manager.add_query_filter('isa_partof_closure', term_id);
return manager.search();
};
}
|
javascript
|
{
"resource": ""
}
|
|
q55966
|
train
|
function( map ){
var empty = true;
if( map != null ){
for(var i in map){
empty = false;
break;
}
}
return empty;
}
|
javascript
|
{
"resource": ""
}
|
|
q55967
|
train
|
function( options ){
var obj = options.map;
var keys = options.keys;
var l = keys.length;
var keepChildren = options.keepChildren;
for(var i = 0; i < l; i++){
var key = keys[i];
if( $$.is.plainObject( key ) ){
$$.util.error('Tried to delete map with object key');
}
var lastKey = i === options.keys.length - 1;
if( lastKey ){
if( keepChildren ){ // then only delete child fields not in keepChildren
for( var child in obj ){
if( !keepChildren[child] ){
delete obj[child];
}
}
} else {
delete obj[key];
}
} else {
obj = obj[key];
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55968
|
train
|
function( str ){
var first, last;
// find first non-space char
for( first = 0; first < str.length && str[first] === ' '; first++ ){}
// find last non-space char
for( last = str.length - 1; last > first && str[last] === ' '; last-- ){}
return str.substring(first, last + 1);
}
|
javascript
|
{
"resource": ""
}
|
|
q55969
|
train
|
function( params ){
var defaults = {
field: 'data',
event: 'data',
triggerFnName: 'trigger',
triggerEvent: false,
immutableKeys: {} // key => true if immutable
};
params = $$.util.extend({}, defaults, params);
return function removeDataImpl( names ){
var p = params;
var self = this;
var selfIsArrayLike = self.length !== undefined;
var all = selfIsArrayLike ? self : [self]; // put in array if not array-like
var single = selfIsArrayLike ? self[0] : self;
// .removeData('foo bar')
if( $$.is.string(names) ){ // then get the list of keys, and delete them
var keys = names.split(/\s+/);
var l = keys.length;
for( var i = 0; i < l; i++ ){ // delete each non-empty key
var key = keys[i];
if( $$.is.emptyString(key) ){ continue; }
var valid = !p.immutableKeys[ key ]; // not valid if immutable
if( valid ){
for( var i_a = 0, l_a = all.length; i_a < l_a; i_a++ ){
delete all[ i_a ]._private[ p.field ][ key ];
}
}
}
if( p.triggerEvent ){
self[ p.triggerFnName ]( p.event );
}
// .removeData()
} else if( names === undefined ){ // then delete all keys
for( var i_a = 0, l_a = all.length; i_a < l_a; i_a++ ){
var _privateFields = all[ i_a ]._private[ p.field ];
for( var key in _privateFields ){
var validKeyToDelete = !p.immutableKeys[ key ];
if( validKeyToDelete ){
delete _privateFields[ key ];
}
}
}
if( p.triggerEvent ){
self[ p.triggerFnName ]( p.event );
}
}
return self; // maintain chaining
}; // function
}
|
javascript
|
{
"resource": ""
}
|
|
q55970
|
train
|
function(){
return {
classes: [],
colonSelectors: [],
data: [],
group: null,
ids: [],
meta: [],
// fake selectors
collection: null, // a collection to match against
filter: null, // filter function
// these are defined in the upward direction rather than down (e.g. child)
// because we need to go up in Selector.filter()
parent: null, // parent query obj
ancestor: null, // ancestor query obj
subject: null, // defines subject in compound query (subject query obj; points to self if subject)
// use these only when subject has been defined
child: null,
descendant: null
};
}
|
javascript
|
{
"resource": ""
}
|
|
q55971
|
train
|
function( expectation ){
var expr;
var match;
var name;
for( var j = 0; j < exprs.length; j++ ){
var e = exprs[j];
var n = e.name;
// ignore this expression if it doesn't meet the expectation function
if( $$.is.fn( expectation ) && !expectation(n, e) ){ continue }
var m = remaining.match(new RegExp( '^' + e.regex ));
if( m != null ){
match = m;
expr = e;
name = n;
var consumed = m[0];
remaining = remaining.substring( consumed.length );
break; // we've consumed one expr, so we can return now
}
}
return {
expr: expr,
match: match,
name: name
};
}
|
javascript
|
{
"resource": ""
}
|
|
q55972
|
train
|
function( roots, fn, directed ){
directed = arguments.length === 1 && !$$.is.fn(fn) ? fn : directed;
fn = $$.is.fn(fn) ? fn : function(){};
var cy = this._private.cy;
var v = $$.is.string(roots) ? this.filter(roots) : roots;
var Q = [];
var connectedEles = [];
var connectedFrom = {};
var id2depth = {};
var V = {};
var j = 0;
var found;
var nodes = this.nodes();
var edges = this.edges();
// enqueue v
for( var i = 0; i < v.length; i++ ){
if( v[i].isNode() ){
Q.unshift( v[i] );
V[ v[i].id() ] = true;
connectedEles.push( v[i] );
id2depth[ v[i].id() ] = 0;
}
}
while( Q.length !== 0 ){
var v = Q.shift();
var depth = id2depth[ v.id() ];
var ret = fn.call(v, j++, depth);
if( ret === true ){
found = v;
break;
}
if( ret === false ){
break;
}
var vwEdges = v.connectedEdges(directed ? '[source = "' + v.id() + '"]' : undefined).intersect( edges );
for( var i = 0; i < vwEdges.length; i++ ){
var e = vwEdges[i];
var w = e.connectedNodes('[id != "' + v.id() + '"]').intersect( nodes );
if( w.length !== 0 && !V[ w.id() ] ){
w = w[0];
Q.push( w );
V[ w.id() ] = true;
id2depth[ w.id() ] = id2depth[ v.id() ] + 1;
connectedEles.push( w );
connectedEles.push( e );
}
}
}
return {
path: new $$.Collection( cy, connectedEles ),
found: new $$.Collection( cy, found )
};
}
|
javascript
|
{
"resource": ""
}
|
|
q55973
|
train
|
function(){
var ele = this[0];
if( ele && ele.isNode() ){
var h = ele._private.style.height;
return h.strValue === 'auto' ? ele._private.autoHeight : h.pxValue;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55974
|
train
|
function( selector ){
var eles = this;
var roots = [];
for( var i = 0; i < eles.length; i++ ){
var ele = eles[i];
if( !ele.isNode() ){
continue;
}
var hasEdgesPointingIn = ele.connectedEdges('[target = "' + ele.id() + '"][source != "' + ele.id() + '"]').length > 0;
if( !hasEdgesPointingIn ){
roots.push( ele );
}
}
return new $$.Collection( this._private.cy, roots ).filter( selector );
}
|
javascript
|
{
"resource": ""
}
|
|
q55975
|
train
|
function( selector ){
var eles = this;
var fNodes = [];
for( var i = 0; i < eles.length; i++ ){
var ele = eles[i];
var eleId = ele.id();
if( !ele.isNode() ){ continue; }
var edges = ele._private.edges;
for( var j = 0; j < edges.length; j++ ){
var edge = edges[j];
var srcId = edge._private.data.source;
var tgtId = edge._private.data.target;
if( srcId === eleId && tgtId !== eleId ){
fNodes.push( edge.target()[0] );
}
}
}
return new $$.Collection( this._private.cy, fNodes ).filter( selector );
}
|
javascript
|
{
"resource": ""
}
|
|
q55976
|
train
|
function(node, dragElements) {
node._private.grabbed = true;
node._private.rscratch.inDragLayer = true;
dragElements.push(node);
for (var i=0;i<node._private.edges.length;i++) {
node._private.edges[i]._private.rscratch.inDragLayer = true;
}
//node.trigger(new $$.Event(e, {type: 'grab'}));
}
|
javascript
|
{
"resource": ""
}
|
|
q55977
|
train
|
function( eles ){
for( var i = 0; i < eles.length; i++ ){
eles[i]._private.grabbed = false;
eles[i]._private.rscratch.inDragLayer = false;
if( eles[i].active() ){ eles[i].unactivate(); }
}
}
|
javascript
|
{
"resource": ""
}
|
|
q55978
|
validateOptions
|
train
|
function validateOptions(options) {
const notSupported = _.reject(_.keys(options), (key) => (
OPTIONS.has(key)
));
if (notSupported.length > 0) {
console.warn(`[${PLUGIN_NAME}] Options ${notSupported} are not supported, use following options: ${Array.from(OPTIONS)}`);
}
}
|
javascript
|
{
"resource": ""
}
|
q55979
|
fixSourceMapOptions
|
train
|
function fixSourceMapOptions(options) {
// Rollup <= 0.48 used `sourceMap` in camelcase, so this plugin used
// this convention at the beginning.
// Now, the `sourcemap` key should be used, but legacy version should still
// be able to use the `sourceMap` key.
const newOptions = _.omitBy(options, (value, key) => (
key === 'sourceMap'
));
// If the old `sourceMap` key is used, set it to `sourcemap` key.
if (_.hasIn(options, 'sourceMap')) {
console.warn(`[${PLUGIN_NAME}] sourceMap has been deprecated, please use sourcemap instead.`);
if (!_.hasIn(newOptions, 'sourcemap')) {
newOptions.sourcemap = options.sourceMap;
}
}
// Validate options.
validateOptions(newOptions);
return newOptions;
}
|
javascript
|
{
"resource": ""
}
|
q55980
|
_ping_count
|
train
|
function _ping_count(){
if( count_url && typeof(count_url) === 'string' && count_url !== '' ){
request({
url: count_url
}, function(error, response, body){
if( error || response.statusCode !== 200 ){
console.log('Unable to ping: ' + count_url);
}else{
console.log('Pinged: ' + count_url);
}
});
}else{
console.log('Will not ping home.');
}
}
|
javascript
|
{
"resource": ""
}
|
q55981
|
_client_compile_task
|
train
|
function _client_compile_task(file) {
var infile = amigo_js_dev_path + '/' +file;
//var outfile = amigo_js_out_path + '/' +file;
var b = browserify(infile);
return b
// not in npm, don't need in browser
.exclude('ringo/httpclient')
.bundle()
// desired output filename to vinyl-source-stream
.pipe(source(file))
.pipe(gulp.dest(amigo_js_out_path));
}
|
javascript
|
{
"resource": ""
}
|
q55982
|
getProfile
|
train
|
function getProfile(provider, access_token, callback) {
let fields;
switch (provider) {
case 'facebook':
facebook.query().get('me?fields=name,email').auth(access_token).request(function (err, res, body) {
if (err) {
callback(err);
} else {
callback(null, {
username: body.name,
email: body.email
});
}
});
break;
case 'google':
google.query('plus').get('people/me').auth(access_token).request(function (err, res, body) {
if (err) {
callback(err);
} else {
callback(null, {
username: body.displayName,
email: body.emails[0].value
});
}
});
break;
case 'github':
github.query().get('user').auth(access_token).request(function (err, res, body) {
if (err) {
callback(err);
} else {
callback(null, {
username: body.login,
email: body.email
});
}
});
break;
case 'linkedin2':
fields = [
'public-profile-url', 'email-address'
];
linkedin.query().select('people/~:(' + fields.join() + ')?format=json').auth(access_token).request(function (err, res, body) {
if (err) {
callback(err);
} else {
callback(null, {
username: substr(body.publicProfileUrl.lastIndexOf('/') + 1),
email: body.emailAddress
});
}
});
break;
default:
callback({
message: 'Unknown provider.'
});
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q55983
|
train
|
function(){
var retval = false;
var lc = jQuery(this).text().toLowerCase();
if( lc.indexOf(stext) >= 0 ){
retval = true;
}
return retval;
}
|
javascript
|
{
"resource": ""
}
|
|
q55984
|
_has_item
|
train
|
function _has_item(in_arg_key){
var retval = false;
if( typeof anchor.current_data[in_arg_key] != 'undefined' ){
retval = true;
}
return retval;
}
|
javascript
|
{
"resource": ""
}
|
q55985
|
_add_item
|
train
|
function _add_item(in_arg_key, data){
var retval = false;
if( typeof anchor.current_data[in_arg_key] == 'undefined' ){
// BUG/TODO: this should be a copy.
anchor.current_data[in_arg_key] = data;
//ll("add_item: adding key (w/data): " + in_arg_key);
retval = true;
}
return retval;
}
|
javascript
|
{
"resource": ""
}
|
q55986
|
_update_value
|
train
|
function _update_value(inkey, intype, inval){
// Update the value in question.
var rval = false;
if( typeof anchor.current_data[inkey] != 'undefined' &&
typeof anchor.current_data[inkey][intype] != 'undefined' ){
anchor.current_data[inkey][intype] = inval;
rval = true;
// ll("\tupdated: " + inkey +
// "'s " + intype +
// ' to ' + inval);
}
// Bookkeeping to keep the "no filter" option selected
// or not in all cases.
if( _get_selected_items().length == 0 ){
anchor.current_data['_nil_']['selected'] = true;
}else{
anchor.current_data['_nil_']['selected'] = false;
}
return rval;
}
|
javascript
|
{
"resource": ""
}
|
q55987
|
_get_selected_items
|
train
|
function _get_selected_items(){
var ret_filters = [];
// Push out the filters that have selected == true.
var all_filters = _get_all_items();
for( var afi = 0; afi < all_filters.length; afi++ ){
var filter_name = all_filters[afi];
var fconf = anchor.current_data[filter_name];
if( fconf &&
typeof fconf['selected'] != 'undefined' &&
fconf['selected'] == true ){
ret_filters.push(filter_name);
}
}
return ret_filters;
}
|
javascript
|
{
"resource": ""
}
|
q55988
|
_render_label
|
train
|
function _render_label(){
var buf = new Array();
// Add the label.
buf.push('<label for="');
buf.push(anchor.mid);
buf.push('" class="select">');
buf.push(anchor.mlabel);
buf.push('</label>');
return buf.join('');
}
|
javascript
|
{
"resource": ""
}
|
q55989
|
_render_option
|
train
|
function _render_option(){
var buf = new Array();
// Sort the items in the mdata array.
// Also keep a lookup for a "special" entry.
// var default_on_p = false;
var mdata_keys = bbop.core.get_keys(anchor.mdata);
function _data_comp(a, b){
// Get the associated data.
var a_data = anchor.mdata[a];
var b_data = anchor.mdata[b];
// if( (a_data['special'] == true && a_data['selected'] == true) ||
// (b_data['special'] == true && b_data['selected'] == true) ){
// default_on_p = true;
// }
//
var retval = 0;
if( a_data['special'] != b_data['special'] ){
if( a_data['count'] == true ){
retval = 1;
}else{
retval = -1;
}
}else if( a_data['count'] != b_data['count'] ){
if( a_data['count'] > b_data['count'] ){
retval = -1;
}else{
retval = 1;
}
}else if( a_data['label'] != b_data['label'] ){
if( a_data['label'] > b_data['label'] ){
retval = 1;
}else{
retval = -1;
}
}
return retval;
}
mdata_keys.sort(_data_comp); // inplace sort
//
for( var mski = 0; mski < mdata_keys.length; mski++ ){
var write_data = anchor.mdata[mdata_keys[mski]];
// Write out option if:
// 1) the default is selected (so we want to see everything)
// 2) the selection is special
// 3) if the default is not selected, either the item is selected or
// 4) it has a count (and is thus interesting)
if( // default_on_p == true ||
write_data['selected'] == true ||
write_data['special'] == true ||
( write_data['count'] && write_data['count'] > 0 ) ){
buf.push('<option');
// Title.
buf.push(' title="');
buf.push(write_data['value']);
buf.push('"');
// Value.
buf.push(' value="');
buf.push(write_data['value']);
buf.push('"');
if( write_data['selected'] ){
buf.push(' selected="selected"');
}
buf.push('>');
//buf.push(bbop.core.crop(write_data['label']));
buf.push(bbop.core.crop(write_data['label'], 40, '...'));
if( write_data['count'] && write_data['count'] > 0 ){
buf.push(' (' + write_data['count'] + ')');
}
buf.push('</option>');
}
}
return buf.join('');
}
|
javascript
|
{
"resource": ""
}
|
q55990
|
_render_select
|
train
|
function _render_select(){
var buf = new Array();
//
buf.push('<select id="');
buf.push(anchor.mid);
buf.push('" name="');
buf.push(anchor.mname);
buf.push('" multiple size="');
buf.push(anchor.msize);
buf.push('">');
buf.push(_render_option());
//
buf.push('</select>');
return buf.join('');
}
|
javascript
|
{
"resource": ""
}
|
q55991
|
forward
|
train
|
function forward(doc){
if( doc && doc['entity'] && doc['category'] ){
// Erase any val, change the placeholder (to try and
// prevent races where the user selects and then hits
// "search" before the forwarding finishes).
jQuery('#' + wired_name).val('');
jQuery('#' + wired_name).attr('placeholder', 'Forwarding to ' +
doc['entity'] + '...');
// Forward to the new doc.
if( doc['category'] === 'ontology_class' ){
window.location.href =
linker.url(doc['entity'], 'term');
}else if( doc['category'] === 'bioentity' ){
window.location.href = linker.url(doc['entity'], 'gp');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q55992
|
_generate_element
|
train
|
function _generate_element(ctype){
var UID = id_base + bbop.core.randomness();
var div_text = '<div id="' + UID + '"></div>';
jQuery("body").append(jQuery(div_text).hide());
var elt = jQuery('#' + UID);
elt.addClass("org_bbop_amigo_ui_widget_base");
elt.addClass("org_bbop_amigo_ui_widget_for_" + ctype);
return elt;
}
|
javascript
|
{
"resource": ""
}
|
q55993
|
envelope
|
train
|
function envelope(service_name){
var anchor = this;
anchor._is_a = 'bbop-service-envelope';
// Start the timer.
anchor._start_time = second_count();
// Theoretical good result frame.
anchor._envelope = {
service: 'n/a',
status: 'success',
arguments: {},
comments: [],
data: {}
};
//
if( service_name && typeof(service_name) === 'string' ){
anchor._envelope['service'] = service_name;
}
}
|
javascript
|
{
"resource": ""
}
|
q55994
|
_response_json_fail
|
train
|
function _response_json_fail(res, envl, message){
envl.status('failure');
envl.comments(message);
return res.json(envl.structure());
}
|
javascript
|
{
"resource": ""
}
|
q55995
|
_param
|
train
|
function _param(req, param, pdefault){
var ret = null;
// Try the route parameter space.
if( req && req.params && typeof(req.params[param]) !== 'undefined' ){
ret = req.params[param];
}
// Try the get space.
if( ! ret ){
if( req && req.query && req.query[param] && typeof(req.query[param]) !== 'undefined' ){
ret = req.query[param];
}
}
// Otherwise, try the body space.
if( ! ret ){
var decoded_body = req.body || {};
if( decoded_body && ! us.isEmpty(decoded_body) && decoded_body[param] ){
ret = decoded_body[param];
}
}
// Reduce to first if array.
if( us.isArray(ret) ){
if( ret.length === 0 ){
ret = pdefault;
}else{
ret = ret[0];
}
}
// Finally, default.
if( ! ret ){
ret = pdefault;
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q55996
|
_extract
|
train
|
function _extract(req, param){
var ret = [];
// Note: no route parameter possible with lists(?).
// Try the get space.
if( req && req.query && typeof(req.query[param]) !== 'undefined' ){
//console.log('as query');
// Input as list, remove dupes.
var paccs = req.query[param];
if( paccs && ! us.isArray(paccs) ){
paccs = [paccs];
}
ret = us.uniq(paccs);
}
// Otherwise, try the body space.
if( us.isEmpty(ret) ){
var decoded_body = req.body || {};
if( decoded_body && ! us.isEmpty(decoded_body) && decoded_body[param] ){
//console.log('as body');
// Input as list, remove dupes.
var baccs = decoded_body[param];
//console.log('decoded_body', decoded_body);
//console.log('baccs', baccs);
if( baccs && ! us.isArray(baccs) ){
baccs = [baccs];
}
ret = us.uniq(baccs);
}
}
return ret;
}
|
javascript
|
{
"resource": ""
}
|
q55997
|
train
|
function(cache){
// Frame to hang our results on.
var results = {
"good": [],
"bad": [],
"ugly": []
};
// Break out the two parts of the species cache.
var doc_lookup = cache['documents'];
var str_refs = cache['references'];
// Comb through the cache, carefully, and get the results
// that we can. First, for each of the entities try and
// pull out the right fields.
us.each(entities, function(entity){
var entity_hits = [];
// Check to see if we can find any document references
// for our given string.
if( str_refs && us.isArray(str_refs[entity]) ){
// For each of the matched IDs, lookup the
// document in question and try and figure out
// which field or fields matched.
var match_proxy_ids = str_refs[entity];
us.each(match_proxy_ids, function(match_proxy_id){
// Retrieve the document by proxy ID.
var doc = doc_lookup[match_proxy_id];
if( doc ){
// Look in all the possibly multi-valued
// fields in the doc for the match.
us.each(bioentity_search_fields, function(search_field){
//console.log("search_field: ", search_field);
var vals = doc[search_field];
// Array-ify the field if not already.
if( vals && ! us.isArray(vals) ){
vals = [vals];
}
us.each(vals, function(val){
// Record that we found the exact
// match we want.
if( entity === val ){
entity_hits.push({
"id": match_proxy_id,
"matched": search_field
});
}
});
});
}
});
}
// The results are good, bad, or ugly, depending on the
// number.
var rtype = null;
if( entity_hits.length === 1 ){
rtype = "good";
}else if( entity_hits.length === 0 ){
rtype = "bad";
}else{
rtype = "ugly";
}
//console.log("results: ", results);
// Push the found results into the right section.
results[rtype].push({
"input": entity,
"results": entity_hits
});
});
return results;
}
|
javascript
|
{
"resource": ""
}
|
|
q55998
|
train
|
function(open, close) {
this.fieldOpen = (typeof open === 'string' && open.length) ? open : '____';
this.fieldClose = (typeof close === 'string' && close.length) ? close : this.fieldOpen;
var fieldPattern = this.fieldOpen +'(.+?)'+ this.fieldClose;
this.fieldRegex = new RegExp(fieldPattern);
this.fieldRegexAll = new RegExp(fieldPattern, 'g');
}
|
javascript
|
{
"resource": ""
}
|
|
q55999
|
train
|
function(varsData) {
if (isJSON(varsData)) {
// JSON variables
varsData = JSON.parse(varsData);
for (var key in varsData) {
if (varsData.hasOwnProperty(key)) {
this.vars[normalizeVarName(key)] = varsData[key];
}
}
}
else {
// Sass variables
var pattern = /\$([^\s:]+)\s*:\s*([^!;]+)/g;
var match = pattern.exec(varsData);
while (match) {
this.vars[ match[1] ] = match[2].trim();
match = pattern.exec(varsData);
}
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.