_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q63800
getBashPath
test
function getBashPath() { if (bashPath) return bashPath; if (fs.existsSync('/usr/local/bin/bash')) { bashPath = '/usr/local/bin/bash'; } else if (fs.existsSync('/bin/bash')) { bashPath = '/bin/bash'; } else { bashPath = 'bash'; } return bashPath; }
javascript
{ "resource": "" }
q63801
Memory
test
function Memory(options) { options = options || {}; var self = this; self.flush = options.db._db._memory.flush || false; self.flushInterval = options.db._db._memory.flushInterval || 10000; self.flushFile = options.file; self.memoryTable = []; console.log('Data will be handled using \'Memory\' driver'); // :S yeah we need to load it synchronously otherwise it might be loaded after the first insert var content = util.fileSystem.readSync(self.flushFile); self.set(content); if (self.flush) { console.log('\'Memory\' driver will flush data every %sms', self.flushInterval); // set interval to flush setInterval(function flushToDisk() { util.fileSystem.lock(self.flushFile, function afterLock(err) { if (err) { throw err; } self.get(function afterGet(err, inMemoryContent) { if (err) { util.fileSystem.unlock(self.flushFile); throw err; } util.fileSystem.write(self.flushFile, inMemoryContent, function afterWrite(err) { util.fileSystem.unlock(self.flushFile); if (err) { throw err; } }); }); }); }, self.flushInterval); } }
javascript
{ "resource": "" }
q63802
deductcost
test
function deductcost() { var cost = []; if (!giving.have || giving.have.length < 1) return; // flatten var cost = []; for (var i = 0; i < giving.have.length; i++) { for (var j = 0; j < giving.have[i].length; j++) { cost.push(giving.have[i][j]); } } if (typeof cost[0] === 'string') cost = [cost]; function deduct(from, amt) { var current = parseInt(from.getAttribute('data-quantity')); current -= amt; from.setAttribute('data-quantity', current); updateAmounts(from); if (current < 1) { from.setAttribute('data-type', 'none'); from.innerHTML = ''; } } [].forEach.call(craftable.querySelectorAll('li'), function(li, i) { var row = Math.floor(i / 3); var has = (li.getAttribute('data-type') || 'none').toLowerCase(); for (var c = 0; c < cost.length; c++) { if (cost[c][0].toLowerCase() === has) { var price = cost[c][1]; cost.splice(c, 1); deduct(li, price); return false; } } }); }
javascript
{ "resource": "" }
q63803
test
function (sub_node) { if ( sub_node ) { walk(sub_node, depth + 1); } else if ( node.pages ) { node.pages.forEach(function (sub_node, name) { walk(sub_node, depth + 1); }); } }
javascript
{ "resource": "" }
q63804
test
function(provides) { if (_.isArray(provides)) { this._arguments = this._provides = (!this._provides) ? provides : this._provides.concat(provides); } else { this._provides = _.extend({}, this._provides, provides); this._arguments = _.map(this.deps, function(key) { return this._provides[key]; }, this); } return this; }
javascript
{ "resource": "" }
q63805
test
function(context, callback) { if (arguments.length === 1) { callback = context; context = this._context; } if (this.isAsync) { // clone the arguments so this.call can be reused with different callbacks var asyncArgs = this._arguments.slice(); // push the callback onto the new arguments array asyncArgs.push(callback); // call the function this.fn.apply(context, asyncArgs); } else { // if the function isn't async, allow it to be called with or without a callback if (callback) { // If a callback is provided, it must use the error-first arguments pattern. // The return value of the function will be the second argument. try { callback(null, this.fn.apply(context, this._arguments)); } catch(e) { callback(e); } } else { // If no callback is provided simply return the result of the function return this.fn.apply(context, this._arguments); } } }
javascript
{ "resource": "" }
q63806
each
test
function each(arr, callback) { var wrapper = this; if (this.isAsync) { return async.each(arr, function(item, cb) { wrapper.call(item, cb); }, callback); } else { arr.each(function(item) { wrapper.call(item); }); if (callback) { callback(); } } }
javascript
{ "resource": "" }
q63807
map
test
function map(arr, callback) { var wrapper = this; if (this.isAsync) { async.map(arr, function(item, cb) { wrapper.call(item, cb); }, callback); } else { callback(null, arr.map(function(item) { return wrapper.call(item); })); } }
javascript
{ "resource": "" }
q63808
test
function(selectedDates, dateStr, instance) { that.setProperty("dateValue", selectedDates, true); that.fireOnChange({selectedDates: selectedDates, dateStr: dateStr, instance: instance}); }
javascript
{ "resource": "" }
q63809
startServer
test
function startServer(options) { options = initOptions(options); var app = connect() , root = options.root , TEST = process.env.TEST , isSilent = options.silent || TEST; if (!isSilent) { app.use(log); } var smOpts = {}; var smOptMap = { ftpl: 'template' , style: 'style' }; Object.keys(smOptMap).forEach(function (key) { if (options[key] !== undefined) smOpts[smOptMap[key]] = options[key]; }); // serve markdown file app.use(serveMarkdown(root, smOpts)); // common files app.use(serveStatic(root, {index: ['index.html']})); // serve directory app.use(serveIndex(root, { icon: true , template: options.dtpl , stylesheet: options.style , view: options.view })); debug('server run in ' + (process.env.TEST ? 'TEST' : 'PRODUCTION') + ' mode') if (!TEST) { app.listen(options.port); showSuccessInfo(options); } return app; }
javascript
{ "resource": "" }
q63810
showSuccessInfo
test
function showSuccessInfo(options) { // server start success if (options.silent) return; console.log(chalk.blue('serve start Success: ') + '\n' + chalk.green('\t url ') + chalk.grey('http://127.0.0.1:') + chalk.red(options.port) + chalk.grey('/') + '\n' + chalk.green('\t serve ') + chalk.grey(options.root) ); }
javascript
{ "resource": "" }
q63811
log
test
function log(req, res, next) { console.log('[' + chalk.grey(ts()) + '] ' + chalk.white(decodeURI(req.url)) ); next(); }
javascript
{ "resource": "" }
q63812
test
function (valueToSet, type, iface, propertyKeys) { type = type.toLowerCase(); propertyKeys.forEach(function(propertyKey) { if(type == 'get') valueToSet['Get'+propertyKey] = function (callback) { iface.getProperty(propertyKey, callback); } else valueToSet['Set'+propertyKey] = function (value, callback) { iface.setProperty(propertyKey, value, callback); } }); }
javascript
{ "resource": "" }
q63813
init
test
function init(user_id,secret,storage) { API_USER_ID=user_id; API_SECRET=secret; TOKEN_STORAGE=storage; var hashName = md5(API_USER_ID+'::'+API_SECRET); if (fs.existsSync(TOKEN_STORAGE+hashName)) { TOKEN = fs.readFileSync(TOKEN_STORAGE+hashName,{encoding:'utf8'}); } if (! TOKEN.length) { getToken(); } }
javascript
{ "resource": "" }
q63814
sendRequest
test
function sendRequest(path, method, data, useToken, callback){ var headers = {} headers['Content-Type'] = 'application/json'; headers['Content-Length'] = Buffer.byteLength(JSON.stringify(data)); if (useToken && TOKEN.length) { headers['Authorization'] = 'Bearer '+TOKEN; } if (method === undefined) { method = 'POST'; } if (useToken === undefined) { useToken = false; } var options = { //uri: API_URL, path: '/'+path, port: 443, hostname: API_URL, method: method, headers: headers, }; var req = https.request( options, function(response) { var str = ''; response.on('data', function (chunk) { if (response.statusCode==401) { getToken(); sendRequest(path, method, data, true, callback); } else { str += chunk; } }); response.on('end', function () { if (response.statusCode != 401) { try { var answer = JSON.parse(str); } catch (ex) { var answer = returnError(); } callback(answer); } }); } ); req.write(JSON.stringify(data)); req.end(); }
javascript
{ "resource": "" }
q63815
getToken
test
function getToken(){ var data={ grant_type:'client_credentials', client_id: API_USER_ID, client_secret: API_SECRET } sendRequest( 'oauth/access_token', 'POST', data, false, saveToken ); function saveToken(data) { TOKEN = data.access_token; var hashName = md5(API_USER_ID+'::'+API_SECRET); fs.writeFileSync(TOKEN_STORAGE+hashName, TOKEN); } }
javascript
{ "resource": "" }
q63816
returnError
test
function returnError(message){ var data = {is_error:1}; if (message !== undefined && message.length) { data['message'] = message } return data; }
javascript
{ "resource": "" }
q63817
createAddressBook
test
function createAddressBook(callback,bookName) { if ((bookName === undefined) || (! bookName.length)) { return callback(returnError("Empty book name")); } var data = {bookName: bookName}; sendRequest( 'addressbooks', 'POST', data, true, callback ); }
javascript
{ "resource": "" }
q63818
editAddressBook
test
function editAddressBook(callback,id,bookName) { if ((id===undefined) || (bookName === undefined) || (! bookName.length)) { return callback(returnError("Empty book name or book id")); } var data = {name: bookName}; sendRequest( 'addressbooks/' + id, 'PUT', data, true, callback ); }
javascript
{ "resource": "" }
q63819
removeAddressBook
test
function removeAddressBook(callback,id){ if (id===undefined) { return callback(returnError('Empty book id')); } sendRequest( 'addressbooks/' + id, 'DELETE', {}, true, callback ); }
javascript
{ "resource": "" }
q63820
getBookInfo
test
function getBookInfo(callback,id){ if (id===undefined) { return callback(returnError('Empty book id')); } sendRequest( 'addressbooks/' + id, 'GET', {}, true, callback ); }
javascript
{ "resource": "" }
q63821
getEmailsFromBook
test
function getEmailsFromBook(callback,id){ if (id===undefined) { return callback(returnError('Empty book id')); } sendRequest( 'addressbooks/' + id + '/emails', 'GET', {}, true, callback ); }
javascript
{ "resource": "" }
q63822
addEmails
test
function addEmails(callback,id,emails){ if ((id===undefined) || (emails === undefined) || (! emails.length)) { return callback(returnError("Empty email or book id")); } var data = {emails: serialize(emails)}; sendRequest( 'addressbooks/' + id + '/emails', 'POST', data, true, callback ); }
javascript
{ "resource": "" }
q63823
getEmailInfo
test
function getEmailInfo(callback,id,email){ if ((id===undefined) || (email === undefined) || (! email.length)) { return callback(returnError("Empty email or book id")); } sendRequest( 'addressbooks/' + id + '/emails/' + email, 'GET', {}, true, callback ); }
javascript
{ "resource": "" }
q63824
campaignCost
test
function campaignCost(callback,id) { if (id===undefined) { return callback(returnError('Empty book id')); } sendRequest( 'addressbooks/' + id + '/cost', 'GET', {}, true, callback ); }
javascript
{ "resource": "" }
q63825
listCampaigns
test
function listCampaigns(callback,limit,offset){ var data={} if (limit === undefined) { limit = null; } else { data['limit'] = limit; } if (offset === undefined) { offset = null; } else { data['offset'] = offset; } sendRequest('campaigns', 'GET', data, true, callback); }
javascript
{ "resource": "" }
q63826
getCampaignInfo
test
function getCampaignInfo(callback,id){ if (id===undefined) { return callback(returnError('Empty book id')); } sendRequest( 'campaigns/' + id, 'GET', {}, true, callback ); }
javascript
{ "resource": "" }
q63827
campaignStatByCountries
test
function campaignStatByCountries(callback,id){ if (id===undefined) { return callback(returnError('Empty book id')); } sendRequest( 'campaigns/' + id + '/countries', 'GET', {}, true, callback ); }
javascript
{ "resource": "" }
q63828
campaignStatByReferrals
test
function campaignStatByReferrals(callback,id){ if (id===undefined) { return callback(returnError('Empty book id')); } sendRequest( 'campaigns/' + id + '/referrals', 'GET', {}, true, callback ); }
javascript
{ "resource": "" }
q63829
createCampaign
test
function createCampaign(callback, senderName, senderEmail, subject, body, bookId, name, attachments){ if ((senderName===undefined)||(! senderName.length)||(senderEmail===undefined)||(! senderEmail.length)||(subject===undefined)||(! subject.length)||(body===undefined)||(! body.length)||(bookId===undefined)){ return callback(returnError('Not all data.')); } if (name===undefined){ name=''; } if (attachments===undefined) { attachments=''; } if (attachments.length){ attachments = serialize(attachments); } var data = { sender_name: senderName, sender_email: senderEmail, //subject: encodeURIComponent(subject), //subject: urlencode(subject), subject: subject, body: base64(body), list_id: bookId, name: name, attachments: attachments } sendRequest( 'campaigns', 'POST', data, true, callback ); }
javascript
{ "resource": "" }
q63830
addSender
test
function addSender(callback, senderName, senderEmail){ if ((senderEmail===undefined)||(!senderEmail.length)||(senderName===undefined)||(!senderName.length)) { return callback(returnError('Empty sender name or email')); } var data = { email: senderEmail, name: senderName } sendRequest( 'senders', 'POST', data, true, callback ); }
javascript
{ "resource": "" }
q63831
activateSender
test
function activateSender(callback, senderEmail, code){ if ((senderEmail===undefined)||(!senderEmail.length)||(code===undefined)||(!code.length)){ return callback(returnError('Empty email or activation code')); } var data = { code: code } sendRequest( 'senders/' + senderEmail + '/code', 'POST', data, true, callback ); }
javascript
{ "resource": "" }
q63832
getSenderActivationMail
test
function getSenderActivationMail(callback, senderEmail ) { if ((senderEmail===undefined)||(!senderEmail.length)){ return callback(returnError('Empty email')); } sendRequest( 'senders/' + senderEmail + '/code', 'GET', {}, true, callback ); }
javascript
{ "resource": "" }
q63833
getEmailGlobalInfo
test
function getEmailGlobalInfo(callback, email) { if ((email===undefined)||(!email.length)){ return callback(returnError('Empty email')); } sendRequest( 'emails/' + email, 'GET', {}, true, callback ); }
javascript
{ "resource": "" }
q63834
removeEmailFromAllBooks
test
function removeEmailFromAllBooks(callback, email){ if ((email===undefined)||(!email.length)){ return callback(returnError('Empty email')); } sendRequest( 'emails/' + email, 'DELETE', {}, true, callback ); }
javascript
{ "resource": "" }
q63835
emailStatByCampaigns
test
function emailStatByCampaigns(callback,email) { if ((email===undefined)||(!email.length)){ return callback(returnError('Empty email')); } sendRequest( 'emails/' + email + '/campaigns', 'GET', {}, true, callback ); }
javascript
{ "resource": "" }
q63836
addToBlackList
test
function addToBlackList(callback, emails, comment){ if ((emails===undefined)||(!emails.length)){ return callback(returnError('Empty email')); } if (comment === undefined) { comment = ''; } var data = { emails: base64(emails), comment: comment } sendRequest( 'blacklist', 'POST', data, true, callback ); }
javascript
{ "resource": "" }
q63837
removeFromBlackList
test
function removeFromBlackList(callback, emails){ if ((emails===undefined)||(!emails.length)){ return callback(returnError('Empty emails')); } var data = { emails: base64(emails), } sendRequest( 'blacklist', 'DELETE', data, true, callback ); }
javascript
{ "resource": "" }
q63838
smtpGetEmailInfoById
test
function smtpGetEmailInfoById(callback,id){ if ((id===undefined)||(! id.length)) { return callback(returnError('Empty id')); } sendRequest( 'smtp/emails/' + id, 'GET', {}, true, callback ); }
javascript
{ "resource": "" }
q63839
minifyFile
test
function minifyFile(resHtml, outputPath) { var resHtml = minify(resHtml, opt, function (err) { if (err) { console.error('error will processing file.'); } }); console.log(''); console.log('Output file name : ' + outputPath); console.log(''); writeFile(resHtml, outputPath); }
javascript
{ "resource": "" }
q63840
writeFile
test
function writeFile(resHtml, outputPath) { fs.writeFile(outputPath, resHtml, function (err) { if (err) { console.log(''); console.log('File error: ' + err + '. Exit.'); } else { console.log(''); console.log('All done. Exit.'.green); } }); }
javascript
{ "resource": "" }
q63841
Cookie
test
function Cookie(options) { this.options = options || {}; this.options.expires = typeof this.options.expires === 'number' ? this.options.expires : 30; this.options.path = this.options.path !== undefined ? this.options.path : '/'; this.options.secure = typeof this.options.secure === 'boolean' ? this.options.secure : false; }
javascript
{ "resource": "" }
q63842
set
test
function set(key, value, options) { options = options || this.options; var days = parseInt(options.expires || -1); if(value !== undefined && typeof value !== 'function') { var t = new Date(); t.setDate((t.getDate() + days)); var res = (document.cookie = [ this.encode(key), '=', this.stringify(value), // use expires attribute, max-age is not supported by IE options.expires ? '; expires=' + t.toUTCString() : '', options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); return res; } }
javascript
{ "resource": "" }
q63843
get
test
function get(key, value) { var i, parts, name, cookie; var result = key ? undefined : {}; /* istanbul ignore next */ var cookies = (document.cookie || '').split('; '); for (i = 0; i < cookies.length; i++) { parts = cookies[i].split('='); name = this.decode(parts.shift()); cookie = parts.join('='); if (key && key === name) { // if second argument (value) is a function it's a converter result = this.read(cookie, value); break; } // prevent storing a cookie that we couldn't decode if (!key && (cookie = this.read(cookie)) !== undefined) { result[name] = cookie; } } return result; }
javascript
{ "resource": "" }
q63844
del
test
function del(key, options) { if(!options) { options = {}; for(var z in this.options) { options[z] = this.options[z]; } } options.expires = -1; this.set(key, '', options); }
javascript
{ "resource": "" }
q63845
clear
test
function clear(except, options) { var keys = this.get(), z; except = except || []; for(z in keys) { if(~except.indexOf(z)) { continue; } this.del(z, options); } }
javascript
{ "resource": "" }
q63846
curry2
test
function curry2 (fn, self) { var out = function () { if (arguments.length === 0) return out return arguments.length > 1 ? fn.apply(self, arguments) : bind.call(fn, self, arguments[0]) } out.uncurry = function uncurry () { return fn } return out }
javascript
{ "resource": "" }
q63847
cloneGalleryItem
test
function cloneGalleryItem(inst, element) { // Clone the element const clone = element.cloneNode(true) // Remove id attribute to avoid unwanted duplicates clone.removeAttribute('id') // Add a helper class clone.classList.add('mh-gallery-item--sort-helper') return clone }
javascript
{ "resource": "" }
q63848
test
function (localFilePath) { let contentType = mime.lookup(localFilePath); let standerFilePath = localFilePath.replace(/\\/g, '/'); fs.readFile(localFilePath, function (readFileErr, fileData) { if (readFileErr) { throw readFileErr; } const putConfig = { Bucket: bucket.Name, Body: fileData, Key: standerFilePath, ContentType: contentType, AccessControlAllowOrigin: options.AccessControlAllowOrigin || '*', CacheControl: options.CacheControl || 'no-cache', Expires: options.Expires || null }; if (options.contentEncoding) { putConfig.ContentEncoding = options.contentEncoding; } oss.putObject(putConfig, function (putObjectErr) { if (putObjectErr) { console.error('error:', putObjectErr); return putObjectErr; } console.log('upload success: ' + localFilePath); if (bucketPaths.indexOf(standerFilePath) === -1) { bucketPaths.push(standerFilePath); } if (localPaths.indexOf(standerFilePath) === -1) { localPaths.push(standerFilePath); } //refresh cdn if (options.oss.autoRefreshCDN && cdn) { if (options.cdn.refreshQuota < 1) { console.error('There is no refresh cdn url quota today.'); return; } let cdnDomain = ''; if (/^http/.test(options.cdn.domain)) { cdnDomain = options.cdn.domain.replace(/^https?:?\/?\/?/, ''); options.cdn.secure === undefined && (options.cdn.secure = /^https/.test(options.cdn.domein)); } else { cdnDomain = options.cdn.domain; } let cdnObjectPath = url.format({ protocol: options.oss.secure ? 'https' : 'http', hostname: cdnDomain, pathname: standerFilePath }); options.debug && console.log('Refreshing CDN file: ', cdnObjectPath); cdn.refreshObjectCaches({ ObjectType: 'File', ObjectPath: cdnObjectPath }, function (refreshCDNErr) { if (refreshCDNErr) { console.error('refresh cdn error: ', refreshCDNErr); } else { options.cdn.refreshQuota--; console.log('Refresh cdn file success: ', cdnObjectPath); } }); } }); }); }
javascript
{ "resource": "" }
q63849
test
function (filePath) { let standerPath = filePath.replace(/\\/g, '/'); oss.deleteObject({ Bucket: bucket.Name, Key: standerPath }, function (err) { if (err) { console.log('error:', err); return err; } let bucketIndex = bucketPaths.indexOf(standerPath); if (bucketIndex !== -1) { bucketPaths.splice(bucketIndex, 1); } let localIndex = localPaths.indexOf(standerPath); if (localIndex !== -1) { localPaths.splice(localIndex, 1); } console.log('delete success:' + standerPath); }); }
javascript
{ "resource": "" }
q63850
setupDispatch
test
function setupDispatch ({ actions: actionHandlers = {}, schemas = {}, services = {}, middlewares = [], identOptions = {} }) { const getService = setupGetService(schemas, services) let dispatch = async (action) => { debug('Dispatch: %o', action) return handleAction( action, { schemas, services, dispatch, identOptions, getService }, actionHandlers ) } if (middlewares.length > 0) { dispatch = compose(...middlewares)(dispatch) } return dispatch }
javascript
{ "resource": "" }
q63851
nextSchedule
test
function nextSchedule (schedule, allowNow = false) { if (schedule) { try { const dates = later.schedule(schedule).next(2) return nextDate(dates, allowNow) } catch (error) { throw TypeError('Invalid schedule definition') } } return null }
javascript
{ "resource": "" }
q63852
deleteFn
test
async function deleteFn (action, { getService } = {}) { debug('Action: DELETE') const { type, id, service: serviceId, endpoint } = action.payload const service = (typeof getService === 'function') ? getService(type, serviceId) : null if (!service) { return createUnknownServiceError(type, serviceId, 'DELETE') } const data = prepareData(action.payload) if (data.length === 0) { return createError(`No items to delete from service '${service.id}'`, 'noaction') } const endpointDebug = (endpoint) ? `endpoint '${endpoint}'` : `endpoint matching ${type} and ${id}` debug('DELETE: Delete from service \'%s\' at %s.', service.id, endpointDebug) const { response } = await service.send(appendToAction(action, { data })) return (response.status === 'ok') ? { status: 'ok' } : response }
javascript
{ "resource": "" }
q63853
request
test
async function request (action, { getService, dispatch }) { debug('Action: REQUEST') const { type, service: serviceId = null, endpoint } = action.payload const service = getService(type, serviceId) if (!service) { return createUnknownServiceError(type, serviceId, 'GET') } const endpointDebug = (endpoint) ? `endpoint '${endpoint}'` : `endpoint matching type '${type}'` debug('REQUEST: Fetch from service %s at %s', service.id, endpointDebug) const { response } = await service.receive(action, dispatch) return response }
javascript
{ "resource": "" }
q63854
getIdent
test
async function getIdent ({ payload, meta }, { getService, identOptions = {} }) { if (!meta.ident) { return createError('GET_IDENT: The request has no ident', 'noaction') } const { type } = identOptions if (!type) { return createError('GET_IDENT: Integreat is not set up with authentication', 'noaction') } const service = getService(type) if (!service) { return createUnknownServiceError(type, null, 'GET_IDENT') } const propKeys = preparePropKeys(identOptions.props) const params = prepareParams(meta.ident, propKeys) if (!params) { return createError('GET_IDENT: The request has no ident with id or withToken', 'noaction') } const { response } = await service.send({ type: 'GET', payload: { type, ...params }, meta: { ident: { root: true } } }) return prepareResponse(response, payload, propKeys) }
javascript
{ "resource": "" }
q63855
integreat
test
function integreat ( { schemas: typeDefs, services: serviceDefs, mappings = [], auths: authDefs = [], ident: identOptions = {} }, { adapters = {}, authenticators = {}, filters = {}, transformers = {}, actions = {} } = {}, middlewares = [] ) { if (!serviceDefs || !typeDefs) { throw new TypeError('Call integreat with at least services and schemas') } // Merge custom actions with built-in actions actions = { ...builtinActions, ...actions } // Setup schemas object from type defs const schemas = R.compose( R.indexBy(R.prop('id')), R.map(schema) )(typeDefs) const pluralTypes = Object.keys(schemas) .reduce((plurals, type) => ({ ...plurals, [schemas[type].plural]: type }), {}) // Setup auths object from auth defs const auths = authDefs .reduce((auths, def) => (def) ? { ...auths, [def.id]: { authenticator: authenticators[def && def.authenticator], options: def.options, authentication: null } } : auths, {}) // Setup services object from service defs. const services = R.compose( R.indexBy(R.prop('id')), R.map(createService({ adapters, auths, transformers, schemas, setupMapping: setupMapping({ filters, transformers, schemas, mappings }) })) )(serviceDefs) // Return Integreat instance return { version, schemas, services, identType: identOptions.type, /** * Function for dispatching actions to Integreat. Will be run through the * chain of middlewares before the relevant action handler is called. * @param {Object} action - The action to dispatch * @returns {Promise} Promise of result object */ dispatch: setupDispatch({ actions, services, schemas, middlewares, identOptions }), /** * Adds the `listener` function to the service's emitter for events with the * given `eventName` name. */ on (eventName, serviceId, listener) { const service = services[serviceId] if (service && service.on) { service.on(eventName, listener) } }, /** * Return schema type from its plural form. */ typeFromPlural (plural) { return pluralTypes[plural] } } }
javascript
{ "resource": "" }
q63856
scheduleToAction
test
function scheduleToAction (def) { if (!def) { return null } const id = def.id || null const schedule = parseSchedule(def.schedule) const nextTime = nextSchedule(schedule, true) return { ...def.action, meta: { id, schedule, queue: (nextTime) ? nextTime.getTime() : true } } }
javascript
{ "resource": "" }
q63857
get
test
async function get (action, { getService } = {}) { const { type, service: serviceId = null, onlyMappedValues = false, endpoint } = action.payload const service = (typeof getService === 'function') ? getService(type, serviceId) : null if (!service) { return createUnknownServiceError(type, serviceId, 'GET') } const id = getIdFromPayload(action.payload) // Do individual gets for array of ids, if there is no collection scoped endpoint if (Array.isArray(id) && !hasCollectionEndpoint(service.endpoints)) { return getIndividualItems(id, action, getService) } const endpointDebug = (endpoint) ? `endpoint '${endpoint}'` : `endpoint matching type '${type}' and id '${id}'` debug('GET: Fetch from service %s at %s', service.id, endpointDebug) const { response } = await service.send(appendToAction(action, { id, onlyMappedValues })) return response }
javascript
{ "resource": "" }
q63858
sendRequest
test
function sendRequest ({ adapter, serviceId }) { return async ({ request, response, connection }) => { if (response) { return response } try { response = await adapter.send(request, connection) return { ...response, access: request.access } } catch (error) { return createError(`Error retrieving from service '${serviceId}'. ${error}`) } } }
javascript
{ "resource": "" }
q63859
schema
test
function schema ({ id, plural, service, attributes: attrDefs, relationships: relDefs, access, internal = false }) { const attributes = { ...expandFields(attrDefs || {}), id: { type: 'string' }, type: { type: 'string' }, createdAt: { type: 'date' }, updatedAt: { type: 'date' } } const relationships = expandFields(relDefs || {}) const defaultAttrs = prepareDefaultAttrs(attributes, attrDefs) const defaultRels = prepareDefaultRels(relationships, relDefs) const castFn = cast({ id, attributes, relationships, defaultAttrs, defaultRels }) return { id, plural: plural || `${id}s`, service, internal, attributes, relationships, access, /** * Will cast the given data according to the type. Attributes will be * coerced to the right format, relationships will be expanded to * relationship objects, and object properties will be moved from * `attributes` or be set with defaults. * @param {Object} data - The data to cast * @param {boolean} onlyMappedValues - Will use defaults if true * @returns {Object} Returned data in the format expected from the schema */ cast (data, { onlyMappedValues = false } = {}) { return mapAny((data) => castFn(data, { onlyMappedValues }), data) }, /** * Will create a query object for a relationship, given the relationship id * and a data item to get field values from. * * If the relationship is set up with a query definition object, each prop * of this object references field ids in the given data item. The returned * query object will have these ids replaced with actual field values. * * @param {string} relId - The id of a relationship * @param {Object} data - A data item to get field values from. * @returns {Object} Query object */ castQueryParams (relId, data) { return castQueryParams(relId, data, { relationships }) } } }
javascript
{ "resource": "" }
q63860
mapping
test
function mapping ({ filters, transformers, schemas = {}, mappings: mappingsArr = [] } = {}) { const mappings = mappingsArr.reduce( (mappings, def) => ({ ...mappings, [def.id]: def }), {} ) const createPipelineFn = createPipeline(filters, transformers, schemas, mappings) return (mapping, overrideType) => { const { id, type, schema, pipeline } = createPipelineFn(mapping, overrideType) if (!pipeline) { return null } const mapper = mapTransform([ fwd('data'), ...pipeline, rev(set('data')) ]) return { id, type, schema, /** * Map data from a service with attributes and relationships. * @param {Object} data - The service item to map from * @param {Object} options - onlyMappedValues * @returns {Object} Target item */ fromService (data, { onlyMappedValues = true } = {}) { return data ? ensureArray( (onlyMappedValues) ? mapper.onlyMappedValues(data) : mapper(data) ) : [] }, /** * Map data to a service with attributes and relationships. * @param {Object} data - The data item to map * @param {Object} target - Optional object to map to data on * @returns {Object} Mapped data */ toService (data, target = null) { const mapped = mapper.rev.onlyMappedValues(data) return ( (target ? Array.isArray(target) ? [...target].concat(mapped) : mergeDeepWith(concatOrRight, target, mapped) : mapped) || null ) } } } }
javascript
{ "resource": "" }
q63861
mapFromService
test
function mapFromService () { return ({ response, request, responseMapper, mappings }) => { if (response.status !== 'ok') { return response } const type = request.params.type || Object.keys(mappings) const { onlyMappedValues, unmapped = false } = request.params if (unmapped) { return response } const { data, status = response.status, error, paging, params } = mapWithEndpoint(responseMapper, response, request.action) if (status !== 'ok') { return removeDataProp({ ...response, status, error }) } const mapType = (type) => (mappings[type]) ? mappings[type].fromService({ ...request, data }, { onlyMappedValues }) : [] return { ...response, status, ...((paging) ? { paging } : {}), ...((params) ? { params } : {}), data: (data) ? flatten(mapAny(mapType, type)) : undefined } } }
javascript
{ "resource": "" }
q63862
test
function(tailInfo){ var z = this; if(tailInfo) { z.q.push(tailInfo); } var ti; //for all changed fds fire readStream for(var i = 0;i < z.q.length;++i) { ti = z.q[i]; if(ti.reading) { //still reading file continue; } if (!z.tails[ti.stat.ino]) { //remove timed out file tail from q z.q.splice(i,1); --i; continue; } //truncated if(ti.stat.size < ti.pos) { ti.pos = 0; } var len = ti.stat.size-ti.pos; //remove from queue because im doing this work. z.q.splice(i,1); --i; z.readTail(ti,len); } }
javascript
{ "resource": "" }
q63863
test
function(){ var z = this; var l = 0; Object.keys(z.tails).forEach(function(k) { l += (z.tails[k].buf||'').length; }); return l; }
javascript
{ "resource": "" }
q63864
preparePipeline
test
function preparePipeline (pipeline, collection = {}) { pipeline = [].concat(pipeline) const replaceWithFunction = (key) => (typeof key === 'string') ? collection[key] : key const isFunctionOrObject = (obj) => obj && ['function', 'object'].includes(typeof obj) return pipeline .map(replaceWithFunction) .filter(isFunctionOrObject) }
javascript
{ "resource": "" }
q63865
castQueryParams
test
function castQueryParams (relId, data, { relationships }) { const relationship = relationships[relId] if (!relationship.query) { return {} } return Object.keys(relationship.query) .reduce((params, key) => { const value = getField(data, relationship.query[key]) if (value === undefined) { throw new TypeError('Missing value for query param') } return { ...params, [key]: value } }, {}) }
javascript
{ "resource": "" }
q63866
setupQueue
test
function setupQueue (queue) { let dispatch = null let subscribed = false return { queue, /** * Set dispatch function to use for dequeuing */ setDispatch (dispatchFn) { dispatch = dispatchFn if (!subscribed && typeof dispatch === 'function') { queue.subscribe(dispatch) subscribed = true } }, /** * Middleware interface for Integreat. Will push queuable actions to queue, * and pass the rest on to the next() function. * * @param {function} next - The next middleware * @returns {Object} A response object */ middleware (next) { return middleware(next, queue) }, /** * Schedule actions from the given defs. * Actions are enqueued with a timestamp, and are ran at the * set time. * @param {array} defs - An array of schedule definitions * @returns {array} Array of returned responses */ async schedule (defs) { return schedule(defs, queue) } } }
javascript
{ "resource": "" }
q63867
getMeta
test
async function getMeta ({ payload, meta }, { getService }) { debug('Action: GET_META') const { service: serviceId, endpoint, keys } = payload const id = `meta:${serviceId}` const service = getService(null, serviceId) if (!service) { debug(`GET_META: Service '${serviceId}' doesn't exist`) return createError(`Service '${serviceId}' doesn't exist`) } const type = service.meta const metaService = getService(type) if (!metaService) { return createError(`Service '${service.id}' doesn't support metadata (setting was '${service.meta}')`) } const endpointDebug = (endpoint) ? `endpoint '${endpoint}'` : `endpoint matching ${type} and ${id}` debug('GET_META: Get meta %s for service \'%s\' on service \'%s\' at %s', keys, service.id, metaService.id, endpointDebug) const { response } = await metaService.send({ type: 'GET', payload: { keys, type, id, endpoint }, meta: { ident: meta.ident } }) if (response.status === 'ok') { const { data } = response const meta = prepareMeta(keys, data[0].attributes) return { ...response, data: { service: serviceId, meta } } } else { return response } }
javascript
{ "resource": "" }
q63868
set
test
async function set (action, { getService, schemas }) { debug('Action: SET') const { service: serviceId, data, endpoint, onlyMappedValues = true } = action.payload const type = extractType(action, data) const id = extractId(data) const service = getService(type, serviceId) if (!service) { return createUnknownServiceError(type, serviceId, 'SET') } const endpointDebug = (endpoint) ? `at endpoint '${endpoint}'` : '' debug('SET: Send to service %s %s', service.id, endpointDebug) const { response, authorizedRequestData } = await service.send(appendToAction(action, { id, type, onlyMappedValues })) return mergeRequestAndResponseData(response, authorizedRequestData) }
javascript
{ "resource": "" }
q63869
setMeta
test
async function setMeta ({ payload, meta }, { getService }) { debug('Action: SET_META') const { service: serviceId, meta: metaAttrs, endpoint } = payload const id = `meta:${serviceId}` const service = getService(null, serviceId) if (!service) { debug(`SET_META: Service '${serviceId}' doesn't exist`) return createError(`Service '${serviceId}' doesn't exist`) } const type = service.meta const metaService = getService(type) if (!metaService) { debug(`SET_META: Service '${service.id}' doesn't support metadata (setting was '${service.meta}')`) return { status: 'noaction' } } const endpointDebug = (endpoint) ? `endpoint '${endpoint}'` : `endpoint matching ${type} and ${id}` debug('SET_META: Send metadata %o for service \'%s\' on service \'%s\' %s', metaAttrs, service.id, metaService.id, endpointDebug) const data = { id, type, attributes: metaAttrs } const { response } = await metaService.send({ type: 'SET', payload: { keys: Object.keys(metaAttrs), type, id, data, endpoint, onlyMappedValues: true }, meta: { ident: meta.ident } }) return response }
javascript
{ "resource": "" }
q63870
exportToJSONSchema
test
function exportToJSONSchema(expSpecifications, baseSchemaURL, baseTypeURL, flat = false) { const namespaceResults = {}; const endOfTypeURL = baseTypeURL[baseTypeURL.length - 1]; if (endOfTypeURL !== '#' && endOfTypeURL !== '/') { baseTypeURL += '/'; } for (const ns of expSpecifications.namespaces.all) { const lastLogger = logger; logger = logger.child({ shrId: ns.namespace}); try { logger.debug('Exporting namespace.'); if (flat) { const { schemaId, schema } = flatNamespaceToSchema(ns, expSpecifications.dataElements, baseSchemaURL, baseTypeURL); namespaceResults[schemaId] = schema; } else { const { schemaId, schema } = namespaceToSchema(ns, expSpecifications.dataElements, baseSchemaURL, baseTypeURL); namespaceResults[schemaId] = schema; } logger.debug('Finished exporting namespace.'); } finally { logger = lastLogger; } } return namespaceResults; }
javascript
{ "resource": "" }
q63871
makeRef
test
function makeRef(id, enclosingNamespace, baseSchemaURL) { if (id.namespace === enclosingNamespace.namespace) { return '#/definitions/' + id.name; } else { return makeShrDefinitionURL(id, baseSchemaURL); } }
javascript
{ "resource": "" }
q63872
isOrWasAList
test
function isOrWasAList(value) { if (value.card.isList) { return true; } const cardConstraints = value.constraintsFilter.own.card.constraints; return cardConstraints.some((oneCard) => oneCard.isList); }
javascript
{ "resource": "" }
q63873
findOptionInChoice
test
function findOptionInChoice(choice, optionId, dataElementSpecs) { // First look for a direct match for (const option of choice.aggregateOptions) { if (optionId.equals(option.identifier)) { return option; } } // Then look for a match on one of the selected options's base types // E.g., if choice has Quantity but selected option is IntegerQuantity for (const option of choice.aggregateOptions) { if (checkHasBaseType(optionId, option.identifier, dataElementSpecs)) { return option; } } return null; }
javascript
{ "resource": "" }
q63874
supportsCodeConstraint
test
function supportsCodeConstraint(identifier, dataElementSpecs) { if (CODE.equals(identifier) || checkHasBaseType(identifier, new Identifier('shr.core', 'Coding'), dataElementSpecs) || checkHasBaseType(identifier, new Identifier('shr.core', 'CodeableConcept'), dataElementSpecs)) { return true; } const element = dataElementSpecs.findByIdentifier(identifier); if (element.value) { if (element.value instanceof IdentifiableValue) { return CODE.equals(element.value.identifier) || checkHasBaseType(element.value.identifier, new Identifier('shr.core', 'Coding'), dataElementSpecs) || checkHasBaseType(element.value.identifier, new Identifier('shr.core', 'CodeableConcept'), dataElementSpecs); } else if (element.value instanceof ChoiceValue) { for (const value of element.value.aggregateOptions) { if (value instanceof IdentifiableValue) { if (CODE.equals(value.identifier) || checkHasBaseType(value.identifier, new Identifier('shr.core', 'Coding'), dataElementSpecs) || checkHasBaseType(value.identifier, new Identifier('shr.core', 'CodeableConcept'), dataElementSpecs)) { return true; } } } } } return false; }
javascript
{ "resource": "" }
q63875
expire
test
async function expire ({ payload, meta = {} }, { dispatch }) { const { service } = payload const { ident } = meta if (!service) { return createError(`Can't delete expired without a specified service`) } if (!payload.endpoint) { return createError(`Can't delete expired from service '${service}' without an endpoint`) } if (!payload.type) { return createError(`Can't delete expired from service '${service}' without one or more specified types`) } const response = await getExpired(payload, ident, dispatch) return deleteExpired(response, service, ident, dispatch) }
javascript
{ "resource": "" }
q63876
transformRange
test
function transformRange(range, ops) { var rangeComps = range.split(':') , newRange var start = rangeComps[0] ops.forEach(op => start = transformRangeAnchor(start, op, /*isStart:*/true)) var end = rangeComps[1] ops.forEach(op => end = transformRangeAnchor(end, op, /*isStart:*/false)) if (start === end) return start return start+':'+end }
javascript
{ "resource": "" }
q63877
transformRangeAnchor
test
function transformRangeAnchor(target, op, isStart) { var thisCell = parseCell(target) if (op instanceof InsertCol) { var otherCell = parseCell(op.newCol) if (otherCell[0] <= thisCell[0]) return column.fromInt(thisCell[0]+1)+thisCell[1] } else if (op instanceof DeleteCol) { var otherCell = parseCell(op.col) if (otherCell[0] < thisCell[0]) return column.fromInt(thisCell[0]-1)+thisCell[1] if (otherCell[0] === thisCell[0]) { // Spreadsheet selection is different from text selection: // While text selection ends in the first *not* selected char ( "foo| |bar" => 3,4) // ... spreadsheet selection ends in the last selected cell. Thus we need to // differentiate between start and end. Shame on those who didn't think about this! if (!isStart) return column.fromInt(thisCell[0]-1)+thisCell[1] } } else if (op instanceof InsertRow) { var otherCell = parseCell(op.newRow) if (otherCell[1] <= thisCell[1]) return column.fromInt(thisCell[0])+(thisCell[1]+1) } else if (op instanceof DeleteRow) { var otherCell = parseCell(op.col) if (otherCell[1] < thisCell[1]) return column.fromInt(thisCell[0])+(thisCell[1]-1) if (otherCell[1] === thisCell[1]) { if (!isStart) return column.fromInt(thisCell[0])+(thisCell[1]-1) } } // If nothing has returned already then this anchor doesn't change return target }
javascript
{ "resource": "" }
q63878
matchEndpoint
test
function matchEndpoint (endpoints) { return ({ type, payload, meta }) => endpoints .find((endpoint) => matchId(endpoint, { type, payload }) && matchType(endpoint, { type, payload }) && matchScope(endpoint, { type, payload }) && matchAction(endpoint, { type, payload }) && matchParams(endpoint, { type, payload }) && matchFilters(endpoint, { type, payload, meta })) }
javascript
{ "resource": "" }
q63879
createAction
test
function createAction (type, payload = {}, meta) { if (!type) { return null } const action = { type, payload } if (meta) { action.meta = meta } return action }
javascript
{ "resource": "" }
q63880
authorizeRequest
test
function authorizeRequest ({ schemas }) { return ({ request }) => { const { access = {}, params = {}, action } = request const { ident = null } = access if (ident && ident.root) { return authItemsAndWrap(request, { status: 'granted', ident, scheme: 'root' }, schemas) } if (!params.type) { return authItemsAndWrap(request, { status: 'granted', ident, scheme: null }, schemas) } const requireAuth = !!request.auth const schema = schemas[params.type] const scheme = getScheme(schema, action) const status = (doAuth(scheme, ident, requireAuth)) ? 'granted' : 'refused' return authItemsAndWrap(request, { status, ident, scheme }, schemas) } }
javascript
{ "resource": "" }
q63881
requestFromAction
test
function requestFromAction ( { type: action, payload, meta = {} }, { endpoint, schemas = {} } = {} ) { const { data, ...params } = payload const { ident = null } = meta const typePlural = getPluralType(params.type, schemas) return { action, params, data, endpoint: (endpoint && endpoint.options) || null, access: { ident }, meta: { typePlural } } }
javascript
{ "resource": "" }
q63882
getService
test
function getService (schemas, services) { return (type, service) => { if (!service && schemas[type]) { service = schemas[type].service } return services[service] || null } }
javascript
{ "resource": "" }
q63883
sync
test
async function sync ({ payload, meta = {} }, { dispatch }) { debug('Action: SYNC') const fromParams = await generateFromParams(payload, meta, dispatch) const toParams = generateToParams(payload, fromParams) const lastSyncedAt = new Date() const results = await Promise.all( fromParams.map(getFromService(dispatch, payload.type, meta)) ) if (results.some((result) => result.status !== 'ok')) { return (results.length === 1) ? results[0] : createError(makeErrorString(results)) } const data = flatten(results.map((result) => result.data)).filter(Boolean) if (data.length === 0 && payload.syncNoData !== true) { return createError(`No items to update from service '${fromParams[0].service}'`, 'noaction') } return Promise.all([ ...createSetMetas(fromParams, lastSyncedAt, meta.ident, dispatch), dispatch(action('SET', { data, ...toParams }, { ...meta, queue: true })) ]) .then((responses) => { return { status: 'ok', data: responses } }) }
javascript
{ "resource": "" }
q63884
test
function (gulp, cwd, config) { if (util.isNullOrUndefined(gulp)) { throw 'gulp must be defined'; } /** * Configuration options that will be injected into every gulp task. * * @type {Object} */ this._config = config || {}, /** * Current working directory that path calculations should be relative to. * * @type {String} */ this._cwd = cwd || __dirname; /** * Actual path of this file relative to the defined working directory. * * @type {String} */ this._root = path.relative(this._cwd, __dirname); /** * Gulp instance. All tasks get injected the same gulp instances. * * @type {Gulp} */ this._gulp = gulp; }
javascript
{ "resource": "" }
q63885
test
function(bg) { bg = bg ? bg : false return (...args) => { return this.output(args.join(' '), this.colors(bg)) } }
javascript
{ "resource": "" }
q63886
test
function (browserify, name, source) { if (utility.isNullOrUndefined(browserify)) { throw 'browserify must be defined.'; } if (!utility.isNonEmptyString(name)) { throw 'name must be defined.'; } if (utility.isNullOrUndefined(source)) { throw 'source must be defined.'; } this._browserify = browserify; this._name = name; this._source = source; this._hasModule = false; this._hasResolver = false; }
javascript
{ "resource": "" }
q63887
mapToService
test
function mapToService () { return ({ request, requestMapper, mappings }) => { const data = mapData(request.data, request, mappings) return { ...request, data: applyEndpointMapper(data, request, requestMapper) } } }
javascript
{ "resource": "" }
q63888
processMessengerBody
test
async function processMessengerBody (body, context) { const allMessages = getAllMessages(body) if (!allMessages || !allMessages.length) return false context = context || {} for (let message of allMessages) { message = _.cloneDeep(message) const messageContext = Object.assign({}, context) try { for (let plugin of middleware) { await plugin(message, messageContext) } } catch (error) { const logError = (messageContext.log && messageContext.log.error instanceof Function) ? messageContext.log.error : console.error logError('Error running middleware', error) } } return true }
javascript
{ "resource": "" }
q63889
create
test
function create(prop) { if (typeof prop !== 'string') { throw new Error('expected the first argument to be a string.'); } return function(app) { if (this.isRegistered('base-' + prop)) return; // map config var config = utils.mapper(app) // store/data .map('store', store(app.store)) .map('data') // options .map('enable') .map('disable') .map('option') .alias('options', 'option') // get/set .map('set') .map('del') // Expose `prop` (config) on the instance app.define(prop, proxy(config)); // Expose `process` on app[prop] app[prop].process = config.process; }; function store(app) { if (!app) return {}; var mapper = utils.mapper(app); app.define(prop, proxy(mapper)); return mapper; } }
javascript
{ "resource": "" }
q63890
ElementMatrix
test
function ElementMatrix(top) { CommanalityMatrix.call(this, top); this.row(' '); this.collum(' '); this.classlist = top.root.classlist; }
javascript
{ "resource": "" }
q63891
publicS3URI
test
function publicS3URI(string) { return encodeURIComponent(string) .replace(/%20/img, '+') .replace(/%2F/img, '/') .replace(/\"/img, "%22") .replace(/\#/img, "%23") .replace(/\$/img, "%24") .replace(/\&/img, "%26") .replace(/\'/img, "%27") .replace(/\(/img, "%28") .replace(/\)/img, "%29") .replace(/\,/img, "%2C") .replace(/\:/img, "%3A") .replace(/\;/img, "%3B") .replace(/\=/img, "%3D") .replace(/\?/img, "%3F") .replace(/\@/img, "%40"); }
javascript
{ "resource": "" }
q63892
test
function (done) { fs.writeFile( path.resolve(__dirname, '../../test/reallife/expected/' + item.key + '.json'), JSON.stringify({ 'title': item.title, 'text': item.text }, null, '\t') + '\n', done ); }
javascript
{ "resource": "" }
q63893
test
function (done) { fs.writeFile( path.resolve(__dirname, '../../test/reallife/source/' + item.key + '.html'), SOURCES[item.key], done ); }
javascript
{ "resource": "" }
q63894
test
function (done) { datamap[item.index].labeled = true; fs.writeFile( path.resolve(__dirname, '../../test/reallife/datamap.json'), JSON.stringify(datamap, null, '\t') + '\n', done ); }
javascript
{ "resource": "" }
q63895
Node
test
function Node(type, parent) { this.type = type; this.parent = parent; this.root = parent ? parent.root : this; this.identifyer = parent ? (++parent.root._counter) : 0; // The specific constructor will set another value if necessary this._textLength = 0; this.tags = 0; this.density = -1; this.children = []; this._text = ''; this._textCompiled = false; this._noneStyleText = ''; this._noneStyleTextCompiled = false; this.blocky = false; this.blockyChildren = false; this.inTree = true; }
javascript
{ "resource": "" }
q63896
TextNode
test
function TextNode(parent, text) { Node.call(this, 'text', parent); // A text node has no children instead it has a text container this.children = null; this._text = text; this._noneStyleText = text; }
javascript
{ "resource": "" }
q63897
ElementNode
test
function ElementNode(parent, tagname, attributes) { Node.call(this, 'element', parent); // Since this is an element there will minimum one tag this.tags = (tagname === 'br' || tagname === 'wbr') ? 0 : 1; // Element nodes also has a tagname and an attribute collection this.tagname = tagname; this.attr = attributes; this.classes = attributes.hasOwnProperty('class') ? attributes['class'].trim().split(WHITE_SPACE) : []; // Add node to the classlist this.root.classlist.addNode(this); this._blockySelfCache = domHelpers.BLOCK_ELEMENTS.hasOwnProperty(tagname); this._countTagnames = {}; }
javascript
{ "resource": "" }
q63898
test
function () { var r; // Recall as new if new isn't provided :) if( Util.isnt.instanceof( NewClass, this ) ) { return ClassUtil.construct( NewClass, arguments ); } // call the constructor if ( Util.is.Function( this.initialize ) ) { r = this.initialize.apply(this, arguments); } // call all constructor hooks this.callInitHooks(); return typeof r != 'undefined' ? r : this; }
javascript
{ "resource": "" }
q63899
distribute
test
function distribute(filename, content){ content = content; fs.appendFile(filename, content + "\n"); log(rulecount + ': Append to ' + filename + ' -> ' + content); }
javascript
{ "resource": "" }