_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q9500
|
queryCoversRange
|
train
|
function queryCoversRange(lessRestrictive, moreRestrictive) {
// Short curcuit if there is an exact match
if (lessRestrictive === moreRestrictive) {
return true;
}
const lessRestrictiveParts = explodeMediaQuery(lessRestrictive);
const moreRestrictiveParts = explodeMediaQuery(moreRestrictive);
return lessRestrictiveParts.reduce((orPrevious, lessAndParts) => {
// Short curcuit if a previous part was not satisfied
if (!orPrevious) {
return false;
}
return moreRestrictiveParts.reduce((prev, moreAndParts) => {
return (
prev || arrayContainsAllElementsOfArray(lessAndParts, moreAndParts)
);
}, false);
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q9501
|
explodeMediaQuery
|
train
|
function explodeMediaQuery(query) {
return query
.split(',')
.map(part => part.trim())
.map(orSection => orSection.split('and').map(part => part.trim()));
}
|
javascript
|
{
"resource": ""
}
|
q9502
|
arrayContainsAllElementsOfArray
|
train
|
function arrayContainsAllElementsOfArray(smaller, larger) {
return smaller.reduce((prev, element) => {
return prev && larger.indexOf(element) >= 0;
}, true);
}
|
javascript
|
{
"resource": ""
}
|
q9503
|
distributeQueryAcrossQuery
|
train
|
function distributeQueryAcrossQuery(firstQuery, secondQuery) {
const aParts = explodeMediaQuery(firstQuery);
const bParts = explodeMediaQuery(secondQuery);
return aParts
.map(aPart => bParts.map(bPart => `${aPart} and ${bPart}`).join(', '))
.join(', ');
}
|
javascript
|
{
"resource": ""
}
|
q9504
|
Resolver
|
train
|
function Resolver(options) {
if (!(this instanceof Resolver)) {
return new Resolver(options);
}
options = options || {};
if (!isObject(options)) {
throw new Error('options must be an object');
}
this._resolver = new cares.Resolver(options);
if (options.servers) {
this.setServers(options.servers);
}
}
|
javascript
|
{
"resource": ""
}
|
q9505
|
format
|
train
|
function format(input, level, options) {
if (util.isArray(input)) {
return array(input, level, options);
} else if (util.isObject(input)) {
return object(input, level, options);
} else {
return stringify(input, options);
}
}
|
javascript
|
{
"resource": ""
}
|
q9506
|
object
|
train
|
function object(input, level, options) {
var spaces = options.spaces;
var inner = indent(level, spaces);
var outer = indent(level - 1, spaces);
var keys = Object.keys(input);
if (options.sortKeys) keys.sort(naturalSort());
var str = keys.map(function (key) {
return inner
+ stringify(key) + ': '
+ format(input[key], level + 1, options);
}).join(',\n');
return [ '{', str, outer + '}' ].join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q9507
|
array
|
train
|
function array(input, level, options) {
var spaces = options.spaces;
var inner = indent(level, spaces);
var outer = indent(level - 1, spaces);
var str = input
.map(function (value) {
return inner + format(value, level + 1, options);
})
.join(',\n');
return [ '[', str, outer + ']' ].join('\n');
}
|
javascript
|
{
"resource": ""
}
|
q9508
|
outImgToXYZ
|
train
|
function outImgToXYZ(i, j, faceIdx, faceSize) {
var a = 2 * i / faceSize,
b = 2 * j / faceSize;
switch(faceIdx) {
case 0: // back
return({x:-1, y:1-a, z:1-b});
case 1: // left
return({x:a-1, y:-1, z:1-b});
case 2: // front
return({x: 1, y:a-1, z:1-b});
case 3: // right
return({x:1-a, y:1, z:1-b});
case 4: // top
return({x:b-1, y:a-1, z:1});
case 5: // bottom
return({x:1-b, y:a-1, z:-1});
}
}
|
javascript
|
{
"resource": ""
}
|
q9509
|
passId
|
train
|
function passId (trace, i, j) {
let id = (trace.id != null ? trace.id : trace)
let n = i
let m = j
let key = id << 16 | (n & 0xff) << 8 | m & 0xff
return key
}
|
javascript
|
{
"resource": ""
}
|
q9510
|
getBox
|
train
|
function getBox (items, i, j) {
let ilox, iloy, ihix, ihiy, jlox, jloy, jhix, jhiy
let iitem = items[i], jitem = items[j]
if (iitem.length > 2) {
ilox = iitem[0]
ihix = iitem[2]
iloy = iitem[1]
ihiy = iitem[3]
}
else if (iitem.length) {
ilox = iloy = iitem[0]
ihix = ihiy = iitem[1]
}
else {
ilox = iitem.x
iloy = iitem.y
ihix = iitem.x + iitem.width
ihiy = iitem.y + iitem.height
}
if (jitem.length > 2) {
jlox = jitem[0]
jhix = jitem[2]
jloy = jitem[1]
jhiy = jitem[3]
}
else if (jitem.length) {
jlox = jloy = jitem[0]
jhix = jhiy = jitem[1]
}
else {
jlox = jitem.x
jloy = jitem.y
jhix = jitem.x + jitem.width
jhiy = jitem.y + jitem.height
}
return [ jlox, iloy, jhix, ihiy ]
}
|
javascript
|
{
"resource": ""
}
|
q9511
|
train
|
function(opt) {
var vKeys = ["cancelBin", "queueBin", "submitBin"];
var msg = "Missing engine binaries parameters keys \"cancelBin\", \"queueBin\", \"submitBin\"";
for (var k in vKeys)
if (!opt.hasOwnProperty(k))
throw (msg);
engine.configure(opt);
}
|
javascript
|
{
"resource": ""
}
|
|
q9512
|
train
|
function() {
var displayString = '###############################\n' + '###### Current jobs pool ######\n' + '###############################\n';
var c = 0;
for (var key in jobsArray) {;
c++;
displayString += '# ' + key + ' : ' + jobsArray[key].status + '\n';
}
if (c === 0)
displayString += ' EMPTY \n';
console.log(displayString);
return null;
}
|
javascript
|
{
"resource": ""
}
|
|
q9513
|
train
|
function(opt) {
//console.log(opt)
if (isStarted) return;
var self = this;
if (!opt) {
throw "Options required to start manager : \"cacheDir\", \"tcp\", \"port\"";
}
cacheDir = opt.cacheDir + '/' + scheduler_id;
TCPip = opt.tcp;
TCPport = opt.port;
jobProfiles = opt.jobProfiles;
cycleLength = opt.cycleLength ? parseInt(opt.cycleLength) : 5000;
if (opt.hasOwnProperty('forceCache')) {
cacheDir = opt.forceCache;
}
if (opt.hasOwnProperty('probPreviousCacheDir')) {
probPreviousCacheDir = opt.probPreviousCacheDir;
}
if(debugMode)
console.log("Attempting to create cache for process at " + cacheDir);
try {
fs.mkdirSync(cacheDir);
} catch (e) {
if (e.code != 'EEXIST') throw e;
console.log("Cache found already found at " + cacheDir);
}
if(debugMode)
console.log('[' + TCPip + '] opening socket at port ' + TCPport);
var s = _openSocket(TCPport);
data = '';
s.on('listening', function(socket) {
isStarted = true;
if(debugMode) {
console.log("Starting pulse monitoring");
console.log("cache Directory is " + cacheDir);
}
core = setInterval(function() {
_pulse()
}, 500);
warden = setInterval(function() {
self.jobWarden()
}, cycleLength);
console.log(" --->jobManager " + scheduler_id + " ready to process jobs<---\n\n");
eventEmitter.emit("ready");
})
.on('data', _parseMessage);
}
|
javascript
|
{
"resource": ""
}
|
|
q9514
|
serial
|
train
|
function serial(promises) {
const results = [];
return promises
.reduce((chain, promise) =>
chain.then(result => {
results.push(result);
return promise
}), Promise.resolve())
.then(result => {
results.push(result);
results.shift();
return results;
})
}
|
javascript
|
{
"resource": ""
}
|
q9515
|
singleToMulti
|
train
|
function singleToMulti(mapping) {
const newMapping = {};
Object.entries(mapping.mapping).forEach(m => {
newMapping[m[0]] = [m[1]];
});
return {
created: mapping.created,
fields: [mapping.field],
key: mapping.key,
mapping: newMapping
};
}
|
javascript
|
{
"resource": ""
}
|
q9516
|
mappingToTable
|
train
|
function mappingToTable(mapping) {
const mp = mapping.hasOwnProperty('field') ? singleToMulti(mapping) : mapping;
const keyField = {key: mp.key, format: 'text'};
const data = {
fields: [keyField].concat(mp.fields),
records: Object.entries(mp.mapping).map(entry => {
const rcd = {};
rcd[mp.key] = entry[0];
mp.fields.forEach((f, i) => {
rcd[f.key] = entry[1][i];
});
return rcd;
})
};
return data;
}
|
javascript
|
{
"resource": ""
}
|
q9517
|
tableToMapping
|
train
|
function tableToMapping(table, key, ignore=['index']) {
const now = new Date();
const mapping = {
created: now.toString(),
fields: table.fields.filter(e => e.key !== key)
.filter(e => !ignore.includes(e.key)),
key: key,
mapping: {}
};
table.records.forEach(row => {
mapping.mapping[row[key]] = mapping.fields.map(e => row[e.key]);
});
return mapping;
}
|
javascript
|
{
"resource": ""
}
|
q9518
|
csvToMapping
|
train
|
function csvToMapping(csvString) {
const lines = csvString.split(/\n|\r|\r\n/);
const header = lines.shift().split(',');
const key = header.shift();
const now = new Date();
const headerIdx = [];
const fields = [];
header.forEach((h, i) => {
if (h === '') return;
headerIdx.push(i);
fields.push({key: h, format: 'text'});
});
const mapping = {
created: now.toString(),
fields: fields,
key: key,
mapping: {}
};
lines.forEach(line => {
const values = line.split(',');
const k = values.shift();
mapping.mapping[k] = Array(headerIdx.length);
headerIdx.forEach(i => {
mapping.mapping[k][i] = values[i];
});
});
return mapping;
}
|
javascript
|
{
"resource": ""
}
|
q9519
|
train
|
function(milliseconds) {
var formattedDate = '',
self = this,
dateObj = new Date(milliseconds),
format = {
d: function() {
var day = format.j()
return (day < 10) ? '0' + day : day
},
D: function() {
return self.weekdays[format.w()].substring(0, 3)
},
j: function() {
return dateObj.getDate()
},
l: function() {
return self.weekdays[format.w()] + 'day'
},
S: function() {
return self.suffix[format.j()] || 'th'
},
w: function() {
return dateObj.getDay()
},
F: function() {
return self._convertMonthIdx(format.n(), true)
},
m: function() {
var month = format.n() + 1
return (month < 10) ? '0' + month : month
},
M: function() {
return self._convertMonthIdx(format.n(), false)
},
n: function() {
return dateObj.getMonth()
},
Y: function() {
return dateObj.getFullYear()
},
y: function() {
return format.Y().substring(2, 4)
}
},
formatPieces = this.dateFormat.split('')
for(i = 0, x = formatPieces.length; i < x; i++) {
formattedDate += format[formatPieces[i]] ? format[formatPieces[i]]() : formatPieces[i]
}
return formattedDate
}
|
javascript
|
{
"resource": ""
}
|
|
q9520
|
train
|
function(date, full) {
return ((full == true) ? this.months[date] : ((this.months[date].length > 3) ? this.months[date].substring(0, 3) : this.months[date]))
}
|
javascript
|
{
"resource": ""
}
|
|
q9521
|
train
|
function(offset) {
offset = offset || 0
var year = this.year
var monthNum = this.month
monthNum += offset
if(monthNum < 0) { year-- }
if(monthNum > 11) { year++ }
return year
}
|
javascript
|
{
"resource": ""
}
|
|
q9522
|
train
|
function(offset) {
var month = this.getOffsetMonth(offset)
, year = this.getOffsetYear(offset)
// checks to see if february is a leap year otherwise return the respective # of days
return (month == 1 && !(year & 3) && (year % 1e2 || !(year % 4e2))) ? 29 : this.daysInMonth[month]
}
|
javascript
|
{
"resource": ""
}
|
|
q9523
|
train
|
function() {
var html = ''
for(i = 0, x = this.weekdays.length; i < x; i++) {
html += '<th>' + this.weekdays[i].substring(0, 2) + '</th>'
}
return html
}
|
javascript
|
{
"resource": ""
}
|
|
q9524
|
train
|
function(offset) {
var monthNum = this.month
offset = offset || 0
monthNum += offset
if(monthNum < 0) { monthNum = 11 }
if(monthNum > 11) { monthNum = 0 }
var month = this.getOffsetMonth(offset)
, year = this.getOffsetYear(offset)
// get the first day of the month we are currently viewing
var firstOfMonth = new Date(year, month, 1).getDay(),
// get the total number of days in the month we are currently viewing
numDays = this.offsetDaysInMonth(offset),
// declare our day counter
dayCount = 0,
html = '',
row = '<tr>'
// print out previous month's "days"
for(i = 1; i <= firstOfMonth; i++) {
row += '<td> </td>'
dayCount++
}
for(i = 1; i <= numDays; i++) {
// if we have reached the end of a week, wrap to the next line
if(dayCount == 7) {
row += '</tr>'
html += row
row = '<tr>'
dayCount = 0
}
// output the text that goes inside each td
// if the day is the current day, add a class of "selected"
// Only show a default date if the selection mode is 'single'
row += '<td data-day="' + i + '" class=""><a href="#">' + i + '</a></td>'
dayCount++
}
// if we haven't finished at the end of the week, start writing out the "days" for the next month
for(i = 1; i <= (7 - dayCount); i++) {
row += '<td> </td>'
}
html += row
return html
}
|
javascript
|
{
"resource": ""
}
|
|
q9525
|
train
|
function() {
// First deselect everything
this.el.all('td.selected').removeClass('selected')
for (var i=0,date;date=this.selected[i];i++) {
var cell = this.el.one('.pane[data-month="' + date.month + '"][data-year="' + date.year + '"] td[data-day="' + date.day + '"]')
if (cell._node) {
cell.addClass('selected')
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9526
|
train
|
function () {
let _that = this[PRIVATE];
if (_that.initialized() && _that.running()) {
_that.gameboy.stopEmulator |= 2;
_that.frames = 0; //Reset internal variables
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9527
|
readUInt64BE
|
train
|
function readUInt64BE(buffer, start) {
var data = buffer.slice(start, start + 8);
return data.readUInt32BE(4, 8);
}
|
javascript
|
{
"resource": ""
}
|
q9528
|
expressInit
|
train
|
function expressInit( req, res, next ) {
req.next = next;
req.context = {};
// patching this according to how express does it
// not jshint ignoring the following lines because then it
// warns that expreq and expres aren't used.
// This works according to express implemenetation
// DO NOT CHANGE IT
req.__proto__ = expreq;
res.__proto__ = expres;
next();
}
|
javascript
|
{
"resource": ""
}
|
q9529
|
parseAhead
|
train
|
function parseAhead( router, req, done ) {
var idx = 0;
var stack = router.stack;
var params = {};
var method = req.method ? req.method.toLowerCase() : undefined;
next();
function next() {
var layer = stack[ idx++ ];
if ( !layer ) {
// strip dangling query params
params = _.transform( params, function( acc, v, k ) {
acc[ k ] = v.split( '?' )[ 0 ]; return acc;
}, {} );
return done( params );
}
if ( layer.method && layer.method !== method ) {
return next();
}
layer.match( req.originalUrl );
params = _.merge( params, layer.params );
next();
}
}
|
javascript
|
{
"resource": ""
}
|
q9530
|
prefix
|
train
|
function prefix( state, url ) {
if ( state.config.urlPrefix ) {
if ( _.isRegExp( url ) ) {
return regex.prefix( state.config.urlPrefix, url );
} else {
var prefixIndex = url.indexOf( state.config.urlPrefix );
var appliedPrefix = prefixIndex === 0 ? '' : state.config.urlPrefix;
return buildUrl( appliedPrefix, url );
}
} else {
return url;
}
}
|
javascript
|
{
"resource": ""
}
|
q9531
|
NWTNodeList
|
train
|
function NWTNodeList(nodes) {
localnwt.implement('DelayableQueue', this);
var wrappedNodes = [];
for( var i = 0, node ; node = nodes[i] ; i++ ) {
wrappedNodes.push(new NWTNodeInstance(node));
}
this.nodes = wrappedNodes;
var iteratedFunctions = [
'anim', 'appendTo', 'remove', 'addClass', 'removeClass', 'setStyle', 'setStyles', 'removeStyle', 'removeStyles', 'swapClass', 'plug'
],
mythis = this;
function getIteratedCallback(method) {
return function() {
for( var j = 0 , node ; node = mythis.nodes[j] ; j++ ) {
node[method].apply(node, arguments);
}
return mythis;
};
};
for( var i = 0, func; func = iteratedFunctions[i] ; i++ ) {
this[func] = getIteratedCallback(func);
}
}
|
javascript
|
{
"resource": ""
}
|
q9532
|
registerTask
|
train
|
function registerTask( task ) {
grunt.registerMultiTask( task.name, task.help, function () {
var done = this.async();
if ( ensureSketchtool() ) {
var options = this.options();
var commands = [];
this.files.forEach( function( file ) {
file.src.filter( function ( src ) {
var command = createCommand( task, src, file.dest, options );
if ( command ) {
commands.push( command );
}
} );
});
async.eachLimit( commands, numCPUs, function ( command, next ) {
executeCommand( command, next );
}, done );
} else {
done(false);
}
} );
}
|
javascript
|
{
"resource": ""
}
|
q9533
|
parseString
|
train
|
function parseString (xml, callback) {
var doc, error, plist;
try {
doc = new DOMParser().parseFromString(xml);
plist = parsePlistXML(doc.documentElement);
} catch(e) {
error = e;
}
callback(error, plist);
}
|
javascript
|
{
"resource": ""
}
|
q9534
|
parseStringSync
|
train
|
function parseStringSync (xml) {
var doc = new DOMParser().parseFromString(xml);
var plist;
if (doc.documentElement.nodeName !== 'plist') {
throw new Error('malformed document. First element should be <plist>');
}
plist = parsePlistXML(doc.documentElement);
// if the plist is an array with 1 element, pull it out of the array
if (plist.length == 1) {
plist = plist[0];
}
return plist;
}
|
javascript
|
{
"resource": ""
}
|
q9535
|
train
|
function(implClass, modClass) {
var impls = {
DelayableQueue : [
/**
* Returns a queueable interface to the original object
* This allows us to insert delays between chainable method calls using the .wait() method
* Currently this is only implemented for the node class, but it should be possible to use this with any object.
*/
'wait', function () {
/**
* Queueable object which implements methods from another interface
* @param object Context for the callback
*/
function QueueableObject(context) {
this.queue = [];
this.context = context;
this.inWork = false;
}
QueueableObject.prototype = {
_add: function(func, args) {
var self = this;
self.queue.push({type: 'chain', func: func, args: args});
if (!self.inWork) {
return self._process();
}
},
/**
* Process the queue
* Shifts an item off the queue and waits for it to finish
*/
_process: function() {
var self = this, item;
self.inWork = true;
if (!self.queue.length) {
return;
}
item = self.queue.shift();
if (item.type == 'wait') {
setTimeout(function(){
self._process();
}, item.duration*1000);
} else {
self.context = item.func.apply(self.context, item.args);
self._process();
}
return self;
},
/**
* Updates the current delay timer
*/
wait: function(duration) {
this.queue.push({type: 'wait', duration: duration});
return this;
}
};
return function (duration) {
var self = this,
mockObj = new QueueableObject(self);
/**
* Returns an executable function
* uses setTimeout and the total queueTimer
*/
getQueuedFunction = function(func) {
return function() {
mockObj._add(func, arguments);
return mockObj;
}
};
/**
* Wrap all class functions
* We can unwrap at the end if the current wait is 0
*/
for( var i in self ) {
if (typeof self[i] != 'function' || i == 'wait' ) { continue; }
mockObj[i] = getQueuedFunction(self[i]);
}
mockObj.wait(duration);
return mockObj;
}
}
]
};
modClass[impls[implClass][0]] = impls[implClass][1]();
}
|
javascript
|
{
"resource": ""
}
|
|
q9536
|
train
|
function() {
var self = this, item;
self.inWork = true;
if (!self.queue.length) {
return;
}
item = self.queue.shift();
if (item.type == 'wait') {
setTimeout(function(){
self._process();
}, item.duration*1000);
} else {
self.context = item.func.apply(self.context, item.args);
self._process();
}
return self;
}
|
javascript
|
{
"resource": ""
}
|
|
q9537
|
train
|
function(event, callback) {
var args = Array.prototype.slice.call(arguments, 1);
localnwt.event._eventData = args;
var customEvt = y.createEvent("UIEvents");
customEvt.initEvent(event, true, false);
this._node.dispatchEvent(customEvt);
}
|
javascript
|
{
"resource": ""
}
|
|
q9538
|
isRunning
|
train
|
function isRunning(specs) {
return specs.dataset.some(coll => {
return coll.contents.some(e => {
return ['ready', 'queued', 'running', 'interrupted'].includes(e.status);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9539
|
train
|
function(dir) {
var curr = this.menu.one('li.active'),
targetNode = curr[dir]();
this.menu.one('li.active').removeClass('active');
targetNode.addClass('active');
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9540
|
train
|
function(items) {
var itemMarkup = '', i;
for (i=0; i< items.length; i++) {
itemMarkup += '<li><a href="#" data-value="' + items[i] + '">' + this.highlighter(items[i]) + '</a></li>';
}
var inputRegion = this.node.region();
this.menu.setHtml(itemMarkup)
this.menu.one('li').addClass('active')
this.menu.setStyles({
left: inputRegion.left,
top: inputRegion.bottom,
display:'block'
});
this.node.fire('typeahead:show')
return this;
}
|
javascript
|
{
"resource": ""
}
|
|
q9541
|
erotic
|
train
|
function erotic(transparent) {
const { stack } = new Error()
const caller = getCallerFromArguments(arguments)
const entryStack = getEntryStack(stack, transparent)
return makeCallback(caller, entryStack, transparent)
}
|
javascript
|
{
"resource": ""
}
|
q9542
|
S3StreamDownload
|
train
|
function S3StreamDownload (s3, s3Params, options) {
var downloader = new Downloader(s3, s3Params, options);
return new DownloadStream(downloader);
}
|
javascript
|
{
"resource": ""
}
|
q9543
|
train
|
function(next) {
self.loadAllExtensions(function() {
// Add middleware to make html5mode work in angular.
self.routers.page.use(function(request, response, next) {
// If between JSON and HTML it prefers HTML, return index.html content since
// we know its a direct browser request or another HTML consuming client.
if (request.accepts(['json', 'html']) === 'html') {
// Serve the right index.html taking into account overrides.
return self.staticDiscover('index.html', function(indexFile) {
response.status(200).sendFile(indexFile);
});
}
next();
});
next();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9544
|
train
|
function(next) {
self.collect('field', function(error, fields) {
if (error) {
return callback(error);
}
self.fields = fields;
self.loadAllTypes(next);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9545
|
train
|
function(next) {
self.storage.init(function(error, collections) {
if (error) {
return next(error);
}
self.collections = collections;
next();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9546
|
processHandler
|
train
|
function processHandler(fn) {
if (_.isFunction(handler)) {
return fn(null, handler);
}
if (_.isString(handler)) {
return self.processStringHandler(mycro, handler, fn);
}
if (_.isObject(handler)) {
// make sure the object defines a `handler` attribute
if (!handler.handler) {
return fn('Unable to locate handler for ' + verb.toUpperCase() + ' ' + path.toString());
}
// extend options with any route specific options
if (handler.options && _.isObject(handler.options)) {
_.extend(options.defaultOptions, handler.options);
}
// allow route to override policy chain
if (handler.policies && _.isArray(handler.policies)) {
options.defaultPolicies = handler.policies;
}
// allow route to augment policy chain
if (handler.additionalPolicies && _.isArray(handler.additionalPolicies)) {
options.defaultPolicies = options.defaultPolicies.concat(handler.additionalPolicies);
}
if (_.isFunction(handler.handler)) {
return fn(null, handler.handler);
}
if (_.isString(handler.handler)) {
return self.processStringHandler(mycro, handler.handler, fn);
}
}
return fn('Unsupported handler type for '+ verb.toUpperCase() + ' ' + path.toString());
}
|
javascript
|
{
"resource": ""
}
|
q9547
|
cleanItem
|
train
|
function cleanItem(value) {
var newvalue = null;
if (Array.isArray(value)) {
if (value.indexOf("consumer") > -1) {
value.forEach(function (key2) {
ids[key2] = "roles";
});
}
newvalue = [];
value.forEach(function (item) {
newvalue.push(cleanItem(item));
})
return newvalue;
}
if ((typeof value !== "object") || (value == null)) {
return value;
}
Object.keys(value).forEach(function (key) {
if (key == "orgs") {
Object.keys(value[key]).forEach(function (key2) {
ids[key2] = "orgs";
});
}
if (key == "_temp") {
return;
} else if (key == "encData" || key == "signature" || key == "encPrivateKey" || key == "publicKey") {
newvalue = newvalue || {};
if (typeof newvalue !== "object") throw new Error("Not Object" + key)
newvalue[key] = "..."
} else {
newvalue = newvalue || {};
if (typeof newvalue !== "object") throw new Error("Not Object" + key)
newvalue[key] = cleanItem(value[key])
}
});
return newvalue;
}
|
javascript
|
{
"resource": ""
}
|
q9548
|
cleanItem3
|
train
|
function cleanItem3(value, parent) {
var newvalue = null;
if (Array.isArray(value)) {
newvalue = [];
var isAllNumbers = (value.length > 0);
var isAllStrings = (value.length > 0)
value.forEach(function (item) {
if (typeof item !== 'number')
isAllNumbers = false;
if (typeof item !== 'string')
isAllStrings = false;
})
if (isAllNumbers)
return [cleanItem3(value[0], parent)];
if (isAllStrings) {
var enumKey = "Enum" + getTypeFromKey(parent);
var hash = value.join("!");
if (hash in enumFromHash)
enumKey = enumFromHash[hash]
else {
var found = true;
value.forEach(function (key) {
if (!(key in enumFromKey)) found = false;
})
if (found) {
enumKey = enumFromKey[value[0]];
} else {
enums[enumKey] = value;
enumFromHash[hash] = enumKey;
value.forEach(function (key) {
enumFromKey[key] = "Enum" + getTypeFromKey(parent);
})
}
}
return [enumKey];
}
value.forEach(function (item) {
newvalue.push(cleanItem3(item, parent));
})
return newvalue;
}
if ((typeof value !== "object") || (value == null)) {
switch (typeof value) {
case 'string':
if (isId(value)) return 'ID';
if (isUser(value)) return 'UserId';
if (isUserOrgPrefix(value)) return 'UserOrOrgIdPrefixed';
if (ids[value] == "orgs") return 'OrgId';
if (ids[value] == "roles") return 'EnumConfigRole';
if (value in enumDefaultKeys.values) return enumDefaultKeys.values[value];
if (ids[value]) return ids[value] + "Id";
return 'String';
case 'number':
if (value > 1300000000 && value < 1700000000)
return value % 1 == 0 ? 'Date' : 'Time'
return value % 1 == 0 ? 'Int' : 'Float'
case 'boolean':
return 'Boolean';
default:
return value == null ? 'NULL' : value;
}
}
var newvalue = {};
Object.keys(value).forEach(function (key) {
newvalue[key] = cleanItem3(value[key], parent + key.substr(0, 1).toUpperCase() + key.substr(1));
});
return newvalue;
}
|
javascript
|
{
"resource": ""
}
|
q9549
|
train
|
function (icuString, options) {
icuString = this.cleanWhiteSpace(icuString);
//args before kwargs
if (typeof options !== 'undefined') {
if (typeof options.string !== 'undefined') {
var stringRe = new RegExp(('\{' + options.string + '\}'), 'g');
icuString = icuString.replace(stringRe, '%s');
}
if (typeof options.number !== 'undefined') {
var numberRe = new RegExp(('\{' + options.number + ', number\}'), 'g');
icuString = icuString.replace(numberRe, '%d');
}
}
icuString = icuString.replace(/\{[a-zA-Z0-9_.|]+\}/g, function (variable_name) {
var name = variable_name.substring(1, (variable_name.length - 1));
return '%(' + name + ')s';
});
icuString = icuString.replace(/\{[a-zA-Z0-9_.|]+, number\}/g, function (variable_name) {
var name = variable_name.substring(1, (variable_name.length - 9));
return '%(' + name + ')d';
});
return icuString;
}
|
javascript
|
{
"resource": ""
}
|
|
q9550
|
train
|
function (msgs, pluralForms) {
var msgKey = 'digit';
var hasVariableName = false;
for (var i=0; i<msgs.length; i++) {
if (msgs[i].match(/%\([a-zA-Z0-9_.|]+\)d/g) !== null) {
var match = msgs[i].match(/%\([a-zA-Z0-9_.|]+\)d/g)[0];
msgKey = match.substring(2, (match.length - 2));
hasVariableName = true;
break;
}
}
var icuMsg = '{' + msgKey + ', plural,\n';
var self = this;
pluralForms.forEach(function (plural) {
var msg = msgs[plural.poPlural];
msg = self.cleanWhiteSpace(msg);
if (hasVariableName) {
msg = msg.replace(/%\([a-zA-Z0-9_.|]+\)d/g, '{' + msgKey + '}');
} else {
msg = msg.replace(/%(d|i)/g, '{' + msgKey + '}');
}
icuMsg = icuMsg + ' ' + plural.icuPlural + ' {' + msg + '}\n';
});
icuMsg = icuMsg + '}';
return icuMsg;
}
|
javascript
|
{
"resource": ""
}
|
|
q9551
|
removeFromList
|
train
|
function removeFromList (array, obj) {
for (var i = 0; i < array.length; i++) {
if (array[i] === obj) {
array.splice(i, 1);
}
return;
}
}
|
javascript
|
{
"resource": ""
}
|
q9552
|
findWhere
|
train
|
function findWhere (array, obj) {
var props = Object.keys(obj);
for (var i = 0; i < array.length; i++) {
var passable = true;
for (var j = 0; j < props.length; j++) {
if (array[i][props[j]] !== obj[props[j]]) {
passable = false;
}
}
if (passable)
return array[i];
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q9553
|
update
|
train
|
function update (obj1, obj2) {
Object.keys(obj2).forEach(function (prop) {
obj1[prop] = obj2[prop];
});
return obj1;
}
|
javascript
|
{
"resource": ""
}
|
q9554
|
randomAlpha
|
train
|
function randomAlpha (n) {
var alpha = "abcdefghijklmnopqrstuvwxyz";
var res = "";
for (var i = 0; i < n; i++) {
res += alpha.charAt(Math.floor(Math.random() * alpha.length));
}
return res;
}
|
javascript
|
{
"resource": ""
}
|
q9555
|
Impromptu
|
train
|
function Impromptu() {
this.state = new Impromptu.State()
this._setRootPath(Impromptu.DEFAULT_CONFIG_DIR)
this.log = new Impromptu.Log(this.state)
this.exec = Impromptu.Exec(this.log)
this.color = new Impromptu.Color(this.state)
this.repository = new Impromptu.RepositoryFactory()
this.db = new Impromptu.DB()
this.cache = new Impromptu.CacheFactory(this.state)
this._addCacheProviders()
this.module = new Impromptu.ModuleFactory(this)
this.plugin = new Impromptu.PluginFactory(this.cache)
this._loadPlugins = this.plugin.claimPluginLoader()
this.prompt = new Impromptu.Prompt(this.color)
}
|
javascript
|
{
"resource": ""
}
|
q9556
|
checkFile
|
train
|
function checkFile( path ) {
if ( typeof path === "undefined" || ! grunt.file.exists( path ) ) {
grunt.log.error( "Source file \"" + path + "\" not found." );
return false;
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q9557
|
isIncludeFile
|
train
|
function isIncludeFile( path ) {
if ( fs.statSync( path ).isFile() &&
getIncludeFileExtensions().indexOf( getFileExtension( path ) ) !== - 1 ) return true;
return false;
}
|
javascript
|
{
"resource": ""
}
|
q9558
|
parseJSON
|
train
|
function parseJSON( path, content ) {
return JSON.parse( content, function( key, value ) {
if ( options.stripComments && key === "{{comment}}" ) return undefined;
// Replace variables in their values
if ( Object.keys( options.variables ).length && typeof value === "string" ) {
value = replaceVariables( value );
}
var match = ( typeof value === "string" ) ? value.match( options.parsePattern ) : null;
if ( match ) {
var folderPath = getFolder( path ) || ".";
var fullPath = folderPath + "/" + match[ 1 ];
return isDirectory( fullPath ) ? parseDirectory( fullPath ) : parseFile( fullPath );
}
return value;
} );
}
|
javascript
|
{
"resource": ""
}
|
q9559
|
replaceVariables
|
train
|
function replaceVariables( value ) {
return value.replace( options.variableRegex, function( match, key ) {
if ( options.variables[ key ] === undefined ) {
grunt.log.warn( "No variable definition found for: " + key );
return "";
}
return options.variables[ key ];
} );
}
|
javascript
|
{
"resource": ""
}
|
q9560
|
parseDirectory
|
train
|
function parseDirectory( path ) {
return fs.readdirSync( path )
.map( function( file ) {
var filePath = path + "/" + file;
if ( isIncludeFile( filePath ) ) return parseFile( filePath );
else if ( isDirectory( filePath ) ) return parseDirectory( filePath );
return null;
} )
.filter( function( value ) {
return value !== null;
} );
}
|
javascript
|
{
"resource": ""
}
|
q9561
|
train
|
function(e) {
var thumbOffset = this.thumb.region().height/2;
this.setPositionIfValid(e._e.pageY - (this.node.region().top + this.scrollbarOffset) - thumbOffset);
}
|
javascript
|
{
"resource": ""
}
|
|
q9562
|
_parseNetworkLocation
|
train
|
function _parseNetworkLocation(networkLocation, obj) {
var pos = networkLocation.indexOf(':');
if (pos === -1) {
obj.host = networkLocation;
} else {
obj.host = networkLocation.substring(0, pos);
if (pos < (networkLocation.length - 1)) {
obj.port = networkLocation.substring(pos + 1);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9563
|
train
|
function(exists, done) {
if (exists) {
done(new AbstractCache.Error('The cache is currently locked.'))
} else {
client.get("lock-process:" + name, done)
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9564
|
capitalize
|
train
|
function capitalize (s) {
if (!s) return s;
if (s.length === 1) return s.toUpperCase();
return s[0].toUpperCase() + s.substring(1);
}
|
javascript
|
{
"resource": ""
}
|
q9565
|
generateOperations
|
train
|
function generateOperations (plural) {
var operations = [];
controller.methods().forEach(function (verb) {
var operation = {};
var titlePlural = capitalize(controller.model().plural());
var titleSingular = capitalize(controller.model().singular());
// Don't do head, post/put for single/plural
if (verb === 'head') return;
if (verb === 'post' && !plural) return;
if (verb === 'put' && plural) return;
// Use the full word
if (verb === 'del') verb = 'delete';
operation.httpMethod = verb.toUpperCase();
if (plural) operation.nickname = verb + titlePlural;
else operation.nickname = verb + titleSingular + 'ById';
operation.responseClass = titleSingular; // TODO sometimes an array!
if (plural) operation.summary = capitalize(verb) + ' some ' + controller.model().plural();
else operation.summary = capitalize(verb) + ' a ' + controller.model().singular() + ' by its unique ID';
operation.parameters = generateParameters(verb, plural);
operation.errorResponses = generateErrorResponses(plural);
operations.push(operation);
});
return operations;
}
|
javascript
|
{
"resource": ""
}
|
q9566
|
DB
|
train
|
function DB() {
this.requests = {}
process.on('message', function(message) {
if (message.type !== 'cache:response') {
return
}
/** @type {{error: Error, response: string, uid: string, method: string}} */
var data = message.data
// The requests for this UID may not exist because there can be multiple
// instances of Impromptu.
if (!(this.requests[data.method] && this.requests[data.method][data.uid])) {
return
}
var callbacks = this.requests[data.method][data.uid]
for (var i = 0; i < callbacks.length; i++) {
var callback = callbacks[i]
callback(data.error, data.response)
}
delete this.requests[data.method][data.uid]
}.bind(this))
}
|
javascript
|
{
"resource": ""
}
|
q9567
|
read
|
train
|
function read (parser, type, key, limit = Infinity) {
let count = 0
pipeline(parser, new Writable({
write (obj, enc, cb) {
if (typeof type === 'string') key = type
if (typeof type === 'number') {
limit = type
type = undefined
}
if (typeof key === 'number') {
limit = key
key = undefined
}
if (count >= limit) {
return cb()
}
if (type instanceof Object && !(obj instanceof type)) {
return cb()
}
dir(key ? obj[key] : obj, { colors: true })
count++
cb()
},
objectMode: true
}), er => {
log(er || 'ok')
server.displayPrompt()
})
}
|
javascript
|
{
"resource": ""
}
|
q9568
|
Ruleset
|
train
|
function Ruleset(rules, composite) {
if (!(this instanceof Ruleset)) {
return new Ruleset(rules, composite);
}
this.composite = composite || 'all';
this.rules = rules || [];
}
|
javascript
|
{
"resource": ""
}
|
q9569
|
stop
|
train
|
function stop(next) {
if (phantomProcess) {
seleniumServerProcess.on('close', function (code, signal) {
// this should really resolve both callbacks rather than guessing phantom wrapper will terminate instantly
if (typeof next === 'function' && !seleniumServerProcess ) {
next();
}
});
// SIGTERM should ensure processes end cleanly, can do killall -9 java if getting startup errors
phantomProcess.kill('SIGTERM');
started = false;
starting = false;
}
if (seleniumServerProcess) {
seleniumServerProcess.on('close', function (code, signal) {
if (typeof next === 'function' ) {
// need to stub out the other callback
next();
}
});
seleniumServerProcess.kill('SIGTERM');
started = false;
starting = false;
}
}
|
javascript
|
{
"resource": ""
}
|
q9570
|
scaleBoxGroup
|
train
|
function scaleBoxGroup(selection) {
selection.classed('mb-3', true);
// Scale type
const scaleOptions = [
{key: 'linear', name: 'Linear'},
{key: 'log', name: 'Log'}
];
selection.append('div')
.classed('scale', true)
.classed('mb-1', true)
.call(lbox.selectBox, 'Scale')
.call(lbox.updateSelectBoxOptions, scaleOptions)
.on('change', function () {
const isLog = box.formValue(d3.select(this)) === 'log';
selection.select('.domain')
.call(isLog ? rbox.logRange : rbox.linearRange)
.call(badge.updateInvalidMessage,
isLog ? 'Please provide a valid range (larger than 0)'
: 'Please provide a valid number');
});
selection.append('div')
.classed('domain', true)
.classed('mb-1', true)
.call(rbox.rangeBox, 'Domain');
}
|
javascript
|
{
"resource": ""
}
|
q9571
|
AbstractCache
|
train
|
function AbstractCache(state, name, options) {
this.state = state
this.name = name
this.options = options
this._update = this._update.bind(this)
this._setLock = false
this._setCallbacks = []
this._needsRefresh = false
this.state.on('refreshCache', function (needsRefresh) {
this._needsRefresh = needsRefresh
}.bind(this))
// Build our own `run` instance-method to accurately reflect the fact that
// `run` is always asynchronous and requires an argument to declare itself
// as such to our API.
var protoRun = this.run
this.run = function(done) {
if (this.options.run) {
return this.options.run.apply(this, arguments)
} else {
return protoRun.apply(this, arguments)
}
}.bind(this)
}
|
javascript
|
{
"resource": ""
}
|
q9572
|
succeedLambdaCallback
|
train
|
function succeedLambdaCallback(callback, response, event, context) {
return executePreSuccessCallback(response, event, context)
.then(() => callback(null, response))
.catch(err => {
console.error(`Unexpected failure after executePreSuccessCallback`, err);
return callback(null, response);
});
}
|
javascript
|
{
"resource": ""
}
|
q9573
|
TwitterAPIConnection
|
train
|
function TwitterAPIConnection(n) {
RED.nodes.createNode(this,n);
var node = this;
node.consumerKey = n.consumerKey;
node.consumerSecret = n.consumerSecret;
node.accessToken = n.accessToken;
node.accessSecret = n.accessSecret;
var id = node.consumerKey;
node.log('create new Twitter instance for: ' + id);
clients[id] = new Twit({
consumer_key: node.consumerKey,
consumer_secret: node.consumerSecret,
access_token: node.accessToken,
access_token_secret: node.accessSecret
});
node.client = clients[id];
this.on("close", function() {
node.log('delete Twitter instance on close event');
delete clients[id];
});
}
|
javascript
|
{
"resource": ""
}
|
q9574
|
buildSchema
|
train
|
function buildSchema(models, typeMap) {
let type;
var _models$map$reduce = models.map(model => {
type = typeMap[model.modelName];
return {
query: (0, _buildQuery2.default)(model, type),
mutation: (0, _buildMutation2.default)(model, type)
};
}).reduce((fields, modelField) => {
fields.query = (0, _assign2.default)({}, fields.query, modelField.query);
fields.mutation = (0, _assign2.default)({}, fields.mutation, modelField.mutation);
return fields;
}, { query: {}, mutation: {} });
const query = _models$map$reduce.query;
const mutation = _models$map$reduce.mutation;
return {
query: query,
mutation: mutation
};
}
|
javascript
|
{
"resource": ""
}
|
q9575
|
loadDefaultStageHandlingOptions
|
train
|
function loadDefaultStageHandlingOptions() {
const options = require('./stages-options.json');
const defaultOptions = options ? options.stageHandlingOptions : {};
const defaults = {
envStageName: 'STAGE',
streamNameStageSeparator: '_',
resourceNameStageSeparator: '_',
injectInCase: 'upper',
extractInCase: 'lower',
defaultStage: undefined
};
return merge(defaults, defaultOptions);
}
|
javascript
|
{
"resource": ""
}
|
q9576
|
toStageSuffixedName
|
train
|
function toStageSuffixedName(unsuffixedName, separator, stage, inCase) {
const name = trim(unsuffixedName);
const stageSuffix = isNotBlank(stage) ? `${trimOrEmpty(separator)}${toCase(trim(stage), inCase)}` : '';
return isNotBlank(name) && isNotBlank(stageSuffix) && !name.endsWith(stageSuffix) ? `${name}${stageSuffix}` : name;
}
|
javascript
|
{
"resource": ""
}
|
q9577
|
toCase
|
train
|
function toCase(value, asCase) {
if (isNotBlank(value)) {
// Convert the given asCase argument to lowercase to facilitate matching
const caseToUse = trimOrEmpty(asCase && asCase.toLowerCase ? asCase.toLowerCase() : asCase);
// Convert the given stage into the requested case
return caseToUse === 'lowercase' || caseToUse === 'lower' ? value.toLowerCase() :
caseToUse === 'uppercase' || caseToUse === 'upper' ? value.toUpperCase() : value;
}
return value;
}
|
javascript
|
{
"resource": ""
}
|
q9578
|
filterArgs
|
train
|
function filterArgs(defaultArgs, opt) {
opt = opt || {};
const packValueToNonNull = value => (0, _assign2.default)({}, value, { type: new _graphql.GraphQLNonNull(value.type) });
return (0, _entries2.default)(defaultArgs).filter(_ref => {
var _ref2 = (0, _slicedToArray3.default)(_ref, 2);
let arg = _ref2[0];
let value = _ref2[1];
if (opt.onlyId && arg !== 'id' && arg !== 'ids') return false;
if (opt.id && (arg === 'id' || arg === 'ids')) return false;
if (opt.plural && !value.onlyPlural && _pluralize2.default.plural(arg) === arg) return false;
return true;
}).map(_ref3 => {
var _ref4 = (0, _slicedToArray3.default)(_ref3, 2);
let arg = _ref4[0];
let value = _ref4[1];
let newValue = (0, _assign2.default)({}, value);
if ((arg === 'id' || arg === 'ids') && opt.idRequired) newValue = packValueToNonNull(newValue);
if (!opt.required && newValue.required && !newValue.context) newValue = packValueToNonNull(newValue);
return [arg, newValue];
}).reduce((args, _ref5) => {
var _ref6 = (0, _slicedToArray3.default)(_ref5, 2);
let arg = _ref6[0];
let value = _ref6[1];
return (0, _assign2.default)(args, { [arg]: value });
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q9579
|
toMongooseArgs
|
train
|
function toMongooseArgs(args) {
// Covert name_first to name: {first}
let keyDepth = [];
return (0, _entries2.default)(args).reduce((args, _ref7) => {
var _ref8 = (0, _slicedToArray3.default)(_ref7, 2);
let key = _ref8[0];
let value = _ref8[1];
keyDepth = key.split('_');
if (keyDepth.length === 1) return (0, _assign2.default)(args, { [key]: value });
keyDepth.reduce((args, depth, index) => {
if (index === keyDepth.length - 1) {
args[depth] = value;
return;
}
args[depth] = args[depth] || {};
return args[depth];
}, args);
return args;
}, {});
}
|
javascript
|
{
"resource": ""
}
|
q9580
|
directoryCleanEverything
|
train
|
function directoryCleanEverything(dirPath, includeExtension, toRemove, replacement) {
if(!fs.existsSync(dirPath)) return;
let isDirectory = fs.statSync(dirPath).isDirectory();
// try cleaning package.json in current dir
if(!isDirectory && dirPath.match(new RegExp(includeExtension + "$", "g"))) {
let content = fs.readFileSync(dirPath).toString();
while(content.indexOf(toRemove) >= 0) {
content = content.replace(toRemove, replacement || "");
}
fs.writeFileSync(dirPath, content);
}
else if(isDirectory) {
// check for subdirectories
let list = fs.readdirSync(dirPath);
for(let dir of list) {
let subDirPath = dirPath + "/" + dir;
directoryCleanEverything(subDirPath, includeExtension, toRemove, replacement);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9581
|
resolveVarValue
|
train
|
function resolveVarValue (name, values) {
if (is.undef(values) || is.args.empty(arguments)) {
message('Error: Missing arguments');
return undefined;
}
if (!is.string(name) || !is.object(values)) {
message('Error: Check arguments type');
return undefined;
}
const varName = name.slice(1);
return values[varName] || null;
}
|
javascript
|
{
"resource": ""
}
|
q9582
|
message
|
train
|
function message (text) {
const normalText = text.toLowerCase();
if (~normalText.indexOf('warning')) {
log.warn(text)
} else if (~normalText.indexOf('error')) {
log.error(text);
} else {
log.debug(text);
}
}
|
javascript
|
{
"resource": ""
}
|
q9583
|
toObjectFromDynamoDBMap
|
train
|
function toObjectFromDynamoDBMap(dynamoDBMap) {
if (!dynamoDBMap || typeof dynamoDBMap !== 'object') {
return dynamoDBMap;
}
const object = {};
const keys = Object.getOwnPropertyNames(dynamoDBMap);
for (let i = 0; i < keys.length; ++i) {
const key = keys[i];
object[key] = toValueFromAttributeValue(dynamoDBMap[key]);
}
return object;
}
|
javascript
|
{
"resource": ""
}
|
q9584
|
toValueFromAttributeValue
|
train
|
function toValueFromAttributeValue(attributeValue) {
if (!attributeValue || typeof attributeValue !== 'object') {
return attributeValue;
}
const values = Object.getOwnPropertyNames(attributeValue).map(type => {
return toValueFromAttributeTypeAndValue(type, attributeValue[type])
});
if (values.length !== 1) {
throw new Error(`Found ${values.length} values on DynamoDB AttributeValue (${stringify(attributeValue)}), but expected only one!`);
}
return values[0];
}
|
javascript
|
{
"resource": ""
}
|
q9585
|
toValueFromAttributeTypeAndValue
|
train
|
function toValueFromAttributeTypeAndValue(attributeType, value) {
switch (attributeType) {
case 'S':
return value;
case 'N':
return toNumberOrIntegerLike(value);
case 'BOOL':
return value === true || value === 'true';
case 'NULL':
return null;
case 'M':
return toObjectFromDynamoDBMap(value);
case 'L':
return value.map(v => toValueFromAttributeValue(v));
case 'SS':
return value;
case 'NS':
return value.map(v => toNumberOrIntegerLike(v));
case 'B':
case 'BS':
return value;
default:
throw new Error(`Unexpected DynamoDB attribute value type (${attributeType})`);
}
}
|
javascript
|
{
"resource": ""
}
|
q9586
|
toKeyValueStrings
|
train
|
function toKeyValueStrings(dynamoDBMap) {
return dynamoDBMap && typeof dynamoDBMap === 'object' ?
Object.getOwnPropertyNames(dynamoDBMap).map(key => `${key}:${stringify(toValueFromAttributeValue(dynamoDBMap[key]))}`) : [];
}
|
javascript
|
{
"resource": ""
}
|
q9587
|
toKeyValuePairs
|
train
|
function toKeyValuePairs(dynamoDBMap) {
return dynamoDBMap && typeof dynamoDBMap === 'object' ?
Object.getOwnPropertyNames(dynamoDBMap).map(key => [key, toValueFromAttributeValue(dynamoDBMap[key])]) : [];
}
|
javascript
|
{
"resource": ""
}
|
q9588
|
forInitial
|
train
|
function forInitial(props) {
const { navigation, scene } = props;
const focused = navigation.state.index === scene.index;
const opacity = focused ? 1 : 0;
// If not focused, move the scene far away.
const translate = focused ? 0 : 1000000;
return {
opacity,
transform: [{ translateX: translate }, { translateY: translate }],
};
}
|
javascript
|
{
"resource": ""
}
|
q9589
|
forHorizontal
|
train
|
function forHorizontal(props) {
const { layout, position, scene } = props;
if (!layout.isMeasured) {
return forInitial(props);
}
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
const opacity = position.interpolate({
inputRange: [first, first + 0.01, index, last - 0.01, last],
outputRange: [0, 1, 1, 0.85, 0],
});
const width = layout.initWidth;
const translateX = position.interpolate({
inputRange: [first, index, last],
outputRange: I18nManager.isRTL
? [-width, 0, width * 0.3]
: [width, 0, width * -0.3],
});
const translateY = 0;
return {
opacity,
transform: [{ translateX }, { translateY }],
};
}
|
javascript
|
{
"resource": ""
}
|
q9590
|
forFadeFromBottomAndroid
|
train
|
function forFadeFromBottomAndroid(props) {
const { layout, position, scene } = props;
if (!layout.isMeasured) {
return forInitial(props);
}
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
const inputRange = [first, index, last - 0.01, last];
const opacity = position.interpolate({
inputRange,
outputRange: [0, 1, 1, 0],
});
const translateY = position.interpolate({
inputRange,
outputRange: [50, 0, 0, 0],
});
const translateX = 0;
return {
opacity,
transform: [{ translateX }, { translateY }],
};
}
|
javascript
|
{
"resource": ""
}
|
q9591
|
forFade
|
train
|
function forFade(props) {
const { layout, position, scene } = props;
if (!layout.isMeasured) {
return forInitial(props);
}
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
const opacity = position.interpolate({
inputRange: [first, index, last],
outputRange: [0, 1, 1],
});
return {
opacity,
};
}
|
javascript
|
{
"resource": ""
}
|
q9592
|
loadAndServe
|
train
|
function loadAndServe() {
ip2co.dbLoad();
ip2co.listenHTTP({hostname: appConfig.listenOpt.http.hostname, port: appConfig.listenOpt.http.port});
}
|
javascript
|
{
"resource": ""
}
|
q9593
|
extrapolateDatesFromLines
|
train
|
function extrapolateDatesFromLines(claimLines, returnChildObj) {
var lowTime;
var highTime;
var pointTime;
if (returnChildObj.date_time) {
if (returnChildObj.date_time.low) {
lowTime = returnChildObj.date_time.low;
}
if (returnChildObj.date_time.high) {
highTime = returnChildObj.date_time.high;
}
if (returnChildObj.date_time.point) {
pointTime = returnChildObj.date_time.point;
}
}
for (var x in claimLines) {
if (typeof (claimLines[x]) === "function") {
continue;
}
var claimLineObj = claimLines[x];
if (claimLineObj.date_time) {
/*if the main claim body has undefined dates, populate it with
claim lines date */
if (claimLineObj.date_time.low && lowTime === undefined) {
lowTime = claimLineObj.date_time.low;
}
if (claimLineObj.date_time.high && highTime === undefined) {
highTime = claimLineObj.date_time.high;
}
if (claimLineObj.date_time.point && pointTime === undefined) {
pointTime = claimLineObj.date_time.point;
}
//if the claim lines are defined, then update them with better/more accurate information
if (lowTime !== undefined && claimLineObj.date_time.low) {
var lowDateTime = new Date(lowTime.date);
var lineLowDateTime = new Date(claimLineObj.date_time.low.date);
if (lineLowDateTime < lowDateTime) {
lowTime = claimLineObj.date_time.low;
}
}
if (highTime !== undefined && claimLineObj.date_time.high) {
var highDateTime = new Date(highTime.date);
var lineHighDateTime = new Date(claimLineObj.date_time.high.date);
if (lineHighDateTime > highDateTime) {
highTime = claimLineObj.date_time.high;
}
}
//on the assumption that the most recent service date is most relevant
if (pointTime !== undefined && claimLineObj.date_time.point) {
var pointDateTime = new Date(pointTime.date);
var linePointDateTime = new Date(claimLineObj.date_time.point.date);
if (pointDateTime > pointDateTime) {
pointTime = claimLineObj.date_time.point;
}
}
}
}
//assign the newly discovered times to the main claims body object
if (returnChildObj.date_time === undefined) {
returnChildObj.date_time = {};
}
if (lowTime) {
returnChildObj.date_time.low = lowTime;
}
if (highTime) {
returnChildObj.date_time.high = highTime;
}
if (pointTime) {
returnChildObj.date_time.point = pointTime;
}
}
|
javascript
|
{
"resource": ""
}
|
q9594
|
$var
|
train
|
function $var(params, fn, envs) {
if (params == null) {
return params;
}
if (typeof params === 'string') {
if (envs && envs[params] !== undefined) {
return envs[params];
}
return;
}
if (Array.isArray(params) && params.length === 2) {
const key = params[0];
if (typeof key === 'string') {
const value = fn.$var(key, fn, envs);
return value === undefined ? params[1] : value;
}
}
throw new Error(
'$var expects a string or an array with two elements of which the first one must be a string'
);
}
|
javascript
|
{
"resource": ""
}
|
q9595
|
$path
|
train
|
function $path(params) {
if (params == null) {
return params;
}
if (typeof params === 'string') {
const path = require('path');
if (path.isAbsolute(params)) {
return params;
}
return path.resolve(process.cwd(), params);
}
throw new Error('$path expects a string');
}
|
javascript
|
{
"resource": ""
}
|
q9596
|
$file
|
train
|
function $file(params, fn) {
if (params == null) {
return params;
}
let file, encoding;
if (typeof params === 'string') {
file = params;
} else if (Array.isArray(params) && params.length === 2) {
file = params[0];
encoding = params[1];
}
if (
typeof file === 'string' &&
(encoding === undefined || typeof encoding === 'string')
) {
file = fn.$path(file);
const fs = require('fs');
if (fs.existsSync(file) && fs.lstatSync(file).isFile()) {
return fs.readFileSync(file, { encoding });
}
}
throw new Error(
'$file expects a string or an array with two string elements'
);
}
|
javascript
|
{
"resource": ""
}
|
q9597
|
$number
|
train
|
function $number(params) {
if (params == null) {
return params;
}
if (typeof params === 'number') {
return params;
}
if (typeof params === 'string') {
return Number(params);
}
throw new Error('$number expects a number or string');
}
|
javascript
|
{
"resource": ""
}
|
q9598
|
train
|
function(db, namespace) {
var collection = this;
collection.trigger('request', collection);
fetch(db, namespace, function(err, res) {
if (err) {
throw err;
}
collection.reset(res, {parse: true});
collection.trigger('sync', collection);
});
return collection;
}
|
javascript
|
{
"resource": ""
}
|
|
q9599
|
BFFS
|
train
|
function BFFS(options) {
if (!this) return new BFFS(options);
options = this.init(options);
var store = options.store;
var prefix = options.prefix;
var env = options.env;
var cdn = options.cdn;
//
// We keep the running status of builds in redis.
//
this.store = store;
//
// Everything else we store in Cassandra.
//
this.datastar = options.datastar;
this.models = options.models;
this.log = options.log;
this.prefix = prefix;
this.envs = env;
this.cdns = this.cdnify(cdn);
this.limit = options.limit;
//
// Always fetch by locale so we default our locale property if it does not
// exist.
//
this.defaultLocale = 'en-US';
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.