_id stringlengths 2 6 | title stringlengths 0 58 | partition stringclasses 3 values | text stringlengths 52 373k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q35100 | train | function()
{
var name = this.getName();
for ( var i = 0 ; i < arguments.length ; i++ )
{
if ( arguments[ i ] == name )
return true;
}
return false;
} | javascript | {
"resource": ""
} | |
q35101 | train | function()
{
var isVisible = ( this.$.offsetHeight || this.$.offsetWidth ) && this.getComputedStyle( 'visibility' ) != 'hidden',
elementWindow,
elementWindowFrame;
// Webkit and Opera report non-zero offsetHeight despite that
// element is inside an invisible iframe. (#4542)
if ( isVisible && ( CKEDITOR.env.webkit || CKEDITOR.env.opera ) )
{
elementWindow = this.getWindow();
if ( !elementWindow.equals( CKEDITOR.document.getWindow() )
&& ( elementWindowFrame = elementWindow.$.frameElement ) )
{
isVisible = new CKEDITOR.dom.element( elementWindowFrame ).isVisible();
}
}
return !!isVisible;
} | javascript | {
"resource": ""
} | |
q35102 | train | function()
{
if ( !CKEDITOR.dtd.$removeEmpty[ this.getName() ] )
return false;
var children = this.getChildren();
for ( var i = 0, count = children.count(); i < count; i++ )
{
var child = children.getItem( i );
if ( child.type == CKEDITOR.NODE_ELEMENT && child.data( 'cke-bookmark' ) )
continue;
if ( child.type == CKEDITOR.NODE_ELEMENT && !child.isEmptyInlineRemoveable()
|| child.type == CKEDITOR.NODE_TEXT && CKEDITOR.tools.trim( child.getText() ) )
{
return false;
}
}
return true;
} | javascript | {
"resource": ""
} | |
q35103 | train | function( opacity )
{
if ( CKEDITOR.env.ie )
{
opacity = Math.round( opacity * 100 );
this.setStyle( 'filter', opacity >= 100 ? '' : 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')' );
}
else
this.setStyle( 'opacity', opacity );
} | javascript | {
"resource": ""
} | |
q35104 | train | function()
{
var $ = this.$;
try
{
// In IE, with custom document.domain, it may happen that
// the iframe is not yet available, resulting in "Access
// Denied" for the following property access.
$.contentWindow.document;
}
catch ( e )
{
// Trick to solve this issue, forcing the iframe to get ready
// by simply setting its "src" property.
$.src = $.src;
// In IE6 though, the above is not enough, so we must pause the
// execution for a while, giving it time to think.
if ( CKEDITOR.env.ie && CKEDITOR.env.version < 7 )
{
window.showModalDialog(
'javascript:document.write("' +
'<script>' +
'window.setTimeout(' +
'function(){window.close();}' +
',50);' +
'</script>")' );
}
}
return $ && new CKEDITOR.dom.document( $.contentWindow.document );
} | javascript | {
"resource": ""
} | |
q35105 | train | function( dest, skipAttributes )
{
var attributes = this.$.attributes;
skipAttributes = skipAttributes || {};
for ( var n = 0 ; n < attributes.length ; n++ )
{
var attribute = attributes[n];
// Lowercase attribute name hard rule is broken for
// some attribute on IE, e.g. CHECKED.
var attrName = attribute.nodeName.toLowerCase(),
attrValue;
// We can set the type only once, so do it with the proper value, not copying it.
if ( attrName in skipAttributes )
continue;
if ( attrName == 'checked' && ( attrValue = this.getAttribute( attrName ) ) )
dest.setAttribute( attrName, attrValue );
// IE BUG: value attribute is never specified even if it exists.
else if ( attribute.specified ||
( CKEDITOR.env.ie && attribute.nodeValue && attrName == 'value' ) )
{
attrValue = this.getAttribute( attrName );
if ( attrValue === null )
attrValue = attribute.nodeValue;
dest.setAttribute( attrName, attrValue );
}
}
// The style:
if ( this.$.style.cssText !== '' )
dest.$.style.cssText = this.$.style.cssText;
} | javascript | {
"resource": ""
} | |
q35106 | train | function( newTag )
{
// If it's already correct exit here.
if ( this.getName() == newTag )
return;
var doc = this.getDocument();
// Create the new node.
var newNode = new CKEDITOR.dom.element( newTag, doc );
// Copy all attributes.
this.copyAttributes( newNode );
// Move children to the new node.
this.moveChildren( newNode );
// Replace the node.
this.getParent() && this.$.parentNode.replaceChild( newNode.$, this.$ );
newNode.$[ 'data-cke-expando' ] = this.$[ 'data-cke-expando' ];
this.$ = newNode.$;
} | javascript | {
"resource": ""
} | |
q35107 | minjs | train | function minjs(config, tools) {
return tools.simpleStream(config, [
config.concat && concat(config.concat),
config.minify && uglify(config.uglifyjs)
])
} | javascript | {
"resource": ""
} |
q35108 | resetStyle | train | function resetStyle( element, prop, resetVal )
{
element.removeStyle( prop );
if ( element.getComputedStyle( prop ) != resetVal )
element.setStyle( prop, resetVal );
} | javascript | {
"resource": ""
} |
q35109 | train | function( id, label, fieldProps )
{
return {
type : 'hbox',
padding : 0,
widths : [ '60%', '40%' ],
children : [
CKEDITOR.tools.extend( {
type : 'text',
id : id,
label : lang[ label ]
}, fieldProps || {}, 1 ),
{
type : 'button',
id : id + 'Choose',
label : lang.chooseColor,
className : 'colorChooser',
onClick : function()
{
var self = this;
getDialogValue( 'colordialog', function( colorDialog )
{
var dialog = self.getDialog();
dialog.getContentElement( dialog._.currentTabId, id ).setValue( colorDialog.getContentElement( 'picker', 'selectedColor' ).getValue() );
});
}
}
]
};
} | javascript | {
"resource": ""
} | |
q35110 | train | function(paths, callback, results, cached) {
results = results || [];
if(!paths.length) {
callback.apply(null, results);
return results;
}
var path = paths.shift();
//what do we do if it's not a string ?
if(typeof path !== 'string') {
results.push(null);
//um skip it?
loadArray(paths, callback, results, cached);
return;
}
acquire.loadPath(path, function(result) {
results.push(result);
loadArray(paths, callback, results, cached);
}, cached);
} | javascript | {
"resource": ""
} | |
q35111 | train | function(source, callback) {
callback = callback || noop;
//if there's a queue
if (queue[source] instanceof Array) {
//just add it
return queue[source].push(callback);
}
//otherwise there is not a queue
//so let's create one
queue[source] = [callback];
var script = document.createElement('script');
var head = document.getElementsByTagName('head')[0];
script.async = 1;
head.appendChild(script);
script.onload = script.onreadystatechange = function( _, isAbort ) {
if(isAbort || !script.readyState || /loaded|complete/.test(script.readyState) ) {
script.onload = script.onreadystatechange = null;
script = undefined;
if(!isAbort) {
queue[source].forEach(function(callback) {
callback();
});
delete queue[source];
}
}
};
script.src = source;
} | javascript | {
"resource": ""
} | |
q35112 | train | function(source, callback) {
callback = callback || noop;
//if there's a queue
if (queue[source] instanceof Array) {
//just call the callback
return callback();
}
//otherwise there is not a queue
//so let's create one
queue[source] = [];
var style = document.createElement('link');
var head = document.getElementsByTagName('head')[0];
style.type = 'text/css';
style.rel = 'stylesheet';
style.href = source;
head.appendChild(style);
callback();
} | javascript | {
"resource": ""
} | |
q35113 | train | function(url, success, fail) {
success = success || noop;
fail = fail || noop;
//if there's a queue
if (queue[url] instanceof Array) {
//just add it
return queue[url].push({
success: success,
fail: fail
});
}
//otherwise there is not a queue
//so let's create one
queue[url] = [{
success: success,
fail: fail
}];
var xhr;
if(typeof XMLHttpRequest !== 'undefined') {
xhr = new XMLHttpRequest();
} else {
var versions = [
'MSXML2.XmlHttp.5.0',
'MSXML2.XmlHttp.4.0',
'MSXML2.XmlHttp.3.0',
'MSXML2.XmlHttp.2.0',
'Microsoft.XmlHttp'];
for(var i = 0; i < versions.length; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
}
}
if(!xhr) {
//fail the queue
queue[url].forEach(function(callback) {
callback.fail(null);
});
delete queue[url];
return;
}
var process = function() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status >= 404 && xhr.status < 600) {
//fail the queue
queue[url].forEach(function(callback) {
callback.fail(xhr);
});
delete queue[url];
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
var response = xhr.responseText;
try {
response = JSON.parse(response);
} catch(e) {}
//fail the queue
queue[url].forEach(function(callback) {
callback.success(response, xhr);
});
delete queue[url];
}
};
xhr.onreadystatechange = process;
xhr.open('GET', url, true);
xhr.send('');
} | javascript | {
"resource": ""
} | |
q35114 | train | function(type, event, handler) {
_.parsers.forEach(function(parser) {
type = type.replace(parser[0], function() {
var args = _.slice(arguments, 1);
args.unshift(event, handler);
return parser[1].apply(event, args) || '';
});
});
return type ? event.type = type : type;
} | javascript | {
"resource": ""
} | |
q35115 | report | train | function report(error, additionalTags, extra) {
let sentTags = tags ? [].concat(tags) : [];
if (additionalTags) {
sentTags = sentTags.concat(additionalTags);
}
return Promise.resolve(sentTags).then(function(t) {
// Need this wrapping so that our internal implementation can safely throw errors
return new Promise(function(resolve) {
const sentError = error.nativeError ? error.nativeError : error;
Raygun.send(sentError, _.merge(extra || {}, error.extra), function(res) {
// No response === stubbed Raygun
if (res) {
if (res.statusCode !== 202) {
console.log('Failed to report error to Raygun', res); //eslint-disable-line no-console
} else {
console.log('Reported error to Raygun', error); //eslint-disable-line no-console
}
}
// Resolve with the error, so that our caller can finish deal
// with it further
resolve(error);
}, error.request, t);
});
}).catch(function(err) {
// Return the same error that we were supposed to report
// and simply log out the error that actually occurred during reporting
console.error(err); //eslint-disable-line no-console
return error;
});
} | javascript | {
"resource": ""
} |
q35116 | LambdaError | train | function LambdaError(code, message, extra, request) {
Error.captureStackTrace(this, this.constructor);
this.name = 'LambdaError';
this.message = `${code}: ${message}`;
this.code = code;
this.extra = extra;
this.request = request;
// Also capture a native error internally, which
// we can send to Raygun later
this.nativeError = new Error(this.message);
Error.captureStackTrace(this.nativeError, this.constructor);
} | javascript | {
"resource": ""
} |
q35117 | train | function ($element, event, fn) {
var handler = {
$element: $element,
event: event,
fn: fn
};
existingHandlers.push(handler);
return $element.on(event, fn);
} | javascript | {
"resource": ""
} | |
q35118 | VNode | train | function VNode(tagName, attributes, children) {
this.simple = true;
this.tagName = tagName; // non-virtual VText
this.attributes = attributes; // javascript
this.children = new VTree(children);
} | javascript | {
"resource": ""
} |
q35119 | groupFieldsByType | train | function groupFieldsByType(list){
var fields = {};
_.each(list.fields, function(v,k) {
if (! fields.hasOwnProperty(v.type)) fields[v.type] = [];
fields[v.type].push(v);
});
return fields;
} | javascript | {
"resource": ""
} |
q35120 | getBytesWithUnit | train | function getBytesWithUnit(bytes) {
if (isNaN(bytes)) {
return;
}
var units = [ ' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB' ];
var amountOf2s = Math.floor(Math.log(+bytes) / Math.log(2));
if (amountOf2s < 1) {
amountOf2s = 0;
}
var i = Math.floor(amountOf2s / 10);
bytes = +bytes / Math.pow(2, 10 * i);
if (bytes.toString().length > bytes.toFixed(2).toString().length) {
bytes = bytes.toFixed(2);
}
return bytes + units[i];
} | javascript | {
"resource": ""
} |
q35121 | renderActionButtons | train | function renderActionButtons() {
$('.manage-resource-container .action-button').each(function (i, action) {
action = $(action);
var type = action.parent().hasClass(FOLDER_TYPE) ? FOLDER_TYPE : "";
var id = action.attr("id"),
dataId = action.parent('.resource-item').attr("id");
var actions = [
{
text: type ? "View" : "Download",
onClick: function (e) {
if (type) {
renderItemsByFolderId(dataId);
} else {
download(dataId);
}
},
permissionAction: "VIEW"
},
{
text: "Permission", data: {id: dataId},
onClick: function (e) {
openPermissions(dataId);
},
permissionAction: "PERMISSION"
},
{
text: "Rename", data: {id: dataId},
onClick: function (e) {
rename(dataId, true);
},
permissionAction: "UPDATE"
},
{
text: "Delete",
onClick: function (e) {
remove(dataId, type);
},
permissionAction: "DELETE"
}
];
var opts = {
handlerId: id,
buttonSize: "mini",
actions: actions
};
var permissionConf = {
modelId: dataId,
modelName: modelName,
permissionSchemaKey: permissionSchemaKey
};
new Rocket.ActionButton(opts, permissionConf)
});
} | javascript | {
"resource": ""
} |
q35122 | ignoreStream | train | function ignoreStream(strategy) {
if (!(strategy instanceof IgnoreStrategy)) {
strategy = DefaultIgnoreStrategy.INSTANCE;
}
return through.obj(function(chunk, enc, cb) {
strategy.execute(this, chunk).then(function(isIgnored) {
if (!isIgnored) {
cb(null, chunk);
} else {
cb(null);
}
});
});
} | javascript | {
"resource": ""
} |
q35123 | train | function( text )
{
var standard = function( text )
{
var span = new CKEDITOR.dom.element( 'span' );
span.setText( text );
return span.getHtml();
};
var fix1 = ( standard( '\n' ).toLowerCase() == '<br>' ) ?
function( text )
{
// #3874 IE and Safari encode line-break into <br>
return standard( text ).replace( /<br>/gi, '\n' );
} :
standard;
var fix2 = ( standard( '>' ) == '>' ) ?
function( text )
{
// WebKit does't encode the ">" character, which makes sense, but
// it's different than other browsers.
return fix1( text ).replace( />/g, '>' );
} :
fix1;
var fix3 = ( standard( ' ' ) == ' ' ) ?
function( text )
{
// #3785 IE8 changes spaces (>= 2) to
return fix2( text ).replace( / /g, ' ' );
} :
fix2;
this.htmlEncode = fix3;
return this.htmlEncode( text );
} | javascript | {
"resource": ""
} | |
q35124 | train | function( func, milliseconds, scope, args, ownerWindow )
{
if ( !ownerWindow )
ownerWindow = window;
if ( !scope )
scope = ownerWindow;
return ownerWindow.setTimeout(
function()
{
if ( args )
func.apply( scope, [].concat( args ) ) ;
else
func.apply( scope ) ;
},
milliseconds || 0 );
} | javascript | {
"resource": ""
} | |
q35125 | train | function( ref )
{
var fn = functions[ ref ];
return fn && fn.apply( window, Array.prototype.slice.call( arguments, 1 ) );
} | javascript | {
"resource": ""
} | |
q35126 | returnResponse | train | function returnResponse(res, Handler, data, perfInstance) {
var content = React.renderToString(React.createElement(Handler, { data: data })),
html = '<!DOCTYPE html>' + content;
options.log && log(options.log, 'perf', perfInstance());
res.end(html);
} | javascript | {
"resource": ""
} |
q35127 | train | function(url, callback) {
var parsedUrl = urlparse(url, true);
var method = this._normalizeSpecMethod(this.spec, {
base_url: parsedUrl.protocol +'//' + parsedUrl.hostname,
headers: {},
method: 'GET',
path: parsedUrl.pathname + parsedUrl.search
});
var request = this._createRequest(method, {}, null);
this._callRequestMiddlewares(this.middlewares.slice(0), method, request, [], callback);
} | javascript | {
"resource": ""
} | |
q35128 | train | function(middleware) {
this.middlewares = this.middlewares.filter(function(element) {
if (element.fun === middleware)
return false;
return true;
});
} | javascript | {
"resource": ""
} | |
q35129 | train | function(methodName, args) {
var method = this.spec.methods[methodName];
if (method.deprecated === true)
console.warn('Method '+ methodName + ' is deprecated.')
var callback = args.pop(); // callback is always at the end
var middleware = args[0];
var params = null;
var payload = null;
var index = 0;
if (typeof middleware != 'function') {
params = args[0];
middleware = null;
} else {
params = args[1];
index = 1;
}
if (args.length > 1) {
payload = args[index + 1];
} else {
if (method.required_params.length == 0
&& method.optional_params.length == 0) {
payload = args[index];
params = null;
}
}
if (this._isValidCall(method, callback, params, payload)) {
var request = this._createRequest(method, params, payload);
var middlewares = this.middlewares.slice(0);
if (middleware !== null) middlewares.push({cond: function() { return true; }, fun: middleware});
this._callRequestMiddlewares(middlewares, method, request, [], callback);
}
} | javascript | {
"resource": ""
} | |
q35130 | train | function(request, callback, response_middlewares) {
var that = this;
request.finalize(function(err, res) {
if (err) callback(err, null);
else that._callResponseMiddlewares(response_middlewares, res, callback);
});
} | javascript | {
"resource": ""
} | |
q35131 | train | function(methodDef, callback, params, payload) {
// check required params
for (var index in methodDef.required_params) {
var requiredParamName = methodDef.required_params[index];
if (!params.hasOwnProperty(requiredParamName)) {
callback(requiredParamName +' param is required');
return false;
}
}
// check unattended params
if (methodDef.unattended_params === false) {
for (var param in params) {
if (methodDef.optional_params.indexOf(param) == -1
&& methodDef.required_params.indexOf(param) == -1) {
callback('unattended param '+ param);
return false;
}
}
}
// TODO: optional_payload is also on spore specification
if (!payload && methodDef.required_payload === true) {
callback("payload is required");
return false;
}
return true;
} | javascript | {
"resource": ""
} | |
q35132 | GenericRestError | train | function GenericRestError (type, status) {
return function Handler (code, message, header) {
return new RestError(type, status, code, message, header)
}
} | javascript | {
"resource": ""
} |
q35133 | train | function(stuff) {
var len = this.str.length;
if (typeof stuff == 'number') {
this.str = this.str.substr(stuff);
} else if (typeof stuff == 'string') {
this.str = this.str.substr(stuff.length);
} else if (stuff instanceof RegExp) {
var m = this.str.match(stuff);
if (m) {
this.str = this.str.substr(m[0].length);
}
}
return len > this.str.length;
} | javascript | {
"resource": ""
} | |
q35134 | mergeReferences | train | function mergeReferences (oldRefs, newRefs) {
const _newRefs = _(newRefs);
return _(oldRefs)
.reject(function (oldRef) {
return _newRefs.any(function (newRef) {
return matches(oldRef, newRef);
});
})
.concat(newRefs)
.uniq()
.sort()
.value();
} | javascript | {
"resource": ""
} |
q35135 | preventAll | train | function preventAll () {
function shield (req) {
req.prevent();
}
measly.on('create', shield);
text(preventButton, 'Shield On..');
preventButton.classList.add('cm-prevent-on');
setTimeout(function () {
measly.off('create', shield);
text(preventButton, 'Prevent for 5s');
preventButton.classList.remove('cm-prevent-on');
}, 5000);
} | javascript | {
"resource": ""
} |
q35136 | mainFunction | train | function mainFunction (arg) {
if (typeof arg == 'string') {
return JS2.Parser.parse(arg).toString();
} else if (arg instanceof Array) {
return new JS2.Array(arg);
} else {
return new JS2.Array();
}
} | javascript | {
"resource": ""
} |
q35137 | havePosts | train | function havePosts( error, post ) {
this.debug( 'haveSingle' );
console.log( require( 'util' ).inspect( post, { showHidden: false, colors: true, depth: 4 } ) );
} | javascript | {
"resource": ""
} |
q35138 | train | function( data )
{
if ( iframe )
iframe.remove();
var src =
'document.open();' +
// The document domain must be set any time we
// call document.open().
( isCustomDomain ? ( 'document.domain="' + document.domain + '";' ) : '' ) +
'document.close();';
// With IE, the custom domain has to be taken care at first,
// for other browers, the 'src' attribute should be left empty to
// trigger iframe's 'load' event.
src =
CKEDITOR.env.air ?
'javascript:void(0)' :
CKEDITOR.env.ie ?
'javascript:void(function(){' + encodeURIComponent( src ) + '}())'
:
'';
iframe = CKEDITOR.dom.element.createFromHtml( '<iframe' +
' style="width:100%;height:100%"' +
' frameBorder="0"' +
' title="' + frameLabel + '"' +
' src="' + src + '"' +
' tabIndex="' + ( CKEDITOR.env.webkit? -1 : editor.tabIndex ) + '"' +
' allowTransparency="true"' +
'></iframe>' );
// Running inside of Firefox chrome the load event doesn't bubble like in a normal page (#5689)
if ( document.location.protocol == 'chrome:' )
CKEDITOR.event.useCapture = true;
// With FF, it's better to load the data on iframe.load. (#3894,#4058)
iframe.on( 'load', function( ev )
{
frameLoaded = 1;
ev.removeListener();
var doc = iframe.getFrameDocument();
doc.write( data );
CKEDITOR.env.air && contentDomReady( doc.getWindow().$ );
});
// Reset adjustment back to default (#5689)
if ( document.location.protocol == 'chrome:' )
CKEDITOR.event.useCapture = false;
mainElement.append( iframe );
} | javascript | {
"resource": ""
} | |
q35139 | blinkCursor | train | function blinkCursor( retry )
{
if ( editor.readOnly )
return;
CKEDITOR.tools.tryThese(
function()
{
editor.document.$.designMode = 'on';
setTimeout( function()
{
editor.document.$.designMode = 'off';
if ( CKEDITOR.currentInstance == editor )
editor.document.getBody().focus();
}, 50 );
},
function()
{
// The above call is known to fail when parent DOM
// tree layout changes may break design mode. (#5782)
// Refresh the 'contentEditable' is a cue to this.
editor.document.$.designMode = 'off';
var body = editor.document.getBody();
body.setAttribute( 'contentEditable', false );
body.setAttribute( 'contentEditable', true );
// Try it again once..
!retry && blinkCursor( 1 );
});
} | javascript | {
"resource": ""
} |
q35140 | train | function( xpath, contextNode )
{
var baseXml = this.baseXml;
if ( contextNode || ( contextNode = baseXml ) )
{
if ( CKEDITOR.env.ie || contextNode.selectSingleNode ) // IE
return contextNode.selectSingleNode( xpath );
else if ( baseXml.evaluate ) // Others
{
var result = baseXml.evaluate( xpath, contextNode, null, 9, null);
return ( result && result.singleNodeValue ) || null;
}
}
return null;
} | javascript | {
"resource": ""
} | |
q35141 | train | function( xpath, contextNode )
{
var baseXml = this.baseXml,
nodes = [];
if ( contextNode || ( contextNode = baseXml ) )
{
if ( CKEDITOR.env.ie || contextNode.selectNodes ) // IE
return contextNode.selectNodes( xpath );
else if ( baseXml.evaluate ) // Others
{
var result = baseXml.evaluate( xpath, contextNode, null, 5, null);
if ( result )
{
var node;
while ( ( node = result.iterateNext() ) )
nodes.push( node );
}
}
}
return nodes;
} | javascript | {
"resource": ""
} | |
q35142 | train | function( xpath, contextNode )
{
var node = this.selectSingleNode( xpath, contextNode ),
xml = [];
if ( node )
{
node = node.firstChild;
while ( node )
{
if ( node.xml ) // IE
xml.push( node.xml );
else if ( window.XMLSerializer ) // Others
xml.push( ( new XMLSerializer() ).serializeToString( node ) );
node = node.nextSibling;
}
}
return xml.length ? xml.join( '' ) : null;
} | javascript | {
"resource": ""
} | |
q35143 | request | train | function request(url, using, fn, disk) {
if ('function' === typeof using) {
disk = fn;
fn = using;
using = null;
}
if (!using) {
if (curl) using = 'curl';
else if (wget) using = 'wget';
else using = 'node';
}
debug('requesting '+ url +' using '+ using);
request[using + ( disk ? 'd' : '')](url, fn);
} | javascript | {
"resource": ""
} |
q35144 | extendThis | train | function extendThis() {
var i, ni, objects, object, prop;
objects = arguments;
for (i = 0, ni = objects.length; i < ni; i++) {
object = objects[i];
for (prop in object) {
this[prop] = object[prop];
}
}
return this;
} | javascript | {
"resource": ""
} |
q35145 | defineAndInheritProperties | train | function defineAndInheritProperties(Component, properties) {
var constructor,
descriptor,
property,
propertyDescriptors,
propertyDescriptorHash,
propertyDescriptorQueue;
// Set properties
Component.properties = properties;
// Traverse the chain of constructors and gather all property descriptors
// Build a queue of property descriptors for combination
propertyDescriptorHash = {};
constructor = Component;
do {
if (constructor.properties) {
for (property in constructor.properties) {
propertyDescriptorQueue = propertyDescriptorHash[property] || (propertyDescriptorHash[property] = []);
propertyDescriptorQueue.unshift(constructor.properties[property]);
}
}
constructor = constructor.superConstructor;
}
while (constructor);
// Combine property descriptors, allowing overriding of individual properties
propertyDescriptors = {};
for (property in propertyDescriptorHash) {
descriptor = propertyDescriptors[property] = extendThis.apply({}, propertyDescriptorHash[property]);
// Allow setters to be strings
// An additional wrapping function is used to allow monkey-patching
// apply is used to handle cases where the setter is called directly
if (typeof descriptor.set === 'string') {
descriptor.set = makeApplier(descriptor.set);
}
if (typeof descriptor.get === 'string') {
descriptor.get = makeApplier(descriptor.get);
}
}
// Store option descriptors on the constructor
Component.properties = propertyDescriptors;
} | javascript | {
"resource": ""
} |
q35146 | train | function(name, func, superPrototype) {
return function PseudoClass_setStaticSuper() {
// Store the old super
var previousSuper = this._super;
// Use the method from the superclass' prototype
// This strategy allows monkey patching (modification of superclass prototypes)
this._super = superPrototype[name];
// Call the actual function
var ret = func.apply(this, arguments);
// Restore the previous value of super
// This is required so that calls to methods that use _super within methods that use _super work
this._super = previousSuper;
return ret;
};
} | javascript | {
"resource": ""
} | |
q35147 | train | function(properties) {
// If a class-like object is passed as properties.extend, just call extend on it
if (properties && properties.extend)
return properties.extend.extend(properties);
// Otherwise, just create a new class with the passed properties
return PseudoClass.extend(properties);
} | javascript | {
"resource": ""
} | |
q35148 | render | train | function render(q) {
if (!q.length) {
complete();
return;
}
const item = q.shift();
// render HTML file
fs.writeFile(`${item.file}.html`, item.html, err => {
if (err) throw err;
// if prerendering is enabled
if (typeof options.prerender === "object" && options.prerender !== null) {
// wait for response from browser
puppet.once("message", height => {
// store height
item.json.height = height;
// render JSON file
fs.writeFile(`${item.file}.json`, JSON.stringify(item.json), err => {
if (err) throw err;
process.send(`success::Generated ${item.name}`);
// render next
render(q);
});
});
// open html file in browser
puppet.send({
url: `http://localhost:${options.prerender.port}/${
options.prerender.path
}/${item.slug}.html`
});
// if no prerendering is to be done
} else {
// render JSON file
fs.writeFile(`${item.file}.json`, JSON.stringify(item.json), err => {
if (err) throw err;
process.send(`success::Generated ${item.name}`);
// render next
render(q);
});
}
});
} | javascript | {
"resource": ""
} |
q35149 | complete | train | function complete() {
quit();
const deleteQueue = [];
fs.readdir(paths.output, (err, files) => {
if (files) {
// lookup array for quick search inside existing component names
const componentsLookup = components.map(item => {
return slugify(item.meta.name);
});
// loop over files
for (let i = 0, l = files.length; i < l; ++i) {
const file = files[i];
const ext = path.extname(file);
// ignore dot files
if (file.indexOf(".") === 0) {
continue;
}
// if json+html file isn't inside lookup, mark for deletion
if (componentsLookup.indexOf(path.basename(file, ext)) === -1) {
deleteQueue.push(file);
}
}
}
// remove file by passing shorter queue
function removeFile(q) {
if (!q.length) {
process.send(true);
return;
}
const file = q.shift();
rimraf(path.resolve(paths.output, file), { read: false }, () => {
removeFile(q);
});
}
removeFile(deleteQueue);
});
} | javascript | {
"resource": ""
} |
q35150 | removeFile | train | function removeFile(q) {
if (!q.length) {
process.send(true);
return;
}
const file = q.shift();
rimraf(path.resolve(paths.output, file), { read: false }, () => {
removeFile(q);
});
} | javascript | {
"resource": ""
} |
q35151 | slugify | train | function slugify(str) {
return str
.toString()
.toLowerCase()
.replace(/\s+/g, "-") // Replace spaces with -
.replace(/[^\w-]+/g, "") // Remove all non-word chars
.replace(/--+/g, "-") // Replace multiple - with single -
.replace(/^-+/, "") // Trim - from start of text
.replace(/-+$/, ""); // Trim - from end of text
} | javascript | {
"resource": ""
} |
q35152 | PageScript | train | function PageScript(req) {
var codeList = [], bottomScriptList = [], cacheKey;
/**
* Add plugin load code. Called for each configured plugin on page.
* @param pluginOptions {Object} Plugin options object described in plugin properties
*/
this.addPluginLoad = function (pluginOptions) {
var pluginLoadJSCode = "Rocket.Plugin.onLoad(" + JSON.stringify(pluginOptions) + ")";
codeList.push({modules: PLUGIN_MODULE, code: pluginLoadJSCode});
};
/**
* Method adds the code & required modules
* @param modules {String} Comma separated list of modules, will be passed to require.js
* @param code {String} Client script Code
*/
this.add = function (modules, code) {
codeList.push({modules: modules, code: code});
};
/**
* Method used to include the code block passed to "BottomScript" mixin
* @param block {Function} jade mixin function
* @param opts {Object} locals or opts passed to "BottomScript" mixin
*/
this.addPageBottomCode = function (block, opts) {
opts.jade = jadeRuntime;
var func = new Function(_.keys(opts), "var jade_debug = [{filename: ''}]," +
" buf = [], jade_indent = [], jade_interp;" +
"(" + block + ")(); return buf.join('')");
bottomScriptList.push(func.apply(null, _.values(opts)).replace(/<[\/]{0,1}(script|SCRIPT)[^><]*>/g, "").trim());
};
/**
* Renders the scripts added or included in this object into html
* @param cb {Function} callback function - arguments - err, html
*/
this.render = function (cb) {
//if cache is configured, get cache key
if (ScriptsCache) {
var page = req.attrs.page;
cacheKey ||
(cacheKey = utils.replaceAll(req.url.replace(/\/$/, ""), "/", "_")+ "__" + page.pageId + "__" + req.session.user.userId);
}
/**
* Function renders html.
* @param callback {Function} callback function - arguments - err, html
*/
function renderHTML(callback) {
async.map(codeList, function (locals, n) {
locals.req = req;
ViewHelper.render({
cache: true,
path: SCRIPT_JADE
}, locals, n)
}, function (err, buf) {
if (!err) {
buf = buf || [];
buf.splice(0, 0, SCRIPT_START_TAG);
buf.push(bottomScriptList.join(""));
buf.push(SCRIPT_END_TAG);
}
callback(err, buf.join(""));
});
}
if (ScriptsCache) {
ScriptsCache.wrap(cacheKey, function (callback) {
renderHTML(callback)
}, cb);
}
else {
renderHTML(cb);
}
}
} | javascript | {
"resource": ""
} |
q35153 | renderHTML | train | function renderHTML(callback) {
async.map(codeList, function (locals, n) {
locals.req = req;
ViewHelper.render({
cache: true,
path: SCRIPT_JADE
}, locals, n)
}, function (err, buf) {
if (!err) {
buf = buf || [];
buf.splice(0, 0, SCRIPT_START_TAG);
buf.push(bottomScriptList.join(""));
buf.push(SCRIPT_END_TAG);
}
callback(err, buf.join(""));
});
} | javascript | {
"resource": ""
} |
q35154 | run | train | function run($templateCache) {
angular.forEach(examples, function (example) {
$templateCache.put(example.id + '-template', example.html);
$templateCache.put(example.id + '-description', example.description);
});
} | javascript | {
"resource": ""
} |
q35155 | ExampleCtrl | train | function ExampleCtrl($scope, $timeout) {
var pomo_nonsense = 'The fallacy of disciplinary boundaries thematizes the figuralization of civil society.',
regex = /(of\s.+\sboundaries|eht)/;
$scope.reset = function reset() {
delete $scope.data.pomo_nonsense;
$timeout(function () {
$scope.data.pomo_nonsense = pomo_nonsense;
});
};
$scope.reverse = function reverse() {
var arr = Array.prototype.slice.call($scope.data.pomo_nonsense);
arr.reverse();
$scope.data.pomo_nonsense = arr.join('');
};
$scope.data = {
regex: regex,
pomo_nonsense: pomo_nonsense
};
} | javascript | {
"resource": ""
} |
q35156 | MainCtrl | train | function MainCtrl($scope, $location) {
$scope.select = function select(id) {
$scope.selected = $scope.selected === id ? null : id;
$location.path('/' + id);
};
$scope.examples = examples;
$scope.select($location.path().substring(1) || examples[0].id);
} | javascript | {
"resource": ""
} |
q35157 | code | train | function code($window) {
return {
restrict: 'E',
require: '?ngModel',
/**
*
* @param {$rootScope.Scope} scope Element Scope
* @param {angular.element} element AngularJS element
* @param {$compile.directive.Attributes} attrs AngularJS Attributes object
* @param {NgModelController} ngModel ngModel controller object
*/
link: function link(scope, element, attrs, ngModel) {
var pre;
if (!ngModel) {
return;
}
pre = element.wrap('<pre></pre>');
element.addClass(attrs.lang);
ngModel.$render = function $render() {
element.text(ngModel.$viewValue);
$window.hljs.highlightBlock(pre[0]);
};
}
};
} | javascript | {
"resource": ""
} |
q35158 | detectIntersection | train | function detectIntersection(a, b) {
if (a instanceof Sphere) {
if (b instanceof Sphere) {
return sphereCollisionDetection.sphereVsSphere(a, b);
} else if (b instanceof Aabb) {
return sphereCollisionDetection.sphereVsAabb(a, b);
} else if (b instanceof Capsule) {
return sphereCollisionDetection.sphereVsCapsule(a, b);
} else if (b instanceof Obb) {
return sphereCollisionDetection.sphereVsObb(a, b);
} else {
return sphereCollisionDetection.sphereVsPoint(a, b);
}
} else if (a instanceof Aabb) {
if (b instanceof Sphere) {
return aabbCollisionDetection.aabbVsSphere(a, b);
} else if (b instanceof Aabb) {
return aabbCollisionDetection.aabbVsAabb(a, b);
} else if (b instanceof Capsule) {
return aabbCollisionDetection.aabbVsCapsule(a, b);
} else if (b instanceof Obb) {
return aabbCollisionDetection.aabbVsObb(a, b);
} else {
return aabbCollisionDetection.aabbVsPoint(a, b);
}
} else if (a instanceof Capsule) {
if (b instanceof Sphere) {
return capsuleCollisionDetection.capsuleVsSphere(a, b);
} else if (b instanceof Aabb) {
return capsuleCollisionDetection.capsuleVsAabb(a, b);
} else if (b instanceof Capsule) {
return capsuleCollisionDetection.capsuleVsCapsule(a, b);
} else if (b instanceof Obb) {
return capsuleCollisionDetection.capsuleVsObb(a, b);
} else {
return capsuleCollisionDetection.capsuleVsPoint(a, b);
}
} else if (a instanceof Obb) {
if (b instanceof Sphere) {
return obbCollisionDetection.obbVsSphere(a, b);
} else if (b instanceof Aabb) {
return obbCollisionDetection.obbVsAabb(a, b);
} else if (b instanceof Capsule) {
return obbCollisionDetection.obbVsCapsule(a, b);
} else if (b instanceof Obb) {
return obbCollisionDetection.obbVsObb(a, b);
} else {
return obbCollisionDetection.obbVsPoint(a, b);
}
} else {
if (b instanceof Sphere) {
return sphereCollisionDetection.sphereVsPoint(b, a);
} else if (b instanceof Aabb) {
return aabbCollisionDetection.aabbVsPoint(b, a);
} else if (b instanceof Capsule) {
return capsuleCollisionDetection.capsuleVsPoint(b, a);
} else if (b instanceof Obb) {
return obbCollisionDetection.obbVsPoint(b, a);
} else {
return false;
}
}
} | javascript | {
"resource": ""
} |
q35159 | convert | train | function convert(program, callback) {
// define no-op callback
if (!callback) {
callback = function (err, blueprint) { }
}
// Read in the file
refparser.parse(program.input, function (err, schema) {
if (err) isMain ? halt(err) : callback(err);
// Read in aglio options
var options = {
themeTemplate: (program.themeTemplate === 'triple' || program.themeTemplate === 'index' || !program.themeTemplate) ?
path.resolve(__dirname, 'templates/' + (program.themeTemplate || 'index') + '.jade') :
themeTemplate,
themeVariables: program.themeVariables,
themeFullWidth: program.themeFullWidth,
noThemeCondense: program.noThemeCondense,
themeStyle: program.themeStyle,
locals: {
livePreview: program.server,
host: ((schema.schemes && schema.schemes.length > 0 && schema.host) ?
(schema.schemes[0] || 'https')
: 'https')
+ '://' + schema.host + (schema.basePath || '')
}
};
swag2blue.run({ '_': [program.input] }, function (err, blueprint) {
if (err) isMain ? halt(err) : callback(err);
aglio.render(blueprint, options, function (err, html, warnings) {
if (err) isMain ? halt(err) : callback(err);
// If we had warnings and not outputting to console, print them out and continue.
if (warnings && !program.output && isMain) {
warn('Encountered ' + warnings.length + ' warnings: \n');
warnings.forEach(function (warning) {
warn("\n");
warn(prettyjson.render(warning, { noColor: true }));
});
warn("\n");
}
if (!program.noMinify) {
html = minify(html, {
collapseBooleanAttributes: true,
collapseWhitespace: true,
minifyCSS: true,
minifyJS: true,
minifyURLs: true,
removeAttributeQuotes: true,
removeComments: true,
removeEmptyAttributes: true,
removeOptionalTags: true,
removeRedundantAttributes: true,
useShortDoctype: true
});
}
// If output is specified, write to file. Otherwise write to console.
if (program.output) {
fs.writeFile(program.output, html, function (err) {
if (err) isMain ? halt(err) : callback(err);
success("Success! Output written to: " + program.output);
callback(null, html);
});
} else {
if (isMain) console.log(html);
callback(null, html);
}
});
});
});
} | javascript | {
"resource": ""
} |
q35160 | check_input | train | function check_input(input, message) {
if (!input) {
error('\n Error: ' + message);
program.outputHelp(colors.red);
process.exit(1);
}
} | javascript | {
"resource": ""
} |
q35161 | adjustPath | train | function adjustPath(builder, path) {
if (builder.protection) {
var pathAndNode = utils.pathAndNode(path);
var nodeName = getProtectedPrefix(builder.protectedId) + pathAndNode.node;
path = utils.join(pathAndNode.path, nodeName);
}
return path;
} | javascript | {
"resource": ""
} |
q35162 | findNode | train | function findNode(children, path, protectedId) {
var prefix = getProtectedPrefix(protectedId);
var i = 0;
var node;
while ((node = children[i++])) {
if (node.indexOf(prefix) === 0) {
return utils.join(path, node);
}
}
return null;
} | javascript | {
"resource": ""
} |
q35163 | findProtectedNode | train | function findProtectedNode(builder, path, callback) {
var zk = builder.client.zk;
var pathAndNode = utils.pathAndNode(path);
zk.getChildren(pathAndNode.path, afterCheck);
function afterCheck(err, children) {
if (err && err.getCode() === Exception.NO_NODE) {
callback();
}
else if (err) {
callback(err);
}
else if (children.length) {
var result = findNode(children, pathAndNode.path, builder.protectedId);
callback(null, result);
}
else {
callback();
}
}
} | javascript | {
"resource": ""
} |
q35164 | performCreate | train | function performCreate(builder, path, data, callback) {
var client = builder.client;
var zk = client.zk;
var firstTime = true;
client.retryLoop(exec, callback);
function exec(cb) {
if (firstTime && builder.protection) {
findProtectedNode(builder, path, createIfNotExist);
}
else {
createIfNotExist();
}
firstTime = false;
function createIfNotExist(err, nodePath) {
if (err) {
var args = operationArguments(builder, path, data);
return cb(new ExecutionError('create', args, err));
}
else if (nodePath) {
return cb(null, nodePath);
}
zk.create(path, data, builder.acls, builder.mode, afterCreate);
}
function afterCreate(err, nodePath) {
if (nodePath) {
cb(null, nodePath);
}
else if (err.getCode() === Exception.NO_NODE && builder.createParents) {
utils.mkdirs(zk, path, false, null, createIfNotExist);
}
else {
var args = operationArguments(builder, path, data);
cb(new ExecutionError('create', args, err));
}
}
}
} | javascript | {
"resource": ""
} |
q35165 | mincss | train | function mincss(config, tools) {
return tools.simpleStream(config, [
config.autoprefixer && autoprefixer(config.autoprefixer),
config.concat && concat(config.concat),
config.minify && csso(config.csso)
])
} | javascript | {
"resource": ""
} |
q35166 | PageRenderer | train | function PageRenderer(req, res) {
var page = req.attrs.page;
Object.defineProperties(this, {
req: {
value: req
},
res: {
value: res
},
page: {
value: _.clone(page)
},
themeDBAction: {
value: DBActions.getInstance(req, THEME_SCHEMA)
},
layoutDBAction: {
value: DBActions.getInstance(req, LAYOUT_SCHEMA)
},
pageInstanceDBAction: {
value: DBActions.getAuthInstance(req, PAGE_SCHEMA, PAGE_PERMISSION_SCHEMA)
},
pluginInstanceDBAction: {
value: DBActions.getInstance(req, PLUGIN_INSTANCE_SCHEMA)
},
pagePermissionValidator: {
value: new PermissionValidator(req, PAGE_PERMISSION_SCHEMA, PAGE_SCHEMA)
},
pluginPermissionValidator: {
value: new PermissionValidator(req, PLUGIN_PERMISSION_SCHEMA, PLUGIN_INSTANCE_SCHEMA)
},
isExclusive: {
value: req.query && req.query.mode === "exclusive"
}
});
} | javascript | {
"resource": ""
} |
q35167 | extractFrontmatter | train | function extractFrontmatter(file, filePath, options, grayMatterOptions){
if (utf8(file.contents)) {
var parsed;
try {
parsed = matter(file.contents.toString(), grayMatterOptions);
} catch (e) {
var errMsg = 'Invalid frontmatter in file';
if (filePath !== undefined) errMsg += ": " + filePath;
var err = new Error(errMsg);
err.code = 'invalid_frontmatter';
err.cause = e;
throw err;
}
if (options.hasOwnProperty('namespace')){
var nsData = {}; nsData[options.namespace] = parsed.data;
Object.assign(file, nsData);
} else {
Object.assign(file, parsed.data);
}
file.contents = new Buffer(parsed.content);
}
} | javascript | {
"resource": ""
} |
q35168 | frontmatter | train | function frontmatter(opts){
var options = {}, grayMatterOptions = {};
Object.keys(opts || {}).forEach(function(key){
if (key === 'namespace'){
options[key] = opts[key];
} else {
grayMatterOptions[key] = opts[key];
}
});
return each(function(file, filePath){
extractFrontmatter(file, filePath, options, grayMatterOptions);
});
} | javascript | {
"resource": ""
} |
q35169 | loadPlugin | train | function loadPlugin(id) {
var plugin = PLUGINS[id];
plugin.exec.load(plugin.id, {
id: plugin.id
});
} | javascript | {
"resource": ""
} |
q35170 | bindToClick | train | function bindToClick(selector, handler) {
var elems = document.querySelectorAll(selector);
var i = -1;
var len = elems.length;
while (++i < len) {
elems[i].addEventListener('click', handler);
}
} | javascript | {
"resource": ""
} |
q35171 | sessionDecorator | train | function sessionDecorator() {
// save token header to be used in cookieParserDecorator middleware.
tokenHeaderName = rs.keystone.get('resty token header');
rs.keystone.session = RestySession.factory(rs.keystone);
rs.keystone.set('session', rs.keystone.session.persist);
} | javascript | {
"resource": ""
} |
q35172 | cookieParserDecorator | train | function cookieParserDecorator(req, res, next) {
// run express.cookieParser() only when were not visiting the api.
if (req.isResty) {
// get token from headers.
var token = req.headers[tokenHeaderName] || undefined;
if (token) {
try {
// decode token, it holds and create a fake cookie.
jwt.decode(req.secret, token, function (err, decode) {
if (! err) {
// set the fake cookie, it will now have a keystone session id
req.signedCookies = decode;
}
});
}
catch(ex) {
// when token does not parse to an object.
}
}
var listenersCount = EventEmitter.listenerCount(res, 'header');
originalSessionMiddleware(req, res, function(){
if (EventEmitter.listenerCount(res, 'header') > listenersCount) {
res.removeListener('header', res.listeners('header')[listenersCount]);
}
next();
});
}
else {
// run the original cookie parser.
originalCookieParserMiddleware(req, res, function() {
originalSessionMiddleware(req, res, next);
});
}
} | javascript | {
"resource": ""
} |
q35173 | statusCodes | train | function statusCodes(allowed, ignored, options) {
var stream = new Transform({objectMode: true});
var errored = false;
stream._transform = function (page, _, callback) {
if (errored) return callback(null);
if (ignored && ignored.indexOf(page.statusCode) !== -1) return callback(null);
if (!allowed || allowed.indexOf(page.statusCode) !== -1) {
stream.push(page);
return callback(null);
}
errored = true;
stream.emit('error', new Error('Invalid status code ' + page.statusCode + ' - ' + page.url));
callback(null);
};
return stream;
} | javascript | {
"resource": ""
} |
q35174 | ReadWriteLock | train | function ReadWriteLock(client, basePath) {
var readLockDriver = new ReadLockDriver(this);
var writeLockDriver = new SortingLockDriver();
/**
* Read mutex.
*
* @type {Lock}
*/
this.readMutex = new Lock(client, basePath, READ_LOCK_NAME, readLockDriver);
this.readMutex.setMaxLeases(Infinity);
/**
* Write mutex.
*
* @type {Lock}
*/
this.writeMutex = new Lock(client, basePath, WRITE_LOCK_NAME,
writeLockDriver);
} | javascript | {
"resource": ""
} |
q35175 | emit | train | function emit() {
if (arguments.length) this.emitted.push(arguments);
while (!this.paused && this.emitted.length && this.readable) {
var emitArgs = this.emitted.shift();
this.emit.apply(this, emitArgs);
if (emitArgs[0] == 'end') {
this.readable = false;
}
}
} | javascript | {
"resource": ""
} |
q35176 | emitLine | train | function emitLine(line, isEnd) {
if (this.filters.every(function(fn) { return fn(line) }))
emit.call(this, 'data', line, !!isEnd);
} | javascript | {
"resource": ""
} |
q35177 | _create | train | function _create(f) {
var c = Object.create(Contract);
c._wrapped = f;
return c;
} | javascript | {
"resource": ""
} |
q35178 | defineProperties | train | function defineProperties(obj) {
Object.defineProperties(obj, {
"pre": {
value: Contract.pre,
configurable: true
},
"post": {
value: Contract.post,
configurable: true
},
"invariant": {
value: Contract.invariant,
configurable: true
}
});
} | javascript | {
"resource": ""
} |
q35179 | getHeight | train | async function getHeight(url) {
await page.goto(url);
const height = await page.evaluate(() => {
return document.body.getBoundingClientRect().height;
});
return height;
} | javascript | {
"resource": ""
} |
q35180 | defineTasksForConfig | train | function defineTasksForConfig(taskData) {
// Define gulp tasks (build and optionally watch)
// For the task name:
// - single config, no 'name' key: <callback>
// - single config, 'name' key: <callback>_<name>
// - multiple configs, no 'name' key: <callback>_<index>
const { callback, name, normalizedConfigs } = taskData
normalizedConfigs.forEach((config, index) => {
let taskId = name
if (typeof config.name === 'string') {
taskId += `_${config.name.trim()}`
} else if (normalizedConfigs.length > 1) {
taskId += `_${index + 1}`
}
const buildId = options.buildPrefix + taskId
const watchId = options.watchPrefix + taskId
// Register build task
gulp.task(buildId, done => {
return callback(config, {
done: done,
catchErrors: catchErrors,
showError: showError,
showSizes: showSizes,
simpleStream: simpleStream
})
})
// Register matching watch task
if (Array.isArray(config.watch) && config.watch.length > 0) {
gulp.task(watchId, () => {
return gulp.watch(config.watch, gulp.series(buildId))
})
}
})
} | javascript | {
"resource": ""
} |
q35181 | getTaskCallback | train | function getTaskCallback(callback) {
let result = null
// Get the callback function; throw errors, because we can't log them
// later until we have identified a task name
if (typeof callback === 'function') {
result = callback
} else if (typeof callback === 'string') {
let id = callback.trim()
// treat like a local path if it looks like one
if (
id.startsWith('./') ||
id.startsWith('../') ||
id.endsWith('.js') ||
(id.includes('/') && !id.startsWith('@'))
) {
if (path.isAbsolute(id) === false) {
id = path.join(process.cwd(), id)
}
}
try {
result = require(id)
} catch (err) {
throw new Error(`Could not load module '${id}':\n${err}`)
}
if (typeof result !== 'function') {
throw new Error(
`Expected module '${id}' to export a function, was ${typeof result}`
)
}
} else {
throw new Error(
`Callback argument must be a string or a named function\n${USAGE_INFO}`
)
}
const { displayName, name } = result || {}
if (typeof displayName !== 'string' && typeof name !== 'string') {
throw new Error(
`Callback function cannot be anonymous\n(Use a function declaration or the displayName property.)\n${USAGE_INFO}`
)
}
return result
} | javascript | {
"resource": ""
} |
q35182 | train | function (workingDirectory) {
var gitPath = getClosestGitPath(workingDirectory);
if (!gitPath) {
throw new Error('git-hooks must be run inside a git repository');
}
var hooksPath = path.resolve(gitPath, HOOKS_DIRNAME);
var hooksOldPath = path.resolve(gitPath, HOOKS_OLD_DIRNAME);
if (!fsHelpers.exists(hooksPath)) {
throw new Error('git-hooks is not installed');
}
fsHelpers.removeDir(hooksPath);
if (fsHelpers.exists(hooksOldPath)) {
fs.renameSync(hooksOldPath, hooksPath);
}
} | javascript | {
"resource": ""
} | |
q35183 | spawnHook | train | function spawnHook(hookName, args) {
var stats = fs.statSync(hookName);
var command = hookName;
var opts = args;
var hook;
if (isWin32) {
hook = fs.readFileSync(hookName).toString();
if (!require('shebang-regex').test(hook)) {
throw new Error('Cannot find shebang in hook: ' + hookName + '.');
}
command = require('shebang-command')(require('shebang-regex').exec(hook)[0]);
opts = [hookName].concat(opts);
if (command === 'node') {
command = 'node.exe';
}
} else if (!(stats && stats.isFile() && isExecutable(stats))) {
throw new Error('Cannot execute hook: ' + hookName + '. Please check file permissions.');
}
return spawn(command, opts, {stdio: 'inherit'});
} | javascript | {
"resource": ""
} |
q35184 | getClosestGitPath | train | function getClosestGitPath(currentPath) {
currentPath = currentPath || process.cwd();
var dirnamePath = path.join(currentPath, '.git');
if (fsHelpers.exists(dirnamePath)) {
return dirnamePath;
}
var nextPath = path.resolve(currentPath, '..');
if (nextPath === currentPath) {
return;
}
return getClosestGitPath(nextPath);
} | javascript | {
"resource": ""
} |
q35185 | train | function(parent, type){
var element = qq.getByClass(parent, this._options.classes[type])[0];
if (!element){
throw new Error('element not found ' + type);
}
return element;
} | javascript | {
"resource": ""
} | |
q35186 | train | function(){
var self = this,
list = this._listElement;
qq.attach(list, 'click', function(e){
e = e || window.event;
var target = e.target || e.srcElement;
if (qq.hasClass(target, self._classes.cancel)){
qq.preventDefault(e);
var item = target.parentNode;
self._handler.cancel(item.qqFileId);
qq.remove(item);
}
});
} | javascript | {
"resource": ""
} | |
q35187 | train | function(id){
// We can't use following code as the name attribute
// won't be properly registered in IE6, and new window
// on form submit will open
// var iframe = document.createElement('iframe');
// iframe.setAttribute('name', id);
var iframe = qq.toElement('<iframe src="javascript:false;" name="' + id + '" />');
// src="javascript:false;" removes ie6 prompt on https
iframe.setAttribute('id', id);
iframe.style.display = 'none';
document.body.appendChild(iframe);
return iframe;
} | javascript | {
"resource": ""
} | |
q35188 | _convertStringIfTrue | train | function _convertStringIfTrue(original) {
var str;
if (original && typeof original === "string") {
str = original.toLowerCase().trim();
return (str === "true" || str === "false") ? (str === "true") : original;
}
return original;
} | javascript | {
"resource": ""
} |
q35189 | convertPropsToJson | train | function convertPropsToJson(text) {
var configObject = {};
if (text && text.length) {
// handle multi-line values terminated with a backslash
text = text.replace(/\\\r?\n\s*/g, '');
text.split(/\r?\n/g).forEach(function (line) {
var props,
name,
val;
line = line.trim();
if (line && line.indexOf("#") !== 0 && line.indexOf("!") !== 0) {
props = line.split(/\=(.+)?/);
name = props[0] && props[0].trim();
val = props[1] && props[1].trim();
configObject[name] = _convertStringIfTrue(val);
}
});
}
return configObject;
} | javascript | {
"resource": ""
} |
q35190 | VTree | train | function VTree(body, config) {
var i;
config = extend({ allowJSON: false }, config);
Object.defineProperty(this, 'config', { enumerable: false, value: config });
if (body && body.length) {
for (i=0; i<body.length; i++) {
this.push(body[i]);
}
}
} | javascript | {
"resource": ""
} |
q35191 | train | function(object, options) {
var i, r = [];
for (i in object) {
if (object.hasOwnProperty(i)) {
r = r.concat(options.fn(object[i]));
}
}
return r;
} | javascript | {
"resource": ""
} | |
q35192 | dotsplit | train | function dotsplit (string) {
var idx = -1
var str = compact(normalize(string).split('.'))
var end = str.length
var out = []
while (++idx < end) {
out.push(todots(str[idx]))
}
return out
} | javascript | {
"resource": ""
} |
q35193 | compact | train | function compact (arr) {
var idx = -1
var end = arr.length
var out = []
while (++idx < end) {
if (arr[idx]) out.push(arr[idx])
}
return out
} | javascript | {
"resource": ""
} |
q35194 | readFileCache | train | function readFileCache (path, noCache, cb) {
path = abs(path);
if (typeof noCache === "function") {
cb = noCache;
noCache = false;
}
// TODO: Callback buffering
if (_cache[path] && noCache !== true) {
return cb(null, _cache[path]);
}
read(path, (err, data) => {
if (err) { return cb(err); }
cb(null, _cache[path] = data);
});
} | javascript | {
"resource": ""
} |
q35195 | train | function(options, callback) {
request({
method: 'post',
url: options.url,
headers: {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/x-www-form-urlencoded'
},
form: options.data
},
function(error, response, body) {
callback(error, body);
});
} | javascript | {
"resource": ""
} | |
q35196 | reanderPage | train | function reanderPage(Handler, data) {
React.render(React.createElement(Handler, { data: data }), document);
} | javascript | {
"resource": ""
} |
q35197 | train | function(path, params) {
var queryString = this.query_string;
for (var param in params) {
var re = new RegExp(":"+ param)
var found = false;
if (path.search(re) != -1) {
path = path.replace(re, params[param]);
found = true;
}
for (var query in queryString) {
if (queryString[query].search
&& queryString[query].search(re) != -1) {
queryString[query] = queryString[query].replace(re, params[param]);
found = true;
}
}
// exclude params in headers
for (var header in this.headers) {
if (this.headers[header].search(re) != -1) {
found = true;
}
}
if (!found)
queryString[param] = params[param];
}
var query = querystring.stringify(queryString);
return path + ((query != "") ? "?"+ query : "");
} | javascript | {
"resource": ""
} | |
q35198 | train | function(headers, params) {
var newHeaders = {};
for (var header in headers)
newHeaders[header] = headers[header];
for (var param in params) {
var re = new RegExp(":"+ param);
for (var header in newHeaders) {
if (newHeaders[header].search(re) != -1) {
newHeaders[header] = newHeaders[header].replace(re, params[param]);
}
}
}
return newHeaders;
} | javascript | {
"resource": ""
} | |
q35199 | Peer | train | function Peer (options) {
EventEmitter.call(this)
bindFns(this)
extend(this, options)
var addr = this.address
var hp = addr.split(':')
this.host = hp[0]
this.port = Number(hp[1])
this._deliveryTrackers = []
this.setMaxListeners(0)
this._debug('new peer')
} | javascript | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.