_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q13400
train
function(objArr) { var ret = []; for(var i = 0; i < objArr.length; i ++) { ret.push(_recipientInfoFromAsn1(objArr[i])); } return ret; }
javascript
{ "resource": "" }
q13401
train
function(recipientsArr) { var ret = []; for(var i = 0; i < recipientsArr.length; i ++) { ret.push(_recipientInfoToAsn1(recipientsArr[i])); } return ret; }
javascript
{ "resource": "" }
q13402
train
function(task, recurse) { // get time since last context swap (ms), if enough time has passed set // swap to true to indicate that doNext was performed asynchronously // also, if recurse is too high do asynchronously var swap = (recurse > sMaxRecursions) || (+new Date() - task.swapTime) > sTimeSlice; var doNext = function(recurse) { recurse++; if(task.state === RUNNING) { if(swap) { // update swap time task.swapTime = +new Date(); } if(task.subtasks.length > 0) { // run next subtask var subtask = task.subtasks.shift(); subtask.error = task.error; subtask.swapTime = task.swapTime; subtask.userData = task.userData; subtask.run(subtask); if(!subtask.error) { runNext(subtask, recurse); } } else { finish(task); if(!task.error) { // chain back up and run parent if(task.parent !== null) { // propagate task info task.parent.error = task.error; task.parent.swapTime = task.swapTime; task.parent.userData = task.userData; // no subtasks left, call run next subtask on parent runNext(task.parent, recurse); } } } } }; if(swap) { // we're swapping, so run asynchronously setTimeout(doNext, 0); } else { // not swapping, so run synchronously doNext(recurse); } }
javascript
{ "resource": "" }
q13403
train
function(task, suppressCallbacks) { // subtask is now done task.state = DONE; delete sTasks[task.id]; if(sVL >= 1) { forge.log.verbose(cat, '[%s][%s] finish', task.id, task.name, task); } // only do queue processing for root tasks if(task.parent === null) { // report error if queue is missing if(!(task.type in sTaskQueues)) { forge.log.error(cat, '[%s][%s] task queue missing [%s]', task.id, task.name, task.type); } else if(sTaskQueues[task.type].length === 0) { // report error if queue is empty forge.log.error(cat, '[%s][%s] task queue empty [%s]', task.id, task.name, task.type); } else if(sTaskQueues[task.type][0] !== task) { // report error if this task isn't the first in the queue forge.log.error(cat, '[%s][%s] task not first in queue [%s]', task.id, task.name, task.type); } else { // remove ourselves from the queue sTaskQueues[task.type].shift(); // clean up queue if it is empty if(sTaskQueues[task.type].length === 0) { if(sVL >= 1) { forge.log.verbose(cat, '[%s][%s] delete queue [%s]', task.id, task.name, task.type); } /* Note: Only a task can delete a queue of its own type. This is used as a way to synchronize tasks. If a queue for a certain task type exists, then a task of that type is running. */ delete sTaskQueues[task.type]; } else { // dequeue the next task and start it if(sVL >= 1) { forge.log.verbose(cat, '[%s][%s] queue start next [%s] remain:%s', task.id, task.name, task.type, sTaskQueues[task.type].length); } sTaskQueues[task.type][0].start(); } } if(!suppressCallbacks) { // call final callback if one exists if(task.error && task.failureCallback) { task.failureCallback(task); } else if(!task.error && task.successCallback) { task.successCallback(task); } } } }
javascript
{ "resource": "" }
q13404
train
function() { var cert; try { cert = this.keychain.getCertPem(); } catch (e) { throw new CError({ body: { code: 'ImATeapot', message: 'missing certificate', cause: e } }).log('body'); } if (!cert) { throw new CError('missing certificate').log(); } if (!this.getDate()) { throw new CError('missing date').log(); } if (!this.getSid()) { throw new CError('missing session identifier').log(); } if (!this.getId()) { throw new CError('missing id').log(); } if (!this.getApp()) { throw new CError('missing app').log(); } var tmp = this.getDate() + '::' + cert +'::' + this.getSid() + '::' + this.getId() + '::' + this.getApp() + '::'; if (this._reply) { // NOTE: username is not mandatory in non browser environment // NOTE: SECRET_SERVER is present only when the client is used inside the authorify module var username = this.getUsername(); if (!username) { username = 'anonymous'; } var password = this.getPassword(); if (!password) { password = forge.util.encode64(forge.random.getBytesSync(16)); } tmp += username + '::' + password + '::' + SECRET_SERVER; } else { tmp += SECRET_CLIENT; } var hmac = forge.hmac.create(); hmac.start('sha256', SECRET); hmac.update(tmp); return hmac.digest().toHex(); }
javascript
{ "resource": "" }
q13405
train
function(data) { if (!(data && 'function' === typeof data.isBase64 && data.isBase64())) { throw new CError('wrong data format to decrypt').log(); } return JSON.parse(this.encoder.decryptAes(data, this.getSecret())); }
javascript
{ "resource": "" }
q13406
getConfigOptions
train
function getConfigOptions(opts) { opts = formatOptions(opts); _.forEach(config, function(value, key) { opts[key] = opts[key] || value; }); opts.headers = opts.headers || {}; return opts; }
javascript
{ "resource": "" }
q13407
fixRequestOptions
train
function fixRequestOptions(method, path, transport, plain, callback) { var opts = { method: method, path: path }; if (_.isFunction(transport)) { opts.callback = transport; opts.plain = false; opts.transport = 'http'; } else { if (_.isString(transport)) { opts.transport = transport; } else if (_.isBoolean(transport)) { opts.plain = transport; } if (_.isFunction(plain)) { opts.callback = plain; opts.plain = opts.plain || false; } else if (_.isBoolean(plain)) { opts.callback = callback; opts.plain = plain; } } return opts; }
javascript
{ "resource": "" }
q13408
logResponse
train
function logResponse(err, res) { if (err || (res && !res.ok)) { if (err) { log.warn('%s on response -> read plaintext body due an error (%s)', app.name, err.message); } else { log.warn('%s on response -> read plaintext body due an error (%s)', app.name, res.error); } } else if (res && !_.isEmpty(res.body)) { if (res.body[my.config.encryptedBodyName]) { log.info('%s on response -> read encrypted body', app.name); } else { log.info('%s on response -> read plaintext body', app.name); } } }
javascript
{ "resource": "" }
q13409
getModuleName
train
function getModuleName(module) { var script = module.replace(/[^a-zA-Z0-9]/g, '.'), parts = script.split('.'), name = parts.shift(); if (parts.length) { for (var p in parts) { name += parts[p].charAt(0).toUpperCase() + parts[p].substr(1, parts[p].length); } } return name; }
javascript
{ "resource": "" }
q13410
train
function(opts) { opts = opts || {}; var path = opts.path || this.path, callback = opts.callback, method = opts.method || this.method, ws = getWebsocketPlugin(), transports = app.config.transports, self = this, i = 0, error, response; if (ws) { if (transports && transports.length > 0) { async.whilst( function () { return (i < transports.length); }, function (done) { self.doConnect(transports[i], method, path, function (err, res) { error = err; response = res; if (!err && res) { i = transports.length; } else { i++; if (i < transports.length) { delete self.request; } } done(); }); }, function (err) { callback(err || error, response); } ); } else { error = 'no transport available'; log.error('%s %s', app.name, error); callback(error); } } else { this.doConnect('http', method, path, callback); } return this; }
javascript
{ "resource": "" }
q13411
train
function(value) { if (value) { if (config.encryptQuery) { this._pendingQuery = this._pendingQuery || []; this._pendingQuery.push(value); } else { this.request.query(value); } } return this; }
javascript
{ "resource": "" }
q13412
train
function(callback) { if (res.session && res.session.cert) { if (res.parsedHeader.payload.mode === 'handshake') { if (my.config.crypter.verifyCertificate(res.session.cert)) { callback(null); } else { callback('unknown certificate'); } } else { callback(null); } } else { callback('wrong session'); } }
javascript
{ "resource": "" }
q13413
train
function(callback) { if (!res.parsedHeader.signature) { callback('unsigned'); } else { var signVerifier = new Crypter({ cert: res.session.cert }); if (signVerifier.verifySignature(JSON.stringify(res.parsedHeader.content), res.parsedHeader.signature)) { callback(null); } else { callback('forgery'); } } }
javascript
{ "resource": "" }
q13414
train
function(callback) { if (parseInt(config.clockSkew, 10) > 0) { var now = new Date().toSerialNumber(), sent = res.parsedHeader.content.date; if ((now - sent) > config.clockSkew * 1000) { callback('date too old'); } else { callback(null); } } else { callback(null); } }
javascript
{ "resource": "" }
q13415
train
function(secret) { var keyIv; if (!secret) { throw new CError('missing secret').log(); } // secret is a Base64 string if(secret.isBase64()){ try { keyIv = forge.util.decode64(secret); } catch (e) { throw new CError('secret not valid').log(); } } else { keyIv = secret; } return keyIv; }
javascript
{ "resource": "" }
q13416
train
function (data, scheme) { // scheme = RSA-OAEP, RSAES-PKCS1-V1_5 scheme = scheme || SCHEME; return forge.util.encode64(this._cert.publicKey.encrypt(data, scheme)); }
javascript
{ "resource": "" }
q13417
train
function (data, scheme) { scheme = scheme || SCHEME; return this._key.decrypt(forge.util.decode64(data), scheme); }
javascript
{ "resource": "" }
q13418
train
function (data, secret, encoder, mode) { // mode = CBC, CFB, OFB, CTR mode = mode || MODE; var keyIv = this.getBytesFromSecret(secret); var cipher = forge.aes.createEncryptionCipher(keyIv, mode); cipher.start(keyIv); cipher.update(forge.util.createBuffer(data)); cipher.finish(); if (encoder === 'url') { return base64url(cipher.output.data); } return forge.util.encode64(cipher.output.data); }
javascript
{ "resource": "" }
q13419
train
function (data, secret, encoder, mode) { // mode = CBC, CFB, OFB, CTR mode = mode || MODE; var keyIv = this.getBytesFromSecret(secret); var cipher = forge.aes.createDecryptionCipher(keyIv, mode); cipher.start(keyIv); var decoded; if (encoder === 'url') { decoded = base64url.decode(data); } else { decoded = forge.util.decode64(data); } cipher.update(forge.util.createBuffer(decoded)); cipher.finish(); return cipher.output.data; }
javascript
{ "resource": "" }
q13420
train
function (pem) { var certificate = forge.pki.certificateFromPem(pem); var issuerCert = caStore.getIssuer(certificate); if (issuerCert) { try { return issuerCert.verify(certificate); } catch (e) { return false; } } return false; }
javascript
{ "resource": "" }
q13421
train
function () { var self = this; this.collectionRegistry = {}; // emit molecuel elements pre init event molecuel.emit('mlcl::collections::init:pre', self); /** * Schema directory config */ if (molecuel.config.collections && molecuel.config.collections.collectionDir) { this.collectionDir = molecuel.config.collections.collectionDir; } /** * Execute after successful elasticsearch connection */ molecuel.on('mlcl::elements::init:post', function (elements) { // add the access to all the db's and searchfunctionality self.elements = elements; self.elastic = elements.elastic; self.database = elements.database; self.registerCollections(); molecuel.emit('mlcl::collections::init:post', self); }); //register block handler molecuel.on('mlcl::blocks::init:modules', function(blocks) { blocks.registerTypeHandler('collection', self.block); }); return this; }
javascript
{ "resource": "" }
q13422
EzMap
train
function EzMap(arr) { this._keys = [] this._values = [] if (isArray(arr) && arr.length) this._initial(arr) }
javascript
{ "resource": "" }
q13423
getOpenTabInfo
train
function getOpenTabInfo(tabItems, openTabs) { const chromeOpenTabItems = Immutable.Seq(openTabs.map(makeOpenTabItem)); // console.log("getOpenTabInfo: openTabs: ", openTabs); // console.log("getOpenTabInfo: chromeOpenTabItems: " + JSON.stringify(chromeOpenTabItems,null,4)); const openUrlMap = Immutable.Map(chromeOpenTabItems.groupBy((ti) => ti.url)); // console.log("getOpenTabInfo: openUrlMap: ", openUrlMap.toJS()); // Now we need to do two things: // 1. augment chromeOpenTabItems with bookmark Ids / saved state (if it exists) // 2. figure out which savedTabItems are not in openTabs const savedItems = tabItems.filter((ti) => ti.saved); // Restore the saved items to their base state (no open tab info), since we // only want to pick up open tab info from what was passed in in openTabs const baseSavedItems = savedItems.map(resetSavedItem); // The entries in savedUrlMap *should* be singletons, but we'll use groupBy to // get a type-compatible Seq so that we can merge with openUrlMap using // mergeWith: const savedUrlMap = Immutable.Map(baseSavedItems.groupBy((ti) => ti.url)); // console.log("getOpenTabInfo: savedUrlMap : " + savedUrlMap.toJS()); function mergeTabItems(openItems, mergeSavedItems) { const savedItem = mergeSavedItems.get(0); return openItems.map((openItem) => openItem.set('saved', true) .set('savedBookmarkId', savedItem.savedBookmarkId) .set('savedBookmarkIndex', savedItem.savedBookmarkIndex) .set('savedTitle', savedItem.savedTitle)); } const mergedMap = openUrlMap.mergeWith(mergeTabItems, savedUrlMap); // console.log("mergedMap: ", mergedMap.toJS()); // console.log("getOpenTabInfo: mergedMap :" + JSON.stringify(mergedMap,null,4)); // partition mergedMap into open and closed tabItems: const partitionedMap = mergedMap.toIndexedSeq().flatten(true).groupBy((ti) => ti.open); // console.log("partitionedMap: ", partitionedMap.toJS()); return partitionedMap; }
javascript
{ "resource": "" }
q13424
hyperBind
train
function hyperBind(store) { this.compile = function(input) { var path = input.split('.'); return { path: input, target: path[path.length - 1] }; }; this.state = function(config, state) { var res = store.get(config.path, state); if (!res.completed) return false; return state.set(config.target, res.value); }; this.children = function(config, state, children) { var value = state.get(config.target); if (typeof value === 'undefined') return ''; return value; }; }
javascript
{ "resource": "" }
q13425
getFields
train
function getFields(tweet) { return _.flatten(tweetLikeObjectsToCheck.map(function(tweetLikeName) { var tweetLike; if (tweetLikeName === null) { tweetLike = tweet; } else { tweetLike = _.get(tweet, tweetLikeName); } if (!tweetLike) return []; return getFieldsFromTweetLike(tweetLike); })); }
javascript
{ "resource": "" }
q13426
getFieldsFromTweetLike
train
function getFieldsFromTweetLike(tweetLike) { var fields = fieldsToCheck.map(function(fieldName) { return _.get(tweetLike, fieldName); }); arrayFieldsToCheck.forEach(function(fieldDescription) { var arr = _.get(tweetLike, fieldDescription.arrayAt); if (_.isArray(arr)) { arr.forEach(function(element) { fields.push(_.get(element, fieldDescription.inEach)); }); } }); return fields.filter(function(field) { return typeof field === 'string' && field.trim().length !== 0; }).map(function(field) { return field.toLowerCase(); }); }
javascript
{ "resource": "" }
q13427
Service
train
function Service(config, callback) { ld.bindAll(this); var eventEmitter = new EventEmitter2({ wildcard: true, delimiter: '.'}); this.cfg = {}; this.network = { local: eventEmitter }; ld.defaults(this.cfg, config, { // id // required, unique service id [^a-zA-Z0-9_] // version // required requestTimeout: 3000, // timeout in ms before device answer port: 6379, // network or proxy port host: 'paukan', // network or proxy host throttling: 200, // do not emit same event fired durning this period (on multiple psubscribe) connections: ['direct', 'remote', 'server'], // try next connection type if previous failed // - direct: connect to redis queue on specified host and port // - remote: connect to remote websocket proxy service on specified host and port // - server: create websocket server and wait incoming connection on specified port }); this.id = this.cfg.id; this.hostname = require('os').hostname(); this.version = this.cfg.version; this.description = this.cfg.description; this.homepage = this.cfg.homepage; this.author = this.cfg.author; this.devices = {}; // list of devices in this service this.log = this.createLogger(this.cfg.logger); if(callback) { this.init(callback); } }
javascript
{ "resource": "" }
q13428
exitHandler
train
function exitHandler(options, err) { if (err) { log.error(err.stack); } if (options.exit) { process.exit(); } if(network) { network.emit('state.'+id+'.service.offline'); } }
javascript
{ "resource": "" }
q13429
applyStyle
train
function applyStyle(str, property, value) { var styleDefinition = CONSOLE_STYLES[property][value]; //No style defined return non modified string if (styleDefinition === null) { return str; } return ESCAPE + '[' + styleDefinition[0] + 'm' + str + ESCAPE + '[' + styleDefinition[1] + 'm'; }
javascript
{ "resource": "" }
q13430
applyStyles
train
function applyStyles(str, style) { //Check if not style if (! style) { return str; } //Check shortcut if string is empty //str = '' + str; if (!str || str.length === 0) { return str; } var output, i, rule, textdecoration; //style = style || {}; output = str; //1. font-weight rule = style['font-weight']; if (rule) { output = applyStyle(output, 'font-weight', rule); } //2. font-style rule = style['font-style']; if (rule) { output = applyStyle(output, 'font-style', rule); } //3. color rule = style.color; if (style.color) { output = applyStyle(output, 'color', rule); } //4. background color rule = style['background-color']; if (rule) { output = applyStyle(output, 'background-color', rule); } //Normalize as array rule = style['text-decoration']; if (isArray(rule)) { //do all decoration i = rule.length - 1; while (i >= 0) { i -= 1; output = applyStyle(output, 'text-decoration', rule[i]); } } else { output = applyStyle(output, 'text-decoration', style['text-decoration']); } }
javascript
{ "resource": "" }
q13431
recursiveFindFile
train
function recursiveFindFile(aDirectory, arrayOfFileNames) { if (debug) debugLog(`recursiveFindFile dir: ${aDirectory}, filenames: ${util.inspect(arrayOfFileNames)}`); // var directory = process.cwd(); let directory = aDirectory; const tmp = directoryHasFile(directory, arrayOfFileNames); if ((tmp === undefined) && directory !== '/') { directory = path.dirname(directory); const anotherTmp = recursiveFindFile(directory, arrayOfFileNames); return anotherTmp; } else if (tmp === undefined) { // ran out of directories return undefined; } const p = path.resolve(directory, tmp); return p; }
javascript
{ "resource": "" }
q13432
angle
train
function angle(a, b){ var ang = (Math.atan2(b.y, b.x) - Math.atan2(a.y, a.x) + Math.PI*2) % (Math.PI*2); if (ang > Math.PI) ang -= Math.PI*2; return ang; }
javascript
{ "resource": "" }
q13433
train
function( noDelay ) { if ( this._.locked ) return; function doBlur() { if ( this.hasFocus ) { this.hasFocus = false; var ct = this._.editor.container; ct && ct.removeClass( 'cke_focus' ); this._.editor.fire( 'blur' ); } } if ( this._.timer ) clearTimeout( this._.timer ); var delay = CKEDITOR.focusManager._.blurDelay; if ( noDelay || !delay ) doBlur.call( this ); else { this._.timer = CKEDITOR.tools.setTimeout( function() { delete this._.timer; doBlur.call( this ); }, delay, this ); } }
javascript
{ "resource": "" }
q13434
train
function( element, isCapture ) { var fm = element.getCustomData( SLOT_NAME ); if ( !fm || fm != this ) { // If this element is already taken by another instance, dismiss it first. fm && fm.remove( element ); var focusEvent = 'focus', blurEvent = 'blur'; // Bypass the element's internal DOM focus change. if ( isCapture ) { // Use "focusin/focusout" events instead of capture phase in IEs, // which fires synchronously. if ( CKEDITOR.env.ie ) { focusEvent = 'focusin'; blurEvent = 'focusout'; } else { CKEDITOR.event.useCapture = 1; } } var listeners = { blur: function() { if ( element.equals( this.currentActive ) ) this.blur(); }, focus: function() { this.focus( element ); } }; element.on( focusEvent, listeners.focus, this ); element.on( blurEvent, listeners.blur, this ); if ( isCapture ) CKEDITOR.event.useCapture = 0; element.setCustomData( SLOT_NAME, this ); element.setCustomData( SLOT_NAME_LISTENERS, listeners ); } }
javascript
{ "resource": "" }
q13435
PostcssCompiler
train
function PostcssCompiler(inputTrees, inputFile, outputFile, plugins, map, useSass, includePaths) { if (!(this instanceof PostcssCompiler)) { return new PostcssCompiler(inputTrees, inputFile, outputFile, plugins, map); } if (!Array.isArray(inputTrees)) { throw new Error('Expected array for first argument - did you mean [tree] instead of tree?'); } CachingWriter.call(this, inputTrees, inputFile); this.inputFile = inputFile; this.outputFile = outputFile; this.plugins = plugins || []; this.map = map || {}; this.warningStream = process.stderr; this.useSass = useSass || false; this.includePaths = includePaths || []; }
javascript
{ "resource": "" }
q13436
coverFile
train
function coverFile(srcFile) { var srcCode = grunt.file.read(srcFile); Instrument = require('coverjs').Instrument; try { return new Instrument(srcCode, {name: srcFile}).instrument(); } catch (e) { grunt.log.error('File ' + srcFile + ' could not be instrumented.'); grunt.fatal(e, 3); } }
javascript
{ "resource": "" }
q13437
createBaseCustomElementClass
train
function createBaseCustomElementClass(win) { if (win.BaseCustomElementClass) { return win.BaseCustomElementClass; } const htmlElement = win.HTMLElement; /** @abstract @extends {HTMLElement} */ class BaseCustomElement extends htmlElement { /** * @see https://github.com/WebReflection/document-register-element#v1-caveat * @suppress {checkTypes} */ constructor(self) { self = super(self); self.createdCallback(self.getChildren()); return self; } /** * Called when elements is created. Sets instance vars since there is no * constructor. * @this {!Element} */ createdCallback() { } attributeChangedCallback(attrName, oldVal, newVal) { } /** * Called when the element is first connected to the DOM. Calls * {@link firstAttachedCallback} if this is the first attachment. * @final @this {!Element} */ connectedCallback() { } /** The Custom Elements V0 sibling to `connectedCallback`. */ attachedCallback() { this.connectedCallback(); } /** * Called when the element is disconnected from the DOM. * @final @this {!Element} */ disconnectedCallback() { } /** The Custom Elements V0 sibling to `disconnectedCallback`. */ detachedCallback() { this.disconnectedCallback(); } getChildren() { return [].slice.call(this.childNodes); } } win.BaseCustomElementClass = BaseCustomElement; return win.BaseCustomElementClass; }
javascript
{ "resource": "" }
q13438
train
function(backdropZ, dialogZ) { this.backdrop_.style.zIndex = backdropZ; this.dialog_.style.zIndex = dialogZ; }
javascript
{ "resource": "" }
q13439
initialize
train
function initialize(app, options) { var log = logger.get(options); app._mukoan = app._mukoan || {}; if (!app._mukoan.initialized) { var config = defaults({}, options, DEFAULT_CONFIGURATION); log.info('Starting and configuring Koa server'); // Setup global error handler and logger app.use(middlewares.error(config.error)); app.on('error', (error) => log.error('Unexpected exception ', error)); app._mukoan.initialized = true; } else { log.warn('Trying to initialize the same Koa instance twice (ignoring action)'); } }
javascript
{ "resource": "" }
q13440
bootstrap
train
function bootstrap(app, options) { var config = defaults({}, options, DEFAULT_CONFIGURATION); var log = logger.get(options); app._mukoan = app._mukoan || {}; if (!app._mukoan.initialized) { initialize(app, options); } if (!app._mukoan.bootstrapped) { // Configure and setup middlewares app.use(middlewares.bodyparser(config.bodyParser)); app.use(middlewares.morgan(config.morgan.format, config.morgan.options)); app.use(middlewares.responseTime()); app.use(middlewares.helmet(config.helmet)); app.use(middlewares.compress({ flush: zlib.Z_SYNC_FLUSH })); app.use(middlewares.conditional()); app.use(middlewares.etag()); app.use(middlewares.cacheControl(config.cacheControl)); app.use(middlewares.cors(config.cors)); app.use(middlewares.favicon(config.favicon)); app.use(middlewares.jwt(config.jwt.options).unless(config.jwt.unless)); app.use(middlewares.json()); app._mukoan.bootstrapped = true; log.debug('Finished configuring Koa server'); } else { log.warn('Trying to bootstrap the same Koa instance twice (ignoring action)'); } return app; }
javascript
{ "resource": "" }
q13441
accessor
train
function accessor(object) { var ref = object || (1, eval)('this'); var len = parts.length; var idx = 0; // iteratively save each segment's reference for (; idx < len; idx += 1) { if (ref) ref = ref[parts[idx]]; } return ref; }
javascript
{ "resource": "" }
q13442
train
function (imgsrc, width, height, callback) { var args = new Args(arguments); checkCommonArgs(args); var Image = Canvas.Image, fs = require("fs"); var img = new Image(); img.onerror = function(err) { callback(false, err); }; img.onload = function() { var w = img.width; var h = img.height; var newx = Math.abs(w / 2 - width / 2); var newy = Math.abs(h / 2 - height / 2); var canvas = new Canvas(width, height); var ctx = canvas.getContext("2d"); ctx.drawImage(img, newx, newy, width, height, 0, 0, width, height); callback(true, canvas); }; if (!isValidFile(imgsrc)) { callback(false, new Error (imgsrc + ' is not a valid file')); } else { img.src = imgsrc; } }
javascript
{ "resource": "" }
q13443
handleMousedown
train
function handleMousedown(event) { // get currently open dialogue var dialogue = getDialogueCurrent(); if (dialogue.options.hardClose) { return; } var result = helper.isInside(event.target, dialogue.dialogue); if (!result) { closeInstance(dialogue); } }
javascript
{ "resource": "" }
q13444
applyCssPosition
train
function applyCssPosition(dialogue) { var positionalEl = dialogue.options.positionTo; var containerPadding = 20; var cssSettings = { top: '', left: '', position: '', margin: '', marginTop: 0, marginRight: 0, marginBottom: 0, marginLeft: 0, maxWidth: dialogue.options.width }; var clientFrame = { positionVertical: window.pageYOffset, height: window.innerHeight, width: window.innerWidth }; var dialogueHeight = parseInt(dialogue.dialogue.offsetHeight); // position container dialogue.container.style.top = parsePx(clientFrame.positionVertical); // position to element or centrally window if (positionalEl) { var boundingRect = positionalEl.getBoundingClientRect(); // calc top cssSettings.position = 'absolute'; cssSettings.top = parseInt(boundingRect.top); cssSettings.left = parseInt(boundingRect.left); // if the right side of the dialogue is poking out of the clientFrame then // bring it back in plus 50px padding if ((cssSettings.left + cssSettings['maxWidth']) > clientFrame.width) { cssSettings.left = clientFrame.width - 50; cssSettings.left = cssSettings.left - cssSettings['maxWidth']; }; // no positional element so center to window } else { cssSettings.position = 'relative'; cssSettings.left = 'auto'; cssSettings.marginTop = 0; cssSettings.marginRight = 'auto'; cssSettings.marginBottom = 0; cssSettings.marginLeft = 'auto'; // center vertically if there is room // otherwise send to top and then just scroll if (dialogueHeight < clientFrame.height) { cssSettings.top = parseInt(clientFrame.height / 2) - parseInt(dialogueHeight / 2) - containerPadding; } else { cssSettings.top = 'auto'; }; }; dialogue.container.style.zIndex = 500 + dialoguesOpen.length; dialogue.dialogue.style.top = parsePx(cssSettings.top); dialogue.dialogue.style.left = parsePx(cssSettings.left); dialogue.dialogue.style.position = parsePx(cssSettings.position); dialogue.dialogue.style.marginTop = parsePx(cssSettings.marginTop); dialogue.dialogue.style.marginRight = parsePx(cssSettings.marginRight); dialogue.dialogue.style.marginBottom = parsePx(cssSettings.marginBottom); dialogue.dialogue.style.marginLeft = parsePx(cssSettings.marginLeft); dialogue.dialogue.style.maxWidth = parsePx(cssSettings.maxWidth); }
javascript
{ "resource": "" }
q13445
closeInstance
train
function closeInstance(dialogue) { // none may be open yet, or one may be open but may be closing another which is not open if (typeof dialogue === 'undefined' || typeof dialogue.options === 'undefined' || !dialoguesOpen.length) { return; } dialoguesOpen.forEach(function(dialogueSingle, index) { if (dialogueSingle.options.id == dialogue.options.id) { dialoguesOpen.splice(index, 1); } }); if (!dialoguesOpen.length) { document.removeEventListener('keyup', handleKeyup); document.removeEventListener('mousedown', handleMousedown); } // .off('click.dialogue.action') // dialogue.container.off(); // needed? docBody.removeChild(dialogue.container); dialogue.options.onClose.call(dialogue); }
javascript
{ "resource": "" }
q13446
train
function (file) { return Path.join(Path.dirname(Path.relative(hbTemplatePath, file)), Path.basename(file, Path.extname(file))); }
javascript
{ "resource": "" }
q13447
scale
train
function scale(sx) { var sy = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; if ((0, _utils.isUndefined)(sy)) sy = sx; return { a: sx, c: 0, e: 0, b: 0, d: sy, f: 0 }; }
javascript
{ "resource": "" }
q13448
train
function (surl) { var search = (surl || window.location.search).match(/\?.*(?=\b|#)/); search && (search = search[0].replace(/^\?/, '')); if (!search) return {}; var queries = {}, params = search.split('&'); util.each(params, function (item) { var param = item.split('='); queries[param[0]] = param[1]; }); return queries; }
javascript
{ "resource": "" }
q13449
train
function( part, fn ) { if ( CKEDITOR.skin.name != getName() ) { CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( getConfigPath() + 'skin.js' ), function() { loadCss( part, fn ); } ); } else { loadCss( part, fn ); } }
javascript
{ "resource": "" }
q13450
train
function( name, path, offset, bgsize ) { name = name.toLowerCase(); if ( !this.icons[ name ] ) { this.icons[ name ] = { path: path, offset: offset || 0, bgsize: bgsize || '16px' }; } }
javascript
{ "resource": "" }
q13451
train
function( name, rtl, overridePath, overrideOffset, overrideBgsize ) { var icon, path, offset, bgsize; if ( name ) { name = name.toLowerCase(); // If we're in RTL, try to get the RTL version of the icon. if ( rtl ) icon = this.icons[ name + '-rtl' ]; // If not in LTR or no RTL version available, get the generic one. if ( !icon ) icon = this.icons[ name ]; } path = overridePath || ( icon && icon.path ) || ''; offset = overrideOffset || ( icon && icon.offset ); bgsize = overrideBgsize || ( icon && icon.bgsize ) || '16px'; return path && ( 'background-image:url(' + CKEDITOR.getUrl( path ) + ');background-position:0 ' + offset + 'px;background-size:' + bgsize + ';' ); }
javascript
{ "resource": "" }
q13452
train
function (LazyValue, Bounce) { var nu = function (baseFn) { var get = function(callback) { baseFn(Bounce.bounce(callback)); }; /** map :: this Future a -> (a -> b) -> Future b */ var map = function (fab) { return nu(function (callback) { get(function (a) { var value = fab(a); callback(value); }); }); }; /** bind :: this Future a -> (a -> Future b) -> Future b */ var bind = function (aFutureB) { return nu(function (callback) { get(function (a) { aFutureB(a).get(callback); }); }); }; /** anonBind :: this Future a -> Future b -> Future b * Returns a future, which evaluates the first future, ignores the result, then evaluates the second. */ var anonBind = function (futureB) { return nu(function (callback) { get(function (a) { futureB.get(callback); }); }); }; var toLazy = function () { return LazyValue.nu(get); }; return { map: map, bind: bind, anonBind: anonBind, toLazy: toLazy, get: get }; }; /** a -> Future a */ var pure = function (a) { return nu(function (callback) { callback(a); }); }; return { nu: nu, pure: pure }; }
javascript
{ "resource": "" }
q13453
train
function (elm, rootElm) { var self = this, x = 0, y = 0, offsetParent, doc = self.doc, body = doc.body, pos; elm = self.get(elm); rootElm = rootElm || body; if (elm) { // Use getBoundingClientRect if it exists since it's faster than looping offset nodes // Fallback to offsetParent calculations if the body isn't static better since it stops at the body root if (rootElm === body && elm.getBoundingClientRect && DomQuery(body).css('position') === 'static') { pos = elm.getBoundingClientRect(); rootElm = self.boxModel ? doc.documentElement : body; // Add scroll offsets from documentElement or body since IE with the wrong box model will use d.body and so do WebKit // Also remove the body/documentelement clientTop/clientLeft on IE 6, 7 since they offset the position x = pos.left + (doc.documentElement.scrollLeft || body.scrollLeft) - rootElm.clientLeft; y = pos.top + (doc.documentElement.scrollTop || body.scrollTop) - rootElm.clientTop; return { x: x, y: y }; } offsetParent = elm; while (offsetParent && offsetParent != rootElm && offsetParent.nodeType) { x += offsetParent.offsetLeft || 0; y += offsetParent.offsetTop || 0; offsetParent = offsetParent.offsetParent; } offsetParent = elm.parentNode; while (offsetParent && offsetParent != rootElm && offsetParent.nodeType) { x -= offsetParent.scrollLeft || 0; y -= offsetParent.scrollTop || 0; offsetParent = offsetParent.parentNode; } } return { x: x, y: y }; }
javascript
{ "resource": "" }
q13454
train
function (element) { var el = element.dom(); var defaultView = el.ownerDocument.defaultView; return Element.fromDom(defaultView); }
javascript
{ "resource": "" }
q13455
train
function (dom, selection) { var caretContainer; caretContainer = getParentCaretContainer(selection.getStart()); if (caretContainer && !dom.isEmpty(caretContainer)) { Tools.walk(caretContainer, function (node) { if (node.nodeType === 1 && node.id !== CARET_ID && !dom.isEmpty(node)) { dom.setAttrib(node, 'data-mce-bogus', null); } }, 'childNodes'); } }
javascript
{ "resource": "" }
q13456
train
function (node, args) { var self = this, impl, doc, oldDoc, htmlSerializer, content, rootNode; // Explorer won't clone contents of script and style and the // selected index of select elements are cleared on a clone operation. if (Env.ie && dom.select('script,style,select,map').length > 0) { content = node.innerHTML; node = node.cloneNode(false); dom.setHTML(node, content); } else { node = node.cloneNode(true); } // Nodes needs to be attached to something in WebKit/Opera // This fix will make DOM ranges and make Sizzle happy! impl = document.implementation; if (impl.createHTMLDocument) { // Create an empty HTML document doc = impl.createHTMLDocument(""); // Add the element or it's children if it's a body element to the new document each(node.nodeName == 'BODY' ? node.childNodes : [node], function (node) { doc.body.appendChild(doc.importNode(node, true)); }); // Grab first child or body element for serialization if (node.nodeName != 'BODY') { node = doc.body.firstChild; } else { node = doc.body; } // set the new document in DOMUtils so createElement etc works oldDoc = dom.doc; dom.doc = doc; } args = args || {}; args.format = args.format || 'html'; // Don't wrap content if we want selected html if (args.selection) { args.forced_root_block = ''; } // Pre process if (!args.no_events) { args.node = node; self.onPreProcess(args); } // Parse HTML content = Zwsp.trim(trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node))); rootNode = htmlParser.parse(content, args); trimTrailingBr(rootNode); // Serialize HTML htmlSerializer = new Serializer(settings, schema); args.content = htmlSerializer.serialize(rootNode); // Post process if (!args.no_events) { self.onPostProcess(args); } // Restore the old document if it was changed if (oldDoc) { dom.doc = oldDoc; } args.node = null; return args.content; }
javascript
{ "resource": "" }
q13457
train
function (original, tag) { var nu = Element.fromTag(tag); var attributes = Attr.clone(original); Attr.setAll(nu, attributes); return nu; }
javascript
{ "resource": "" }
q13458
train
function (original, tag) { var nu = shallowAs(original, tag); // NOTE // previously this used serialisation: // nu.dom().innerHTML = original.dom().innerHTML; // // Clone should be equivalent (and faster), but if TD <-> TH toggle breaks, put it back. var cloneChildren = Traverse.children(deep(original)); InsertAll.append(nu, cloneChildren); return nu; }
javascript
{ "resource": "" }
q13459
train
function (original, tag) { var nu = shallowAs(original, tag); Insert.before(original, nu); var children = Traverse.children(original); InsertAll.append(nu, children); Remove.remove(original); return nu; }
javascript
{ "resource": "" }
q13460
train
function(arr, f) { var r = []; for (var i = 0; i < arr.length; i++) { var x = arr[i]; if (x.isSome()) { r.push(x.getOrDie()); } else { return Option.none(); } } return Option.some(f.apply(null, r)); }
javascript
{ "resource": "" }
q13461
train
function (args) { var self = this, rng = self.getRng(), tmpElm = self.dom.create("body"); var se = self.getSel(), whiteSpaceBefore, whiteSpaceAfter, fragment; args = args || {}; whiteSpaceBefore = whiteSpaceAfter = ''; args.get = true; args.format = args.format || 'html'; args.selection = true; self.editor.fire('BeforeGetContent', args); if (args.format === 'text') { return self.isCollapsed() ? '' : Zwsp.trim(rng.text || (se.toString ? se.toString() : '')); } if (rng.cloneContents) { fragment = args.contextual ? FragmentReader.read(self.editor.getBody(), rng).dom() : rng.cloneContents(); if (fragment) { tmpElm.appendChild(fragment); } } else if (rng.item !== undefined || rng.htmlText !== undefined) { // IE will produce invalid markup if elements are present that // it doesn't understand like custom elements or HTML5 elements. // Adding a BR in front of the contents and then remoiving it seems to fix it though. tmpElm.innerHTML = '<br>' + (rng.item ? rng.item(0).outerHTML : rng.htmlText); tmpElm.removeChild(tmpElm.firstChild); } else { tmpElm.innerHTML = rng.toString(); } // Keep whitespace before and after if (/^\s/.test(tmpElm.innerHTML)) { whiteSpaceBefore = ' '; } if (/\s+$/.test(tmpElm.innerHTML)) { whiteSpaceAfter = ' '; } args.getInner = true; args.content = self.isCollapsed() ? '' : whiteSpaceBefore + self.serializer.serialize(tmpElm, args) + whiteSpaceAfter; self.editor.fire('GetContent', args); return args.content; }
javascript
{ "resource": "" }
q13462
train
function (rng, forward) { var self = this, sel, node, evt; if (!isValidRange(rng)) { return; } // Is IE specific range if (rng.select) { self.explicitRange = null; try { rng.select(); } catch (ex) { // Needed for some odd IE bug #1843306 } return; } if (!self.tridentSel) { sel = self.getSel(); evt = self.editor.fire('SetSelectionRange', { range: rng, forward: forward }); rng = evt.range; if (sel) { self.explicitRange = rng; try { sel.removeAllRanges(); sel.addRange(rng); } catch (ex) { // IE might throw errors here if the editor is within a hidden container and selection is changed } // Forward is set to false and we have an extend function if (forward === false && sel.extend) { sel.collapse(rng.endContainer, rng.endOffset); sel.extend(rng.startContainer, rng.startOffset); } // adding range isn't always successful so we need to check range count otherwise an exception can occur self.selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null; } // WebKit egde case selecting images works better using setBaseAndExtent when the image is floated if (!rng.collapsed && rng.startContainer === rng.endContainer && sel.setBaseAndExtent && !Env.ie) { if (rng.endOffset - rng.startOffset < 2) { if (rng.startContainer.hasChildNodes()) { node = rng.startContainer.childNodes[rng.startOffset]; if (node && node.tagName === 'IMG') { sel.setBaseAndExtent( rng.startContainer, rng.startOffset, rng.endContainer, rng.endOffset ); // Since the setBaseAndExtent is fixed in more recent Blink versions we // need to detect if it's doing the wrong thing and falling back to the // crazy incorrect behavior api call since that seems to be the only way // to get it to work on Safari WebKit as of 2017-02-23 if (sel.anchorNode !== rng.startContainer || sel.focusNode !== rng.endContainer) { sel.setBaseAndExtent(node, 0, node, 1); } } } } } self.editor.fire('AfterSetSelectionRange', { range: rng, forward: forward }); } else { // Is W3C Range fake range on IE if (rng.cloneRange) { try { self.tridentSel.addRange(rng); } catch (ex) { //IE9 throws an error here if called before selection is placed in the editor } } } }
javascript
{ "resource": "" }
q13463
train
function () { var level; if (self.typing) { self.add(); self.typing = false; setTyping(false); } if (index > 0) { level = data[--index]; Levels.applyToEditor(editor, level, true); setDirty(true); editor.fire('undo', { level: level }); } return level; }
javascript
{ "resource": "" }
q13464
train
function (elm, afterDeletePosOpt) { return Options.liftN([Traverse.prevSibling(elm), Traverse.nextSibling(elm), afterDeletePosOpt], function (prev, next, afterDeletePos) { var offset, prevNode = prev.dom(), nextNode = next.dom(); if (NodeType.isText(prevNode) && NodeType.isText(nextNode)) { offset = prevNode.data.length; prevNode.appendData(nextNode.data); Remove.remove(next); Remove.remove(elm); if (afterDeletePos.container() === nextNode) { return new CaretPosition(prevNode, offset); } else { return afterDeletePos; } } else { Remove.remove(elm); return afterDeletePos; } }).orThunk(function () { Remove.remove(elm); return afterDeletePosOpt; }); }
javascript
{ "resource": "" }
q13465
queryCommandValue
train
function queryCommandValue(command) { var func; if (editor.quirks.isHidden() || editor.removed) { return; } command = command.toLowerCase(); if ((func = commands.value[command])) { return func(command); } // Browser commands try { return editor.getDoc().queryCommandValue(command); } catch (ex) { // Fails sometimes see bug: 1896577 } }
javascript
{ "resource": "" }
q13466
train
function (dom, node) { return node && dom.isBlock(node) && !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) && !/^(fixed|absolute)/i.test(node.style.position) && dom.getContentEditable(node) !== "true"; }
javascript
{ "resource": "" }
q13467
moveToCaretPosition
train
function moveToCaretPosition(root) { var walker, node, rng, lastNode = root, tempElm; if (!root) { return; } // Old IE versions doesn't properly render blocks with br elements in them // For example <p><br></p> wont be rendered correctly in a contentEditable area // until you remove the br producing <p></p> if (Env.ie && Env.ie < 9 && parentBlock && parentBlock.firstChild) { if (parentBlock.firstChild == parentBlock.lastChild && parentBlock.firstChild.tagName == 'BR') { dom.remove(parentBlock.firstChild); } } if (/^(LI|DT|DD)$/.test(root.nodeName)) { var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild); if (firstChild && /^(UL|OL|DL)$/.test(firstChild.nodeName)) { root.insertBefore(dom.doc.createTextNode('\u00a0'), root.firstChild); } } rng = dom.createRng(); // Normalize whitespace to remove empty text nodes. Fix for: #6904 // Gecko will be able to place the caret in empty text nodes but it won't render propery // Older IE versions will sometimes crash so for now ignore all IE versions if (!Env.ie) { root.normalize(); } if (root.hasChildNodes()) { walker = new TreeWalker(root, root); while ((node = walker.current())) { if (node.nodeType == 3) { rng.setStart(node, 0); rng.setEnd(node, 0); break; } if (moveCaretBeforeOnEnterElementsMap[node.nodeName.toLowerCase()]) { rng.setStartBefore(node); rng.setEndBefore(node); break; } lastNode = node; node = walker.next(); } if (!node) { rng.setStart(lastNode, 0); rng.setEnd(lastNode, 0); } } else { if (root.nodeName == 'BR') { if (root.nextSibling && dom.isBlock(root.nextSibling)) { // Trick on older IE versions to render the caret before the BR between two lists if (!documentMode || documentMode < 9) { tempElm = dom.create('br'); root.parentNode.insertBefore(tempElm, root); } rng.setStartBefore(root); rng.setEndBefore(root); } else { rng.setStartAfter(root); rng.setEndAfter(root); } } else { rng.setStart(root, 0); rng.setEnd(root, 0); } } selection.setRng(rng); // Remove tempElm created for old IE:s dom.remove(tempElm); selection.scrollIntoView(root); }
javascript
{ "resource": "" }
q13468
train
function (editor, clientX, clientY) { var bodyElm = Element.fromDom(editor.getBody()); var targetElm = editor.inline ? bodyElm : Traverse.documentElement(bodyElm); var transposedPoint = transpose(editor.inline, targetElm, clientX, clientY); return isInsideElementContentArea(targetElm, transposedPoint.x, transposedPoint.y); }
javascript
{ "resource": "" }
q13469
Editor
train
function Editor(id, settings, editorManager) { var self = this, documentBaseUrl, baseUri; documentBaseUrl = self.documentBaseUrl = editorManager.documentBaseURL; baseUri = editorManager.baseURI; /** * Name/value collection with editor settings. * * @property settings * @type Object * @example * // Get the value of the theme setting * tinymce.activeEditor.windowManager.alert("You are using the " + tinymce.activeEditor.settings.theme + " theme"); */ settings = EditorSettings.getEditorSettings(self, id, documentBaseUrl, editorManager.defaultSettings, settings); self.settings = settings; AddOnManager.language = settings.language || 'en'; AddOnManager.languageLoad = settings.language_load; AddOnManager.baseURL = editorManager.baseURL; /** * Editor instance id, normally the same as the div/textarea that was replaced. * * @property id * @type String */ self.id = id; /** * State to force the editor to return false on a isDirty call. * * @property isNotDirty * @type Boolean * @deprecated Use editor.setDirty instead. */ self.setDirty(false); /** * Name/Value object containing plugin instances. * * @property plugins * @type Object * @example * // Execute a method inside a plugin directly * tinymce.activeEditor.plugins.someplugin.someMethod(); */ self.plugins = {}; /** * URI object to document configured for the TinyMCE instance. * * @property documentBaseURI * @type tinymce.util.URI * @example * // Get relative URL from the location of document_base_url * tinymce.activeEditor.documentBaseURI.toRelative('/somedir/somefile.htm'); * * // Get absolute URL from the location of document_base_url * tinymce.activeEditor.documentBaseURI.toAbsolute('somefile.htm'); */ self.documentBaseURI = new URI(settings.document_base_url, { base_uri: baseUri }); /** * URI object to current document that holds the TinyMCE editor instance. * * @property baseURI * @type tinymce.util.URI * @example * // Get relative URL from the location of the API * tinymce.activeEditor.baseURI.toRelative('/somedir/somefile.htm'); * * // Get absolute URL from the location of the API * tinymce.activeEditor.baseURI.toAbsolute('somefile.htm'); */ self.baseURI = baseUri; /** * Array with CSS files to load into the iframe. * * @property contentCSS * @type Array */ self.contentCSS = []; /** * Array of CSS styles to add to head of document when the editor loads. * * @property contentStyles * @type Array */ self.contentStyles = []; // Creates all events like onClick, onSetContent etc see Editor.Events.js for the actual logic self.shortcuts = new Shortcuts(self); self.loadedCSS = {}; self.editorCommands = new EditorCommands(self); self.suffix = editorManager.suffix; self.editorManager = editorManager; self.inline = settings.inline; if (settings.cache_suffix) { Env.cacheSuffix = settings.cache_suffix.replace(/^[\?\&]+/, ''); } if (settings.override_viewport === false) { Env.overrideViewPort = false; } // Call setup editorManager.fire('SetupEditor', self); self.execCallback('setup', self); /** * Dom query instance with default scope to the editor document and default element is the body of the editor. * * @property $ * @type tinymce.dom.DomQuery * @example * tinymce.activeEditor.$('p').css('color', 'red'); * tinymce.activeEditor.$().append('<p>new</p>'); */ self.$ = DomQuery.overrideDefaults(function () { return { context: self.inline ? self.getBody() : self.getDoc(), element: self.getBody() }; }); }
javascript
{ "resource": "" }
q13470
train
function (text) { if (text && Tools.is(text, 'string')) { var lang = this.settings.language || 'en', i18n = this.editorManager.i18n; text = i18n.data[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function (a, b) { return i18n.data[lang + '.' + b] || '{#' + b + '}'; }); } return this.editorManager.translate(text); }
javascript
{ "resource": "" }
q13471
train
function (args) { var self = this, content, body = self.getBody(); if (self.removed) { return ''; } // Setup args object args = args || {}; args.format = args.format || 'html'; args.get = true; args.getInner = true; // Do preprocessing if (!args.no_events) { self.fire('BeforeGetContent', args); } // Get raw contents or by default the cleaned contents if (args.format == 'raw') { content = Tools.trim(self.serializer.getTrimmedContent()); } else if (args.format == 'text') { content = body.innerText || body.textContent; } else { content = self.serializer.serialize(body, args); } // Trim whitespace in beginning/end of HTML if (args.format != 'text') { args.content = trim(content); } else { args.content = content; } // Do post processing if (!args.no_events) { self.fire('GetContent', args); } return args.content; }
javascript
{ "resource": "" }
q13472
train
function() { // Call the base contructor. this.base(); /** * The characters to be used for each indentation step. * * // Use tab for indentation. * editorInstance.dataProcessor.writer.indentationChars = '\t'; */ this.indentationChars = '\t'; /** * The characters to be used to close "self-closing" elements, like `<br>` or `<img>`. * * // Use HTML4 notation for self-closing elements. * editorInstance.dataProcessor.writer.selfClosingEnd = '>'; */ this.selfClosingEnd = ' />'; /** * The characters to be used for line breaks. * * // Use CRLF for line breaks. * editorInstance.dataProcessor.writer.lineBreakChars = '\r\n'; */ this.lineBreakChars = '\n'; this.sortAttributes = 1; this._.indent = 0; this._.indentation = ''; // Indicate preformatted block context status. (#5789) this._.inPre = 0; this._.rules = {}; var dtd = CKEDITOR.dtd; for ( var e in CKEDITOR.tools.extend( {}, dtd.$nonBodyContent, dtd.$block, dtd.$listItem, dtd.$tableContent ) ) { this.setRules( e, { indent: !dtd[ e ][ '#' ], breakBeforeOpen: 1, breakBeforeClose: !dtd[ e ][ '#' ], breakAfterClose: 1, needsSpace: ( e in dtd.$block ) && !( e in { li: 1, dt: 1, dd: 1 } ) } ); } this.setRules( 'br', { breakAfterOpen: 1 } ); this.setRules( 'title', { indent: 0, breakAfterOpen: 0 } ); this.setRules( 'style', { indent: 0, breakBeforeClose: 1 } ); this.setRules( 'pre', { breakAfterOpen: 1, // Keep line break after the opening tag indent: 0 // Disable indentation on <pre>. } ); }
javascript
{ "resource": "" }
q13473
train
function( tagName, attributes ) { var rules = this._.rules[ tagName ]; if ( this._.afterCloser && rules && rules.needsSpace && this._.needsSpace ) this._.output.push( '\n' ); if ( this._.indent ) this.indentation(); // Do not break if indenting. else if ( rules && rules.breakBeforeOpen ) { this.lineBreak(); this.indentation(); } this._.output.push( '<', tagName ); this._.afterCloser = 0; }
javascript
{ "resource": "" }
q13474
train
function( tagName, isSelfClose ) { var rules = this._.rules[ tagName ]; if ( isSelfClose ) { this._.output.push( this.selfClosingEnd ); if ( rules && rules.breakAfterClose ) this._.needsSpace = rules.needsSpace; } else { this._.output.push( '>' ); if ( rules && rules.indent ) this._.indentation += this.indentationChars; } if ( rules && rules.breakAfterOpen ) this.lineBreak(); tagName == 'pre' && ( this._.inPre = 1 ); }
javascript
{ "resource": "" }
q13475
train
function( tagName ) { var rules = this._.rules[ tagName ]; if ( rules && rules.indent ) this._.indentation = this._.indentation.substr( this.indentationChars.length ); if ( this._.indent ) this.indentation(); // Do not break if indenting. else if ( rules && rules.breakBeforeClose ) { this.lineBreak(); this.indentation(); } this._.output.push( '</', tagName, '>' ); tagName == 'pre' && ( this._.inPre = 0 ); if ( rules && rules.breakAfterClose ) { this.lineBreak(); this._.needsSpace = rules.needsSpace; } this._.afterCloser = 1; }
javascript
{ "resource": "" }
q13476
train
function( text ) { if ( this._.indent ) { this.indentation(); !this._.inPre && ( text = CKEDITOR.tools.ltrim( text ) ); } this._.output.push( text ); }
javascript
{ "resource": "" }
q13477
train
function() { this._.output = []; this._.indent = 0; this._.indentation = ''; this._.afterCloser = 0; this._.inPre = 0; }
javascript
{ "resource": "" }
q13478
normalizeToBase
train
function normalizeToBase(text) { var rExps = [ {re: /[\xC0-\xC6]/g, ch: "A"}, {re: /[\xE0-\xE6]/g, ch: "a"}, {re: /[\xC8-\xCB]/g, ch: "E"}, {re: /[\xE8-\xEB]/g, ch: "e"}, {re: /[\xCC-\xCF]/g, ch: "I"}, {re: /[\xEC-\xEF]/g, ch: "i"}, {re: /[\xD2-\xD6]/g, ch: "O"}, {re: /[\xF2-\xF6]/g, ch: "o"}, {re: /[\xD9-\xDC]/g, ch: "U"}, {re: /[\xF9-\xFC]/g, ch: "u"}, {re: /[\xC7-\xE7]/g, ch: "c"}, {re: /[\xD1]/g, ch: "N"}, {re: /[\xF1]/g, ch: "n"} ]; $.each(rExps, function () { text = text.replace(this.re, this.ch); }); return text; }
javascript
{ "resource": "" }
q13479
UsbHid
train
function UsbHid() { var vendorId = 0x0fc5; // always 0x0FC5 for Delcom products var productId = 0xb080; // always 0xB080 for Delcom HID device this.device = this._find(vendorId, productId); this.dataMap = { off: '\x00', green: '\x01', red: '\x02', blue: '\x04', yellow: '\x04' }; }
javascript
{ "resource": "" }
q13480
ToJSFilter
train
function ToJSFilter (inputTree, options) { if (!(this instanceof ToJSFilter)) { return new ToJSFilter(inputTree, options); } options = options || {}; options.extensions = options.extensions || ['txt']; options.targetExtension = 'js'; Filter.call(this, inputTree, options); this.trimFiles = options.trimFiles || false; }
javascript
{ "resource": "" }
q13481
define
train
function define(scope, Type, name) { var propName = name || 'super' , propInernalName = '_' + propName; Object.defineProperty(scope, propName, { writeable: false, get: function() { if(!this[propInernalName]) { this[propInernalName] = create(this, Type); } return this[propInernalName]; } }); }
javascript
{ "resource": "" }
q13482
create
train
function create(scope, Type) { // make result the constructor var result = function() { Type.apply(scope, arguments); }; // attach methods to result for(var key in Type.prototype) { if(typeof Type.prototype[key] === 'function') { result[key] = Type.prototype[key].bind(scope); } } return result; }
javascript
{ "resource": "" }
q13483
train
function (name) { return new DatabaseAPI(hoodie, { name: name, editable_permissions: true, _id: exports.convertID, prepare: exports.prepareDoc, parse: exports.parseDoc }) }
javascript
{ "resource": "" }
q13484
all
train
function all(values, keyName) { if(values instanceof Array) { var results = {}; for(var i=0; i<values.length; i++) { var obj2 = values[i]; var res = get(obj2, keyName); if(res != undefined) { results[res] = 0; } } var results2 = []; for(var result in results) { results2.push(result); } return results2; } }
javascript
{ "resource": "" }
q13485
getTasksFromYakefile
train
function getTasksFromYakefile(cwd, fileOption) { // find the yakefile and load (actually a dynamic 'require') tasks // first create an empty collection - dont need to use the global collection const tc1 = TC.TaskCollection(); //preload const tc2 = TASKS.loadPreloadedTasks(tc1); const yakefileCandidates = Yakefile.defaultFilenames(); if( fileOption !== undefined ) yakefileCandidates = [fileOption]; const yakeFilePath = Yakefile.recursiveFindFile(cwd, yakefileCandidates); if (yakeFilePath === undefined) { const msg = yakefileCandidates.join(); // console.log(util.inspect(yakefileCandidates)); ERROR.raiseError(`cannot find yakefile among : ${msg}`); } const collection = TASKS.requireTasks(yakeFilePath, tc2); return collection; }
javascript
{ "resource": "" }
q13486
getTasksFromTaskfile
train
function getTasksFromTaskfile() { // tasks will already be loaded and are in the global collection so get it const tc = TASKS.globals.globalTaskCollection; //this time the preloads come after the custom tasks - no choice const collection = TASKS.loadPreloadedTasks(tc); return collection; }
javascript
{ "resource": "" }
q13487
getTasksFromArray
train
function getTasksFromArray(cfgArray) { const tc = TC.TaskCollection(); // tasks are defined in a datascripture - load it const tc2 = TASKS.loadTasksFromArray(cfgArray, tc); //this time the preloads come after the custom tasks - could have done it the other way round const collection = TASKS.loadPreloadedTasks(tc2); return collection; }
javascript
{ "resource": "" }
q13488
tryShowTasks
train
function tryShowTasks(options, collection) { if (options.getValueFor('showTasks') !== undefined) { REPORTS.printTaskList(collection); return true; } return false; }
javascript
{ "resource": "" }
q13489
tryRunTask
train
function tryRunTask(args, collection) { let nameOfTaskToRun = 'default'; const a = args.getArgs(); if (a.length > 0) { nameOfTaskToRun = a[0]; } const firstTask = collection.getByName(nameOfTaskToRun); if (firstTask === undefined) { // console.log('ERROR'); ERROR.raiseError(`task ${nameOfTaskToRun} not found`); } TASKS.invokeTask(collection, firstTask); // console.log(chalk.white.bold(`${firstTask.name()} - completed `) + chalk.green.bold('OK')); }
javascript
{ "resource": "" }
q13490
taskFileMain
train
function taskFileMain(argv) { if( argv === undefined ) argv = process.argv const [options, args, helpText] = CLI.taskFileParse(argv); const collection = getTasksFromTaskfile(); const p = loadPackageJson(); if( tryShowVersion(options, p.version) ) return; if( tryShowTasks(options, collection) ) return; if( tryShowHelp(options, helpText) ) return; tryRunTask(args, collection); }
javascript
{ "resource": "" }
q13491
yakeFileMain
train
function yakeFileMain(argv, cwd) { if( cwd === undefined) cwd = process.cwd(); if( argv === undefined ) argv = process.argv const [options, args, helpText] = CLI.CliParse(argv); const collection = getTasksFromYakefile(cwd, options.getValueFor('file')); const p = loadPackageJson(); if( tryShowVersion(options, p.version) ) return; if( tryShowTasks(options, collection) ) return; if( tryShowHelp(options, helpText) ) return; tryRunTask(args, collection); }
javascript
{ "resource": "" }
q13492
train
function() { var self = this; var insightsPanel = self.buildInsightsPanel(); var media = insightsPanel + '<div class="media">' + ' <div class="media-left">' + // the visual chart as media-object. ' <div class="media-object" id="' + self.getId('chart') + '">Charts</div>' + ' </div>' + ' <div class="media-body">' + ' <div id="' + self.getId('summary') + '">Summary</div>' + ' </div>' + '</div>'; $('#' + self.attrId).html(media); }
javascript
{ "resource": "" }
q13493
train
function() { var self = this; var panel = '<div class="panel panel-success">' + ' <div class="panel-heading">' + ' visual data dashboard mockups' + ' </div>' + ' <div class="panel-body">' + ' <div class="row">' + // the visual chart. ' <div class="col-md-8">' + ' <div id="' + self.getId('chart') + '">Charts</div>' + ' </div>' + // the information column ' <div class="col-md-4">' + ' <div id="' + self.getId('summary') + '">Summary</div>' + ' </div>' + ' </div>' + ' </div>' + ' <div class="panel-footer">' + ' visual data footer mockups' + ' </div>' + '</div>'; $('#' + self.attrId).html(panel); // Draw the chart, $('#' + self.getId('chart')).html('') .bilevelSunburst({date: self.options.date}, self.treemapData); }
javascript
{ "resource": "" }
q13494
train
function() { var self = this; // Draw the chart, $('#' + self.getId('chart')).html('') .bilevelSunburst({date: self.options.date}, self.treemapData); }
javascript
{ "resource": "" }
q13495
train
function() { var self = this; var summary = self.tableSummaryBuilder(self.groupsSummary, self.pagesSummary, self.total); $('#' + self.getId('summary')).html(summary); }
javascript
{ "resource": "" }
q13496
train
function(groupName, totalSites, totalPages, totalPageviews) { var format = d3.format(',d'); // build var summary = '<tr>' + '<td>' + groupName + '</td>' + '<td>' + format(totalPageviews) + '</td>' + '<td>' + format(totalPages) + '</td>' + //'<td>' + totalSites + '</td>' + '</tr>'; return summary; }
javascript
{ "resource": "" }
q13497
train
function() { var self = this; if(this.options.insightsFeeder) { // use the customize insights feeder self.options.insightsFeeder(self); } else { // using the default insights feeder. self.defaultInsightsFeeder(self); } }
javascript
{ "resource": "" }
q13498
train
function(visualData) { var insightsList = '<li class="list-group-item">The site served' + ' <strong>' + visualData.total[0] + '</strong> total pageviews on' + ' <strong>' + visualData.total[1] + '</strong> pages of' + ' <strong>' + visualData.total[2] + '</strong> sites' + '</li>' + // the first group '<li class="list-group-item">The No. 1 group is <strong>' + visualData.groupsPageviews[0][0] + '</strong>, which has <strong>' + visualData.groupsPageviews[0][1] + '</strong> pageviews' + '</li>' + // the most viewed single page '<li class="list-group-item">The most views single page is <strong>' + visualData.jsonData[0][0] + '</strong>, which has <strong>' + visualData.jsonData[0][2] + '</strong> pageviews' + '</li>'; $('#' + visualData.getId('insightsList')).html(insightsList); }
javascript
{ "resource": "" }
q13499
run
train
function run (x, cb) { const s = speculum(null, Echo, x) s.on('end', cb) s.on('error', cb) const reader = new Count({ highWaterMark: 0 }, 10) reader.pipe(s).resume() }
javascript
{ "resource": "" }