_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q59800
generateMarkdownTable
validation
function generateMarkdownTable(api) { if (isEmpty(api.props)) return ''; return HEADER.concat( join(map(api.props, (description, propName) => join([ `\`${propName}\``, description.required ? 'true' : '', inferType(description.type), replaceNewlineWithBreak(getValue(description, 'defaultValue.value', '')), replaceNewlineWithBreak(description.description), ], ' | ') ), '\n') ); }
javascript
{ "resource": "" }
q59801
buildDocs
validation
function buildDocs(api) { const view = buildTemplateView(api); // build up readmes one at a time const queue = d3.queue(1); Object.keys(api).forEach((filepath) => { queue.defer(buildReadMe, filepath, view); }); queue.await((err) => { if (err) { console.log(err); } console.log('Finished building docs'); }); }
javascript
{ "resource": "" }
q59802
flush
validation
function flush(callback) { // Ideally, this function would be a call to Polymer.dom.flush, but that // doesn't support a callback yet // (https://github.com/Polymer/polymer-dev/issues/851), // ...and there's cross-browser flakiness to deal with. // Make sure that we're invoking the callback with no arguments so that the // caller can pass Mocha callbacks, etc. var done = function done() { callback(); }; // Because endOfMicrotask is flaky for IE, we perform microtask checkpoints // ourselves (https://github.com/Polymer/polymer-dev/issues/114): var isIE = navigator.appName === 'Microsoft Internet Explorer'; if (isIE && window.Platform && window.Platform.performMicrotaskCheckpoint) { var reallyDone_1 = done; done = function doneIE() { Platform.performMicrotaskCheckpoint(); nativeSetTimeout(reallyDone_1, 0); }; } // Everyone else gets a regular flush. var scope; if (window.Polymer && window.Polymer.dom && window.Polymer.dom.flush) { scope = window.Polymer.dom; } else if (window.Polymer && window.Polymer.flush) { scope = window.Polymer; } else if (window.WebComponents && window.WebComponents.flush) { scope = window.WebComponents; } if (scope) { scope.flush(); } // Ensure that we are creating a new _task_ to allow all active microtasks to // finish (the code you're testing may be using endOfMicrotask, too). nativeSetTimeout(done, 0); }
javascript
{ "resource": "" }
q59803
setup
validation
function setup(options) { var childRunner = ChildRunner.current(); if (childRunner) { _deepMerge(_config, childRunner.parentScope.WCT._config); // But do not force the mocha UI delete _config.mochaOptions.ui; } if (options && typeof options === 'object') { _deepMerge(_config, options); } if (!_config.root) { // Sibling dependencies. var root = scriptPrefix('browser.js'); _config.root = basePath(root.substr(0, root.length - 1)); if (!_config.root) { throw new Error('Unable to detect root URL for WCT sources. Please set WCT.root before including browser.js'); } } }
javascript
{ "resource": "" }
q59804
expandUrl
validation
function expandUrl(url, base) { if (!base) return url; if (url.match(/^(\/|https?:\/\/)/)) return url; if (base.substr(base.length - 1) !== '/') { base = base + '/'; } return base + url; }
javascript
{ "resource": "" }
q59805
scriptPrefix
validation
function scriptPrefix(filename) { var scripts = document.querySelectorAll('script[src*="' + filename + '"]'); if (scripts.length !== 1) { return null; } var script = scripts[0].src; return script.substring(0, script.indexOf(filename)); }
javascript
{ "resource": "" }
q59806
drawFaviconArc
validation
function drawFaviconArc(context, total, start, length, color) { var arcStart = ARC_OFFSET + Math.PI * 2 * (start / total); var arcEnd = ARC_OFFSET + Math.PI * 2 * ((start + length) / total); context.beginPath(); context.strokeStyle = color; context.lineWidth = ARC_WIDTH; context.arc(16, 16, 16 - ARC_WIDTH / 2, arcStart, arcEnd); context.stroke(); }
javascript
{ "resource": "" }
q59807
loadSuites
validation
function loadSuites(files) { files.forEach(function (file) { if (/\.js(\?.*)?$/.test(file)) { jsSuites$1.push(file); } else if (/\.html(\?.*)?$/.test(file)) { htmlSuites$1.push(file); } else { throw new Error('Unknown resource type: ' + file); } }); }
javascript
{ "resource": "" }
q59808
loadJsSuites
validation
function loadJsSuites(_reporter, done) { debug('loadJsSuites', jsSuites$1); var loaders = jsSuites$1.map(function (file) { // We only support `.js` dependencies for now. return loadScript.bind(util, file); }); parallel(loaders, done); }
javascript
{ "resource": "" }
q59809
_runMocha
validation
function _runMocha(reporter, done, waited) { if (get('waitForFrameworks') && !waited) { var waitFor = (get('waitFor') || whenFrameworksReady).bind(window); waitFor(_runMocha.bind(null, reporter, done, true)); return; } debug('_runMocha'); var mocha = window.mocha; var Mocha = window.Mocha; mocha.reporter(reporter.childReporter(window.location)); mocha.suite.title = reporter.suiteTitle(window.location); mocha.grep(GREP); // We can't use `mocha.run` because it bashes over grep, invert, and friends. // See https://github.com/visionmedia/mocha/blob/master/support/tail.js#L137 var runner = Mocha.prototype.run.call(mocha, function (_error) { if (document.getElementById('mocha')) { Mocha.utils.highlightTags('code'); } done(); // We ignore the Mocha failure count. }); // Mocha's default `onerror` handling strips the stack (to support really old // browsers). We upgrade this to get better stacks for async errors. // // TODO(nevir): Can we expand support to other browsers? if (navigator.userAgent.match(/chrome/i)) { window.onerror = null; window.addEventListener('error', function (event) { if (!event.error) return; if (event.error.ignore) return; runner.uncaught(event.error); }); } }
javascript
{ "resource": "" }
q59810
injectMocha
validation
function injectMocha(Mocha) { _injectPrototype(Console, Mocha.reporters.Base.prototype); _injectPrototype(HTML, Mocha.reporters.HTML.prototype); // Mocha doesn't expose its `EventEmitter` shim directly, so: _injectPrototype(MultiReporter, Object.getPrototypeOf(Mocha.Runner.prototype)); }
javascript
{ "resource": "" }
q59811
loadSync
validation
function loadSync() { debug('Loading environment scripts:'); var a11ySuiteScriptPath = 'web-component-tester/data/a11ySuite.js'; var scripts = get('environmentScripts'); var a11ySuiteWillBeLoaded = window.__generatedByWct || scripts.indexOf(a11ySuiteScriptPath) > -1; // We can't inject a11ySuite when running the npm version because it is a // module-based script that needs `<script type=module>` and compilation // for browsers without module support. if (!a11ySuiteWillBeLoaded && !window.__wctUseNpm) { // wct is running as a bower dependency, load a11ySuite from data/ scripts.push(a11ySuiteScriptPath); } scripts.forEach(function (path) { var url = expandUrl(path, get('root')); debug('Loading environment script:', url); // Synchronous load. document.write('<script src="' + encodeURI(url) + '"></script>'); // jshint ignore:line }); debug('Environment scripts loaded'); var imports = get('environmentImports'); imports.forEach(function (path) { var url = expandUrl(path, get('root')); debug('Loading environment import:', url); // Synchronous load. document.write('<link rel="import" href="' + encodeURI(url) + '">'); // jshint ignore:line }); debug('Environment imports loaded'); }
javascript
{ "resource": "" }
q59812
listenForErrors
validation
function listenForErrors() { window.addEventListener('error', function (event) { globalErrors.push(event.error); }); // Also, we treat `console.error` as a test failure. Unless you prefer not. var origConsole = console; var origError = console.error; console.error = function wctShimmedError() { origError.apply(origConsole, arguments); if (get('trackConsoleError')) { throw 'console.error: ' + Array.prototype.join.call(arguments, ' '); } }; }
javascript
{ "resource": "" }
q59813
extendInterfaces
validation
function extendInterfaces(helperName, helperFactory) { interfaceExtensions.push(function () { var Mocha = window.Mocha; // For all Mocha interfaces (probably just TDD and BDD): Object.keys(Mocha.interfaces) .forEach(function (interfaceName) { // This is the original callback that defines the interface (TDD or // BDD): var originalInterface = Mocha.interfaces[interfaceName]; // This is the name of the "teardown" or "afterEach" property for the // current interface: var teardownProperty = interfaceName === 'tdd' ? 'teardown' : 'afterEach'; // The original callback is monkey patched with a new one that appends // to the global context however we want it to: Mocha.interfaces[interfaceName] = function (suite) { // Call back to the original callback so that we get the base // interface: originalInterface.apply(this, arguments); // Register a listener so that we can further extend the base // interface: suite.on('pre-require', function (context, _file, _mocha) { // Capture a bound reference to the teardown function as a // convenience: var teardown = context[teardownProperty].bind(context); // Add our new helper to the testing context. The helper is // generated by a factory method that receives the context, // the teardown function and the interface name and returns // the new method to be added to that context: context[helperName] = helperFactory(context, teardown, interfaceName); }); }; }); }); }
javascript
{ "resource": "" }
q59814
addLocalGulpTasks
validation
function addLocalGulpTasks(subfile, submodule, tasks) { var gulpMod = findModule(function(mod) { return (path.basename(path.dirname(mod.id)) === 'gulp'); }, submodule); var localInst = gulpMod.exports; // copy all the tasks over for (var name in localInst.tasks) { if (localInst.tasks.hasOwnProperty(name)) { var task = localInst.tasks[name]; if (!task.__hubadded) { task.__hubadded = true; addSubtask(subfile, tasks, task.name, task.dep, task.fn); } } } }
javascript
{ "resource": "" }
q59815
loadFiles
validation
function loadFiles(pattern, rootDir) { // assert `pattern` is a valid glob (non-empty string) or array of globs var isString = typeof pattern === 'string'; var isArray = Array.isArray(pattern); if ((!isString && !isArray) || (pattern.length === 0)) { throw new TypeError('A glob pattern or an array of glob patterns is required.'); } // find all the gulpfiles - needs to happen synchronously so we create the tasks before gulp runs var filelist = resolveGlob(pattern, rootDir) .map(function(filename) { return path.relative(process.cwd(), path.join(rootDir, filename)); }); var subfiles = getSubfiles(filelist); // load all the gulpfiles subfiles.forEach(function (subfile) { util.log( 'Loading', util.colors.yellow(subfile.relativePath)); loadSubfile(subfile, tasks); }); }
javascript
{ "resource": "" }
q59816
validation
function (args, callback) { let child = this .runProtractor(args) .on('exit', function (code) { if (child) { child.kill(); } if (callback) { callback(code); } }); }
javascript
{ "resource": "" }
q59817
validation
function (optsOrCallback, cb) { let callback = cb ? cb : optsOrCallback; let options = cb ? optsOrCallback : null; let args = ['update', '--standalone']; let browsers = ['chrome']; if (options) { if (options.browsers && options.browsers.length > 0) { browsers = options.browsers; } browsers.forEach(function (element) { args.push('--' + element); }); if (options.args) { args = args.concat(options.args); } } childProcess .spawn( COMMAND_RELATIVE_PATH + WEB_DRIVER_COMMAND, args, { 'cwd': protractorDirToUse, 'stdio': 'inherit' } ) .once('close', callback); }
javascript
{ "resource": "" }
q59818
validation
function (callback, verbose, updateOptions, startOptions) { log(PLUGIN_NAME + ' - Webdriver standalone will be updated'); return new Promise((resolve) => { this.webDriverUpdate(updateOptions, () => { log(PLUGIN_NAME + ' - Webdriver standalone is updated'); resolve(this.webDriverStandaloneStart(callback, verbose, startOptions)); }); }); }
javascript
{ "resource": "" }
q59819
validation
function () { !fs.existsSync(__dirname + '/target') && fs.mkdirSync(__dirname + '/target'); !fs.existsSync(__dirname + '/target/e2e') && fs.mkdirSync(__dirname + '/target/e2e'); var reporterPath = path.resolve(path.join(__dirname, '/target/e2e')); console.info('The JUnit report will be generated into the following path:', reporterPath); jasmine .getEnv() .addReporter(new reporters.JUnitXmlReporter({ 'savePath': reporterPath, 'consolidate': true, 'consolidateAll': true })); }
javascript
{ "resource": "" }
q59820
USBProcess
validation
function USBProcess(id, daemon) { // The numerical identifer for this process this.id = id; /* active && !closed = Process is running as usual !active && !closed = Process has been sent a signal but not completely closed (resources freed) !active && closed = Process has stopped running and has already been destroyed */ // Status of whether this process is running this.active = true; // Status of whether this process was cleaned up this.closed = false; // Boolean of whether this process has been forcibly killed this.forceKill = false; // Code to be set upon process death this.exitedWithError = false; // Some processes, like `sysupgrade` will not be close-able // because OpenWRT does not have the spidaemon active. // In these cases, just close without trying to send kill signal this.waitForClose = true; // 4 remote process streams this.control = new RemoteWritableStream(this, daemon, protocol.controlWrite, protocol.controlClose); this.stdin = new RemoteWritableStream(this, daemon, protocol.stdinWrite, protocol.stdinClose); this.stdout = new RemoteReadableStream(this, daemon, protocol.stdoutAck); this.stderr = new RemoteReadableStream(this, daemon, protocol.stderrAck); // Once the process is killed this.once('death', (data) => { // This process is no longer running this.active = false; // Close the input streams because the remote proc can't handle data this.control.end(); this.stdin.end(); // Close the process this.closeProcessIfReady(); // Check for a non-zero exit code var exitCode = parseInt(data.arg); debug(`Death for "${this.commandString}" with exit code: ${exitCode}`); if (exitCode !== 0 && !this.forceKill) { this.exitedWithError = true; } }); // Tell the USBDaemon to close the remote process this.close = () => { // Write the close command daemon.write(protocol.closeProcess(this.id)); // Mark this process as closed this.closed = true; }; // Send a signal to the remote process this.kill = (signal) => { // Mark our boolean this.forceKill = true; // If we should wait for close (most processes should) if (this.waitForClose) { // Write the signal command daemon.write(protocol.killProcess(this.id, signal)); } else { // Mark the process as inactive and closed this.active = false; this.closed = true; // Emit the close event setImmediate(() => this.emit('close')); } }; // Checks if this process is ready to be closed // and closes it if it can this.closeProcessIfReady = () => { // If this process hasn't been closed before // and all of the streams are closed if (!this.active && !this.closed && this.stdout.closed && this.stderr.closed) { // Close this process this.close(); } }; // When any of the streams complete, check if the process is ready to close this.stdout.once('end', () => this.closeProcessIfReady()); this.stderr.once('end', () => this.closeProcessIfReady()); // This function is primarily intended for compatibility with the ssh2 stream API this.stdout.signal = (signalToSend) => { switch (signalToSend) { case 'KILL': this.kill(9); break; case 'SIGINT': this.kill(2); break; } }; // Tell the remote daemon that this process was created daemon.write(protocol.newProcess(this.id)); // Tell the remote daemon that we can start receiving outbound data this.stdout.ack(MAX_BUFFER_SIZE); this.stderr.ack(MAX_BUFFER_SIZE); }
javascript
{ "resource": "" }
q59821
RemoteWritableStream
validation
function RemoteWritableStream(process, daemon, writeHeaderFunc, closeHeaderFunc) { // Inherit from Writable Streams stream.Writable.call(this); // The id of the process that this is a stream of this.process = process; // The daemon to write data to this.daemon = daemon; // The amount of credit allocated to the stream (backpressure) this.credit = 0; // An array of backpressure entries this.backPressure = new Array(0); // A flag indicating whether this stream has passed EOF this.closed = false; // The function to generate the header necessary for a write this.writeHeaderFunc = writeHeaderFunc; // The function to generate the header necessary to close the stream this.closeHeaderFunc = closeHeaderFunc; // When the drain event is called, continue draining back pressured packets this.on('drain', () => this._drainBackPressure()); // When the stream has finished this.once('finish', () => { // If the parent process is not already closed if (!this.process.closed) { // Tell the remote daemon that we are done this.daemon.write(closeHeaderFunc(this.process.id)); } // Mark the flag for this stream this.closed = true; }); }
javascript
{ "resource": "" }
q59822
RemoteReadableStream
validation
function RemoteReadableStream(process, daemon, ackHeaderFunc) { // Inherit from Readable Streams stream.Readable.call(this); // The id of the process of this stream this.process = process; // The daemon to write data to this.daemon = daemon; // The function we use to generate acknowledgement packets this.ackHeaderFunc = ackHeaderFunc; // The amount of backpressure credit on this stream this.credit = 0; // A flag indicating whether this stream was closed this.closed = false; // This puts the stream into 'flowing mode' // so that the stream emits ('end') events without 'data' listeners this.resume(); // When we receive data from the daemon, we handle it this.on('incoming', (data) => this.handleIncoming(data)); }
javascript
{ "resource": "" }
q59823
logAndFinish
validation
function logAndFinish(tessel) { // The Tessels in `tessels` that we won't be using MUST // have their connections closed /* istanbul ignore else */ if (tessel) { log.info(`Connected to ${tessel.displayName}.`); controller.closeTesselConnections(tessels.filter(closable => closable !== tessel)) .then(() => resolve(tessel)); } else { log.info('Please specify a Tessel by name [--name <tessel name>]'); controller.closeTesselConnections(tessels) .then(() => reject('Multiple possible Tessel connections found.')); } }
javascript
{ "resource": "" }
q59824
validation
function(path) { var p = path; const ar = p.indexOf('->'); if (ar >= 0) { p = p.substring(ar + 2); } const cu = p.indexOf('/{'); if (cu > 0) { p = p.substring(0, cu); } return p; }
javascript
{ "resource": "" }
q59825
ChartJsProvider
validation
function ChartJsProvider () { var options = {}; var ChartJs = { Chart: Chart, getOptions: function (type) { var typeOptions = type && options[type] || {}; return angular.extend({}, options, typeOptions); } }; /** * Allow to set global options during configuration */ this.setOptions = function (type, customOptions) { // If no type was specified set option for the global object if (! customOptions) { customOptions = type; options = angular.extend(options, customOptions); return; } // Set options for the specific chart options[type] = angular.extend(options[type] || {}, customOptions); }; this.$get = function () { return ChartJs; }; }
javascript
{ "resource": "" }
q59826
validation
function(str, delim) { var res = []; var segs = str.split(delim); var accum = ''; for (let i = 0; i < segs.length; i++) { var seg = segs[i]; if (seg.endsWith('\\')) { accum += seg.substring(0, seg.length - 1) + delim; } else { accum += seg; res.push(accum); accum = ''; } } return res; }
javascript
{ "resource": "" }
q59827
validation
function(input) { var dollarCurly = input.indexOf('${'); if (dollarCurly >= 0) { var endCurly = input.indexOf('}', dollarCurly); if (endCurly >= 0) { return { start: dollarCurly, stop: endCurly, expr: input.substring(dollarCurly + 2, endCurly) }; } } return null; }
javascript
{ "resource": "" }
q59828
validation
function(input, it) { var output = input; var expr; while((expr = this.getExpr(output)) !== null) { var evalsTo = $parse(expr.expr)({it: it}); output = output.substring(0, expr.start) + evalsTo + output.substring(expr.stop + 1); } return output; }
javascript
{ "resource": "" }
q59829
validation
function(selector, context, skipFiltering) { // quick return for #id case var match; if (!context && (match = selector.match(idRegexp))) { var element = require('./view').byId(match[1]); return new Collection(element ? [element] : []); } context = context || require('./attaching').Attaching.instances(); if (context.length === undefined) { context = [context]; } var tokens = Selector.tokenize(selector), expr = tokens[0], extra = tokens[1], result = context, mapper; while (expr.length > 0) { mapper = mappers[expr[0]] ? mappers[expr.shift()] : mappers['']; result = mapper(result); if (expr.length === 0) { break; } result = Selector.reduce(expr.shift(), result); } if (extra) { result = result.concat(Selector.find(extra, context, true)); } return skipFiltering ? result : new Collection(utils.unique(result)); }
javascript
{ "resource": "" }
q59830
uki
validation
function uki(val, context) { if (typeof val === "string") { return selector.find(val, context); } if (val.length === undefined) { val = [val]; } if (val.length > 0 && utils.isFunction(val[0].typeName)) { return new collection.Collection(val); } return builder.build(val); }
javascript
{ "resource": "" }
q59831
domHandler
validation
function domHandler(e) { e = e || env.root.event; var wrapped = wrapDomEvent(e); evt.trigger(this, normalize(wrapped)); }
javascript
{ "resource": "" }
q59832
validation
function(name, value) { if (arguments.length > 1) { for (var i = this.length - 1; i >= 0; i--) { utils.prop(this[i], name, value); } return this; } else { return this[0] ? utils.prop(this[0], name) : ""; } }
javascript
{ "resource": "" }
q59833
validation
function(index) { var range = this._visibleRange(), dm = this.metrics().rowDimensions(index), maxY = dm.top + dm.height, minY = dm.top; if (maxY >= range.to) { this.scrollableParent().scroll(0, maxY - range.to + // hackish overflow to compensate for bottom scroll bar (index === this.data().length - 1 ? 100 : 0) ); } else if (minY < range.from) { this.scrollableParent().scroll(0, minY - range.from); } this._wrappedUpdate(); return this; }
javascript
{ "resource": "" }
q59834
validation
function(type) { return Focusable._domForEvent.call(this, type) || Container.prototype.domForEvent.call(this, type); }
javascript
{ "resource": "" }
q59835
validation
function() { var result = [], indexes = this.selection().indexes(); for (var i=0, l = indexes.length; i < l; i++) { var item = this._data.slice(indexes[i], indexes[i]+1)[0]; if (item) result.push(item); }; return result; }
javascript
{ "resource": "" }
q59836
validation
function(tagName, options, children) { var e = env.doc.createElement(tagName); utils.forEach(options || {}, function(value, name) { if (name == 'style') { e.style.cssText = value; } else if (name == 'html') { e.innerHTML = value; } else if (name == 'className') { e.className = value; } else { e.setAttribute(name, value); } }); children && utils.forEach(children, function(c) { e.appendChild(c); }); return e; }
javascript
{ "resource": "" }
q59837
validation
function(elem, ignoreScroll) { var rect = elem.getBoundingClientRect(); var result = { top: rect.top | 0, left: rect.left | 0, right: rect.right | 0, bottom: rect.bottom | 0, width: (rect.right - rect.left) | 0, height: (rect.bottom - rect.top) | 0 }; if (ignoreScroll) { return result; } var body = env.doc.body; result.top += env.root.pageYOffset || body.scrollTop; result.top += env.root.pageXOffset || body.scrollLeft; return result; }
javascript
{ "resource": "" }
q59838
validation
function(context) { var _children = []; _children.push(React.DOM.i({className: 'icon ' + context.icon})); React.Children.forEach(context.children, function(child) { _children.push(child); }); context.children = _children; }
javascript
{ "resource": "" }
q59839
validation
function(context) { context.icon = 'loading'; context.disabled = true; if (this.props.loadingMessage) { context.children = this.props.loadingMessage; } }
javascript
{ "resource": "" }
q59840
_watchedEventsBindAll
validation
function _watchedEventsBindAll(context) { var watchedEvents = getState('__watchedEvents', context); if (watchedEvents) { var data; for (var name in watchedEvents) { if (watchedEvents.hasOwnProperty(name)) { data = watchedEvents[name]; var target = getTarget(data.target, context); if (target) { target[data.type](data.event, data.callback, data.context); } } } } }
javascript
{ "resource": "" }
q59841
_watchedEventsUnbindAll
validation
function _watchedEventsUnbindAll(keepRegisteredEvents, context) { var watchedEvents = getState('__watchedEvents', context); if (watchedEvents) { var data; for (var name in watchedEvents) { if (watchedEvents.hasOwnProperty(name)) { data = watchedEvents[name]; var target = getTarget(data.target, context); if (target) { target.off(data.event, data.callback, data.context); } } } if (!keepRegisteredEvents) { setState({ __watchedEvents: [] }, context); } } }
javascript
{ "resource": "" }
q59842
validation
function() { var args = Array.prototype.slice.call(arguments), target = this; // allow the first parameter to be the target if (typeof args[0] !== 'string') { target = args[0]; args.splice(0, 1); } return function() { target.trigger.apply(target, args); }; }
javascript
{ "resource": "" }
q59843
S3Receiver
validation
function S3Receiver (s3ClientOpts) { s3ClientOpts = s3ClientOpts || {}; s3ClientOpts = _.extend({}, globalOpts, s3ClientOpts); var wasMaxBytesPerUpstreamQuotaExceeded; var wasMaxBytesPerFileQuotaExceeded; var maxBytesPerUpstream = s3ClientOpts.maxBytes || undefined; var maxBytesPerFile = s3ClientOpts.maxBytesPerFile || undefined; var receiver = Writable({ objectMode: true }); receiver.once('error', (unusedErr)=>{ // console.log('ERROR ON receiver ::', unusedErr); });//œ var bytesWrittenByFd = {}; // console.log('constructed receiver'); receiver._write = (incomingFileStream, encoding, proceed)=>{ // console.log('uploading file w/ skipperFd', incomingFileStream.skipperFd); // Check for `.skipperFd` (or if not present, `.fd`, for backwards compatibility) if (!_.isString(incomingFileStream.skipperFd) || incomingFileStream.skipperFd === '') { if (!_.isString(incomingFileStream.fd) || incomingFileStream.fd === '') { return proceed(new Error('In skipper-s3: Incoming file stream does not have the expected `.skipperFd` or `.fd` properties-- at least not as a valid string. If you are using sails-hook-uploads or skipper directly, this should have been automatically attached! Here is what we got for `.fd` (legacy property): `'+incomingFileStream.fd+'`. And here is what we got for `.skipperFd` (new property): `'+incomingFileStream.skipperFd+'`')); } else { // Backwards compatibility: incomingFileStream.skipperFd = incomingFileStream.fd; } }//fi var incomingFd = incomingFileStream.skipperFd; bytesWrittenByFd[incomingFd] = 0;//« bytes written for this file so far incomingFileStream.once('error', (unusedErr)=>{ // console.log('ERROR ON incoming readable file stream in Skipper S3 adapter (%s) ::', incomingFileStream.filename, unusedErr); });//œ _uploadFile(incomingFd, incomingFileStream, (progressInfo)=>{ bytesWrittenByFd[incomingFd] = progressInfo.written; incomingFileStream.byteCount = progressInfo.written;//« used by Skipper core let totalBytesWrittenForThisUpstream = 0; for (let fd in bytesWrittenByFd) { totalBytesWrittenForThisUpstream += bytesWrittenByFd[fd]; }//∞ // console.log('maxBytesPerUpstream',maxBytesPerUpstream); // console.log('bytesWrittenByFd',bytesWrittenByFd); // console.log('totalBytesWrittenForThisUpstream',totalBytesWrittenForThisUpstream); if (maxBytesPerUpstream && totalBytesWrittenForThisUpstream > maxBytesPerUpstream) { wasMaxBytesPerUpstreamQuotaExceeded = true; return false; } else if (maxBytesPerFile && bytesWrittenByFd[incomingFd] > maxBytesPerFile) { wasMaxBytesPerFileQuotaExceeded = true; return false; } else { if (s3ClientOpts.onProgress) { s3ClientOpts.onProgress(progressInfo); } else { receiver.emit('progress', progressInfo);// « for backwards compatibility } return true; } }, s3ClientOpts, (err)=>{ if (err) { // console.log(('Receiver: Error writing `' + incomingFileStream.filename + '`:: ' + require('util').inspect(err) + ' :: Cancelling upload and cleaning up already-written bytes...').red); if (flaverr.taste({name: 'RequestAbortedError'}, err)) { if (maxBytesPerUpstream && wasMaxBytesPerUpstreamQuotaExceeded) { err = flaverr({code: 'E_EXCEEDS_UPLOAD_LIMIT'}, new Error(`Upload too big! Exceeded quota ("maxBytes": ${maxBytesPerUpstream})`)); } else if (maxBytesPerFile && wasMaxBytesPerFileQuotaExceeded) { err = flaverr({code: 'E_EXCEEDS_FILE_SIZE_LIMIT'}, new Error(`One of the attempted file uploads was too big! Exceeded quota ("maxBytesPerFile": ${maxBytesPerFile})`)); }//fi }//fi receiver.emit('error', err); } else { incomingFileStream.byteCount = bytesWrittenByFd[incomingFd];//« used by Skipper core receiver.emit('writefile', incomingFileStream); return proceed(); } });//_∏_ };//ƒ return receiver; }
javascript
{ "resource": "" }
q59844
normalizeProtocol
validation
function normalizeProtocol(protocol) { if (protocol && protocol.length > 0 && protocol.charAt(protocol.length - 1) !== ':') { return protocol + ':' } return protocol }
javascript
{ "resource": "" }
q59845
buildSvg
validation
function buildSvg(path, { size: { width, height }, VIEW_BOX }, pathOptions) { const svgOptions = { viewBox: `0 0 ${VIEW_BOX} ${VIEW_BOX}`, 'shape-rendering': 'optimizeSpeed', }; const svgOptionsStr = Object.entries(svgOptions).map(([key, value]) => `${key}="${encodeURIComponent(value)}"`) .join(' '); const pathOptionsStr = Object.entries(pathOptions).map(([key, value]) => `${key}="${encodeURIComponent(value)}"`) .join(' '); const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" ${ svgOptionsStr}><path ${pathOptionsStr} d="${path}" /></svg>`; const sprite = Sprite.fromImage(`data:image/svg+xml;charset=utf8,${svg}`); sprite._generatedSvgTexture = true; return sprite; }
javascript
{ "resource": "" }
q59846
requestPromise
validation
function requestPromise(options) { return new Promise((resolve, reject) => { request(options, (error, response) => { if (!error && response.statusCode === 200) { resolve(response); } else if (error) { reject(error); } else { reject(new Error(`Status code is ${response.statusCode}`)); } }); }); }
javascript
{ "resource": "" }
q59847
prettify
validation
function prettify(result) { const collection = {}; Object.keys(result).forEach(key => { const readableKey = aliases[key]; let value = result[key]; if (key === 'published') { value = moment(value).format('LLL'); } if (key === 'propertiesCount') { const array = []; value.forEach(item => { array.push([item.property, item.count]); }); if (array.length !== 0) { value = array.join('\n').replace(/,/g, ': '); } } if (KEY_BYTE.indexOf(key) !== -1) { value = numeral(value).format('0.0b').replace(/^0\.0B$/, '0'); } if (KEY_PERCENT.indexOf(key) !== -1) { value = numeral(value).format('0.0%').replace(/^0\.0%$/, '0'); } if (KEY_NUMBER.indexOf(key) !== -1) { value = numeral(value).format('0.000'); } if (Array.isArray(value)) { const maxLen = 64; value = value.map(val => { if (val.length > maxLen) { return `${val.substring(0, maxLen)}...`; } return val; }); value = value.join('\n') === '' ? 'N/A' : value.join('\n'); } collection[readableKey] = value; }); return collection; }
javascript
{ "resource": "" }
q59848
validation
function(match, value, index, length) { if (!this.currentMacro) return; this.currentMacro.args.push({ start: index + value.length, index: index, length: length, value: value }); }
javascript
{ "resource": "" }
q59849
validation
function(match, strUntilValue, name, value, index) { var self = this; var containsTemplate = false; // Check if attribute is included in the "attributes" option if (!this.isRelevantTagAttr(this.currentTag, name)) { return; } this.matches.push({ start: index + strUntilValue.length, length: value.length, value: value, containsTemplate: isTemplate(value) }); }
javascript
{ "resource": "" }
q59850
getPropType
validation
function getPropType(propValue) { const propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } return propType; }
javascript
{ "resource": "" }
q59851
default_headers
validation
function default_headers(class_context) { class_context = class_context || {}; let headers = {}; if (class_context.token) { headers.Token = class_context.token; } if (!isBrowser) { headers['User-Agent'] = `Tago-Nodelib-${pkg.version}`; } return headers; }
javascript
{ "resource": "" }
q59852
version
validation
function version() { const url = `${config.api_url}/status`; const method = 'GET'; const headers = default_headers(); const options = Object.assign({}, headers, {url, method}); return request(options); }
javascript
{ "resource": "" }
q59853
getTokenByName
validation
function getTokenByName(account, device_id, names = null) { return co(function*() { const tokens = yield account.devices.tokenList(device_id); if (!tokens || !tokens[0]) return; let token; if (names) { names = Array.isArray(names) ? names : [names]; for (const name of names) { token = tokens.find((token) => token.name.indexOf(name) >= 0); if (token) break; } } else { token = tokens[0]; } if (!token) throw `Can't find Token for ${device_id} in ${names}`; return token.token; }).catch((error) => { throw error; }); }
javascript
{ "resource": "" }
q59854
makeNext
validation
function makeNext(browser) { return function next(code) { exitCode += code; currentRun++; if (code === 0) { // Add Browser name here console.log(browser + ' success'); } else { console.log(browser + ' fail'); } if (currentRun == numberOfRuns) { process.exit(exitCode); } }; }
javascript
{ "resource": "" }
q59855
validation
function () { var buildRequest = buildJSONRequest.bind(this); if(arguments.length == 2) { // Empty Body var cbSuccess = callbackWrap.bind(this, arguments[0]); var cbFailure = callbackWrap.bind(this, arguments[1]); cordova.exec(cbSuccess, cbFailure, "BMSRequest", "send", [buildRequest()]); } else if(arguments.length >= 3) { // Non-empty Body if(typeof arguments[0] == "string" || typeof arguments[0] == "object") { var cbSuccess = callbackWrap.bind(this, arguments[1]); var cbFailure = callbackWrap.bind(this, arguments[2]); cordova.exec(cbSuccess, cbFailure, "BMSRequest", "send", [buildRequest(arguments[0])]); } } }
javascript
{ "resource": "" }
q59856
getLongestArray
validation
function getLongestArray (arrays) { var lengths = arrays.map(array => array.length) return Math.max.apply(null, lengths) }
javascript
{ "resource": "" }
q59857
loadScript
validation
function loadScript(src) { return new Promise(resolve => { const script = document.createElement('script'); script.onload = resolve; script.src = src; document.head.appendChild(script); }); }
javascript
{ "resource": "" }
q59858
loadStylesheet
validation
function loadStylesheet(href) { return new Promise(resolve => { const link = document.createElement('link'); link.onload = resolve; link.rel = 'stylesheet' link.type = 'text/css'; link.href = href; document.head.appendChild(link); }); }
javascript
{ "resource": "" }
q59859
saveWarning
validation
function saveWarning(req, res) { var text = req.body.action === 'save' ? req.body.warning_text : ''; dreadnot.setWarning(req.remoteUser, text, function(err) { if (err) { res.respond(err); } else { getWarning(req, res); } }); }
javascript
{ "resource": "" }
q59860
handleError
validation
function handleError(err, req, res) { switch (err.name) { case 'NotFoundError': res.send(err, 404); break; default: res.send(err, 500); } }
javascript
{ "resource": "" }
q59861
responseCallback
validation
function responseCallback(req, res) { return function(err, data) { if (err) { handleError(err, req, res); } else { res.send(data); } }; }
javascript
{ "resource": "" }
q59862
CloudMonitoring
validation
function CloudMonitoring(options, log) { this._options = options; this.log = log || logmagic.local('cloudmonitoring'); this.defaultSuppressionDuration = options.defaultSuppressionDuration || DEFAULT_SUPPRESSION_DURATION; this.monitoringApiUri = options.monitoringApiUri || DEFAULT_MONITORING_API_URI; this.keystoneClient = new KeystoneClient(options.authUri || DEFAULT_AUTH_URI, { username: options.username, apiKey: options.apiKey } ); }
javascript
{ "resource": "" }
q59863
Nagios
validation
function Nagios(options, log) { var parsed = url.parse(options.url); // Inject auth into the URL delete parsed.host; parsed['auth'] = sprintf('%s:%s', options.username, options.password); this._url = url.format(parsed); this._options = options; this.log = log || logmagic.local('nagios'); }
javascript
{ "resource": "" }
q59864
NewRelic
validation
function NewRelic(license_key, options, log) { this.url = "https://api.newrelic.com"; this._options = options; this.license_key = license_key; if (!this._options.hasOwnProperty('user')) { this._options['user'] = 'dreadnot'; } this.log = log || logmagic.local('sensu'); }
javascript
{ "resource": "" }
q59865
PagerDuty
validation
function PagerDuty(options, log) { var parsed = url.parse(options.url); delete parsed.host; this.url = url.format(parsed); this.users = options.users; this.schedules = options.schedules; this.log = log || logmagic.local('pagerduty'); this.pagerduty_auth = sprintf('Token token=%s', options.password); }
javascript
{ "resource": "" }
q59866
Stack
validation
function Stack(name, dreadnot, config) { var self = this, logName = sprintf('deploy.stack.%s', name), sinkName = sprintf('stack.%s', name), moduleName; if (config.stacks[name].hasOwnProperty('module_name')) { moduleName = config.stacks[name].module_name; } else { moduleName = name; } this.name = name; this.dreadnot = dreadnot; this.module = require(path.join(path.resolve(dreadnot.stackdir), moduleName)); this.config = config; this.stackConfig = config.stacks[name]; this.log = logmagic.local(logName); this.logRoot = path.join(config.data_root, 'logs', name); this.newestDeployments = {}; this.repo = this.stackConfig.repo || name; this.current = null; this._cache = {}; this._waiting = {}; logmagic.registerSink(sinkName, function(moduleName, lvl, msg, obj) { var both = moduleName.split('.').slice(-2), logPath = ['regions', both[0], 'deployments', both[1], 'log'].join('.'); // Fix serialization of Error objects if (obj.err && obj.err instanceof Error) { obj.err = { name: obj.err.name, message: obj.err.message, stack: obj.err.stack }; } self.emit(logPath, { lvl: lvl, msg: msg, obj: obj }); }); logmagic.route(sprintf('%s.*', logName), logmagic.INFO, sinkName); }
javascript
{ "resource": "" }
q59867
render
validation
function render(req, res, template, data, options) { res.render(template, misc.merge({ user: req.remoteUser, title: dreadnot.config.name, env: dreadnot.config.env, url: req.originalUrl, emsg: res.emsg, wmsg: dreadnot.warning, helpers: viewHelpers, data: data }, options || {})); }
javascript
{ "resource": "" }
q59868
handleError
validation
function handleError(req, res, err) { switch (err.name) { case 'NotFoundError': render(req, res, 'error', err, {status: 404}); break; default: render(req, res, 'error', err, {status: 500}); } }
javascript
{ "resource": "" }
q59869
renderCallback
validation
function renderCallback(req, res, template) { return function(err, data) { if (err) { handleError(req, res, err); } else { render(req, res, template, data); } }; }
javascript
{ "resource": "" }
q59870
getLogin
validation
function getLogin(req, res) { var next = req.param('next'); render(req, res, 'login.jade', {next: next}); }
javascript
{ "resource": "" }
q59871
attemptLogin
validation
function attemptLogin(req, res) { var username = req.param('username'), password = req.param('password'), next = req.param('next', '/'); authdb.validate(username, password, function(err, valid) { if (valid) { req.session.authed = true; req.session.username = username; res.redirect(next); } else { res.emsg = 'Invalid Username or Password'; render(req, res, 'login.jade', {next: next}); } }); }
javascript
{ "resource": "" }
q59872
getStacks
validation
function getStacks(req, res) { var data = {}; async.auto({ stacks: function(callback) { dreadnot.getStackSummaries(function(err, stacks) { data.stacks = stacks; callback(err); }); }, regions: ['stacks', function(callback) { async.forEach(data.stacks, function(stack, callback) { dreadnot.getRegionSummaries(stack.name, function(err, regions) { if (err) { callback(err); return; } stack.regions = regions; async.forEach(stack.regions, function(region, callback) { // TODO: Should this go in dreadnot.js or stack.js maybe? if (region.latest_deployment === '0') { region.latest_deployment = null; callback(); return; } dreadnot.getDeploymentSummary(stack.name, region.name, region.latest_deployment, function(err, deployment) { region.latest_deployment = deployment; callback(err); }); }, callback); }); }, callback); }], }, function(err) { renderCallback(req, res, 'stacks.jade')(err, data); }); }
javascript
{ "resource": "" }
q59873
getDeployments
validation
function getDeployments(req, res) { async.parallel({ stack: dreadnot.getStackSummary.bind(dreadnot, req.params.stack), region: dreadnot.getRegionSummary.bind(dreadnot, req.params.stack, req.params.region), deployments: dreadnot.getDeploymentSummaries.bind(dreadnot, req.params.stack, req.params.region) }, renderCallback(req, res, 'deployments.jade')); }
javascript
{ "resource": "" }
q59874
getDeployment
validation
function getDeployment(req, res) { async.parallel({ stack: dreadnot.getStackSummary.bind(dreadnot, req.params.stack), region: dreadnot.getRegionSummary.bind(dreadnot, req.params.stack, req.params.region), deployment: dreadnot.getDeploymentSummary.bind(dreadnot, req.params.stack, req.params.region, req.params.deployment) }, renderCallback(req, res, 'deployment.jade')); }
javascript
{ "resource": "" }
q59875
Jenkins
validation
function Jenkins(options, log) { var parsed = url.parse(options.url); if (options.username && options.password) { parsed['auth'] = util.format('%s:%s', options.username, options.password); } this._url = url.format(parsed); this._options = options; this.log = log || logmagic.local('jenkins'); }
javascript
{ "resource": "" }
q59876
validation
function (query, queryOptions, callback) { if (!queryOptions) { callback = query; query = {}; queryOptions = {}; } else if (!callback) { callback = queryOptions; queryOptions = {}; } this.find(query, queryOptions, function (err, items) { if (err) { return callback(err); } callback(null, items[0]); }); }
javascript
{ "resource": "" }
q59877
validation
function (obj) { var res = _.assign(_.assign({}, this), obj); for (var f in this) { if (_.isFunction(this[f])) { res[f] = this[f]; } } if (_.isFunction(res.checkConnection)) { res.checkConnection(); } return res; }
javascript
{ "resource": "" }
q59878
validation
function(name, func) { wrapper.prototype[name] = function() { var args = slice.call(arguments); unshift.call(args, this._wrapped); return result(func.apply(_, args), this._chain); }; }
javascript
{ "resource": "" }
q59879
validation
function(fn, context) { return fn.call(context || global, _.bind(r, this), _, this); }
javascript
{ "resource": "" }
q59880
validation
function(abbr, syntax, profile, contextNode) { if (!abbr) return ''; syntax = syntax || defaultSyntax; // profile = profile || defaultProfile; var filters = r('filters'); var parser = r('abbreviationParser'); profile = r('profile').get(profile, syntax); r('tabStops').resetTabstopIndex(); var data = filters.extractFromAbbreviation(abbr); var outputTree = parser.parse(data[0], { syntax: syntax, contextNode: contextNode }); var filtersList = filters.composeList(syntax, profile, data[1]); filters.apply(outputTree, filtersList, profile); return outputTree.toString(); }
javascript
{ "resource": "" }
q59881
validation
function() { if (global.console && global.console.log) global.console.log.apply(global.console, arguments); }
javascript
{ "resource": "" }
q59882
validation
function(child, position) { child = child || new AbbreviationNode; child.parent = this; if (_.isUndefined(position)) { this.children.push(child); } else { this.children.splice(position, 0, child); } return child; }
javascript
{ "resource": "" }
q59883
validation
function() { var node = new AbbreviationNode(); var attrs = ['abbreviation', 'counter', '_name', '_text', 'repeatCount', 'hasImplicitRepeat', 'start', 'end', 'content', 'padding']; _.each(attrs, function(a) { node[a] = this[a]; }, this); // clone attributes node._attributes = _.map(this._attributes, function(attr) { return _.clone(attr); }); node._data = _.clone(this._data); // clone children node.children = _.map(this.children, function(child) { child = child.clone(); child.parent = node; return child; }); return node; }
javascript
{ "resource": "" }
q59884
validation
function() { var attrs = []; var res = this.matchedResource(); if (require('elements').is(res, 'element') && _.isArray(res.attributes)) { attrs = attrs.concat(res.attributes); } return optimizeAttributes(attrs.concat(this._attributes)); }
javascript
{ "resource": "" }
q59885
validation
function(name, value) { if (arguments.length == 2) { // modifying attribute var ix = _.indexOf(_.pluck(this._attributes, 'name'), name.toLowerCase()); if (~ix) { this._attributes[ix].value = value; } else { this._attributes.push({ name: name, value: value }); } } return (_.find(this.attributeList(), function(attr) { return attr.name == name; }) || {}).value; }
javascript
{ "resource": "" }
q59886
validation
function() { var utils = require('utils'); var start = this.start; var end = this.end; var content = this.content; // apply output processors var node = this; _.each(outputProcessors, function(fn) { start = fn(start, node, 'start'); content = fn(content, node, 'content'); end = fn(end, node, 'end'); }); var innerContent = _.map(this.children, function(child) { return child.toString(); }).join(''); content = require('abbreviationUtils').insertChildContent(content, innerContent, { keepVariable: false }); return start + utils.padString(content, this.padding) + end; }
javascript
{ "resource": "" }
q59887
validation
function() { if (!this.children.length) return null; var deepestChild = this; while (deepestChild.children.length) { deepestChild = _.last(deepestChild.children); } return deepestChild; }
javascript
{ "resource": "" }
q59888
parseAbbreviation
validation
function parseAbbreviation(abbr) { abbr = require('utils').trim(abbr); var root = new AbbreviationNode; var context = root.addChild(), ch; /** @type StringStream */ var stream = require('stringStream').create(abbr); var loopProtector = 1000, multiplier; while (!stream.eol() && --loopProtector > 0) { ch = stream.peek(); switch (ch) { case '(': // abbreviation group stream.start = stream.pos; if (stream.skipToPair('(', ')')) { var inner = parseAbbreviation(stripped(stream.current())); if (multiplier = stream.match(/^\*(\d+)?/, true)) { context._setRepeat(multiplier[1]); } _.each(inner.children, function(child) { context.addChild(child); }); } else { throw 'Invalid abbreviation: mo matching ")" found for character at ' + stream.pos; } break; case '>': // child operator context = context.addChild(); stream.next(); break; case '+': // sibling operator context = context.parent.addChild(); stream.next(); break; case '^': // climb up operator var parent = context.parent || context; context = (parent.parent || parent).addChild(); stream.next(); break; default: // consume abbreviation stream.start = stream.pos; stream.eatWhile(function(c) { if (c == '[' || c == '{') { if (stream.skipToPair(c, pairs[c])) { stream.backUp(1); return true; } throw 'Invalid abbreviation: mo matching "' + pairs[c] + '" found for character at ' + stream.pos; } if (c == '+') { // let's see if this is an expando marker stream.next(); var isMarker = stream.eol() || ~'+>^*'.indexOf(stream.peek()); stream.backUp(1); return isMarker; } return c != '(' && isAllowedChar(c); }); context.setAbbreviation(stream.current()); stream.start = stream.pos; } } if (loopProtector < 1) throw 'Endless loop detected'; return root; }
javascript
{ "resource": "" }
q59889
locateOutputPlaceholder
validation
function locateOutputPlaceholder(text) { var range = require('range'); var result = []; /** @type StringStream */ var stream = require('stringStream').create(text); while (!stream.eol()) { if (stream.peek() == '\\') { stream.next(); } else { stream.start = stream.pos; if (stream.match(outputPlaceholder, true)) { result.push(range.create(stream.start, outputPlaceholder)); continue; } } stream.next(); } return result; }
javascript
{ "resource": "" }
q59890
insertPastedContent
validation
function insertPastedContent(node, content, overwrite) { var nodesWithPlaceholders = node.findAll(function(item) { return hasOutputPlaceholder(item); }); if (hasOutputPlaceholder(node)) nodesWithPlaceholders.unshift(node); if (nodesWithPlaceholders.length) { _.each(nodesWithPlaceholders, function(item) { item.content = replaceOutputPlaceholders(item.content, content); _.each(item._attributes, function(attr) { attr.value = replaceOutputPlaceholders(attr.value, content); }); }); } else { // on output placeholders in subtree, insert content in the deepest // child node var deepest = node.deepestChild() || node; if (overwrite) { deepest.content = content; } else { deepest.content = require('abbreviationUtils').insertChildContent(deepest.content, content); } } }
javascript
{ "resource": "" }
q59891
tokener
validation
function tokener(value, type, conf) { var w = walker, c = conf || {}; tokens.push({ charstart: isset(c['char']) ? c['char'] : w.chnum, charend: isset(c.charend) ? c.charend : w.chnum, linestart: isset(c.line) ? c.line : w.linenum, lineend: isset(c.lineend) ? c.lineend : w.linenum, value: value, type: type || value }); }
javascript
{ "resource": "" }
q59892
tokenize
validation
function tokenize() { var ch = walker.ch; if (ch === " " || ch === "\t") { return white(); } if (ch === '/') { return comment(); } if (ch === '"' || ch === "'") { return str(); } if (ch === '(') { return brace(); } if (ch === '-' || ch === '.' || isDigit(ch)) { // tricky - char: minus (-1px) or dash (-moz-stuff) return num(); } if (isNameChar(ch)) { return identifier(); } if (isOp(ch)) { return op(); } if (ch === "\n") { tokener("line"); walker.nextChar(); return; } throw error("Unrecognized character"); }
javascript
{ "resource": "" }
q59893
getNewline
validation
function getNewline(content, pos) { return content.charAt(pos) == '\r' && content.charAt(pos + 1) == '\n' ? '\r\n' : content.charAt(pos); }
javascript
{ "resource": "" }
q59894
validation
function(source) { // transform tokens var pos = 0; return _.map(this.lex(source), function(token) { if (token.type == 'line') { token.value = getNewline(source, pos); } return { type: token.type, start: pos, end: (pos += token.value.length) }; }); }
javascript
{ "resource": "" }
q59895
validation
function() { var res = require('resources'); if (!res) { return '\n'; } var nl = res.getVariable('newline'); return _.isString(nl) ? nl : '\n'; }
javascript
{ "resource": "" }
q59896
validation
function(strings) { var lengths = _.map(strings, function(s) { return _.isString(s) ? s.length : +s; }); var max = _.max(lengths); return _.map(lengths, function(l) { var pad = max - l; return pad ? this.repeatString(' ', pad) : ''; }, this); }
javascript
{ "resource": "" }
q59897
validation
function(text, pad) { var padStr = (_.isNumber(pad)) ? this.repeatString(require('resources').getVariable('indentation') || '\t', pad) : pad; var result = []; var lines = this.splitByLines(text); var nl = this.getNewline(); result.push(lines[0]); for (var j = 1; j < lines.length; j++) result.push(nl + padStr + lines[j]); return result.join(''); }
javascript
{ "resource": "" }
q59898
validation
function(text, pad) { var lines = this.splitByLines(text); for (var i = 0; i < lines.length; i++) { if (lines[i].search(pad) == 0) lines[i] = lines[i].substr(pad.length); } return lines.join(this.getNewline()); }
javascript
{ "resource": "" }
q59899
validation
function(text, start, end) { var range = require('range').create(start, end); var reSpace = /[\s\n\r\u00a0]/; // narrow down selection until first non-space character while (range.start < range.end) { if (!reSpace.test(text.charAt(range.start))) break; range.start++; } while (range.end > range.start) { range.end--; if (!reSpace.test(text.charAt(range.end))) { range.end++; break; } } return range; }
javascript
{ "resource": "" }