_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q64400
|
Limon
|
test
|
function Limon (input, options) {
if (!(this instanceof Limon)) {
return new Limon(input, options)
}
lazy.use(this, {
fn: function (app, opts) {
app.options = lazy.utils.extend(app.options, opts)
}
})
this.defaults(input, options)
this.use(lazy.plugin.prevNext())
}
|
javascript
|
{
"resource": ""
}
|
q64401
|
planner
|
test
|
function planner(origin, dest, opts) {
var tasks = new TaskPlanner();
var cmds = generateCommands(origin, dest);
var state = _.cloneDeep(origin);
var result;
opts = xtend(defaults, opts);
assert(opts.mode === 'quick' || opts.mode === 'safe', 'unknown mode');
tasks.addTask({ cmd: 'nop' }, {});
generateDetachTasks(tasks, origin, opts);
generateDetachTasks(tasks, dest, opts); // needed because of safe mode
generateConfigureTasks(tasks, origin, dest, opts);
_.forIn(state.topology.containers, function(container) {
container.running = true;
container.started = true;
container.added = true;
});
_.forIn(dest.topology.containers, function(container) {
var containers = state.topology.containers;
if (!containers[container.id]) {
containers[container.id] = {
id: container.id,
containedBy: container.containedBy,
running: false,
started: false,
added: false
};
}
});
result = cmds.reduce(function(acc, cmd) {
var plan = tasks.plan(state, cmd);
if (!plan) {
throw new Error('unable to generate ' + cmd.cmd + ' for id ' + cmd.id);
}
return acc.concat(plan);
}, []).filter(function(cmd) {
return cmd && cmd.cmd !== 'nop';
});
if (!opts.noLinkUnlinkRemove) {
result = linkFilter(result);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q64402
|
test
|
function(strip) {
if (!strip) {
console.log(messagingTexts.noStrip);
}
if (!(strip instanceof pixel.Strip)) {
console.log(messagingTexts.wrongStrip);
}
pattern.reset(strip, interval);
interval = pattern.domino(strip, 'white');
}
|
javascript
|
{
"resource": ""
}
|
|
q64403
|
test
|
function(strip) {
if (!strip) {
console.log(messagingTexts.noStrip);
}
if (!(strip instanceof pixel.Strip)) {
console.log(messagingTexts.wrongStrip);
}
pattern.reset(strip, interval);
setTimeout(function() {
pattern.flash(strip, 'green', 2);
}, 10);
}
|
javascript
|
{
"resource": ""
}
|
|
q64404
|
create
|
test
|
function create(parent, baseUrl, params, callback) {
parent.getClient().post(baseUrl, params, function(err, definition, response) {
if (err) return callback(err);
callback(null, new this(parent, definition));
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q64405
|
register
|
test
|
function register ( type, lang, handler ) {
if (Array.isArray(lang)) {
lang.forEach((v) => store[type].langs[v] = handler);
return;
}
store[type].langs[lang] = handler;
}
|
javascript
|
{
"resource": ""
}
|
q64406
|
test
|
function( kind, promisesDfd ) {
return function() {
// operate on this unless we forced a deferred to work on
var dfd = promisesDfd || this;
var fnSet = [].slice.call( arguments );
// as long as this is a progress handler or the state isn't reached add it
// otherwise call it right now
if ( kind === 'progress' || dfd.state === 'pending' ) {
dfd[ kind + 's' ].push( fnSet );
} else {
callSet.call( dfd, fnSet, this[ kind + 'Args' ] );
}
// if we forced a promiseDfd, return the promise
if ( promisesDfd ) {
return dfd.promise;
}
// otherwise return the root deferred like normal
return dfd;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q64407
|
test
|
function( set, args) {
// nothing to see here folks
if ( set.length < 1 ) {
return;
}
// the args to call with
var apply = [];
// we passed inline arguments
if ( set.length > 1 ) {
for ( var i = 1; i < set.length; i++ ) {
// is it one of those cool perform.arg(X) thingies?
// if not, just put the passed args in there
if ( set[i] instanceof Argument ) {
apply[i] = args[ set[i].num ];
} else {
apply[i] = set[i];
}
apply = apply.slice(1);
}
} else {
apply = args;
}
// actually call the fn with the appropriate args
set[0].apply( this, apply );
}
|
javascript
|
{
"resource": ""
}
|
|
q64408
|
test
|
function( kind, args ) {
var bucket = this[ kind + 's' ];
for ( var i = 0; i < bucket.length; i++ ) {
callSet.call( this, bucket[i], args );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q64409
|
test
|
function() {
var dfd = this;
// since people might be used to .promise()
var promise = function(){
return promise;
};
promise.done = stackNFire( 'done', dfd );
promise.fail = stackNFire( 'fail', dfd );
promise.progress = stackNFire( 'progress', dfd );
promise.state = dfd.state;
return promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q64410
|
test
|
function( kind ) {
return function() {
if ( this.state === 'pending' ) {
if ( kind !== 'progress' ) {
this[ kind + 'Args' ] = arguments;
this.state = this.promise.state = kind;
}
callSets.call( this, kind, arguments );
}
return this;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q64411
|
test
|
function() {
this.dones = [];
this.doneArgs = [];
this.fails = [];
this.failArgs = [];
this.pendings = [];
this.pendingArgs = [];
this.state = 'pending';
// expose the promise
this.promise = iPromise.call( this );
}
|
javascript
|
{
"resource": ""
}
|
|
q64412
|
test
|
function( performer ) {
// everything checks out
var state = performer.state;
// everything resolved
if ( state.allCount === 0 ) {
var args = [];
for ( var i = 0; i < performer.args.length; i++ ) {
args = args.concat( [].concat( performer.args[i].args ) );
}
// either fail/done are 0 or something went wrong
if ( state.targetCount === 0 ) {
performer._dfd.resolve.apply ( performer._dfd, args );
} else {
performer._dfd.reject.apply( performer._dfd, args );
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q64413
|
test
|
function(schema) {
this._decoders = decoders;
this._encoders = encoders;
this._schemas = {};
// Allow to pass the fields direclty
if(Object.keys(schema).join(',') !== 'name,fields'){
schema = {
name: '_auto-' + new Date().getTime(),
fields: schema
};
}
this._schema = schema;
this._fieldIndex = Object.keys(schema.fields);
this._schemas[schema.name] = schema;
}
|
javascript
|
{
"resource": ""
}
|
|
q64414
|
test
|
function(selector, properties, value) {
let rule = postcss.rule({selector: selector})
let decls = _.map(properties, function(property) {
return postcss.decl({prop: property, value: value})
})
rule.append(decls)
return rule
}
|
javascript
|
{
"resource": ""
}
|
|
q64415
|
test
|
function(breakpoints, spacingScale) {
return _.map(breakpoints, function(breakpointValue, breakpointKey) {
let mediaQuery = postcss.atRule({
name: 'media',
params: breakpointValue,
})
let rules = _.flatMap(spacingScale, function(scaleValue, scaleKey) {
return _.map(helpers, function(helperValues, helperKey) {
return makeFunctionalRule(
`.${breakpointKey}-${helperKey}${scaleKey}`,
helperValues,
scaleValue
)
})
})
return mediaQuery.append(rules)
})
}
|
javascript
|
{
"resource": ""
}
|
|
q64416
|
destroy
|
test
|
function destroy(callback) {
this.getClient().destroy(this.definition._links.self.href, function(err, definition, response) {
if (err) return callback(err);
callback();
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q64417
|
load_config
|
test
|
function load_config () {
let config = {};
if (fs.existsSync(pgrunner_config_file)) {
config = JSON.parse(fs.readFileSync(pgrunner_config_file, {'encoding':'utf8'}));
if (argv.v) {
debug.log('Loaded from ', pgrunner_config_file);
}
}
if (!is.array(config.servers)) {
config.servers = [];
}
return config;
}
|
javascript
|
{
"resource": ""
}
|
q64418
|
save_config
|
test
|
function save_config (config) {
fs.writeFileSync(pgrunner_config_file, JSON.stringify(config, null, 2), {'encoding':'utf8'});
if (argv.v) {
debug.log('Saved to ', pgrunner_config_file);
}
}
|
javascript
|
{
"resource": ""
}
|
q64419
|
get_server_opts
|
test
|
function get_server_opts (opts) {
debug.assert(opts).is('object');
debug.assert(opts.settings).is('object');
return {
'dbconfig': opts.dbconfig,
'host': opts.settings.host,
'port': opts.settings.port,
'user': opts.settings.user,
'database': opts.settings.database
};
}
|
javascript
|
{
"resource": ""
}
|
q64420
|
getResources
|
test
|
function getResources(domains) {
return store.getResources().then(rsrcs => {
return rsrcs.filter(e => domains.includes(e.domain));
});
}
|
javascript
|
{
"resource": ""
}
|
q64421
|
urlFormat
|
test
|
function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (isString(obj)) {
obj = urlParse(obj);
} else if (!isObject(obj) || isNull(obj)) {
throw new TypeError('Parameter "urlObj" must be an object, not ' +
isNull(obj) ? 'null' : typeof obj);
} else if (!(obj instanceof Url)) {
return Url.prototype.format.call(obj);
} else {
return obj.format();
}
}
|
javascript
|
{
"resource": ""
}
|
q64422
|
rayLineVsCircle
|
test
|
function rayLineVsCircle(ray, circle) {
var rayLine = new Line2(
ray.start.x,
ray.start.y,
ray.end.x,
ray.end.y
);
return rayLine.intersectCircle(circle.position, circle.radius);
}
|
javascript
|
{
"resource": ""
}
|
q64423
|
scopeUrl
|
test
|
function scopeUrl(options, inst) {
options = _.extend(_.clone(options || {}), inst)
if (typeof options !== 'object' && (!options.tournament_id || !options.flight_id))
throw new Error('tournament_id or flight_id required to make tibreak preference api calls')
var url = ''
if (options.tournament_id) {
url += ngin.Tournament.urlRoot() + '/' + options.tournament_id
} else if (options.flight_id) {
url += ngin.Flight.urlRoot() + '/' + options.flight_id
}
return url + TiebreakPreference.urlRoot()
}
|
javascript
|
{
"resource": ""
}
|
q64424
|
test
|
function(options, callback) {
var url = scopeUrl(options, this)
return Super.fetch.call(this, url, options, callback)
}
|
javascript
|
{
"resource": ""
}
|
|
q64425
|
test
|
function(module, debug) {
this.debug = debug || false;
this.jsonrpc = "2.0";
// check & load the methods in module
this.methods = module;
if(handy.getType(module)=='string') {
this.methods = require(module);
}
if(this.debug) {
logger.debug('Loaded with methods:'+_.functions(this.methods));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q64426
|
_getParamNames
|
test
|
function _getParamNames(func) {
var funStr = func.toString();
return funStr.slice(funStr.indexOf('(')+1, funStr.indexOf(')')).match(/([^\s,]+)/g);
}
|
javascript
|
{
"resource": ""
}
|
q64427
|
_getChangedProperties
|
test
|
function _getChangedProperties() {
var retVal = {}, key;
for (key in this._changed) {
retVal[key] = this._changed[key];
}
return retVal;
}
|
javascript
|
{
"resource": ""
}
|
q64428
|
update
|
test
|
function update(properties, callback) {
if (typeof properties == 'function') {
callback = properties;
properties = {};
}
var key, changed;
var exceptions = ['addresses_update_action', 'emails_update_action', 'phone_numbers_update_action'];
for (key in properties) {
if ('set' + inflection.camelize(key) in this) {
this['set' + inflection.camelize(key)](properties[key]);
} else if(exceptions.indexOf(key) != -1) {
this._changed[key] = properties[key];
}
}
changed = this._getChangedProperties();
this.getClient().patch(this.definition._links.self.href, changed, function(err, definition, response) {
if (err) return callback(err);
this.definition = definition;
this._setup();
callback(null, this);
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
q64429
|
byClass
|
test
|
function byClass (c) {
c = classnames(c)
if (/^\./.test(c)) {
throw new Error('No need to "." on start')
}
return bySelector(`.${c}`)
}
|
javascript
|
{
"resource": ""
}
|
q64430
|
subtemplate
|
test
|
function subtemplate(template, data) {
try {
return new JSDOC.JsPlate(publish.conf.templatesDir+template).process(data);
}
catch(e) { print(e.message); quit(); }
}
|
javascript
|
{
"resource": ""
}
|
q64431
|
makeSignature
|
test
|
function makeSignature(params) {
if (!params) return "()";
var signature = "("
+
params.filter(
function($) {
return !/\w+\.\w+/.test($.name);
}
).map(
function($) {
var name = $.isOptional ?
'[' + $.name + ']' : $.name;
return name;
}
).join(", ")
+
")";
return signature;
}
|
javascript
|
{
"resource": ""
}
|
q64432
|
approach
|
test
|
function approach(index, x, onAxis)
{
while (0 <= x && x <= 1) {
candidateHSVA[index] = x;
WebInspector.Color.hsva2rgba(candidateHSVA, candidateRGBA);
WebInspector.Color.blendColors(candidateRGBA, bgRGBA, blendedRGBA);
var fgLuminance = WebInspector.Color.luminance(blendedRGBA);
var dLuminance = fgLuminance - desiredLuminance;
if (Math.abs(dLuminance) < (onAxis ? epsilon / 10 : epsilon))
return x;
else
x += (index === V ? -dLuminance : dLuminance);
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q64433
|
updateNodeColor
|
test
|
function updateNodeColor(data) {
d3.selectAll('.node').select('.node-symbol')
.style('fill', d => d3scale.scaleFunction(data.scale)(d[data.column.key]));
}
|
javascript
|
{
"resource": ""
}
|
q64434
|
mainControlBox
|
test
|
function mainControlBox() {
d3.select('#show-struct')
.on('change', function () {
const data = nodeContentInput();
d3.select('#main-control').datum(data);
updateNodeStructure(data);
})
.dispatch('change');
}
|
javascript
|
{
"resource": ""
}
|
q64435
|
centerGraph
|
test
|
function centerGraph(newScale, duration, delay)
{
if (typeof delay === 'function') { delay = delay.call(this); }
delay = typeof delay === 'number' ? delay : 0;
setTimeout(function()
{
if (typeof newScale === 'function') { newScale = newScale.call(this); }
if (typeof duration === 'function') { duration = duration.call(this); }
newScale = typeof newScale === 'number' ? newScale : zoom.scale();
duration = typeof duration === 'number' ? duration : 200;
if (typeof newScale !== 'number') { throw new TypeError("centerGraph error: 'newScale' is not a 'number'."); }
if (typeof duration !== 'number') { throw new TypeError("centerGraph error: 'duration' is not a 'number'."); }
var bounds = graph.node().getBBox();
var centerSVGX = (graphWidth * newScale / 2);
var centerSVGY = (graphHeight * newScale / 2);
var centerGraphX = (bounds.x * newScale) + (bounds.width * newScale / 2);
var centerGraphY = (bounds.y * newScale) + (bounds.height * newScale / 2);
// Translate
var centerTranslate =
[
(graphWidth / 2) - centerSVGX + (centerSVGX - centerGraphX),
(graphHeight / 2) - centerSVGY + (centerSVGY - centerGraphY)
];
// Store values
zoom
.translate(centerTranslate)
.scale(newScale);
// Render transition
graph.transition()
.duration(duration)
.attr('transform', 'translate(' + zoom.translate() + ')' + ' scale(' + zoom.scale() + ')');
// Hides any existing node context menu.
hideNodeContextMenu();
}, delay);
}
|
javascript
|
{
"resource": ""
}
|
q64436
|
detectAllNodesFixed
|
test
|
function detectAllNodesFixed()
{
if (data)
{
var currentNodesFixed = data.allNodesFixed;
var allNodesFixed = true;
data.nodes.forEach(function(node) { if (!node.fixed) { allNodesFixed = false; } });
data.allNodesFixed = allNodesFixed;
if (currentNodesFixed !== allNodesFixed) { updateMenuUI(); } // Update freeze / unfreeze menu option.
}
}
|
javascript
|
{
"resource": ""
}
|
q64437
|
fadeRelatedNodes
|
test
|
function fadeRelatedNodes(targetNode, selected, nodes, links)
{
var opacity = selected ? 0.1 : 1;
var elm = findElementByNode('circle', targetNode);
// Highlight circle
elm.classed('selected', opacity < 1);
// Clean links
$('path.link').removeAttr('data-show');
// Traverse all nodes and set `dimmed` class to nodes that are dimmed / not connected in addition to setting
// fill and stroke opacity.
nodes.style('stroke-opacity', function(otherNode)
{
var thisOpacity = isConnected(targetNode, otherNode) ? 1 : opacity;
this.setAttribute('fill-opacity', thisOpacity);
this.setAttribute('stroke-opacity', thisOpacity);
// Depending on opacity add or remove 'dimmed' class.
this.classList[thisOpacity === 1 ? 'remove' : 'add']('dimmed');
return thisOpacity;
});
// Traverse all links and set `data-show` and `marker-end` for connected links given the `targetNode`.
links.style('stroke-opacity', function(otherNode)
{
if (otherNode.source === targetNode)
{
// Highlight target / sources of the link
var elmNodes = graph.selectAll('.' + formatClassName('node', otherNode.target));
elmNodes.attr('fill-opacity', 1);
elmNodes.attr('stroke-opacity', 1);
elmNodes.classed('dimmed', false);
// Highlight arrows
var elmCurrentLink = $('path.link[data-source=' + otherNode.source.index + ']');
elmCurrentLink.attr('data-show', true);
elmCurrentLink.attr('marker-end', 'url(#regular)');
return 1;
}
else
{
return opacity;
}
});
// Modify all links that have not had 'data-show' added above.
var elmAllLinks = $('path.link:not([data-show])');
elmAllLinks.attr('marker-end', opacity === 1 ? 'url(#regular)' : '');
}
|
javascript
|
{
"resource": ""
}
|
q64438
|
findElementByNode
|
test
|
function findElementByNode(prefix, node)
{
var selector = '.' + formatClassName(prefix, node);
return graph.select(selector);
}
|
javascript
|
{
"resource": ""
}
|
q64439
|
getElementCoords
|
test
|
function getElementCoords(element)
{
var ctm = element.getCTM();
return { x: ctm.e + element.getAttribute('cx') * ctm.a, y: ctm.f + element.getAttribute('cy') * ctm.d };
}
|
javascript
|
{
"resource": ""
}
|
q64440
|
getSVG
|
test
|
function getSVG(elementType)
{
var returnVal;
var svgElement;
var cached;
switch (elementType)
{
case 'circle':
case 'g':
case 'path':
case 'text':
returnVal = function(data)
{
svgElement = svgElementMap[elementType].pop();
cached = svgElement != null;
svgElement = svgElement != null ? svgElement : document.createElementNS('http://www.w3.org/2000/svg',
elementType);
// Copy data to SVG element.
if (typeof data === 'object') { for (var key in data) { svgElement.setAttribute(key, data[key]); } }
return svgElement;
};
break;
default:
throw new TypeError('getSVG error: unknown elementType.');
}
return returnVal;
}
|
javascript
|
{
"resource": ""
}
|
q64441
|
hideNodeContextMenu
|
test
|
function hideNodeContextMenu(event)
{
// Provide an early out if there is no selected context node.
if (typeof selectedContextNode === 'undefined') { return; }
var contextMenuButton = $('#context-menu');
var popupmenu = $('#contextpopup .mdl-menu__container');
// If an event is defined then make sure it isn't targeting the context menu.
if (event)
{
event.preventDefault();
// Picked element is not the menu
if (!$(event.target).parents('#contextpopup').length > 0)
{
// Hide menu if currently visible
if (popupmenu.hasClass('is-visible')) { contextMenuButton.click(); }
fadeRelatedNodes(selectedContextNode, false, nodes, links);
selectedContextNode = undefined;
}
}
else // No event defined so always close context menu and remove node highlighting.
{
// Hide menu if currently visible
if (popupmenu.hasClass('is-visible')) { contextMenuButton.click(); }
fadeRelatedNodes(selectedContextNode, false, nodes, links);
selectedContextNode = undefined;
}
}
|
javascript
|
{
"resource": ""
}
|
q64442
|
isConnected
|
test
|
function isConnected(targetNode, otherNode)
{
return targetNode.index === otherNode.index || linkedByIndex[targetNode.index + ',' + otherNode.index];
}
|
javascript
|
{
"resource": ""
}
|
q64443
|
onControlDepsClicked
|
test
|
function onControlDepsClicked()
{
// Do nothing if scope has not changed
if (this.value === appOptions.currentScope) { return; }
// If max depth is set to sticky and current level is equal max level of old scope then set max level for
// the new scope.
if (appOptions.maxDepthSticky && appOptions.currentLevel === dataPackageMap[appOptions.currentScope].maxLevel)
{
appOptions.currentLevel = dataPackageMap[this.value].maxLevel
}
appOptions.currentScope = this.value;
var maxLevel = dataPackageMap[appOptions.currentScope].maxLevel;
// Adjust current level if it is greater than max level for current scope.
if (appOptions.currentLevel > maxLevel) { appOptions.currentLevel = maxLevel; }
// Update control level UI based on current and max level for given scope.
$('.control-level input').attr({ max: maxLevel });
$('.control-level input').val(appOptions.currentLevel);
$('.control-level label').html(appOptions.currentLevel);
// Redraw graph data
updateAll({ redrawOnly: true });
// Center graph w/ zoom fit w/ 1 second transition applied after a potential 2 seconds delay for debounce.
centerGraph(zoomFit, 1000, data.allNodesFixed ? 0 : 2000);
}
|
javascript
|
{
"resource": ""
}
|
q64444
|
onControlLevelChanged
|
test
|
function onControlLevelChanged()
{
appOptions.currentLevel = parseInt(this.value);
$('.control-level input').val(appOptions.currentLevel);
$('.control-level label').html(appOptions.currentLevel);
// Redraw graph data
updateAll({ redrawOnly: true });
// Center graph w/ zoom fit w/ 1 second transition applied after a potential 2 seconds delay for debounce.
centerGraph(zoomFit, 1000, data.allNodesFixed ? 0 : 2000);
}
|
javascript
|
{
"resource": ""
}
|
q64445
|
onControlMenuClicked
|
test
|
function onControlMenuClicked()
{
switch ($(this).data('action'))
{
case 'toggleFreezeAllNodes':
setNodesFixed(!data.allNodesFixed);
break;
case 'showFullNames':
appOptions.showFullNames = !appOptions.showFullNames;
updateAll({ redrawOnly: true });
break;
case 'showTableView':
appOptions.showTableView = !appOptions.showTableView;
$('.control-table').toggleClass('hidden', !appOptions.showTableView);
updateTableUIExtent();
break;
case 'maxDepthSticky':
appOptions.maxDepthSticky = !appOptions.maxDepthSticky;
break;
}
// Defer updating menu UI until menu is hidden.
setTimeout(updateMenuUI, 200);
}
|
javascript
|
{
"resource": ""
}
|
q64446
|
onControlTableRowContextClick
|
test
|
function onControlTableRowContextClick(node, event)
{
event.preventDefault(); // Prevents default browser context menu from showing.
onNodeContextClick(node, { x: event.pageX, y: event.pageY });
}
|
javascript
|
{
"resource": ""
}
|
q64447
|
onControlTableRowMouseOver
|
test
|
function onControlTableRowMouseOver(nodes, links, node, enter)
{
// Hide the node context menu if currently showing when a new table row / node is moused over.
if (node !== selectedContextNode) { hideNodeContextMenu(event); }
onNodeMouseOverOut(nodes, links, enter, node);
}
|
javascript
|
{
"resource": ""
}
|
q64448
|
onControlZoomClicked
|
test
|
function onControlZoomClicked()
{
var newScale = 1;
var scalePercentile = 0.20;
// Add or subtract scale percentile from current scale value.
switch ($(this).data('action'))
{
case 'zoom_in':
newScale = Math.max(Math.min(zoom.scale() * (1 + scalePercentile), maxScaleExtent), minScaleExtent);
break;
case 'zoom_out':
newScale = Math.max(zoom.scale() * (1 - scalePercentile), minScaleExtent);
break;
case 'zoom_all_out':
newScale = zoomFit();
break;
}
centerGraph(newScale);
}
|
javascript
|
{
"resource": ""
}
|
q64449
|
onNodeContextMenuClick
|
test
|
function onNodeContextMenuClick()
{
// When a context menu is selected remove node highlighting.
hideNodeContextMenu();
console.log('!! action: ' + $(this).data('action') + '; link: ' + $(this).data('link'));
switch ($(this).data('action'))
{
case 'openLink':
var link = $(this).data('link');
if (typeof link === 'string')
{
window.open(link, '_blank', 'location=yes,menubar=yes,scrollbars=yes,status=yes');
}
break;
}
}
|
javascript
|
{
"resource": ""
}
|
q64450
|
onNodeContextClick
|
test
|
function onNodeContextClick(targetNode, coords)
{
// Hides any existing node context menu.
hideNodeContextMenu();
if (typeof coords !== 'object') { coords = getElementCoords(this); }
var popupmenu = $('#contextpopup .mdl-menu__container');
var packageData = targetNode.packageData;
var packageLink, packageType, scmLink, scmType;
if (packageData)
{
if (packageData.packageLink)
{
packageLink = packageData.packageLink.link;
packageType = packageData.packageLink.type;
// Create proper name for package type.
switch (packageType)
{
case 'npm':
packageType = 'NPM';
break;
}
}
if (packageData.scmLink)
{
scmLink = packageData.scmLink.link;
scmType = packageData.scmLink.type;
// Create proper name for SCM type.
switch (scmType)
{
case 'github':
scmType = 'Github';
break;
}
}
}
// Populate data for the context menu.
popupmenu.find('li').each(function(index)
{
var liTarget = $(this);
switch (index)
{
case 0:
if (scmLink && scmType)
{
liTarget.text('Open on ' + scmType);
liTarget.data('link', scmLink);
liTarget.removeClass('hidden');
}
else
{
liTarget.addClass('hidden');
}
break;
case 1:
if (packageLink && packageType)
{
liTarget.text('Open on ' + packageType);
liTarget.data('link', packageLink);
liTarget.removeClass('hidden');
}
else
{
liTarget.addClass('hidden');
}
break;
case 2:
if (packageData && packageData.version)
{
liTarget.text('Version: ' + packageData.version);
liTarget.removeClass('hidden');
}
else
{
liTarget.addClass('hidden');
}
break;
}
});
// Wrapping in a 100ms timeout allows MDL to draw animation when showing a context menu after one has been hidden.
setTimeout(function()
{
// Assign new selected context node and highlight related nodes.
selectedContextNode = targetNode;
fadeRelatedNodes(selectedContextNode, true, nodes, links);
// For MDL a programmatic click of the hidden context menu.
var contextMenuButton = $("#context-menu");
contextMenuButton.click();
// Necessary to defer reposition of the context menu.
setTimeout(function()
{
popupmenu.parent().css({ position: 'relative' });
popupmenu.css({ left: coords.x, top: coords.y, position:'absolute' });
}, 0);
}, 100);
}
|
javascript
|
{
"resource": ""
}
|
q64451
|
onNodeMouseDown
|
test
|
function onNodeMouseDown(nodes, links, targetNode)
{
hideNodeContextMenu();
// Only select / drag nodes with left clicked otherwise stop propagation of event.
if (d3.event.button === 0)
{
selectedDragNode = targetNode;
// Select / highlight related nodes or remove attributes based on enter state.
fadeRelatedNodes(targetNode, true, nodes, links);
}
else
{
d3.event.stopPropagation();
}
}
|
javascript
|
{
"resource": ""
}
|
q64452
|
onNodeMouseOverOut
|
test
|
function onNodeMouseOverOut(nodes, links, enter, targetNode)
{
// If there is an existing selected node then exit early.
if (isNodeSelected()) { return; }
// Select / highlight related nodes or remove attributes based on enter state.
fadeRelatedNodes(targetNode, enter, nodes, links);
}
|
javascript
|
{
"resource": ""
}
|
q64453
|
onResize
|
test
|
function onResize()
{
// Update graph parameters.
graphWidth = window.innerWidth;
graphHeight = window.innerHeight;
graph.attr('width', graphWidth).attr('height', graphHeight);
layout.size([graphWidth, graphHeight]).resume();
updateMenuUI();
updateTableUIExtent();
// Hides any existing node context menu.
hideNodeContextMenu();
centerGraph(zoomFit, 1000, data.allNodesFixed ? 0 : 2000);
}
|
javascript
|
{
"resource": ""
}
|
q64454
|
onTick
|
test
|
function onTick()
{
nodes.attr('cx', function(node) { return node.x; })
.attr('cy', function(node) { return node.y; })
.attr('transform', function(node) { return 'translate(' + node.x + ',' + node.y + ')'; });
// Pull data from data.nodes array. Provides a curve to the links.
links.attr('d', function(link)
{
var sourceX = data.nodes[link.source.index].x;
var sourceY = data.nodes[link.source.index].y;
var targetX = data.nodes[link.target.index].x;
var targetY = data.nodes[link.target.index].y;
var dx = targetX - sourceX,
dy = targetY - sourceY,
dr = Math.sqrt(dx * dx + dy * dy);
return 'M' + sourceX + ',' + sourceY + 'A' + dr + ',' + dr + ' 0 0,1 ' + targetX + ',' + targetY;
});
}
|
javascript
|
{
"resource": ""
}
|
q64455
|
recycleGraph
|
test
|
function recycleGraph()
{
var childNodes = graph.selectAll('g > *').remove();
if (!Array.isArray(childNodes) && !Array.isArray(childNodes['0'])) { return; }
// Get the child nodes group from selection.
childNodes = childNodes['0'];
for (var cntr = 0; cntr < childNodes.length; cntr++)
{
var childNode = childNodes[cntr];
if (childNode instanceof SVGPathElement) { svgElementMap['path'].push(childNode); }
else if (childNode instanceof SVGCircleElement) { svgElementMap['circle'].push(childNode); }
else if (childNode instanceof SVGTextElement) { svgElementMap['text'].push(childNode); }
else if (childNode instanceof SVGGElement)
{
childNode.removeAttribute('transform'); // Must remove current transform.
svgElementMap['g'].push(childNode);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q64456
|
reverseGraphLinks
|
test
|
function reverseGraphLinks()
{
for (var key in dataPackageMap)
{
var graphData = dataPackageMap[key];
graphData.links.forEach(function(link)
{
var linkSource = link.source;
link.source = link.target;
link.target = linkSource;
});
}
}
|
javascript
|
{
"resource": ""
}
|
q64457
|
updateMenuUI
|
test
|
function updateMenuUI()
{
if (data)
{
$('.control-menu li[data-action=toggleFreezeAllNodes]').html(data.allNodesFixed ?
'Unfreeze nodes' : 'Freeze nodes');
}
appMenuToggleOptions.forEach(function(key)
{
var icon = appOptions[key] ? 'check_box' : 'check_box_outline_blank';
$('.control-menu li[data-action=' + key + '] i').html(icon);
});
}
|
javascript
|
{
"resource": ""
}
|
q64458
|
updateTableUI
|
test
|
function updateTableUI()
{
var table = $('.control-table tbody');
table.off('mouseenter', 'tr', onControlTableRowMouseOver);
table.off('mouseleave', 'tr', onControlTableRowMouseOver);
table.off('contextmenu', 'tr', onControlTableRowContextClick);
table.empty();
if (data)
{
data.nodes.forEach(function(node)
{
var nd = node.packageData;
var name = appOptions.showFullNames ? nd.actualPackageName : nd.packageName;
var isAliased = nd.isAlias ? ' isAliased' : '';
var tr = $(
'<tr>' +
'<td class="mdl-data-table__cell--non-numeric' + isAliased + '">' + name + '</td>' +
'<td class="mdl-data-table__cell--non-numeric">' + nd.jspmType + '</td>' +
'<td class="mdl-data-table__cell--non-numeric">' + nd.version + '</td>' +
'<td class="mdl-data-table__cell--non-numeric">' + node.minLevel + '</td>' +
'</tr>');
table.append(tr);
tr.on('mouseenter', onControlTableRowMouseOver.bind(this, nodes, links, node, true));
tr.on('mouseleave', onControlTableRowMouseOver.bind(this, nodes, links, node, false));
tr.on('contextmenu', onControlTableRowContextClick.bind(this, node));
});
// Removes sort order for any header and signals update for new data
$('#nodeTable th').removeClass('headerSortDown');
$('#nodeTable th').removeClass('headerSortUp');
$('#nodeTable').trigger('update');
updateTableUIExtent();
}
}
|
javascript
|
{
"resource": ""
}
|
q64459
|
updateTableUIExtent
|
test
|
function updateTableUIExtent()
{
var tableDiv = $('.control-table-inner');
var nodeTable = $('#nodeTable');
var tableHeight = nodeTable.height();
var offset = tableDiv.offset();
var maxTableHeight = window.innerHeight - offset.top - 20;
tableDiv.css('max-height', maxTableHeight);
nodeTable.css('margin-right', tableHeight > maxTableHeight ? '10px' : '0px');
}
|
javascript
|
{
"resource": ""
}
|
q64460
|
zoomFit
|
test
|
function zoomFit()
{
var bounds = graph.node().getBBox();
var parent = graph.node().parentElement;
var fullWidth = parent.clientWidth, fullHeight = parent.clientHeight;
var width = bounds.width, height = bounds.height;
if (width === 0 || height === 0) { return 1; } // nothing to fit
var scale = 0.75 / Math.max(width / fullWidth, height / fullHeight);
scale = Math.max(Math.min(scale, maxScaleExtent), minScaleExtent);
return scale;
}
|
javascript
|
{
"resource": ""
}
|
q64461
|
getWindowWidth
|
test
|
function getWindowWidth() {
if (window.innerWidth) {
return window.innerWidth;
} else if (document.documentElement.clientWidth) {
return document.documentElement.clientWidth;
} else if (document.body.clientWidth) {
return document.body.clientWidth;
} else{
return 0;
}
}
|
javascript
|
{
"resource": ""
}
|
q64462
|
test
|
function(cssScreen, cssHandheld, mobileMaxWidth) {
// Set config values
if (typeof(cssScreen) != "undefined") {
config.cssScreen = cssScreen;
}
if (typeof(cssHandheld) != "undefined") {
config.cssHandheld = cssHandheld;
}
if (typeof(mobileMaxWidth) != "undefined") {
config.mobileMaxWidth = mobileMaxWidth;
}
// Check if CSS is loaded
var cssloadCheckNode = document.createElement('div');
cssloadCheckNode.className = config.testDivClass;
document.getElementsByTagName("body")[0].appendChild(cssloadCheckNode);
if (cssloadCheckNode.offsetWidth != 100 && noMediaQuery == false) {
noMediaQuery = true;
}
cssloadCheckNode.parentNode.removeChild(cssloadCheckNode)
if (noMediaQuery == true) {
// Browser does not support Media Queries, so JavaScript will supply a fallback
var cssHref = "";
// Determines what CSS file to load
if (getWindowWidth() <= config.mobileMaxWidth) {
cssHref = config.cssHandheld;
newCssMediaType = "handheld";
} else {
cssHref = config.cssScreen;
newCssMediaType = "screen";
}
// Add CSS link to <head> of page
if (cssHref != "" && currentCssMediaType != newCssMediaType) {
var currentCssLinks = document.styleSheets
for (var i = 0; i < currentCssLinks.length; i++) {
for (var ii = 0; ii < currentCssLinks[i].media.length; ii++) {
if (typeof(currentCssLinks[i].media) == "object") {
if (currentCssLinks[i].media.item(ii) == "fallback") {
currentCssLinks[i].ownerNode.parentNode.removeChild(currentCssLinks[i].ownerNode)
i--
break;
}
} else {
if (currentCssLinks[i].media.indexOf("fallback") >= 0) {
currentCssLinks[i].owningElement.parentNode.removeChild(currentCssLinks[i].owningElement)
i--
break;
}
}
}
}
if (typeof(cssHref) == "object") {
for (var i = 0; i < cssHref.length; i++) {
addCssLink(cssHref[i])
}
} else {
addCssLink(cssHref)
}
currentCssMediaType = newCssMediaType;
}
// Check screen size again if user resizes window
addEvent(window, wbos.CssTools.MediaQueryFallBack.LoadCssDelayed, 'onresize')
}
}
|
javascript
|
{
"resource": ""
}
|
|
q64463
|
do_success
|
test
|
function do_success(req, res, msg) {
res.writeHead(200, {'Content-Type': ((typeof msg === 'string') ? 'text/plain' : 'application/json')});
msg = (typeof msg === 'string') ? msg : helpers.stringify(msg);
res.end(msg);
}
|
javascript
|
{
"resource": ""
}
|
q64464
|
do_failure
|
test
|
function do_failure(req, res, opts) {
opts = opts || {};
var obj = {
'type': opts.type || 'error',
'code': opts.code || 501,
'desc': opts.desc || (''+opts)
};
res.writeHead(obj.code, {'Content-Type': 'application/json'});
res.end(helpers.stringify(obj) + '\n');
}
|
javascript
|
{
"resource": ""
}
|
q64465
|
do_create_req
|
test
|
function do_create_req(config, routes) {
routes = routes || {};
var version = routes.version || {};
if(version && (typeof version === 'object')) {
} else {
version = {'self':routes.version || config.pkg.version};
}
if(!version.api) {
version.api = api_config.pkg.version;
}
routes.version = version;
var router = new RequestRouter(routes);
var req_counter = 0;
/* Inner Request handler */
function do_req(req, res) {
req_counter += 1;
return router.resolve( req, res );
} // do_req
return do_req;
}
|
javascript
|
{
"resource": ""
}
|
q64466
|
do_create_server
|
test
|
function do_create_server(config, do_req) {
var http = require('http');
if(config.host) {
http.createServer(do_req).listen(config.port, config.host);
//console.log("Server running at http://"+config.host+":"+config.port+"/");
} else {
http.createServer(do_req).listen(config.port);
//console.log("Server running at http://0.0.0.0:"+config.port);
}
return http;
}
|
javascript
|
{
"resource": ""
}
|
q64467
|
setup_server
|
test
|
function setup_server(config, opts) {
config._def('port', 3000);
var req_handler = do_create_req(config, opts);
var server = do_create_server(config, function(req, res) {
req_handler(req, res).then(function(obj) {
if(obj === api.replySent) {
// Silently return since reply has been handler already.
return;
} else if(obj === api.notFound) {
do_failure(req, res, {'verb': 'notFound', 'desc':'The requested resource could not be found.', 'code':404});
} else {
do_success(req, res, obj);
}
}).fail(function(err) {
do_failure(req, res, err);
if(!(err instanceof errors.HTTPError)) {
require('prettified').errors.print(err);
}
}).done();
});
return server;
}
|
javascript
|
{
"resource": ""
}
|
q64468
|
test
|
function(element, ev, fn){
if(element.addEventListener)
element.addEventListener(ev, fn, false);
else element.attachEvent("on" + ev, fn);
}
|
javascript
|
{
"resource": ""
}
|
|
q64469
|
Reply
|
test
|
function Reply(parent, definition) {
var key;
for (key in updateMixin) {
this[key] = updateMixin[key];
}
Reply.super_.apply(this, arguments);
}
|
javascript
|
{
"resource": ""
}
|
q64470
|
serveGitFile
|
test
|
function serveGitFile(repo, tree, parts, res, next) {
//console.log("Serving git file: " + parts);
var thisPart = parts.shift();
var isLastPart = parts.length === 0;
var entryIndex = -1;
for (var i=0; i < tree.entries.length; i++) {
if (tree.entries[i].name === thisPart) {
entryIndex = i;
break;
}
}
if (entryIndex < 0) return next();
var entry = tree.entries[entryIndex];
if (isLastPart) {
repo.getBlob(entry.id, function(err, buf) {
if (err) return next(err);
if (!buf.data) return next();
serveBuffer(buf.data, res, thisPart);
});
} else {
repo.getTree(entry.id, function(err, entryTree) {
if (err) return next(err);
serveGitFile(repo, entryTree, parts, res, next);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q64471
|
processFileList
|
test
|
function processFileList(files, base, settings, state) {
for (var i = 0; i < files.length; i++) {
var modulePath = path.join(base, files[i]);
var stats = fs.statSync(modulePath);
if (stats.isFile()) {
// Try to load the module
var module = require(modulePath);
var relative = path.relative(settings.source, modulePath);
__log('Relative path: %s', relative);
var pathWithoutExtension = relative.substr(0, relative.lastIndexOf('.'));
var routeName = pathWithoutExtension.replace(/\\/g, '/').replace(/\./g, '_');
var isRoot = new RegExp(settings.rootModule + '/?$', 'g').test(routeName);
var routePath = routeName;
// Special case for an index file - put these in the root of the api
if (isRoot) {
if(routePath.lastIndexOf('/') > -1)
routePath = routePath.substr(0, routePath.lastIndexOf('/'));
else
routePath = undefined;
}
__log('%s (%s)', routeName, routePath);
var apiPath = utils.combineApiPath(settings.root, routePath);
state.endpoints[routeName] = {
baseUrl: apiPath,
filename: modulePath,
routeName: routeName
};
__log(state.endpoints[routeName]);
settings.app.use(apiPath, module);
}
else if (stats.isDirectory()) {
var dirFiles = fs.readdirSync(modulePath);
processFileList(dirFiles, modulePath, settings, state);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q64472
|
packageModule
|
test
|
function packageModule(global, name, api) {
if (global.define && global.define.amd) {
define([], api);
} else if (typeof exports !== "undefined") {
module.exports = api;
} else {
global[name] = api;
}
}
|
javascript
|
{
"resource": ""
}
|
q64473
|
Ebus
|
test
|
function Ebus(p) {
"use strict";
this.debug = false;
this.yields = false;
this.handlers = {};
if (p) {
this.priorities = p;
} else {
this.priorities = {};
}
}
|
javascript
|
{
"resource": ""
}
|
q64474
|
ApiClient
|
test
|
function ApiClient(config) {
var self = this
this.config = _.extend({}, config, {client:this})
config.headers = _.extend({}, config.headers, { Accept: 'application/json' })
this.auth = config.auth
models.sync = require('./sync')
models.Model = require('./modelbase')
models.NginModel = require('./nginModel')
// add each model to the ApiClient
Object.keys(models).forEach(function(modelName) {
Object.defineProperty(self, modelName, {
get: function() { return models[modelName](self) },
enumerable:true,
configurable:true
})
})
_.extend(this, models)
}
|
javascript
|
{
"resource": ""
}
|
q64475
|
getFirstIndexOf
|
test
|
function getFirstIndexOf(value, array) {
error_if_not_primitive_or_array_1.errorIfNotPrimitiveOrArray(value);
if (isArray_notArray_1.isArray(value)) {
return getFirstIndexOfArray_1.getFirstIndexOfArray(value, array);
}
else { // if primitive...
return getIndexOfPrimitive_1.getIndexOfPrimitive(value, array);
}
}
|
javascript
|
{
"resource": ""
}
|
q64476
|
scopeUrl
|
test
|
function scopeUrl(options, inst) {
options = _.extend({}, inst, options)
if (!options.season_id)
throw new Error('season_id required to make division instance api calls')
return ngin.Season.urlRoot() + '/' + options.season_id + Division.urlRoot()
}
|
javascript
|
{
"resource": ""
}
|
q64477
|
Customer
|
test
|
function Customer(parent, definition) {
var key;
for (key in updateMixin) {
this[key] = updateMixin[key];
}
Customer.super_.apply(this, arguments);
}
|
javascript
|
{
"resource": ""
}
|
q64478
|
copy
|
test
|
function copy(obj) {
return Object.getOwnPropertyNames(obj || {}).reduce((a, c) => {
a[c] = obj[c];
return a;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q64479
|
formatWith
|
test
|
function formatWith(options) {
options = Object.assign({}, DEFAULTS, options);
return (message, ...args) => {
return _formatter(options, message, ...args);
};
}
|
javascript
|
{
"resource": ""
}
|
q64480
|
test
|
function(sourceDir, destFile, opts) {
opts = opts || { archive_path: '/' };
return new Promise(function (resolve, reject) {
try {
var archive = archiver.create('zip', {
zlib: {
level: 9
}
});
var output = fs.createWriteStream(destFile);
output.on('finish', function () {
resolve(destFile);
});
archive.pipe(output);
archive.directory(sourceDir, opts.archive_path);
archive.finalize();
} catch(err) {
reject(err);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q64481
|
test
|
function(sourceFile, destDir) {
return new Promise(function(resolve, reject) {
var zip = new AdmZip(sourceFile);
try {
zip.extractAllTo(destDir);
resolve(destDir);
} catch(err) {
reject(err);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q64482
|
test
|
function(sourceDir, destFile, opts) {
opts = opts || { archive_path: '/' };
return new Promise(function(resolve, reject) {
// pack
var tempFile = destFile + '.tmp.tar';
try {
var archive = archiver.create('tar');
var output = fs.createWriteStream(tempFile);
output.on('finish', function () {
resolve(tempFile);
});
archive.pipe(output);
archive.directory(sourceDir, opts.archive_path);
archive.finalize();
} catch (err) {
reject(err);
}
})
.then(function(tempFile) {
// compress
try {
var data = new Buffer(fs.readFileSync(tempFile), 'utf8');
var compressed = new Buffer(Bzip2.compressFile(data));
fs.writeFileSync(destFile, compressed);
return destFile;
} catch(err) {
throw err;
} finally {
rimraf.sync(tempFile);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q64483
|
test
|
function(sourceFile, destDir) {
return new Promise(function(resolve, reject) {
// expand
var tempFile = sourceFile + '.tmp.tar';
try {
var data = new Buffer(fs.readFileSync(sourceFile));
var expanded = Bzip2.decompressFile(data);
fs.writeFileSync(tempFile, new Buffer(expanded));
resolve(tempFile);
} catch(err) {
reject(err);
}
}).then(function(tempFile) {
// un-pack
return new Promise(function(resolve, reject) {
try {
var rs = fs.createReadStream(tempFile);
rs.pipe(tar.extract(destDir).on('finish', function() {
rimraf.sync(tempFile);
resolve(destDir);
}));
} catch (err) {
rimraf.sync(tempFile);
reject(err);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q64484
|
make
|
test
|
async function make(dir) {
try {
await makePromise(mkdir, dir)
} catch (err) {
if (err.code == 'ENOENT') {
const parentDir = dirname(dir)
await make(parentDir)
await make(dir)
} else if (err.code != 'EEXIST') { // created in parallel
throw err
}
}
}
|
javascript
|
{
"resource": ""
}
|
q64485
|
fabricator
|
test
|
function fabricator(stack, options) {
options = options || {};
//
// Empty strings, arrays or objects should not be processed, return early.
//
if (empty(stack)) return [];
switch (is(stack)) {
case 'string':
stack = read(stack, options);
break;
case 'object':
stack = Object.keys(stack).reduce(iterator(read, stack, options), []);
break;
case 'array':
stack = stack.reduce(iterator(read, null, options), []);
break;
default:
if ('function' !== typeof stack) {
throw new Error('Unsupported type, cannot fabricate an: '+ is(stack));
}
stack = [init(stack, undefined, options)];
}
return (stack || []).filter(Boolean);
}
|
javascript
|
{
"resource": ""
}
|
q64486
|
read
|
test
|
function read(filepath, options) {
if ('string' !== is(filepath)) return fabricator(filepath, options);
if (options.source) filepath = path.resolve(options.source, filepath);
//
// Check if the provided string is a JS file or when recursion is not allowed.
//
if (js(filepath) || options.recursive === false) return [
init(filepath, path.basename(filepath, '.js'), options)
];
//
// Read the directory, only process files.
//
if (!fs.existsSync(filepath)) return false;
return fs.readdirSync(filepath).map(function locate(file) {
file = path.resolve(filepath, file);
var stat = fs.statSync(file);
if (stat.isDirectory() && fs.existsSync(path.join(file, 'index.js'))) {
//
// Use the directory name instead of `index` for name as it probably has
// more meaning then just `index` as a name.
//
return init(path.join(file, 'index.js'), path.basename(file, '.js'), options);
}
//
// Only allow JS files, init determines if it is a constructible instance.
//
if (!stat.isFile() || !js(file)) return;
return init(file, path.basename(file, '.js'), options);
});
}
|
javascript
|
{
"resource": ""
}
|
q64487
|
iterator
|
test
|
function iterator(traverse, obj, options) {
return function reduce(stack, entity) {
var base = obj ? obj[entity] : entity
, name = options.name || entity;
//
// Fabricated objects should provide each constructor with the name
// of its property on the original object.
//
if (obj) options.name = entity;
//
// Run the functions, traverse will handle init.
//
if (js(base)) {
return stack.concat(init(
base,
'string' === is(name) ? name : '',
options
));
}
//
// When we've been supplied with an array as base assume we want to keep it
// as array and do not want it to be merged.
//
if (Array.isArray(base)) {
options.name = name; // Force the name of the entry for all items in array.
stack.push(traverse(base, options));
return stack;
}
return stack.concat(traverse(base, options));
};
}
|
javascript
|
{
"resource": ""
}
|
q64488
|
js
|
test
|
function js(file) {
var type = is(file);
return 'function' === type
|| 'string' === type && path.extname(file) === '.js';
}
|
javascript
|
{
"resource": ""
}
|
q64489
|
empty
|
test
|
function empty(value) {
if (!value) return true;
switch (is(value)) {
case "object": return !Object.keys(value).length;
case "array": return !value.length;
default: return !value;
}
}
|
javascript
|
{
"resource": ""
}
|
q64490
|
click
|
test
|
function click(e) {
var op = 'remove';
if (this.className==='menuLink') {
op = document.body.classList.contains('menu-open') ? 'remove' : 'add';
e.preventDefault();
}
document.body.classList[op]('menu-open');
}
|
javascript
|
{
"resource": ""
}
|
q64491
|
ShellStream
|
test
|
function ShellStream(args){
if(this instanceof ShellStream === false){
return new ShellStream(args);
}
this._command = args;
this._events = [];
var self = this;
// Create holders for events to be added
streams.forEach(function(stream){
self[stream] = {on:this.on, _events:[]};
});
}
|
javascript
|
{
"resource": ""
}
|
q64492
|
test
|
function(name, specs) {
this.name = name;
this.id = 0;
this.properties = specs.properties || [];
this.extends = specs.extends || null;
this.depends = specs.depends || null;
this.factory = specs.factory || "new";
this.init = specs.init || "default";
this.frequent = false;
this.keepUsedProperties = false;
this.initProperties = true;
this.initConstructorArgs = [];
this.propCustomAssign = {};
this.propAssign = "";
this.propCustomGet = {};
this.propGet = "";
this.postInit = specs.postInit || "";
this.embed = specs.embed || [];
if (this.postInit) this.postInit += "\n";
// Calculate a safe name
this.safeName = name.replace(/[,\.\- \_]/g, '_');
// Change init to 'constructor' if init is array
if (this.init instanceof Array) {
this.initConstructorArgs = this.init;
this.init = "constructor";
this.factory = "create"
} else if (this.init instanceof {}.constructor) {
this.propCustomAssign = this.init;
this.init = "default";
// Extract default
if (this.propCustomAssign['default']) {
this.propAssign = this.propCustomAssign['default'];
delete this.propCustomAssign['default'];
}
} else if (this.init !== "default") {
// Custom user init function
if (this.factory === "new")
this.factory = "create";
}
// Check if we have custom property getters
if (specs.getter) {
if (typeof specs == 'object') {
this.propCustomGet = specs.getter;
// Extract default
if (this.propCustomGet['default']) {
this.propGet = this.propCustomGet['default'];
delete this.propCustomGet['default'];
}
} else {
this.propGet = specs.getter;
}
}
// Initialize boolean fields
if (specs.frequent !== undefined) {
this.frequent = (["yes","true","1"].indexOf(specs.frequent.toString().toLowerCase()) >= 0);
}
if (specs.initProperties !== undefined) {
this.initProperties = (["yes","true","1"].indexOf(specs.initProperties.toString().toLowerCase()) >= 0);
}
if (specs.keepUsedProperties !== undefined) {
this.keepUsedProperties = (["yes","true","1"].indexOf(specs.keepUsedProperties.toString().toLowerCase()) >= 0);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q64493
|
test
|
function( o ) {
// Don't extend 'depends', extend only 'extends'
if (this.extends) {
this.embed = o.embed.concat(this.embed);
this.properties = o.properties.concat(this.properties);
this.postInit = o.postInit + this.postInit;
// Replace init & Factory if different
if (this.init === "default") this.init = o.init;
if (this.factory === "new") this.factory = o.factory;
// Replace default property assigned if not defined
if (!this.propAssign) this.propAssign = o.propAssign;
// Implement undefined extended property assigners
for (var k in o.propCustomAssign) {
if (!this.propCustomAssign[k]) {
this.propCustomAssign[k] = o.propCustomAssign[k];
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q64494
|
test
|
function( instVar, prefix ) {
var code = "[", getCode = "", prop="", defaultGet = "$inst.$prop";
if (this.defaultGet) defaultGet = defaultGet;
for (var i=0, l=this.properties.length; i<l; ++i) {
prop = this.properties[i];
if (i > 0) code += ",";
if (this.propCustomGet[prop]) {
getCode = this.propCustomGet[prop]
.replace(/\$inst/g, instVar)
.replace(/\$prop/g, prop);
} else {
getCode = defaultGet
.replace(/\$inst/g, instVar)
.replace(/\$prop/g, prop);
}
// Check if we should embed this property
if (this.embed.indexOf(prop) === -1) {
code += "\n" + prefix + getCode;
} else {
code += "\n" + prefix + "new BinaryEncoder.FileResource( " + getCode + " )";
}
}
code += "]";
return code;
}
|
javascript
|
{
"resource": ""
}
|
|
q64495
|
test
|
function() {
var props = this.properties.slice().sort();
return 'init' + crypto.createHash('md5').update(props.join(",")).digest("hex");
}
|
javascript
|
{
"resource": ""
}
|
|
q64496
|
test
|
function( instVar, valVar, pageszVar, offsetVar, prefix, indent ) {
var code = "", usedProps = {}, defaultAssign = "$inst.$prop = $value",
replaceVariableMacro = (function(s,v) {
var i = this.properties.indexOf(v);
if (i >= 0) {
usedProps[v] = true;
} else {
throw "Macro "+s+" refers to a property not part of property table!";
}
}).bind(this);
//
// [default] - Default empty constructor
//
if (this.init == "default") {
//
// [constructor] - Call constructor
//
} else if (this.init == 'constructor') {
code += prefix + this.name+".call("+instVar;
for (var i=0, l=this.initConstructorArgs.length; i<l; i++) {
var arg = this.initConstructorArgs[i],
partIdx = arg.search(/[\.\[]/),
part = "", found = false;
// Try to translate constructor arguments to components of the value
// array when possivle
if (partIdx == -1) partIdx = arg.length;
part = arg.substr(0,partIdx);
for (var j=0, jl=this.properties.length; j<jl; ++j) {
if (this.properties[j] == part) {
arg = valVar + "["+offsetVar+'+'+pageszVar+'*'+j+"]" + arg.substr(partIdx);
usedProps[part] = true;
found = true;
break;
}
}
// Warn user if not found
if (!found) {
console.warn("Could not find property '"+arg+"' in "+this.name+". Assuming literal");
}
// Update constructor call
code += ",\n"+prefix+indent+arg;
}
code += ");\n";
//
// [other] - Custom user function
//
} else {
console.warn("Using custom init function for "+this.name);
code += prefix + this.init + "(" + instVar +", " + valVar + ");\n";
}
// Replace variable macros in the property assigners & track handled properties
for (var k in this.propCustomAssign) {
this.propCustomAssign[k] = this.propCustomAssign[k]
.replace(/\$\$(\w+)/g, replaceVariableMacro);
}
// Get default assign function
if (this.propAssign) defaultAssign = this.propAssign;
defaultAssign = defaultAssign
.replace(/\$\$(\w+)/g, replaceVariableMacro);
// Call property initializer (might be shared with other instances)
if (this.initProperties) {
for (var i=0, l=this.properties.length; i<l; ++i) {
var prop = this.properties[i];
// Skip properties used in the constructor
if (usedProps[prop] && !this.keepUsedProperties) continue;
if (this.propCustomAssign[prop]) {
code += prefix + this.propCustomAssign[prop]
.replace(/\$inst/g, instVar)
.replace(/\$prop/g, prop)
.replace(/\$values/g, valVar)
.replace(/\$value/g, valVar+"["+offsetVar+'+'+pageszVar+'*'+i+"]") + ";\n";
} else {
code += prefix + defaultAssign
.replace(/\$inst/g, instVar)
.replace(/\$prop/g, prop)
.replace(/\$values/g, valVar)
.replace(/\$value/g, valVar+"["+offsetVar+'+'+pageszVar+'*'+i+"]") + ";\n";
}
}
}
// Call post-init
if (this.postInit) {
code += "\n" + prefix + "// Custom init function\n";
code += prefix + this.postInit.replace(/\n/g, "\n"+prefix)
.replace(/\$inst/g, instVar)
.replace(/\$values/g, valVar)
.replace(/\$\$(\w+)/g, replaceVariableMacro);
}
return code;
}
|
javascript
|
{
"resource": ""
}
|
|
q64497
|
bufferMode
|
test
|
function bufferMode( contents, options, callback ) {
ProfileCompiler( contents.toString('utf-8'), options, function(err, encBuf, decBuf){
if (err) {
callback(err);
return;
}
// Callback buffers
callback(null, new Buffer(encBuf,'utf8'),
new Buffer(decBuf,'utf8') );
});
}
|
javascript
|
{
"resource": ""
}
|
q64498
|
streamMode
|
test
|
function streamMode( contents, options, callback ) {
toArray(contents, function(err, chunks) {
if (err) {
callback(err);
return;
}
bufferMode( Buffer.concat(chunks), options, function(err, encBuf, decBuf) {
if (err) {
callback(err);
return;
}
var encStream = new Readable();
encStream.push(encBuf);
encStream.push(null);
var decStream = new Readable();
decStream.push(decBuf);
decStream.push(null);
// Callback streams
callback(null, encStream, decStream);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q64499
|
test
|
function( err, encContents, decContents ) {
// Emmit errors
if (err) {
var error = new PluginError(PLUGIN_NAME, err, { showStack: true });
self.emit('error', error);
done();
return;
}
// Get base name
var dir = path.dirname( originalFile.path );
var name = path.basename( originalFile.path );
var parts = name.split("."); parts.pop();
var baseName = self.config.name || parts.join(".");
// The encode file
var f = originalFile.clone();
f.contents = encContents;
f.path = path.join( dir, baseName + '-encode.js' );
self.push(f);
// The decode file
var f = originalFile.clone();
f.contents = decContents;
f.path = path.join( dir, baseName + '-decode.js' );
self.push(f);
// We are done
done();
return;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.