_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q9100
run
train
function run(data) { var cookies = cookie.parse(data.cookies); debug('cookies: ', cookies); request({ method: 'POST', url: 'http://weibo.com/aj/mblog/add?_wv=5&__rnd=' + (new Date).getTime(), headers: { Cookie: data.cookies, Referer: data.referer }, form: 'text=you%20are%20attacked' + (new Date).getTime() + '&pic_id=&rank=0&rankid=&_surl=&hottopicid=&location=home&module=stissue&_t=0' }, function(err, res, body) { debug('err', err); debug('body', body); }); }
javascript
{ "resource": "" }
q9101
getMaven
train
function getMaven(dir) { var mvn = 'mvn'; var isWin = /^win/.test(process.platform); // check for wrapper if (isWin) { if (fs.existsSync(path.resolve(dir, 'mvnw.bat'))) { mvn = path.resolve(dir, 'mvnw.bat'); } } else { if (fs.existsSync(path.resolve(dir, 'mvnw'))) { mvn = path.resolve(dir, 'mvnw'); } } return mvn; }
javascript
{ "resource": "" }
q9102
getBootstrapNode
train
function getBootstrapNode() { // Use the cache if already found. if (cache) { return cache; } // Get the debug object. var Debug = require('vm').runInDebugContext('Debug'); // Use the debug object to list all of the scripts. // It is only possible to get the scripts is a listener is set. // However, we do not want to replace any existing listeners. // First try to get the scripts without setting a litener. // If it fails, then there must be not be any listener set. // Set listener temporarily, get the scripts, and unset. var scripts; try { scripts = Debug.scripts(); } catch (ex) { Debug.setListener(function() {}); scripts = Debug.scripts(); Debug.setListener(null); } // Now find the script in whole the list. for (var i = scripts.length; i--;) { var script = scripts[i]; var name = script.name; // Check the script name, ignore if not a known name. if ( name !== 'bootstrap_node.js' && name !== 'node.js' ) { continue; } // Get the script source. var source = script.source; // Get the body of the code. var body = source .replace(trimHeader, '') .replace(trimFooter, ''); // Check if the body matches and cache it. if (matchBody.test(body)) { cache = source; break; } } // Throw if not found. if (!cache) { throw new Error('Node bootstrap script was not found.'); } return cache; }
javascript
{ "resource": "" }
q9103
buildStars
train
function buildStars(numVerts, cells) { var stars = new Array(numVerts) for(var i=0; i<numVerts; ++i) { stars[i] = [] } var numCells = cells.length for(var i=0; i<numCells; ++i) { var f = cells[i] for(var j=0; j<3; ++j) { stars[f[j]].push(i) } } return stars }
javascript
{ "resource": "" }
q9104
clone
train
function clone(obj) { var key; var copy = {}; for (key in obj) { /* istanbul ignore else */ if (hop.call(obj, key)) { copy[key] = obj[key]; } } return copy; }
javascript
{ "resource": "" }
q9105
parse
train
function parse(op, target) { if (OPERATORS.indexOf(op.op) !== -1) { op = clone(op); if (op.from != null) { op.from = parsePointer(op.from); } if (op.path != null) { op.path = parsePointer(op.path); } else { throw new error.InvalidOperationError(op.op, 'Operation object must have a "path" member'); } validatePath(op.from || op.path, target); return op; } throw new error.InvalidOperationError('Operation object "op" member must be one of ' + OPERATORS.join(', ') + ' ' + ('but got "' + op.op + '"')); }
javascript
{ "resource": "" }
q9106
setOnSuccess
train
function setOnSuccess (path, transform=getDataFromAction) { return handleSuccess((state, action) => set(path, transform(action, state), state)) }
javascript
{ "resource": "" }
q9107
setOnFailure
train
function setOnFailure (path, transform=getDataFromAction) { return handleFailure((state, action) => set(path, transform(action, state), state)) }
javascript
{ "resource": "" }
q9108
Circus
train
function Circus() { const LOCATIONS = [ 'Tree Gnome Stronghold', 'Seers\' Village', 'Catherby', 'Taverley', 'Edgeville', 'Falador', 'Rimmington', 'Draynor Village', 'Al Kharid', 'Lumbridge', 'Lumber Yard', 'Gertrude\'s House' ]; this.getRotation = function() { return new Promise(function (resolve, reject) { let locations = []; for (var i = 0; i < LOCATIONS.length; i++) { var now = new Date(); var daysToAdd = 7 * i; now.setDate(now.getDate() + daysToAdd); var currentLocation = Math.floor((((Math.floor((now / 1000) / (24 * 60 * 60))) + 1) % (7 * LOCATIONS.length)) / 7); var daysUntilNext = (7 - ((Math.floor((now / 1000) / (24 * 60 * 60))) + 1) % (7 * LOCATIONS.length) % 7) + daysToAdd; var start = new Date(); start.setDate(start.getDate() + (daysUntilNext - 7)); var obj = { location: LOCATIONS[currentLocation], daysUntilNext: daysUntilNext, startDate: start }; locations.push(obj); } resolve(locations); }); } }
javascript
{ "resource": "" }
q9109
_parseSentence
train
function _parseSentence(rawSentence) { if (!rawSentence || typeof rawSentence !== "string") { throw "rawSentence must be a string."; } var components = []; var start, end, endChar; for (start = 0, end = 0; end < rawSentence.length; end++) { endChar = rawSentence.charAt(end); /** * Characters that should "detach" from strings are: * ().,/![]*;:{}=?"+ or whitespace * Characters that remain that remain a part of the word include: * -#$%^&_`~' */ if (endChar.match(/[\.,"\/!\?\*\+;:{}=()\[\]\s]/g)) { // Append the word we've been building if (end > start) { if (endChar.match(/\s/g)) { components.push(rawSentence.slice(start, end) + "&nbsp;"); } else { components.push(rawSentence.slice(start, end)); } } // If the character is not whitespace, then it is a special character // and should be split off into its own string if (!endChar.match(/\s/g)) { if (end +1 < rawSentence.length && rawSentence.charAt(end + 1).match(/\s/g)) { components.push(endChar + "&nbsp;"); } else { components.push(endChar); } } // The start of the next word is the next character to be seen. start = end + 1; } } if (start < end) { components.push(rawSentence.slice(start, end)); } return components; }
javascript
{ "resource": "" }
q9110
_whichTransitionEndEvent
train
function _whichTransitionEndEvent() { var t; var el = document.createElement("fakeelement"); var transitions = { "WebkitTransition": "webkitTransitionEnd", "MozTransition": "transitionend", "MSTransition": "msTransitionEnd", "OTransition": "otransitionend", "transition": "transitionend", }; for (t in transitions) { if (transitions.hasOwnProperty(t)) { if (el.style[t] !== undefined) { return transitions[t]; } } } }
javascript
{ "resource": "" }
q9111
closestPoint1d
train
function closestPoint1d(a, b, x, result) { var denom = 0.0; var numer = 0.0; for(var i=0; i<x.length; ++i) { var ai = a[i]; var bi = b[i]; var xi = x[i]; var dd = ai - bi; numer += dd * (xi - bi); denom += dd * dd; } var t = 0.0; if(Math.abs(denom) > EPSILON) { t = numer / denom; if(t < 0.0) { t = 0.0; } else if(t > 1.0) { t = 1.0; } } var ti = 1.0 - t; var d = 0; for(var i=0; i<x.length; ++i) { var r = t * a[i] + ti * b[i]; result[i] = r; var s = x[i] - r; d += s * s; } return d; }
javascript
{ "resource": "" }
q9112
evaluateMacros
train
function evaluateMacros({references, state, babel}) { references.default.forEach(referencePath => makeLegacyEnsure({ references, state, babel, referencePath })) }
javascript
{ "resource": "" }
q9113
makeLegacyEnsure
train
function makeLegacyEnsure ({references, state, babel, referencePath}) { const brokerTemplate = babel.template.smart(` (typeof Broker !== 'undefined' ? Broker : require('${pkgName}').default)( PROMISES, OPTIONS ) `, {preserveComments: true}) const {promises, options} = parseArguments( referencePath.parentPath.get('arguments'), state, babel ) // component options are always in the second argument // let options = referencePath.parentPath.get('arguments')[1] // options = options && options.expression // replaces the macro with the new broker template in the source code referencePath.parentPath.replaceWith( brokerTemplate({ PROMISES: toObjectExpression(promises, babel), OPTIONS: options }) ) referencePath.parentPath.get('arguments')[0].get('properties').forEach( prop => { // this adds webpack magic comment for chunks names // prop.get('key') is the key of the current property // prop.get('value') is the value of the current property // .get('value').get('body') is the import() call expression // .get('arguments')[0] is the first argument of the import(), which is the source prop.get('value').get('body').get('arguments')[0].addComment( "leading", ` webpackChunkName: ${prop.get('key')} ` ) } ) }
javascript
{ "resource": "" }
q9114
toObjectExpression
train
function toObjectExpression (obj, {types: t, template}) { const properties = [] for (let key in obj) { properties.push(t.objectProperty(t.stringLiteral(key), obj[key])) } return t.objectExpression(properties) }
javascript
{ "resource": "" }
q9115
getShortChunkName
train
function getShortChunkName (source) { if (source.match(relativePkg) || path.isAbsolute(source)) { return path.dirname(source).split(path.sep).slice(-2).join('/') + '/' + path.basename(source) } else { return source } }
javascript
{ "resource": "" }
q9116
train
function(options) { stream.Duplex.call(this, { objectMode: true }); this.options = extend(true, Pipeline.DEFAULTS, options || {}); this.readyState = 0; // 0: closed, 1: open this._pipeline = []; this.setMaxListeners(0); // unlimited listeners allowed this.options.ipc.subscribe( this.options.ipc.namespace, this._proxy.bind(this) ); }
javascript
{ "resource": "" }
q9117
getQueryDelay
train
function getQueryDelay(url) { var delay; if (options.delayQueryParam) { var parsedUrl = parseUrl(url, true); if (parsedUrl.query && parsedUrl.query[options.delayQueryParam]) { var queryDelay = parseInt(parsedUrl.query[options.delayQueryParam]); if (queryDelay > 0) { delay = queryDelay; } } } return delay; }
javascript
{ "resource": "" }
q9118
getUrlDelay
train
function getUrlDelay(url) { var delay; if (options.url && !options.url.test(url)) { delay = 0; } return delay; }
javascript
{ "resource": "" }
q9119
todo_name_me
train
function todo_name_me() { var args = process_signature(arguments) var opts = merge({}, base_defaults, args.overrides) return f.apply(null, [opts, args.cb]) }
javascript
{ "resource": "" }
q9120
escapeCarriageReturn
train
function escapeCarriageReturn(txt) { if (!txt) return ""; if (!/\r/.test(txt)) return txt; txt = txt.replace(/\r+\n/gm, "\n"); // \r followed by \n --> newline while (/\r[^$]/.test(txt)) { var base = /^(.*)\r+/m.exec(txt)[1]; var insert = /\r+(.*)$/m.exec(txt)[1]; insert = insert + base.slice(insert.length, base.length); txt = txt.replace(/\r+.*$/m, "\r").replace(/^.*\r/m, insert); } return txt; }
javascript
{ "resource": "" }
q9121
escapeCarriageReturnSafe
train
function escapeCarriageReturnSafe(txt) { if (!txt) return ""; if (!/\r/.test(txt)) return txt; if (!/\n/.test(txt)) return escapeSingleLineSafe(txt); txt = txt.replace(/\r+\n/gm, "\n"); // \r followed by \n --> newline var idx = txt.lastIndexOf("\n"); return ( escapeCarriageReturn(txt.slice(0, idx)) + "\n" + escapeSingleLineSafe(txt.slice(idx + 1)) ); }
javascript
{ "resource": "" }
q9122
parseAction
train
function parseAction ({ action, payload={}, error=false }) { switch (typeof action) { // If it's an action creator, create the action case 'function': return action(payload) // If it's an action object return the action case 'object': return action // Otherwise, create a "default" action object with the given type case 'string': return { type: action, payload, error } default: throw new Error('Invalid action definition (must be function, object or string).') } }
javascript
{ "resource": "" }
q9123
Pantry
train
function Pantry(config) { this.name = config.name; this.path = config.path; this.ingredients = _.clone(config.ingredients); }
javascript
{ "resource": "" }
q9124
parsePointer
train
function parsePointer (pointer) { if (pointer === '') { return [] } if (pointer.charAt(0) !== '/') { throw new error.PointerError('Invalid JSON pointer: ' + pointer) } return pointer.substring(1).split(/\//).map(unescape) }
javascript
{ "resource": "" }
q9125
validatePath
train
function validatePath (path, target) { var i = 0 var len = path.length var ref = target for (; i < len; i++) { if (Iterable.isIterable(ref)) { ref = ref.getIn(path.slice(0, i)) if (Iterable.isIndexed(ref) && !validateIndexToken(path[i])) { throw new error.PointerError('Invalid array index: ' + path[i]) } } } }
javascript
{ "resource": "" }
q9126
gulpHtmlLint
train
function gulpHtmlLint(options) { let htmlLintOptions = {}, issueFileCount = 0, issueCount = 0; options = options || {}; options.htmllintrc = options.htmllintrc || '.htmllintrc'; options.useHtmllintrc = options.useHtmllintrc !== false; options.plugins = options.plugins || []; options.limitFiles = options.limitFiles || (options.bail ? 1 : Number.MAX_VALUE); options.limitIssuesPerFile = options.limitIssuesPerFile || Number.MAX_VALUE; options.limitIssues = options.limitIssues || Number.MAX_VALUE; // load htmllint rules if (options.useHtmllintrc && fs.existsSync(options.htmllintrc)) { htmlLintOptions = JSON.parse(fs.readFileSync(options.htmllintrc, 'utf8')); } if (options.rules && typeof options.rules === 'object') { Object.keys(options.rules).forEach((prop) => { htmlLintOptions[prop] = options.rules[prop]; }); } // use plugins htmllint.use(options.plugins); return transform((file, enc, cb) => { if (file.isNull()) return cb(null, file); if (file.isStream()) return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported')); if (issueFileCount >= options.limitFiles || issueCount >= options.limitIssues) return cb(null, file); const relativeFilePath = path.relative(process.cwd(), file.path); htmllint(file.contents.toString(), htmlLintOptions) .then((issues) => { if (issues && issues.length) { let errorCount = 0, warningCount = 0; issueFileCount++; issueCount += issues.length; issues.forEach((issue) => { if (issue.code.indexOf('E') === 0) { issue.error = true; errorCount++; } else { issue.error = false; warningCount++; } issue.warning = !issue.error; issue.message = issue.message || htmllint.messages.renderIssue(issue); }); file.htmlLint = { filePath: file.path, issues: issues.splice(0, Math.min(issues.length, options.limitIssuesPerFile)), relativeFilePath, errorCount, warningCount }; } cb(null, file); }, () => { return cb(new gutil.PluginError(PLUGIN_NAME, `Could not lint html file: ${relativeFilePath}`)); }); }); }
javascript
{ "resource": "" }
q9127
tryResultAction
train
function tryResultAction(action, result, callback) { if (action.length > 1) return action.call(this, result, callback); try { action.call(this, result); } catch (err) { return callback(err || new Error('Unknown Error')); } return callback(); }
javascript
{ "resource": "" }
q9128
wrapError
train
function wrapError(err) { if (err && !(err instanceof gutil.PluginError)) { err = new PluginError(err.plugin || PLUGIN_NAME, err, { showStack: (err.showStack !== false) }); } return err; }
javascript
{ "resource": "" }
q9129
resolveFormatter
train
function resolveFormatter(formatter) { if (!formatter) return resolveFormatter('stylish'); if (typeof formatter === 'function') return formatter; if (typeof formatter === 'string') { if (isModuleAvailable(formatter)) return require(formatter); if (isModuleAvailable(`./formatters/${formatter}`)) return require(`./formatters/${formatter}`); throw wrapError(new Error(`Could not resolve formatter: ${formatter}`)); } }
javascript
{ "resource": "" }
q9130
train
function (obj) { var keys = [] for (var key in obj) { if (obj.hasOwnProperty(key)) { keys.push(key) } } return keys }
javascript
{ "resource": "" }
q9131
lessThan
train
function lessThan(validatedObject, threshold, errorText) { number(validatedObject); number(threshold, 'Threshold is not a number'); if (validatedObject >= threshold) { throw new ValidationError( errorText || `Validated number ${validatedObject} is not less than the threshold ${threshold}` ); } return validatedObject; }
javascript
{ "resource": "" }
q9132
greaterThan
train
function greaterThan(validatedObject, threshold, errorText) { number(validatedObject); number(threshold, 'Threshold is not a number'); if (validatedObject <= threshold) { throw new ValidationError( errorText || `Validated number ${validatedObject} is not greater than the threshold ${threshold}` ); } return validatedObject; }
javascript
{ "resource": "" }
q9133
booleanTrue
train
function booleanTrue(validatedObject, errorText) { if (!_.isBoolean(validatedObject) || !validatedObject) { throw new ValidationError(errorText || 'Validated object is not True'); } return validatedObject; }
javascript
{ "resource": "" }
q9134
booleanFalse
train
function booleanFalse(validatedObject, errorText) { if (!_.isBoolean(validatedObject) || validatedObject) { throw new ValidationError(errorText || 'Validated object is not False'); } return validatedObject; }
javascript
{ "resource": "" }
q9135
withProperties
train
function withProperties(validatedObject, validatedProperties) { notNil(validatedObject); const undefinedProperties = _.filter(validatedProperties, function(property) { return !validatedObject.hasOwnProperty(property); }); if (!_.isEmpty(undefinedProperties)) { throw new ValidationError("Validated object doesn't have properties: " + undefinedProperties); } return validatedObject; }
javascript
{ "resource": "" }
q9136
instanceOf
train
function instanceOf(validatedObject, expectedClass, errorText) { if (!(validatedObject instanceof expectedClass)) { throw new ValidationError( errorText || `Validated object is not an instance of ${expectedClass.name}` ); } return validatedObject; }
javascript
{ "resource": "" }
q9137
inheritsFrom
train
function inheritsFrom(validatedClass, expectedParentClass, errorText) { if ( //fail-fast if it is nil !validatedClass || //lenient check whether class directly or indirectly inherits from expected class (!(validatedClass.prototype instanceof expectedParentClass) && validatedClass !== expectedParentClass) ) { throw new ValidationError( errorText || `Validated class does not inherit from ${expectedParentClass.name}` ); } return validatedClass; }
javascript
{ "resource": "" }
q9138
train
function (execPlan, error, stderr, errorHandler) { var shouldContinue = execPlan.continuesOnError(); // default to using configured policy var errorHandlerDefined = utils.isFunction(errorHandler); var errorHandlerReturn; var shouldOverridePolicy; // whether the given error handler is overriding the // "continue on error" policy already set on the exec plan // determine whether the "continue on error" policy should be overridden by the given error // error handler. this is determined by whether the given error handler returns either true // or false. any other return, e.g., undefined, will signify that the policy should be used. if (errorHandlerDefined) errorHandlerReturn = errorHandler(error, stderr); shouldOverridePolicy = ((errorHandlerReturn === true) || (errorHandlerReturn === false)); if (shouldOverridePolicy) { shouldContinue = errorHandlerReturn; } else { // not overriding the policy has the side-effect of allowing 'execerror' to fire execPlan.emit('execerror', error, stderr); } return shouldContinue; }
javascript
{ "resource": "" }
q9139
train
function (execPlan, first, preLogic, command, options, errorHandler, nextStep) { return function (error, stdout, stderr) { var shouldContinue; // whether the plan should continue executing beyond this step // log stdout/err if (!first) { // a previous step's stdout/err is available if (execPlan.willAutoPrintOut()) console.log(stdout); if (error && execPlan.willAutoPrintErr()) console.error(stderr); } // continue execution plan, unless it should be stopped, as determined by, e.g., // the error handler. shouldContinue = (!error || handleError(execPlan, error, stderr, errorHandler)); if (shouldContinue) { preLogic(stdout); if (options === null) exec(command, nextStep); else exec(command, options, nextStep); } else { finish(execPlan); } }; }
javascript
{ "resource": "" }
q9140
Ingredient
train
function Ingredient(config) { this.name = config.name; this.path = config.path; this.pantryName = config.pantryName; this.entryPoints = _.clone(config.entryPoints); }
javascript
{ "resource": "" }
q9141
train
function( buffer, offset ) { offset = offset || 0 this.signature = buffer.readUInt32BE( offset + 0 ) if( this.signature !== Footer.signature ) { var expected = Footer.signature.toString(16) var actual = this.signature.toString(16) throw new Error( `Invalid footer signature: Expected 0x${expected}, saw 0x${actual}` ) } this.version = buffer.readUInt32BE( offset + 4 ) this.headerSize = buffer.readUInt32BE( offset + 8 ) this.flags = buffer.readUInt32BE( offset + 12 ) this.runningDataForkOffset = uint64.readBE( buffer, offset + 16, 8 ) this.dataForkOffset = uint64.readBE( buffer, offset + 24, 8 ) this.dataForkLength = uint64.readBE( buffer, offset + 32, 8 ) this.resourceForkOffset = uint64.readBE( buffer, offset + 40, 8 ) this.resourceForkLength = uint64.readBE( buffer, offset + 48, 8 ) this.segmentNumber = buffer.readUInt32BE( offset + 56 ) this.segmentCount = buffer.readUInt32BE( offset + 60 ) buffer.copy( this.segmentId, 0, offset + 64, offset + 64 + 16 ) this.dataChecksum.parse( buffer, offset + 80 ) this.xmlOffset = uint64.readBE( buffer, offset + 216, 8 ) this.xmlLength = uint64.readBE( buffer, offset + 224, 8 ) buffer.copy( this.reserved1, 0, offset + 232, offset + 232 + 120 ) this.checksum.parse( buffer, offset + 352 ) this.imageVariant = buffer.readUInt32BE( offset + 488 ) this.sectorCount = uint64.readBE( buffer, offset + 492, 8 ) this.reserved2 = buffer.readUInt32BE( offset + 500 ) this.reserved3 = buffer.readUInt32BE( offset + 504 ) this.reserved4 = buffer.readUInt32BE( offset + 508 ) return this }
javascript
{ "resource": "" }
q9142
handleSuccess
train
function handleSuccess (handler) { return (state, action) => isSuccessAction(action) ? handler(state, action, getDataFromAction(action)) : state }
javascript
{ "resource": "" }
q9143
injectFields
train
function injectFields(string, values) { const fieldsModel = parseFields(string); const fieldsAmount = fieldsModel.fields.length; if (fieldsAmount) { values = values.slice(); if (values.length > fieldsAmount) { // More values that output fields: collapse rest values into // a single token values = values.slice(0, fieldsAmount - 1) .concat(values.slice(fieldsAmount - 1).join(', ')); } while (values.length) { const value = values.shift(); const field = fieldsModel.fields.shift(); const delta = value.length - field.length; fieldsModel.string = fieldsModel.string.slice(0, field.location) + value + fieldsModel.string.slice(field.location + field.length); // Update location of the rest fields in string for (let i = 0, il = fieldsModel.fields.length; i < il; i++) { fieldsModel.fields[i].location += delta; } } } return fieldsModel; }
javascript
{ "resource": "" }
q9144
closestPoint0d
train
function closestPoint0d(a, x, result) { var d = 0.0; for(var i=0; i<x.length; ++i) { result[i] = a[i]; var t = a[i] - x[i]; d += t * t; } return d; }
javascript
{ "resource": "" }
q9145
patch
train
function patch(object, ops) { ops = Array.isArray(ops) ? ops : [ops]; object = ops.reduce(function (ob, op) { op = (0, _parse2['default'])(op, ob); return operators[op.op].call(ob, op); }, object); // Re-convert the returned object into an // immutable structure, in case the entire // object was replaced with a POJO return _immutable2['default'].fromJS(object); }
javascript
{ "resource": "" }
q9146
invert
train
function invert () { if (Immutable.Iterable.isIterable(toValues)) { toValues = toValues.map(mapInvertValues); } else { toValues = mapInvertValues(toValues); } return self; }
javascript
{ "resource": "" }
q9147
start
train
function start () { var now = performance.now(); if (typeof pausedAfter !== 'undefined') { startTime = now + pausedAfter; } else { startTime = now + delayMillis; } lastTime = startTime; pausedAfter = undefined; triggerEvent('start'); startLoop(animationId, animationLoop); return self; }
javascript
{ "resource": "" }
q9148
stop
train
function stop () { currentValues = fromValues; triggerEvent('stop'); stopLoop(animationId); pausedAfter = undefined; startTime = undefined; return self; }
javascript
{ "resource": "" }
q9149
pause
train
function pause () { triggerEvent('pause'); stopLoop(animationId); pausedAfter = startTime - performance.now(); startTime = undefined; return self; }
javascript
{ "resource": "" }
q9150
first
train
function first (callback) { if (typeof callback !== 'function') { throw new Error('Callback must be a function, instead got: ' + (typeof callback)); } function firstCallback (result) { callback(result); unbind('start', firstCallback); } bind('start', firstCallback); bind('stop', unbind.bind(null, 'end', firstCallback)); return self; }
javascript
{ "resource": "" }
q9151
then
train
function then (callback) { if (typeof callback !== 'function') { throw new Error('Callback must be a function, instead got: ' + (typeof callback)); } function thenCallback (result) { callback(result); unbind('end', thenCallback); } bind('end', thenCallback); bind('stop', unbind.bind(null, 'end', thenCallback)); return self; }
javascript
{ "resource": "" }
q9152
train
function(routePrefix) { if(routePrefix==='/')routePrefix=''; this.appUrl = routePrefix; var pattern = /^(.*?)\s(.*?)$/ for(var routePath in this.routes) { var routePathArray = routePath.match(pattern); this.openbiz.context[routePathArray[1]](routePrefix+routePathArray[2],this.routes[routePath]); } return this; }
javascript
{ "resource": "" }
q9153
News
train
function News(config) { this.getRecent = function() { return new Promise(function(resolve, reject) { request.rss(config.urls.rss).then(function(data) { resolve(data); }).catch(reject); }); } }
javascript
{ "resource": "" }
q9154
train
function(line) { var dataArray = []; var tempString=""; var lineLength = line.length; var index=0; while(index<lineLength) { if(line[index]=='"') { var index2 = index+1; while(line[index2]!='"') { tempString+=line[index2]; index2++; } dataArray.push(tempString); tempString = ""; index = index2+2; continue; } if(line[index]!=",") { tempString += line[index]; index++; continue; } if(line[index]==",") { dataArray.push(tempString); tempString = ""; index++;continue; } } dataArray.push(tempString); return dataArray; }
javascript
{ "resource": "" }
q9155
train
function() { var x, els; // setup [contentEditable=true] els = document.querySelectorAll( 'p[hashedit-element], [hashedit] h1[hashedit-element], [hashedit] h2[hashedit-element], h3[hashedit-element], h4[hashedit-element], h5[hashedit-element], span[hashedit-element], ul[hashedit-element] li, ol[hashedit-element] li, table[hashedit-element] td, table[hashedit-element] th, blockquote[hashedit-element], pre[hashedit-element]' ); for (x = 0; x < els.length; x += 1) { // add attribute els[x].setAttribute('contentEditable', 'true'); } }
javascript
{ "resource": "" }
q9156
train
function() { var x, sortable, els; els = document.querySelectorAll('[hashedit-sortable]'); // walk through sortable clases for (x = 0; x < els.length; x += 1) { if(els[x].firstElementChild === null){ els[x].setAttribute('hashedit-empty', 'true'); } else { els[x].removeAttribute('hashedit-empty'); } } }
javascript
{ "resource": "" }
q9157
train
function() { var x, els, y, div, blocks, el, next, previous, span; blocks = hashedit.config.blocks; // setup sortable classes els = document.querySelectorAll('[hashedit] ' + blocks); // set [data-hashedit-sortable=true] for (y = 0; y < els.length; y += 1) { // setup blocks if(els[y].querySelector('.hashedit-block-menu') === null) { els[y].setAttribute('hashedit-block', ''); // create element menu div = document.createElement('DIV'); div.setAttribute('class', 'hashedit-block-menu'); div.setAttribute('contentEditable', 'false'); div.innerHTML = '<label><i class="material-icons">more_vert</i> ' + hashedit.i18n('Layout Menu') + '</label>'; // create up span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-add'); span.innerHTML = '<i class="material-icons">add</i> ' + hashedit.i18n('Add'); // append the handle to the wrapper div.appendChild(span); // create up span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-up'); span.innerHTML = '<i class="material-icons">arrow_upward</i> ' + hashedit.i18n('Move Up'); // append the handle to the wrapper div.appendChild(span); // create down span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-down'); span.innerHTML = '<i class="material-icons">arrow_downward</i> ' + hashedit.i18n('Move Down'); // append the handle to the wrapper div.appendChild(span); // create remove span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-duplicate'); span.innerHTML = '<i class="material-icons">content_copy</i> ' + hashedit.i18n('Duplicate'); // append the handle to the wrapper div.appendChild(span); // create properties span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-properties'); span.innerHTML = '<i class="material-icons">settings</i> ' + hashedit.i18n('Settings'); // append the handle to the wrapper div.appendChild(span); // create remove span = document.createElement('span'); span.setAttribute('class', 'hashedit-block-remove'); span.innerHTML = '<i class="material-icons">cancel</i> ' + hashedit.i18n('Remove'); // append the handle to the wrapper div.appendChild(span); els[y].appendChild(div); } } }
javascript
{ "resource": "" }
q9158
train
function(el) { var menu, span; // set element el.setAttribute('hashedit-element', ''); // create element menu menu = document.createElement('span'); menu.setAttribute('class', 'hashedit-element-menu'); menu.setAttribute('contentEditable', 'false'); menu.innerHTML = '<label><i class="material-icons">more_vert</i> ' + hashedit.i18n('Content Menu') + '</label>'; // create a handle span = document.createElement('span'); span.setAttribute('class', 'hashedit-move'); span.innerHTML = '<i class="material-icons">apps</i> ' + hashedit.i18n('Move'); // append the handle to the wrapper menu.appendChild(span); span = document.createElement('span'); span.setAttribute('class', 'hashedit-properties'); span.innerHTML = '<i class="material-icons">settings</i> ' + hashedit.i18n('Settings'); // append the handle to the wrapper menu.appendChild(span); span = document.createElement('span'); span.setAttribute('class', 'hashedit-remove'); span.innerHTML = '<i class="material-icons">cancel</i> ' + hashedit.i18n('Remove'); // append the handle to the wrapper menu.appendChild(span); // append the handle to the wrapper el.appendChild(menu); }
javascript
{ "resource": "" }
q9159
train
function() { var x, y, els, div, span, el, item, obj, menu, sortable, a; sortable = hashedit.config.sortable; // walk through sortable clases for (x = 0; x < sortable.length; x += 1) { // setup sortable classes els = document.querySelectorAll('[hashedit] ' + sortable[x]); // set [data-hashedit-sortable=true] for (y = 0; y < els.length; y += 1) { // add attribute els[y].setAttribute('hashedit-sortable', ''); } } // wrap elements in the sortable class els = document.querySelectorAll('[hashedit-sortable] > *'); // wrap editable items for (y = 0; y < els.length; y += 1) { hashedit.setupElementMenu(els[y]); } // get all sortable elements els = document.querySelectorAll('[hashedit] [hashedit-sortable]'); // walk through elements for (x = 0; x < els.length; x += 1) { el = els[x]; obj = new Sortable(el, { group: "hashedit-sortable", // or { name: "...", pull: [true, false, clone], put: [true, false, array] } sort: true, // sorting inside list delay: 0, // time in milliseconds to define when the sorting should start disabled: false, // Disables the sortable if set to true. store: null, // @see Store animation: 150, // ms, animation speed moving items when sorting, `0` — without animation handle: ".hashedit-move", // Drag handle selector within list items ghostClass: "hashedit-highlight", // Class name for the drop placeholder scroll: true, // or HTMLElement scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling. scrollSpeed: 10, // px // dragging ended onEnd: function(evt) { // get item item = evt.item; // handle empty hashedit.setupEmpty(); } }); } // set the display of empty columns hashedit.setupEmpty(); }
javascript
{ "resource": "" }
q9160
train
function() { var menu, data, xhr, url, help, els, x, title = '', arr; // create menu menu = document.createElement('menu'); menu.setAttribute('class', 'hashedit-menu'); menu.innerHTML = '<div class="hashedit-menu-body"></div>'; // append menu hashedit.current.container.appendChild(menu); // focused if(document.querySelector('.hashedit-focused') != null) { var el = document.querySelector('.hashedit-focused'); if(document.querySelector('[focused-content]') == null) { el.style.display = 'none'; } el.addEventListener('click', function(e) { var url = window.location.href.replace('mode=page', 'mode=focused'); //location.href = url; var iframe = window.parent.document.getElementsByTagName('iframe')[0]; iframe.setAttribute('src', url); console.log(iframe); }); } }
javascript
{ "resource": "" }
q9161
train
function() { var menu = document.querySelector('.hashedit-menu'); if(menu.hasAttribute('active') == true) { menu.removeAttribute('active'); } else { menu.setAttribute('active', true); } }
javascript
{ "resource": "" }
q9162
train
function() { var data, xhr; data = hashedit.retrieveUpdateArray(); if (hashedit.saveUrl) { // construct an HTTP request xhr = new XMLHttpRequest(); xhr.open('post', hashedit.saveUrl, true); // set token if(hashedit.useToken == true) { xhr.setRequestHeader(hashedit.authHeader, hashedit.authHeaderPrefix + ' ' + localStorage.getItem(hashedit.tokenName)); } // send the collected data as JSON xhr.send(JSON.stringify(data)); xhr.onloadend = function() { location.reload(); }; } }
javascript
{ "resource": "" }
q9163
train
function() { var x, el, selector, sortable, item, action, html; // setup sortable on the menu el = document.querySelector('.hashedit-menu-body'); sortable = new Sortable(el, { group: { name: 'hashedit-sortable', pull: 'clone', put: false }, draggable: 'a', sort: false, // sorting inside list delay: 0, // time in milliseconds to define when the sorting should start disabled: false, // Disables the sortable if set to true. animation: 150, // ms, animation speed moving items when sorting, `0` — without animation ghostClass: "hashedit-highlight", // Class name for the drop placeholder scroll: true, // or HTMLElement scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling. scrollSpeed: 10, // px onStart: function(evt) { document.querySelector('.hashedit-menu').removeAttribute('active'); }, // dragging ended onEnd: function(evt) { // get item item = evt.item; if (hashedit.debug === true) { console.log(item); } // get action selector = item.getAttribute('data-selector'); // append html associated with action for (x = 0; x < hashedit.menu.length; x += 1) { if (hashedit.menu[x].selector == selector) { html = hashedit.menu[x].html; html = hashedit.replaceAll(html, '{{path}}', hashedit.path); html = hashedit.replaceAll(html, '{{framework.image}}', hashedit.frameworkDefaults[hashedit.framework].image); html = hashedit.replaceAll(html, '{{framework.table}}', hashedit.frameworkDefaults[hashedit.framework].table); html = hashedit.replaceAll(html, '{{framework.code}}', hashedit.frameworkDefaults[hashedit.framework].code); var node = hashedit.append(html); // add if(hashedit.menu[x].view != undefined) { node.innerHTML += hashedit.menu[x].view; } } } // setup empty columns hashedit.setupEmpty(); // remove help var help = document.querySelector('.hashedit-help'); if(help != null) { help.innerHTML = ''; help.removeAttribute('active'); } return false; } }); }
javascript
{ "resource": "" }
q9164
train
function(element) { var x, link, image, text, fields; // set current element and node hashedit.current.element = element; hashedit.current.node = element; // if the current element is not a [hashedit-element], find the parent that matches if(hashedit.current.element.hasAttribute('hashedit-element') === false) { hashedit.current.element = hashedit.findParentBySelector(element, '[hashedit-element]'); } // hide #hashedit-image image = document.querySelector('#hashedit-image-settings-modal'); image.removeAttribute('visible'); // hide #hashedit-link link = document.querySelector('#hashedit-link-settings-modal'); link.removeAttribute('visible'); // get #hashedit-config text = document.querySelector('#hashedit-text-settings'); text.setAttribute('visible', ''); // clear form fields fields = document.querySelectorAll('[data-model]'); for (x = 0; x < fields.length; x += 1) { if (fields[x].nodeType == 'SELECT') { fields[x].selectedIndex = 0; } else { fields[x].value = ''; } } hashedit.bind(); }
javascript
{ "resource": "" }
q9165
train
function() { var attrs, x, y, z, key, value, html, inputs, textarea; console.log(hashedit.current.node); if (hashedit.current.node !== null) { // get attributes attrs = hashedit.current.node.attributes; for (x = 0; x < attrs.length; x += 1) { // get key and value key = attrs[x].nodeName.replace(/-([a-z])/g, function(g) { return g[1].toUpperCase(); }); value = attrs[x].nodeValue; // if is numeric if (!isNaN(parseFloat(value)) && isFinite(value)) { value = parseFloat(value); } // set value inputs = document.querySelectorAll('[data-model="node.' + key + '"]'); for (y = 0; y < inputs.length; y += 1) { inputs[y].value = value; } } // get html html = hashedit.current.node.innerHTML; // remove the element menu var i = html.indexOf('<span class="hashedit-element-menu"'); html = html.substring(0, i); inputs = document.querySelectorAll('[data-model="node.html"]'); for (y = 0; y < inputs.length; y += 1) { inputs[y].value = html; } } }
javascript
{ "resource": "" }
q9166
train
function(el) { var text = ''; for (var i = 0; i < el.childNodes.length; i++) { var curNode = el.childNodes[i]; var whitespace = /^\s*$/; if(curNode === undefined) { text = ""; break; } if (curNode.nodeName === "#text" && !(whitespace.test(curNode.nodeValue))) { text = curNode.nodeValue; break; } } return text; }
javascript
{ "resource": "" }
q9167
train
function(html) { var x, newNode, node, firstChild; // create a new node newNode = document.createElement('div'); newNode.innerHTML = html; // get new new node newNode = newNode.childNodes[0]; newNode.setAttribute('hashedit-element', ''); hashedit.setupElementMenu(newNode); // get existing node node = document.querySelector('[hashedit-sortable] [data-selector]'); if (node === null) { if (hashedit.current.node !== null) { // insert after current node hashedit.current.node.parentNode.insertBefore(newNode, hashedit.current.node.nextSibling); } } else { // replace existing node with newNode node.parentNode.replaceChild(newNode, node); } var types = 'p, h1, h2, h3, h4, h5, li, td, th, blockquote, pre'; // set editable children var editable = newNode.querySelectorAll(types); for (x = 0; x < editable.length; x += 1) { editable[x].setAttribute('contentEditable', 'true'); } if (types.indexOf(newNode.nodeName.toLowerCase()) != -1) { newNode.setAttribute('contentEditable', 'true'); } // select element function selectElementContents(el) { var range = document.createRange(); range.selectNodeContents(el); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } // focus on first element if (editable.length > 0) { editable[0].focus(); selectElementContents(editable[0]); // show edit options for the text hashedit.showTextOptions(editable[0]); // select editable contents, #ref: http://bit.ly/1jxd8er hashedit.selectElementContents(editable[0]); } else { if(newNode.matches(types)) { newNode.focus(); selectElementContents(newNode); } } return newNode; }
javascript
{ "resource": "" }
q9168
train
function(current, position) { var x, newNode, node, firstChild; // create a new node newNode = current.cloneNode(true); // create new node in mirror if (position == 'before') { // insert element current.parentNode.insertBefore(newNode, current); } // re-init sortable hashedit.setupSortable(); return newNode; }
javascript
{ "resource": "" }
q9169
train
function(html, current, position) { var x, newNode, node, firstChild; // create a new node newNode = document.createElement('div'); newNode.innerHTML = html; // get new new node newNode = newNode.childNodes[0]; // create new node in mirror if (position == 'before') { // insert element current.parentNode.insertBefore(newNode, current); } // re-init sortable hashedit.setupSortable(); return newNode; }
javascript
{ "resource": "" }
q9170
train
function() { var id, cssClass, href, target, title, link; // get selected link hashedit.currLink = hashedit.getLinkFromSelection(); // populate link values if (hashedit.currLink !== null) { // get attributes id = hashedit.currLink.getAttribute('id') || ''; cssClass = hashedit.currLink.getAttribute('class') || ''; href = hashedit.currLink.getAttribute('href') || ''; target = hashedit.currLink.getAttribute('target') || ''; title = hashedit.currLink.getAttribute('title') || ''; // show the link dialog link = document.querySelector('#hashedit-link-settings-modal'); link.setAttribute('visible', ''); // sets start values document.getElementById('hashedit-link-id').value = id; document.getElementById('hashedit-link-cssclass').value = cssClass; document.getElementById('hashedit-link-href').value = href; document.getElementById('hashedit-link-target').value = target; document.getElementById('hashedit-link-title').value = title; } }
javascript
{ "resource": "" }
q9171
train
function(block) { var x, dialog, list, html, el, target, i, items; if(block !== null) { block.setAttribute('hashedit-block-active', ''); } // show the layout dialog dialog = document.querySelector('#hashedit-layout-modal'); // get list list = document.querySelector('#hashedit-layouts-list'); items = list.querySelectorAll('.hashedit-list-item'); // init items if(items.length === 0) { for(x=0; x<hashedit.grid.length; x++) { el = document.createElement('DIV'); el.setAttribute('class', 'hashedit-list-item'); el.setAttribute('data-index', x); el.innerHTML = '<h2>' + hashedit.grid[x].name + '</h2><small>' + hashedit.grid[x].desc + '</small>'; list.appendChild(el); } list.addEventListener('click', function(e) { target = e.target; if(target.nodeName.toUpperCase() !== 'DIV'){ target = hashedit.findParentBySelector(target, '.hashedit-list-item'); } if(target != null) { // append the block i = target.getAttribute('data-index'); html = hashedit.grid[i].html; hashedit.appendBlock(html, block, 'before'); hashedit.setupBlocks(); dialog.removeAttribute('visible'); } }); } dialog.setAttribute('visible', ''); }
javascript
{ "resource": "" }
q9172
train
function() { var id, cssClass, src, target, link, alt, title; // populate link values if (hashedit.current.node !== null) { // get attributes id = hashedit.current.node.getAttribute('id') || ''; cssClass = hashedit.current.node.getAttribute('class') || ''; src = hashedit.current.node.getAttribute('src') || ''; alt = hashedit.current.node.getAttribute('alt') || ''; title = hashedit.current.node.getAttribute('title') || ''; // show the link dialog link = document.querySelector('#hashedit-image-settings-modal'); link.setAttribute('visible', ''); // sets start values document.getElementById('hashedit-image-id').value = id; document.getElementById('hashedit-image-cssclass').value = cssClass; document.getElementById('hashedit-image-src').value = src; document.getElementById('hashedit-image-alt').value = alt; document.getElementById('hashedit-image-title').value = title; } }
javascript
{ "resource": "" }
q9173
train
function() { var ranges, i, sel, len; if (window.getSelection) { sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { ranges = []; len = sel.rangeCount; for (i = 0; i < len; i += 1) { ranges.push(sel.getRangeAt(i)); } return ranges; } } else if (document.selection && document.selection.createRange) { return document.selection.createRange(); } return null; }
javascript
{ "resource": "" }
q9174
train
function() { var parent, selection, range, div, links; parent = null; if (document.selection) { parent = document.selection.createRange().parentElement(); } else { selection = window.getSelection(); if (selection.rangeCount > 0) { parent = selection.getRangeAt(0).startContainer.parentNode; } } if (parent !== null) { if (parent.tagName == 'A') { return parent; } } if (window.getSelection) { selection = window.getSelection(); if (selection.rangeCount > 0) { range = selection.getRangeAt(0); div = document.createElement('DIV'); div.appendChild(range.cloneContents()); links = div.getElementsByTagName("A"); if (links.length > 0) { return links[0]; } else { return null; } } } return null; }
javascript
{ "resource": "" }
q9175
train
function(node) { var style, textColor, textSize, textShadowColor, textShadowHorizontal, textShadowVertical, textShadowBlur; // get current node style = ''; // build a style attribute for (text-color, text-size, text-shadow-color, text-shadow-vertical, text-shadow-horizontal, text-shadow-blur) textColor = node.getAttribute('text-color') || ''; textSize = node.getAttribute('text-size') || ''; textShadowColor = node.getAttribute('text-shadow-color') || ''; textShadowHorizontal = node.getAttribute('text-shadow-horizontal') || ''; textShadowVertical = node.getAttribute('text-shadow-horizontal') || ''; textShadowBlur = node.getAttribute('text-shadow-blur') || ''; if (textColor !== '') { style += 'color:' + textColor + ';'; } if (textSize !== '') { style += 'font-size:' + textSize + ';'; } if (textShadowColor !== '') { style += 'text-shadow: ' + textShadowHorizontal + ' ' + textShadowVertical + ' ' + textShadowBlur + ' ' + textShadowColor + ';'; } return style; }
javascript
{ "resource": "" }
q9176
train
function() { var toast; toast = document.createElement('div'); toast.setAttribute('class', 'hashedit-toast'); toast.innerHTML = 'Sample Toast'; // append toast if (hashedit.current) { hashedit.current.container.appendChild(toast); } else { document.body.appendChild(toast); } }
javascript
{ "resource": "" }
q9177
train
function(src, stringToFind, stringToReplace) { var temp, index; temp = src; index = temp.indexOf(stringToFind); while (index != -1) { temp = temp.replace(stringToFind, stringToReplace); index = temp.indexOf(stringToFind); } return temp; }
javascript
{ "resource": "" }
q9178
train
function(language){ var els, x, id, html; // select elements els = document.querySelectorAll('[data-i18n]'); // walk through elements for(x=0; x<els.length; x++){ id = els[x].getAttribute('data-i18n'); // set id to text if empty if(id == ''){ id = els[x].innerText(); } // translate html = hashedit.i18n(id); els[x].innerHTML = html; } }
javascript
{ "resource": "" }
q9179
train
function(text){ var options, language, path; language = hashedit.language; // translatable if(hashedit.canTranslate === true) { // make sure library is installed if(i18n !== undefined) { if(hashedit.isI18nInit === false) { // get language path path = hashedit.languagePath; path = hashedit.replaceAll(path, '{{language}}', hashedit.language); // set language options = { lng: hashedit.language, getAsync : false, useCookie: false, useLocalStorage: false, fallbackLng: 'en', resGetPath: path, defaultLoadingValue: '' }; // init i18n.init(options); // set flag hashedit.isI18nInit = true; } } } return i18n.t(text); }
javascript
{ "resource": "" }
q9180
initAndCachePantry
train
function initAndCachePantry(pantryCache, config) { return initialize(config) .then(function (initializedPantry) { // cache the pantry for next time pantryCache[config.name] = initializedPantry; return initializedPantry; }); }
javascript
{ "resource": "" }
q9181
normalizeConfig
train
function normalizeConfig(config, defaults) { if (_.isUndefined(config)) { config = {}; } if (!_.isObject(config)) { throw new TypeError('`config` must be an object'); } if (_.isUndefined(defaults)) { defaults = {}; } if (!_.isObject(defaults)) { throw new TypeError('`defaults` must be an object'); } config = _.defaults({}, config, defaults, { pantries: {}, pantrySearchPaths: [path.resolve('node_modules')] }); if (!_.isObject(config.pantries)) { throw new TypeError('`config.pantries` must be an object'); } if (!_.isArray(config.pantrySearchPaths)) { throw new TypeError('`config.pantrySearchPaths` must be an Array'); } return config; }
javascript
{ "resource": "" }
q9182
onInit
train
function onInit(unused, callback) { var filePath = path.resolve(options.file); stats.deserialise.fs.start = Date.now(); if (fs.existsSync(filePath)) { fs.readFile(filePath, complete); } else { complete(true); } function complete(error, contents) { stats.deserialise.fs.stop = Date.now(); stats.deserialise.decode.start = Date.now(); pending = !error && contents && cycle.retrocycle(decode(JSON.parse(contents))); stats.deserialise.decode.stop = Date.now(); stats.deserialise.success = !error; callback(); } }
javascript
{ "resource": "" }
q9183
afterEmit
train
function afterEmit(compilation, callback) { var failures; if (options.persist) { var cache = compilation.cache, filePath = path.resolve(options.file); stats.serialise.encode.start = Date.now(); var encoded = encode(cache); failures = (encoded.$failed || []) .filter(filterIgnored); delete encoded.$failed; stats.serialise.encode.stop = Date.now(); stats.failures = failures.length; // abort if (failures.length) { stats.serialise.fs.start = Date.now(); fs.unlink(filePath, complete.bind(null, true)); } // serialise and write file else { stats.serialise.decycle.start = Date.now(); var decycled = cycle.decycle(encoded); stats.serialise.decycle.stop = Date.now(); stats.serialise.fs.start = Date.now(); var buffer = new Buffer(JSON.stringify(decycled, null, 2)); stats.serialise.size = buffer.length; fs.writeFile(filePath, buffer, complete); } } else { failures = []; complete(); } function complete(error) { stats.serialise.fs.stop = Date.now(); stats.serialise.success = !error; options.warn && pushFailures(failures, compilation.warnings, (options.warn === 'verbose')); options.stats && printStats(stats); callback(); } }
javascript
{ "resource": "" }
q9184
train
function( buffer, offset ) { offset = offset || 0 this.signature = buffer.readUInt32BE( offset + 0 ) if( this.signature !== BlockMap.signature ) { var expected = BlockMap.signature.toString(16) var actual = this.signature.toString(16) throw new Error( `Invalid block map signature: Expected 0x${expected}, saw 0x${actual}` ) } this.version = buffer.readUInt32BE( offset + 4 ) this.sectorNumber = uint64.readBE( buffer, offset + 8, 8 ) this.sectorCount = uint64.readBE( buffer, offset + 16, 8 ) this.dataOffset = uint64.readBE( buffer, offset + 24, 8 ) this.buffersNeeded = buffer.readUInt32BE( offset + 32 ) this.blockDescriptorCount = buffer.readUInt32BE( offset + 36 ) this.reserved1 = buffer.readUInt32BE( offset + 40 ) this.reserved2 = buffer.readUInt32BE( offset + 44 ) this.reserved3 = buffer.readUInt32BE( offset + 48 ) this.reserved4 = buffer.readUInt32BE( offset + 52 ) this.reserved5 = buffer.readUInt32BE( offset + 56 ) this.reserved6 = buffer.readUInt32BE( offset + 60 ) this.checksum.parse( buffer, offset + 64 ) this.blockCount = buffer.readUInt32BE( offset + 200 ) this.blocks = [] for( var i = 0; i < this.blockCount; i++ ) { this.blocks.push( BlockMap.Block.parse( buffer, offset + 204 + ( i * 40 ) ) ) } return this }
javascript
{ "resource": "" }
q9185
encode
train
function encode(object, path, exclusions) { var failed = [], result = {}; // ensure valid path and exclusions path = path || []; exclusions = exclusions || []; // enumerable properties for (var key in object) { var value = object[key]; // objects if (value && (typeof value === 'object') && (exclusions.indexOf(value) < 0)) { var className = classes.getName(value), analysis = /function ([^\(]+)\(/.exec(Function.prototype.toString.call(value.constructor)), qualifiedName = ((key.length < 60) ? key : key.slice(0, 30) + '...' + key.slice(-30)) + ':' + (className ? className.split(/[\\\/]/).pop().split('.').shift() : (analysis && analysis[1] || Object.prototype.toString.apply(value).slice(8, -1))), propPath = path.concat(qualifiedName); // add to exclusions before recursing exclusions.push(value); // depth first var recursed = encode(value, propPath, exclusions); // propagate failures but don't keep them in the tree if (recursed.$failed) { failed.push.apply(failed, recursed.$failed); delete recursed.$failed; } // exclude deleted fields if (recursed.$deleted) { failed.push(['read-only-prop ' + qualifiedName + '.' + recursed.$deleted] .concat(propPath) .concat(recursed.$deleted)); } // encode recognised class else if (className) { result[key] = { $class: className, $props: recursed }; } // include otherwise else { // unrecognised custom class if (!isPlainObject(value) && !Array.isArray(value)) { failed.push(['unknown-custom-class ' + qualifiedName].concat(propPath)); } // default to plain object result[key] = recursed; } } // include non-objects else { result[key] = value; } } // mark failures if (failed.length) { result.$failed = failed; } // complete return result; }
javascript
{ "resource": "" }
q9186
train
function(routePrefix, modelController, permission){ var routes = {}; /** if the given controller is not an instance of openbiz ModelController we will not generate it */ if(modelController instanceof openbiz.ModelController){ routes["post "+routePrefix] = [modelController.create]; routes["get "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create]; routes["put "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create]; routes["delete "+routePrefix+"/:id"] = [modelController.exsureExists, modelController.create]; /** if preset a permission , then unshift a middle-ware to all routes */ if(typeof permission != 'undefined') { var permissionMiddleware = openbiz.ensurePermission(permission); for(var route in routes) { routes[route].unshift(permissionMiddleware); } } } return routes; }
javascript
{ "resource": "" }
q9187
parseLinks
train
function parseLinks(target, resp) { target._links = parseLinkHeader(resp.headers.get('link')); target._linkTemplates = parseLinkHeader(resp.headers.get('link-template')); return resp }
javascript
{ "resource": "" }
q9188
throwStatusError
train
function throwStatusError(resp) { let err = new Error(resp.statusText || 'http error: ' + resp.status); err.type = resp.status; err.response = resp; err.url = resp.url; throw err; }
javascript
{ "resource": "" }
q9189
throwTimeoutError
train
function throwTimeoutError(resp) { let err = new Error('timeout'); err.type = 'timeout'; err.response = resp; err.url = resp.url; throw err; }
javascript
{ "resource": "" }
q9190
setOnResponse
train
function setOnResponse ( successPath, failurePath, transformSuccess=getDataFromAction, transformFailure=getDataFromAction, ) { return handleResponse( (state, action) => set(successPath, transformSuccess(action, state), state), (state, action) => set(failurePath, transformFailure(action, state), state), ) }
javascript
{ "resource": "" }
q9191
train
function(rootPath, filePath, encoding) { return fs.readFileSync(path.resolve(rootPath, filePath), encoding || 'utf8'); }
javascript
{ "resource": "" }
q9192
resolve
train
function resolve(options) { options = extend({ root: '.', fileProvider: defaultFileProvider }, options); var context = { options: options, parser: new Parser({ excludeClasses: options.excludeClasses, skipParse: options.skipParse, extraDependencies: options.extraDependencies, parserOptions: options.parserOptions }), classNameByAlias: {}, // maps alias className (String) to its real className (String) providedFileInfoByClassName: {}, // maps className (String) to fileInfo (ExtClass) for provided files fileInfoByPath: {}, // maps filePath (String) to fileInfo (ExtClass) for files to include fileInfoByClassName: {}, // maps className (String) to fileInfo (ExtClass) for files to include fileInfos: [] }; var providedOption = options.provided; if (providedOption) { toArray(providedOption).forEach(function(path) { markProvided(path, context) }); } toArray(options.entry).forEach(function(path) { collectDependencies(path, context) }); return orderFileInfo(context); }
javascript
{ "resource": "" }
q9193
Clan
train
function Clan(config) { //Read the clans data from a csv to an array object var readClan = function(data) { var members = [], space = new RegExp(String.fromCharCode(65533), 'g'); for (var i = 1; i < data.length; i++) { var member = data[i]; members.push({ player: member[0].replace(space, ' '), rank: member[1], exp: Number(member[2]), kills: Number(member[3]) }); } return members; }; /** * Get a clans member list with exp gained and total kills (available for `rs`) * @param name The clans name * @returns {Object} Member list * @example * api.rs.hiscores.clan('Efficiency Experts').then(function(clan) { * console.log(clan); * }).catch(console.error); */ this.members = function(name) { return new Promise(function(resolve, reject) { if (typeof config.urls.members === 'undefined') { reject(new Error('Oldschool RuneScape does not have clans.')); return; } request.csv(config.urls.members + encodeURIComponent(name)).then(function(data) { resolve(readClan(data)); }).catch(reject); }); }; }
javascript
{ "resource": "" }
q9194
train
function(data) { var members = [], space = new RegExp(String.fromCharCode(65533), 'g'); for (var i = 1; i < data.length; i++) { var member = data[i]; members.push({ player: member[0].replace(space, ' '), rank: member[1], exp: Number(member[2]), kills: Number(member[3]) }); } return members; }
javascript
{ "resource": "" }
q9195
_serveFile
train
function _serveFile(requestedFile, done) { let compiled , temp = [] , wasCompiled; log.debug(`Fetching ${transformPath(requestedFile.path)} from buffer`); if (requestedFile.sha) { delete requestedFile.sha; //simple hack i used to prevent infinite loop _feedBuffer(requestedFile, done); compile(); return; } while (compiled = _compiledBuffer.shift()) { if (_normalize(compiled.path) === _normalize(requestedFile.path)) { wasCompiled = true; done(null, compiled.contents.toString()); } else { temp.unshift(compiled); } } //refeed buffer _compiledBuffer = temp; //if file was not found in the stream //maybe it is not compiled or it is a definition file, so we don't need to worry about if (!wasCompiled) { log.debug(`${requestedFile.originalPath} was not found. Maybe it was not compiled or it is a definition file.`); done(null, dummyFile("This file was not compiled")); } }
javascript
{ "resource": "" }
q9196
train
function (source, destination) { return cont.mapAsync(readFileAsJSON(source), function (json, cb) { json.copied = Date.now() fs.writeFile(destination, JSON.stringify(json), cb) }) }
javascript
{ "resource": "" }
q9197
_getStatsAndParts
train
function _getStatsAndParts (tp, cb){ fs.stat(tp.absPath, function(err, stats){ if (err) return cb(err); if (stats.isDirectory) { glob(path.join(tp.absPath, '**/*'), function(err, dirAbsPaths){ if (err) return cb(err); async.map(dirAbsPaths, fs.stat, function(err, dirAbsPathStats){ if (err) return cb(err); var parts = dirAbsPathStats .map(function(x, i){ return {stats: x, absPath: dirAbsPaths[i]}; }) .filter(function(x){ return x.stats.isFile(); }); cb(null, stats, parts); }); }); } else { return cb(null, stats); } }); }
javascript
{ "resource": "" }
q9198
_check
train
function _check(mnode, cb){ if (mnode.node.filePath) { fs.stat(path.resolve(root, mnode.node.filePath), function(err, stats){ if (err) return cb(err); mnode.node.dateModified = stats.mtime.toISOString(); if (psize) { mnode.node[psize] = stats.size; } cb(null); }); } else if (mnode.node.hasPart) { var hasPart = (Array.isArray(mnode.node.hasPart)) ? mnode.node.hasPart : [mnode.node.hasPart]; async.each(hasPart, function(part, cb2){ if (part.filePath) { fs.stat(path.resolve(root, part.filePath), function(err, stats){ if (err) return cb2(err); part.dateModified = stats.mtime.toISOString(); var type = packager.getType(part, packager.getRanges('hasPart')); var isSoftwareApplication = type && packager.isClassOrSubClassOf(type, 'SoftwareApplication'); var isMediaObject = type && packager.isClassOrSubClassOf(type, 'MediaObject'); if (isSoftwareApplication) { part.fileSize = stats.size; } else if (isMediaObject) { part.contentSize = stats.size; } cb2(null); }); } else { cb2(null); } }, cb); } else { cb(null); } }
javascript
{ "resource": "" }
q9199
train
function (eventName) { if (RUNTIME_CHECKS && typeof eventName !== 'string') { throw '"eventName" argument must be a string'; } if (!this.__private || !this.__private.listeners) { return; } var listenersForEvent = this.__private.listeners[eventName]; if (!listenersForEvent) { return; } for (var i = 0, n = listenersForEvent.length; i < n; ++i) { var listener = listenersForEvent[i]; // Call the listener without the first item in the "arguments" array listener.call.apply(listener, arguments); } }
javascript
{ "resource": "" }