_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q9600
|
compileEntity
|
train
|
function compileEntity() {
var entity = extend({
buildId: bff.key(payload),
extension: file.extension,
filename: file.filename,
fingerprint: print,
url: file.url
}, payload);
return entity;
}
|
javascript
|
{
"resource": ""
}
|
q9601
|
train
|
function(){
_prompt.question("You entered '" + _destination + "'. Is this correct? (Y/N)\n", function(input){
var response = input.trim().toLowerCase();
evaluateConfirmation(response);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9602
|
train
|
function(){
console.log("Unknown Response");
if (_pathConfirmationCounter < 3){
console.log("Please enter a 'Y' or an 'N' when answering.\n");
_pathConfirmationCounter++;
confirmDestination();
} else {
console.log("Unable to install at this time due to too many unknown responses.\n");
_prompt.close();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9603
|
train
|
function(){
if (destinationIsRelative){
_destination = _path.join(process.cwd(), "../..", _destination);
}
if(!_fs.existsSync(_destination)){
_fs.mkdirSync(_destination);
}
var destinationPath = _path.join(_destination, "/" + SCRIPT_NAME);
var sourcePath = _path.resolve(_path.dirname(module.filename), "../src/" + SCRIPT_NAME);
var source = _fs.createReadStream(sourcePath);
var dest = _fs.createWriteStream(destinationPath);
dest.pipe(source);
console.log("Client Installation Complete!\n");
console.log(SCRIPT_NAME + " has been installed at: " + destinationPath);
_prompt.close();
}
|
javascript
|
{
"resource": ""
}
|
|
q9604
|
pipeRunStep
|
train
|
function pipeRunStep(){
//Public APIs
/**
* run: run this step
* Should be implemented by subclasses
*/
this.run = function( callback ){
throw new Error("Called run method from abstract pipeRunStep class");
}
this.getLabel = function(){
return this.label || "Unknown label";
}
this.getPipe = function(){
return (this.pipeRunStats && this.pipeRunStats.getPipe()) || null;
}
this.getPipeRunner = function(){
return this.pipeRunner || null;
}
this.setStepMessage = function(message){
this.stats.message = message;
this.pipeRunStats.broadcastRunEvent();
}
this.setPercentCompletion = function( percent ){
this.stats.percent = percent;
}
this.beginStep = function( pipeRunner, pipeRunStats ){
pipeRunStats.logger.info( "Step %s started", this.getLabel() );
//Reference to the main stats object
this.pipeRunStats = pipeRunStats;
this.pipeRunner = pipeRunner;
pipeRunStats.setMessage( this.label );
//Record the start time
this.stats.startTime = moment();
this.stats.status = "RUNNING";
this.setPercentCompletion(0);
this.pipeRunStats.save();
}
this.endStep = function(callback, err){
//Set the end time and elapsed time
this.stats.endTime = moment();
this.stats.elapsedTime = moment.duration( this.stats.endTime.diff( this.stats.startTime ) ).humanize();
this.stats.status = err ? "ERROR" : "FINISHED";
if ( err ){
this.setStepMessage( err );
}
this.setPercentCompletion(100);
this.pipeRunStats.save( callback, err );
this.pipeRunStats.logger.info({
message: require('util').format("Step %s completed", this.getLabel() ),
stats: this.stats
});
}
/**
* toJSON serialization function
*/
this.toJSON = function(){
return {
label: this.getLabel()
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9605
|
genValuePartial_fromObject
|
train
|
function genValuePartial_fromObject(gen, field, fieldIndex, prop) {
if (field.resolvedType) {
if (field.resolvedType instanceof Enum) {
gen('switch(d%s){', prop);
for (let values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {
if (field.repeated && values[keys[i]] === field.typeDefault) gen('default:');
gen('case%j:', keys[i])('case %i:', values[keys[i]])('m%s=%j', prop, values[keys[i]])('break');
}
gen('}');
} else {
gen('if(typeof d%s!=="object")', prop)('throw TypeError(%j)', field.fullName + ': object expected')('m%s=types[%i].fromObject(d%s)', prop, fieldIndex, prop);
}
} else {
let isUnsigned = false;
switch (field.type) {
case 'double':
case 'float':
gen('m%s=Number(d%s)', prop, prop); // also catches "NaN", "Infinity"
break;
case 'uint32':
case 'fixed32':
gen('m%s=d%s>>>0', prop, prop);
break;
case 'int32':
case 'sint32':
case 'sfixed32':
gen('m%s=d%s|0', prop, prop);
break;
case 'uint64':
isUnsigned = true;
// eslint-disable-line no-fallthrough
case 'int64':
case 'sint64':
case 'fixed64':
case 'sfixed64':
gen('if(util.Long)')('(m%s=util.Long.fromValue(d%s)).unsigned=%j', prop, prop, isUnsigned)('else if(typeof d%s==="string")', prop)('m%s=parseInt(d%s,10)', prop, prop)('else if(typeof d%s==="number")', prop)('m%s=d%s', prop, prop)('else if(typeof d%s==="object")', prop)('m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)', prop, prop, prop, isUnsigned ? 'true' : '');
break;
case 'bytes':
gen('if(typeof d%s==="string")', prop)('util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)', prop, prop, prop)('else if(d%s.length)', prop)('m%s=d%s', prop, prop);
break;
case 'string':
gen('m%s=String(d%s)', prop, prop);
break;
case 'bool':
gen('m%s=Boolean(d%s)', prop, prop);
break;
default:
break;
/* default: gen
("m%s=d%s", prop, prop);
break; */
}
}
return gen;
}
|
javascript
|
{
"resource": ""
}
|
q9606
|
genValuePartial_toObject
|
train
|
function genValuePartial_toObject(gen, field, fieldIndex, prop, map) {
if (field.resolvedType) {
if (field.resolvedType instanceof Enum) {
if (map) {
gen('d%s.set(k, o.enums===String?types[%i].values[m%s.get(k)]:m%s.get(k));', prop, fieldIndex, prop, prop);
} else {
gen('d%s=o.enums===String?types[%i].values[m%s]:m%s', prop, fieldIndex, prop, prop);
}
} else {
if (map) {
gen('d%s.set(k, types[%i].toObject(m%s.get(k),o));', prop, fieldIndex, prop);
} else {
gen('d%s=types[%i].toObject(m%s,o)', prop, fieldIndex, prop);
}
}
} else {
let isUnsigned = false;
switch (field.type) {
case 'double':
case 'float':
if (map) {
gen('d%s.set(k, o.json&&!isFinite(m%s.get(k))?String(m%s.get(k)):m%s.get(k));', prop, prop, prop, prop);
} else {
gen('d%s=o.json&&!isFinite(m%s)?String(m%s):m%s;', prop, prop, prop, prop);
}
break;
case 'uint64':
isUnsigned = true;
// eslint-disable-line no-fallthrough
case 'int64':
case 'sint64':
case 'fixed64':
case 'sfixed64':
if (map) {
gen('if(typeof m%s==="number"){', prop)('d%s.set(k, o.longs===String?String(m%s.get(k)):m%s.get(k));', prop, prop, prop)('} else {')('d%s.set(k, o.longs===String?util.Long.prototype.toString.call(m%s.get(k)):o.longs===Number?new util.LongBits(m%s.get(k).low>>>0,m%s.get(k).high>>>0).toNumber(%s):m%s.get(k));', prop, prop, prop, prop, isUnsigned ? 'true' : '', prop)('}');
} else {
gen('if(typeof m%s==="number"){', prop)('d%s=o.longs===String?String(m%s):m%s;', prop, prop, prop)('} else {')('d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s', prop, prop, prop, prop, isUnsigned ? 'true' : '', prop)('}');
}
break;
case 'bytes':
if (map) {
gen('d%s.set(k, o.bytes===String?util.base64.encode(m%s.get(k),0,m%s.get(k).length):o.bytes===Array?Array.prototype.slice.call(m%s.get(k)):m%s.get(k));', prop, prop, prop, prop, prop);
} else {
gen('d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s', prop, prop, prop, prop, prop);
}
break;
default:
if (map) {
gen('d%s.set(k, m%s.get(k));', prop, prop);
} else {
gen('d%s=m%s', prop, prop);
}
break;
}
}
return gen;
}
|
javascript
|
{
"resource": ""
}
|
q9607
|
checkSum
|
train
|
function checkSum(num) {
if (num == null) {
return 0;
}
var doubled = _splitDigits(num).reverse().map(function(v, idx) {
return idx % 2 === 0 ? v * 2 : v;
});
var sum = doubled.reduce(function(tmp, v) {
return tmp + _sum(v);
}, 0);
var check = 10 - (sum % 10);
return check === 10 ? 0 : check;
}
|
javascript
|
{
"resource": ""
}
|
q9608
|
isValid
|
train
|
function isValid(checkNumber) {
if (checkNumber == null) {
return false;
}
var numbers = _splitDigits(checkNumber);
return numbers.pop() === checkSum(numbers.join(''));
}
|
javascript
|
{
"resource": ""
}
|
q9609
|
generate
|
train
|
function generate(length) {
var len = length - 1;
var ary = new Array(len);
for (var i = 0; i < len; i++) {
ary.push(Math.floor(Math.random() * 10));
}
var num = ary.join('');
return num + '' + checkSum(num);
}
|
javascript
|
{
"resource": ""
}
|
q9610
|
bufferSplice
|
train
|
function bufferSplice (buffer, start, count/*, [...items] */) {
var args = assertArgs(arguments, {
buffer: [Buffer, 'object'],
'[start]': 'integer',
'[count]': 'integer',
'[...items]': [Buffer, 'string', 'array', 'object', 'number']
})
defaults(args, {
start: buffer.length,
count: buffer.length,
items: []
})
buffer = args.buffer
start = args.start
count = args.count
var opts
if (!Buffer.isBuffer(buffer)) {
opts = buffer
buffer = opts.buffer
}
var items = args.items.map(castBuffer)
var end = start + count
var modified = Buffer.concat(
[ buffer.slice(0, start) ]
.concat(items)
.concat(buffer.slice(end, buffer.length))
)
if (opts) {
opts.buffer = modified // opts.buffer becomes modified buffer
return buffer.slice(start, end) // removed buffer
}
return modified // modified buffer
}
|
javascript
|
{
"resource": ""
}
|
q9611
|
mapCOW
|
train
|
function mapCOW(arr, func) {
var res = null;
for(var i=0; i<arr.length; i++) {
var item = func(arr[i]);
if(item !== arr[i]) {
if(!res) {
res = arr.slice();
}
res[i] = item;
}
}
return res || arr;
}
|
javascript
|
{
"resource": ""
}
|
q9612
|
FrameHandler
|
train
|
function FrameHandler(deviceOrFrameHandler) {
var self = this;
// call super class
EventEmitter2.call(this, {
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
if (this.log) {
this.log = _.wrap(this.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
} else if (FrameHandler.prototype.log) {
FrameHandler.prototype.log = _.wrap(FrameHandler.prototype.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
this.log = FrameHandler.prototype.log;
} else {
var debug = require('debug')(this.constructor.name);
this.log = function(msg) {
debug(msg);
};
}
this.analyzeInterval = 20;
if (deviceOrFrameHandler) {
this.incomming = [];
deviceOrFrameHandler.on('receive', function (frame) {
var unwrappedFrame;
if (self.analyzeNextFrame) {
self.incomming = self.incomming.concat(Array.prototype.slice.call(frame, 0));
self.trigger();
} else {
if (self.unwrapFrame) {
unwrappedFrame = self.unwrapFrame(_.clone(frame));
if (self.log) self.log('receive unwrapped frame: ' + unwrappedFrame.toHexDebug());
self.emit('receive', unwrappedFrame);
} else {
if (self.log) self.log('receive frame: ' + frame.toHexDebug());
self.emit('receive', frame);
}
}
});
deviceOrFrameHandler.on('close', function() {
if (self.log) self.log('close');
self.emit('close');
self.removeAllListeners();
deviceOrFrameHandler.removeAllListeners();
deviceOrFrameHandler.removeAllListeners('receive');
self.incomming = [];
});
}
this.on('send', function(frame) {
if (self.wrapFrame) {
var wrappedFrame = self.wrapFrame(_.clone(frame));
if (self.log) self.log('send wrapped frame: ' + wrappedFrame.toHexDebug());
deviceOrFrameHandler.send(wrappedFrame);
} else {
if (self.log) self.log('send frame: ' + frame.toHexDebug());
deviceOrFrameHandler.send(frame);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q9613
|
isValidTransition
|
train
|
function isValidTransition (link, context) {
var isValid = true;
if (!(PromisePipe.envTransitions[context._env] && PromisePipe.envTransitions[context._env][link._env])) {
if (!isSystemTransition(link._env)) {
isValid = false;
}
}
return isValid;
}
|
javascript
|
{
"resource": ""
}
|
q9614
|
passChains
|
train
|
function passChains (first, last, sequence) {
return sequence.map(function (el) {
return el._id;
}).slice(first, last + 1);
}
|
javascript
|
{
"resource": ""
}
|
q9615
|
lastChain
|
train
|
function lastChain (first, sequence) {
var index = getIndexOfNextEnvAppearance(first, PromisePipe.env, sequence);
return index === -1 ? (sequence.length - 1) : (index - 1);
}
|
javascript
|
{
"resource": ""
}
|
q9616
|
getChainIndexById
|
train
|
function getChainIndexById(id, sequence){
return sequence.map(function(el){
return el._id;
}).indexOf(id);
}
|
javascript
|
{
"resource": ""
}
|
q9617
|
getIndexOfNextEnvAppearance
|
train
|
function getIndexOfNextEnvAppearance(fromIndex, env, sequence){
return sequence.map(function(el){
return el._env;
}).indexOf(env, fromIndex);
}
|
javascript
|
{
"resource": ""
}
|
q9618
|
rangeChain
|
train
|
function rangeChain (id, sequence) {
var first = getChainIndexById(id, sequence);
return [first, lastChain(first, sequence)];
}
|
javascript
|
{
"resource": ""
}
|
q9619
|
setMessage
|
train
|
function setMessage (msg) {
if (msg && typeof msg === 'string') {
this.message = msg
} else if (this.constructor.name !== 'CustomError') {
this.message = this.constructor.DEFAULT_ERROR_MESSAGE
} else {
this.message = undefined
}
}
|
javascript
|
{
"resource": ""
}
|
q9620
|
createStackTrace
|
train
|
function createStackTrace () {
var stack = new Error().stack
var splited = stack.split('\n')
var modifiedStack = splited[0].concat('\n', splited.splice(3).join('\n'))
this.stack = modifiedStack
}
|
javascript
|
{
"resource": ""
}
|
q9621
|
EventedSerialDeviceLoader
|
train
|
function EventedSerialDeviceLoader(Device, vendorId, productId) {
// call super class
SerialDeviceLoader.call(this, Device, false);
this.vidPidPairs = [];
if (!productId && _.isArray(vendorId)) {
this.vidPidPairs = vendorId;
} else {
this.vidPidPairs = [{vendorId: vendorId, productId: productId}];
}
}
|
javascript
|
{
"resource": ""
}
|
q9622
|
getMaxLines
|
train
|
function getMaxLines(height) {
var availHeight = height || element.clientHeight,
lineHeight = getLineHeight(element);
return Math.max(Math.floor(availHeight / lineHeight), 0);
}
|
javascript
|
{
"resource": ""
}
|
q9623
|
getLineHeight
|
train
|
function getLineHeight(elem) {
var lh = computeStyle(elem, 'line-height');
if (lh == 'normal') {
// Normal line heights vary from browser to browser. The spec recommends
// a value between 1.0 and 1.2 of the font size. Using 1.1 to split the diff.
lh = parseInt(computeStyle(elem, 'font-size')) * 1.2;
}
return parseInt(lh);
}
|
javascript
|
{
"resource": ""
}
|
q9624
|
getLastChild
|
train
|
function getLastChild(elem) {
//Current element has children, need to go deeper and get last child as a text node
if (elem.lastChild.children && elem.lastChild.children.length > 0) {
return getLastChild(Array.prototype.slice.call(elem.children).pop());
}
//This is the absolute last child, a text node, but something's wrong with it. Remove it and keep trying
else if (!elem.lastChild || !elem.lastChild.nodeValue || elem.lastChild.nodeValue === '' || elem.lastChild.nodeValue == opt.truncationChar) {
elem.lastChild.parentNode.removeChild(elem.lastChild);
return getLastChild(element);
}
//This is the last child we want, return it
else {
return elem.lastChild;
}
}
|
javascript
|
{
"resource": ""
}
|
q9625
|
truncate
|
train
|
function truncate(target, maxHeight) {
if (!maxHeight) {
return;
}
/**
* Resets global variables.
*/
function reset() {
splitOnChars = opt.splitOnChars.slice(0);
splitChar = splitOnChars[0];
chunks = null;
lastChunk = null;
}
var nodeValue = target.nodeValue.replace(opt.truncationChar, '');
//Grab the next chunks
if (!chunks) {
//If there are more characters to try, grab the next one
if (splitOnChars.length > 0) {
splitChar = splitOnChars.shift();
}
//No characters to chunk by. Go character-by-character
else {
splitChar = '';
}
chunks = nodeValue.split(splitChar);
}
//If there are chunks left to remove, remove the last one and see if
// the nodeValue fits.
if (chunks.length > 1) {
// console.log('chunks', chunks);
lastChunk = chunks.pop();
// console.log('lastChunk', lastChunk);
applyEllipsis(target, chunks.join(splitChar));
}
//No more chunks can be removed using this character
else {
chunks = null;
}
//Insert the custom HTML before the truncation character
if (truncationHTMLContainer) {
target.nodeValue = target.nodeValue.replace(opt.truncationChar, '');
element.innerHTML = target.nodeValue + ' ' + truncationHTMLContainer.innerHTML + opt.truncationChar;
}
//Search produced valid chunks
if (chunks) {
//It fits
if (element.clientHeight <= maxHeight) {
//There's still more characters to try splitting on, not quite done yet
if (splitOnChars.length >= 0 && splitChar !== '') {
applyEllipsis(target, chunks.join(splitChar) + splitChar + lastChunk);
chunks = null;
}
//Finished!
else {
return element.innerHTML;
}
}
}
//No valid chunks produced
else {
//No valid chunks even when splitting by letter, time to move
//on to the next node
if (splitChar === '') {
applyEllipsis(target, '');
target = getLastChild(element);
reset();
}
}
//If you get here it means still too big, let's keep truncating
if (opt.animate) {
setTimeout(function() {
truncate(target, maxHeight);
}, opt.animate === true ? 10 : opt.animate);
} else {
return truncate(target, maxHeight);
}
}
|
javascript
|
{
"resource": ""
}
|
q9626
|
reset
|
train
|
function reset() {
splitOnChars = opt.splitOnChars.slice(0);
splitChar = splitOnChars[0];
chunks = null;
lastChunk = null;
}
|
javascript
|
{
"resource": ""
}
|
q9627
|
_animateFunc
|
train
|
function _animateFunc(func, element, duration, opts) {
opts = Object.assign({}, opts);
var tween;
return new Promise(function(resolve, reject, onCancel) {
opts.onComplete = resolve;
tween = func(element, duration, opts);
onCancel &&
onCancel(function() {
tween.kill();
});
});
}
|
javascript
|
{
"resource": ""
}
|
q9628
|
animate
|
train
|
function animate(Promise, TweenModule) {
var animateTo = _animateFunc.bind(null, TweenModule.to);
var util = animateTo;
util.to = animateTo;
util.from = _animateFunc.bind(null, TweenModule.from);
util.set = function animateSet(element, params) {
params = Object.assign({}, params);
return new Promise(function(resolve, reject) {
params.onComplete = resolve;
TweenModule.set(element, params);
});
};
util.fromTo = function animateFromTo(element, duration, from, to) {
to = Object.assign({}, to);
var tween;
return new Promise(function(resolve, reject, onCancel) {
to.onComplete = resolve;
tween = TweenModule.fromTo(element, duration, from, to);
onCancel &&
onCancel(function() {
tween.kill();
});
});
};
util.killTweensOf = TweenModule.killTweensOf.bind(TweenModule);
util.all = Promise.all;
return util;
}
|
javascript
|
{
"resource": ""
}
|
q9629
|
binOpEmitter
|
train
|
function binOpEmitter(str) {
return function(node, frame) {
this.compile(node.left, frame);
this.emit(str);
this.compile(node.right, frame);
};
}
|
javascript
|
{
"resource": ""
}
|
q9630
|
train
|
function( fn ){
// Get the object's base
var objectBase = getObjectBase( this, fn );
// If the function is not found anywhere in the prototype chain
// there is a pretty big problem
if( ! objectBase.base ) throw new Error( "inherited coun't find method in chain (getInherited)" );
// At this point, I know the key. To look for the super method, I
// only have to check if one of the parent __proto__ has a matching key `k`
var p = Object.getPrototypeOf( objectBase.base );
return p[ objectBase.key ];
}
|
javascript
|
{
"resource": ""
}
|
|
q9631
|
train
|
function(){
// These will be worked out from `arguments`
var SuperCtorList, protoMixin;
var MixedClass, ResultClass;
var list = [];
var i, l, ii, ll;
var proto;
var r = workoutDeclareArguments( arguments );
SuperCtorList = r.SuperCtorList;
protoMixin = r.protoMixin;
// No parameters: inheriting from Object directly, no multiple inheritance
if( SuperCtorList.length === 0 ){
MixedClass = Object;
}
// Only one parameter: straght single inheritance.
else if( SuperCtorList.length === 1 ){
MixedClass = SuperCtorList[ 0 ];
// More than one parameter: multiple inheritance at work
// MixedClass will end up being an artificially made constructor
// where the prototype chain is the sum of _every_ prototype in
// every element of SuperCtorList (taking out duplicates)
} else {
MixedClass = Object;
// NOW:
// Go through every __proto__ of every derivative class, and augment
// MixedClass by inheriting from A COPY OF each one of them.
list = [];
for( i = 0, l = SuperCtorList.length; i < l; i ++ ){
// Get the prototype list, in the right order
// (the reversed discovery order)
// The result will be placed in `subList`
var subList = [];
if( typeof SuperCtorList[ i ] === 'undefined' || typeof SuperCtorList[ i ].prototype === 'undefined'){
throw new Error("Invalid constructor!")
}
proto = SuperCtorList[ i ].prototype;
while( proto ){
if( proto.constructor !== Object ) subList.push( proto );
proto = Object.getPrototypeOf( proto );
}
subList = subList.reverse();
// Add each element of sublist as long as it's not already in the main `list`
for( ii = 0, ll = subList.length; ii < ll; ii ++ ){
if( ! constructorAlreadyInList( subList[ ii ].constructor, list ) ) list.push( subList[ ii ] );
}
}
// For each element in the prototype list that isn't Object(),
// augment MixedClass with a copy of the new prototype
for( ii = 0, ll = list.length; ii < ll; ii ++ ){
proto = list[ ii ];
var M = MixedClass;
if( proto.constructor !== Object ){
MixedClass = makeConstructor( MixedClass, proto, proto.constructor );
copyClassMethods( M, MixedClass ); // Methods previously inherited
copyClassMethods( proto.constructor, MixedClass ); // Extra methods from the father constructor
}
}
}
// Finally, inherit from the MixedClass, and add
// class methods over
// MixedClass might be:
// * Object (coming from no inheritance),
// * SuperCtorList[0] (coming from single inheritance)
// * A constructor with the appropriate prototype chain (multiple inheritance)
ResultClass = makeConstructor( MixedClass, protoMixin );
copyClassMethods( MixedClass, ResultClass );
// Add getInherited, inherited() and inheritedAsync() to the prototype
// (only if they are not already there)
if( ! ResultClass.prototype.getInherited ) {
ResultClass.prototype.getInherited = getInherited;
}
if( ! ResultClass.prototype.inherited ) {
ResultClass.prototype.inherited = makeInheritedFunction( 'sync' );
}
if( ! ResultClass.prototype.inheritedAsync ) {
ResultClass.prototype.inheritedAsync = makeInheritedFunction( 'async' );
}
// Add instanceOf
if( ! ResultClass.prototype.instanceOf ) {
ResultClass.prototype.instanceOf = instanceOf;
}
// Add class-wide method `extend`
ResultClass.extend = function(){
return extend.apply( this, arguments );
};
// That's it!
return ResultClass;
}
|
javascript
|
{
"resource": ""
}
|
|
q9632
|
elementType
|
train
|
function elementType(element) {
var name = element.nodeName.toLowerCase();
if (name !== "input") {
if (name === "select" && element.multiple) {
return "select-multiple";
}
return name;
}
var type = element.getAttribute('type');
if (!type) {
return "text";
}
return type.toLowerCase();
}
|
javascript
|
{
"resource": ""
}
|
q9633
|
getValue
|
train
|
function getValue(element) {
var name = elementType(element);
switch (name) {
case "checkbox":
case "radio":
if (!element.checked) {
return false;
}
var val = element.getAttribute('value');
return val == null ? true : val;
case "select":
case "select-multiple":
var options = element.options;
var values = [];
for (var i = 0, len = options.length; i < len; i++) {
if (options[i].selected) {
values.push(options[i].value);
}
}
return name === "select-multiple" ? values : values[0];
default:
return element.value;
}
}
|
javascript
|
{
"resource": ""
}
|
q9634
|
getActivity
|
train
|
function getActivity(activityId) {
var activity = activities[activityId];
if (activity === undefined) {
throw new Error('activity with id "' + activityId + '" not found.');
}
return activity;
}
|
javascript
|
{
"resource": ""
}
|
q9635
|
writeActivity
|
train
|
function writeActivity(template, activity) {
if (!enabled) {
return;
}
var handlers = outputHandlers.get();
if (handlers.length === 0) {
throw new Error('No output handlers defined.');
}
handlers.forEach(function(handler) {
handler(template(activity));
});
}
|
javascript
|
{
"resource": ""
}
|
q9636
|
createActivity
|
train
|
function createActivity(activityMessage) {
if (activityMessage === undefined ||
activityMessage === undefined ||
typeof activityMessage !== 'string') {
throw new Error('Creating a new activity requires an activity message.');
}
var activityId = uuid++;
var activity = {
id: activityId,
message: activityMessage,
timestamps: []
};
activities[activityId] = activity;
return activityId;
}
|
javascript
|
{
"resource": ""
}
|
q9637
|
markActivity
|
train
|
function markActivity(activityId) {
var activity = getActivity(activityId);
var timeNow = Date.now();
activity.timestamps.push(timeNow);
return timeNow;
}
|
javascript
|
{
"resource": ""
}
|
q9638
|
startActivity
|
train
|
function startActivity(activityMessage) {
var activityId = createActivity(activityMessage);
markActivity(activityId);
var activity = getActivity(activityId);
writeActivity(activityEvents.start, activity);
return activityId;
}
|
javascript
|
{
"resource": ""
}
|
q9639
|
endActivity
|
train
|
function endActivity(activityId) {
markActivity(activityId);
var activity = destroyActivity(activityId)
writeActivity(activityEvents.end, activity);
return activity;
}
|
javascript
|
{
"resource": ""
}
|
q9640
|
JSONPathNode
|
train
|
function JSONPathNode(n) {
// Create a RED node
RED.nodes.createNode(this,n);
// Store local copies of the node configuration (as defined in the .html)
this.expression = n.expression;
this.split = n.split;
var node = this;
this.on("input", function(msg) {
if ( msg.hasOwnProperty("payload") ) {
var input = msg.payload;
if (typeof msg.payload === "string") {
// It's a string: parse it as JSON
try {
input = JSON.parse(msg.payload);
} catch (e) {
node.warn("The message received is not JSON. Ignoring it.");
return;
}
}
// Evalute the JSONPath expresssion
var evalResult = jsonPath.eval(input, node.expression);
if (!node.split) {
// Batch it in one message. Carry pre-existing properties
msg.payload = evalResult;
node.send(msg);
} else {
// Send one message per match result
var response = evalResult.map(function (value) {
return {"payload": value};
});
node.send([response]);
}
}
});
this.on("close", function() {
// Called when the node is shutdown - eg on redeploy.
// Allows ports to be closed, connections dropped etc.
// eg: this.client.disconnect();
});
}
|
javascript
|
{
"resource": ""
}
|
q9641
|
Template
|
train
|
function Template (filename, context) {
// Save the context for reuse in sub-templates
this.context = context || {}
this.context.include = this.render.bind(this)
this.context.forEach = forEach
// Save the filename for the initial render
this.filename = filename
// Create a cache so we only read files once
this.cache = {}
}
|
javascript
|
{
"resource": ""
}
|
q9642
|
SerialDeviceGuider
|
train
|
function SerialDeviceGuider(deviceLoader) {
var self = this;
// call super class
DeviceGuider.call(this, deviceLoader);
this.currentState.getDeviceByPort = function(port) {
return _.find(self.currentState.plugged, function(d) {
return d.get('portName') && port && d.get('portName').toLowerCase() === port.toLowerCase();
});
};
this.currentState.getConnectedDeviceByPort = function(port) {
return _.find(self.currentState.connected, function(d) {
return d.get('portName') && port && d.get('portName').toLowerCase() === port.toLowerCase();
});
};
}
|
javascript
|
{
"resource": ""
}
|
q9643
|
HashCodeContext
|
train
|
function HashCodeContext(value, hashCode, options) {
if (options == null) {
options = {};
}
/**
* A reference to {@link Nevis.hashCode} which can be called within a {@link HashCodeGenerator}.
*
* @private
* @type {Function}
*/
this._hashCode = hashCode;
/**
* The options to be used to generate the hash code for the value.
*
* @public
* @type {Nevis~HashCodeOptions}
*/
this.options = {
allowCache: options.allowCache !== false,
filterProperty: options.filterProperty != null ? options.filterProperty : function() {
return true;
},
ignoreHashCode: Boolean(options.ignoreHashCode),
ignoreInherited: Boolean(options.ignoreInherited),
ignoreMethods: Boolean(options.ignoreMethods)
};
/**
* The string representation of the value whose hash code is to be generated.
*
* This is generated using <code>Object.prototype.toString</code> and is intended to be primarily used for more
* specific type-checking.
*
* @public
* @type {string}
*/
this.string = Object.prototype.toString.call(value);
/**
* The type of the value whose hash code is to be generated.
*
* This is generated using <code>typeof</code> and is intended to be primarily used for simple type-checking.
*
* @public
* @type {string}
*/
this.type = typeof value;
/**
* The value whose hash code is to be generated.
*
* @public
* @type {*}
*/
this.value = value;
}
|
javascript
|
{
"resource": ""
}
|
q9644
|
checkPackageJsonInGit
|
train
|
function checkPackageJsonInGit () {
return exec('git', ['status', '--porcelain', 'package.json'])
.then(function ([stdout, stderr]) {
debug('git status --porcelain package.json', 'stdout', stdout, 'stderr', stderr)
if (stdout.indexOf('package.json') >= 0) {
throw new Error('package.json has changes!\n' +
'I would like to add scripts to your package.json, but ' +
'there are changes that have not been commited yet.\n' +
'I don\'t want to damage anything, so I\'m not doing anyhting right now. ' +
'Please commit your package.json')
}
})
}
|
javascript
|
{
"resource": ""
}
|
q9645
|
combineStatsAndIndexes
|
train
|
function combineStatsAndIndexes(done, results) {
var indexes = results.getIndexes;
var stats = results.getIndexStats;
var sizes = results.getIndexSizes;
_.each(indexes, function(idx, i) {
_.assign(indexes[i], stats[idx.name]);
_.assign(indexes[i], sizes[idx.name]);
});
done(null, indexes);
}
|
javascript
|
{
"resource": ""
}
|
q9646
|
OpenConnection
|
train
|
function OpenConnection(connection) {
let base = new pg.Client({
host: connection.Hostname || 'localhost',
port: parseInt(connection.Port) || 5432,
user: connection.Username,
password: connection.Password,
database: connection.Database
});
base.connect();
return new PostgreSQL(base);
}
|
javascript
|
{
"resource": ""
}
|
q9647
|
train
|
function(renderData){
var renderArr = Object.keys(renderData).map(function(mask){
return {
mask: mask,
context: renderData[mask].context,
component: renderData[mask].component,
params: renderData[mask].params,
data: renderData[mask].data
}
})
function renderComp(renderArr){
var partial = renderArr.shift();
if(renderArr.length > 0) partial.params.children = [renderComp(renderArr)];
partial.params.mask = partial.mask;
partial.params.data = partial.data;
partial.params.context = partial.context;
if(!partial.component) {
var result = partial.data || '';
if(partial.params.children && partial.params.children[0]) result +=partial.params.children[0];
return result;
}
return partial.component(partial.params)
}
return renderComp(renderArr);
}
|
javascript
|
{
"resource": ""
}
|
|
q9648
|
DeviceLoader
|
train
|
function DeviceLoader() {
var self = this;
// call super class
EventEmitter2.call(this, {
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
if (this.log) {
this.log = _.wrap(this.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
} else if (DeviceLoader.prototype.log) {
DeviceLoader.prototype.log = _.wrap(DeviceLoader.prototype.log, function(func, msg) {
func(self.constructor.name + ': ' + msg);
});
this.log = DeviceLoader.prototype.log;
} else {
var debug = require('debug')(this.constructor.name);
this.log = function(msg) {
debug(msg);
};
}
this.lookupIntervalId = null;
this.oldDevices = [];
this.isRunning = false;
}
|
javascript
|
{
"resource": ""
}
|
q9649
|
createLogger
|
train
|
function createLogger (config) {
config = config || {}
let level
if (process.env.KOOP_LOG_LEVEL) {
level = process.env.KOOP_LOG_LEVEL
} else if (process.env.NODE_ENV === 'production') {
level = 'info'
} else {
level = 'debug'
}
if (!config.logfile) {
// no logfile defined, log to STDOUT an STDERRv
const debugConsole = new winston.transports.Console({
colorize: process.env.NODE_ENV === 'production',
level,
stringify: true,
json: true
})
return new winston.Logger({ transports: [debugConsole] })
}
// we need a dir to do log rotation so we get the dir from the file
const logpath = path.dirname(config.logfile)
const logAll = new winston.transports.File({
filename: config.logfile,
name: 'log.all',
dirname: logpath,
colorize: true,
json: false,
level,
formatter: formatter
})
const logError = new winston.transports.File({
filename: config.logfile.replace('.log', '.error.log'),
name: 'log.error',
dirname: logpath,
colorize: true,
json: false,
level: 'error',
formatter: formatter
})
// always log errors
const transports = [logError]
// only log everthing if debug mode is on
if (process.env['LOG_LEVEL'] === 'debug') {
transports.push(logAll)
}
return new winston.Logger({ transports })
}
|
javascript
|
{
"resource": ""
}
|
q9650
|
formatter
|
train
|
function formatter (options) {
const line = [
new Date().toISOString(),
options.level
]
if (options.message !== undefined) line.push(options.message)
if (options.meta && Object.keys(options.meta).length) line.push(JSON.stringify(options.meta))
return line.join(' ')
}
|
javascript
|
{
"resource": ""
}
|
q9651
|
difference
|
train
|
function difference(object, base) {
return transform(object, (result, value, key) => {
if (!isEqual(value, base[key])) {
result[key] = isObject(value) && isObject(base[key]) ? difference(value, base[key]) : value;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q9652
|
train
|
function ( method, params, cb ) {
if ( typeof params === 'function' ) {
cb = params;
params = {};
}
params = extend(params, {request: method});
this.__request({
method: 'get',
url: this.options.api_url,
qs: params
}, function ( err, response, data ) {
if ( err ) {
cb(err, response, data);
} else {
try {
data = JSON.parse(data);
} catch ( parseError ) {
cb(new Error('Status Code: ' + response.statusCode), response, data);
}
if ( response.statusCode === 200 ) {
cb(null, response, data);
} else {
cb(new Error('Status Code: ' + response.statusCode), response, data);
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9653
|
_createBiquadFilter
|
train
|
function _createBiquadFilter (defaults) {
return function (context, opts) {
if (audioContext) {
opts = context;
context = audioContext;
}
opts = assign(opts, defaults);
var filter = context.createBiquadFilter();
Object.keys(opts).forEach(function (option) {
if (option !== 'type') {
filter[option].value = opts[option];
} else {
filter.type = opts[option];
}
});
return filter;
};
}
|
javascript
|
{
"resource": ""
}
|
q9654
|
train
|
function(options, ...rest) {
Entity.apply(this, [options, ...rest]);
this.itemType = options.itemType;
this.itemFactory = options.itemFactory;
this.body = defaults(options.body, {
count: 0,
items: []
});
if (options.items) {
this.body.items = options.items.map(function(item) {
return this.createItemEntity(item);
});
this.body.count = this.body.items.length;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9655
|
set_references
|
train
|
function set_references( vm_options )
{
if ( vm_options.Dialog )
{
Dialog = vm_options.Dialog;
}
if ( !Dialog )
{
if ( typeof window !== 'undefined' && window.Dialog )
{
Dialog = window.Dialog;
}
else
{
throw new Error( 'No reference to Dialog' );
}
}
if ( vm_options.GiDispa )
{
GiDispa = vm_options.GiDispa;
}
else if ( !GiDispa && typeof window !== 'undefined' && window.GiDispa )
{
GiDispa = window.GiDispa;
}
if ( vm_options.GiLoad )
{
GiLoad = vm_options.GiLoad;
}
else if ( !GiLoad && typeof window !== 'undefined' && window.GiLoad )
{
GiLoad = window.GiLoad;
}
if ( vm_options.GlkOte )
{
GlkOte = vm_options.GlkOte;
}
if ( !GlkOte )
{
if ( typeof window !== 'undefined' && window.GlkOte )
{
GlkOte = window.GlkOte;
}
else
{
throw new Error('No reference to GlkOte');
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9656
|
patch
|
train
|
function patch(element, previous, attrs) {
if (!previous && !attrs) {
return attrs;
}
var attrName, ns, name, value, split;
previous = previous || {};
attrs = attrs || {};
for (attrName in previous) {
if (previous[attrName] && !attrs[attrName]) {
split = splitAttrName(attrName);
ns = namespaces[split[0]];
name = split[1];
element.removeAttributeNS(ns, name);
}
}
for (attrName in attrs) {
value = attrs[attrName];
if (previous[attrName] === value) {
continue;
}
if (value) {
split = splitAttrName(attrName);
ns = namespaces[split[0]];
name = split[1];
element.setAttributeNS(ns, name, value);
}
}
return attrs;
}
|
javascript
|
{
"resource": ""
}
|
q9657
|
getFile
|
train
|
function getFile(filepath) {
var fileObj = {
path: filepath,
content: null
};
try {
fs.accessSync(filepath, fs.F_OK);
} catch(e) {
console.log(e.message);
return fileObj;
}
fileObj.content = fs.readFileSync(filepath, 'utf-8').trim();
return fileObj;
}
|
javascript
|
{
"resource": ""
}
|
q9658
|
Floppy
|
train
|
function Floppy(url, fn) {
if (!(this instanceof Floppy)) return new Floppy(url, fn);
this.readyState = Floppy.LOADING;
this.start = +new Date();
this.callbacks = [];
this.dependent = 0;
this.cleanup = [];
this.url = url;
if ('function' === typeof fn) {
this.add(fn);
}
}
|
javascript
|
{
"resource": ""
}
|
q9659
|
translateResponse
|
train
|
function translateResponse(obj){
for(var k in obj){
if(obj[k] instanceof Array){
for(var i=0;i<obj[k].length;i++){
// just an array of strings
if(obj[k][i] instanceof Buffer){
obj[k][i] = obj[k][i].toString()
} else {
// and array of objects..
for(var k1 in obj[k][i]){
if(obj[k][i][k1] instanceof Buffer){
obj[k][i][k1] = obj[k][i][k1].toString()
}
}
}
}
} else if(obj[k] instanceof Buffer) {
obj[k] = obj[k].toString()
} else {
for(var rk in obj[k]){
if(obj[k][rk] instanceof Buffer){
obj[k][rk] = obj[k][rk].toString()
} else if(obj[k][rk] instanceof Array){
for(var i=0;i<obj[k][rk].length;i++){
if(obj[k][rk][i] instanceof Buffer){
obj[k][rk][i] = obj[k][rk][i].toString()
} else {
obj[k][rk][i] = obj[k][rk][i];
}
}
}
}
}
}
return obj
}
|
javascript
|
{
"resource": ""
}
|
q9660
|
train
|
function(req) {
if(!req || !req.url) return false;
if(typeof(path) === 'string') {
return (req.url).match(path) && ((req.url).match(path).index === 0);
// RegExp
} else {
return (req.url).match(path) !== null;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q9661
|
ignoreValue
|
train
|
function ignoreValue(value) {
if (value === null || value === undefined || value.length === 0) {
return true;
}
if (value.length === 0) {
return true;
}
if (typeof (value) === 'object') {
return false;
}
value = value.toLowerCase();
var ignoreValues = ['not available', 'no information'];
for (var x = 0; x < ignoreValues.length; x++) {
if (value.indexOf(ignoreValues[x]) >= 0) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q9662
|
LDA
|
train
|
function LDA(...classes) {
// Compute pairwise LDA classes (needed for multiclass LDA)
if(classes.length < 2) {
throw new Error('Please pass at least 2 classes');
}
let numberOfPairs = classes.length * (classes.length - 1) / 2;
let pair1 = 0;
let pair2 = 1;
let pairs = new Array(numberOfPairs);
for(let i = 0; i < numberOfPairs; i++){
pairs[i] = computeLdaParams(classes[pair1], classes[pair2], pair1, pair2);
pair2++;
if(pair2 == classes.length) {
pair1++;
pair2 = pair1 + 1;
}
}
this.pairs = pairs;
this.numberOfClasses = classes.length;
}
|
javascript
|
{
"resource": ""
}
|
q9663
|
train
|
function(Device, filter) {
var sub = new EventEmitter2({
wildcard: true,
delimiter: ':',
maxListeners: 1000 // default would be 10!
});
sub.Device = Device;
sub.filter = filter;
sub.oldDevices = [];
sub.newDevices = [];
/**
* Calls the callback with an array of devices.
* @param {Array} ports When called within this file this are the listed system ports. [optional]
* @param {Function} callback The function, that will be called when finished lookup.
* `function(err, devices){}` devices is an array of Device objects.
*/
sub.lookup = function(ports, callback) {
if (!callback) {
callback = ports;
ports = null;
}
if (this.newDevices.length > 0) {
if (callback) { callback(null, this.newDevices); }
return;
} else {
var self = this;
globalSerialDeviceLoader.lookup(function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err, self.newDevices); }
});
}
};
/**
* Calls lookup function with optional callback
* and emits 'plug' for new attached devices
* and 'unplug' for removed devices.
* @param {Function} callback The function, that will be called when finished triggering. [optional]
* `function(err, devices){}` devices is an array of Device objects.
*/
sub.trigger = function(callback) {
var self = this;
globalSerialDeviceLoader.trigger(function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err, self.newDevices); }
});
};
/**
* Starts to lookup.
* @param {Number} interval The interval milliseconds. [optional]
* @param {Function} callback The function, that will be called when trigger has started. [optional]
* `function(err, devices){}` devices is an array of Device objects.
*/
sub.startLookup = function(interval, callback) {
if (!callback && _.isFunction(interval)) {
callback = interval;
interval = null;
}
subscribers.push(this);
var self = this;
if (isRunning) {
if (callback) { callback(null, self.newDevices); }
return;
} else {
globalSerialDeviceLoader.startLookup(interval, function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err, self.newDevices); }
});
}
};
/**
* Removes itself as subscriber.
* If last stops the interval that calls trigger function.
*/
sub.stopLookup = function() {
var self = this;
if (!isRunning) {
return;
} else {
subscribers = _.reject(function(s) {
return s === self;
});
if (subscribers.length === 0) {
globalSerialDeviceLoader.stopLookup();
}
return;
}
};
return sub;
}
|
javascript
|
{
"resource": ""
}
|
|
q9664
|
train
|
function(callback) {
sp.list(function(err, ports) {
if (err && !err.name) {
err = new Error(err);
}
if (err && callback) { return callback(err); }
async.forEach(subscribers, function(s, callback) {
if (s) {
var resPorts = s.filter(ports);
var devices = _.map(resPorts, function(p) {
var found = _.find(s.oldDevices, function(dev) {
return dev.get('portName') && p.comName && dev.get('portName').toLowerCase() === p.comName.toLowerCase();
});
if (found) {
return found;
} else {
var newDev = new s.Device(p.comName);
newDev.set(p);
return newDev;
}
}) || [];
s.newDevices = devices;
}
callback(null);
}, function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { return callback(err); }
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9665
|
train
|
function(callback) {
globalSerialDeviceLoader.lookup(function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (err && callback) { return callback(err); }
async.forEach(subscribers, function(s, callback) {
if (s && s.oldDevices.length !== s.newDevices.length) {
var devs = [];
if (s.oldDevices.length > s.newDevices.length) {
devs = _.difference(s.oldDevices, s.newDevices);
_.each(devs, function(d) {
if (s.log) s.log('unplug device with id ' + device.id);
if (d.close) {
d.close();
}
s.emit('unplug', d);
});
} else {
devs = _.difference(s.newDevices, s.oldDevices);
_.each(devs, function(d) {
if (s.log) s.log('plug device with id ' + device.id);
s.emit('plug', d);
});
}
s.oldDevices = s.newDevices;
}
callback(null);
}, function(err) {
if (err && !err.name) {
err = new Error(err);
}
if (callback) { return callback(err); }
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9666
|
train
|
function(interval, callback) {
if (lookupIntervalId) {
return;
}
isRunning = true;
if (!callback && _.isFunction(interval)) {
callback = interval;
interval = null;
}
interval = interval || 500;
globalSerialDeviceLoader.trigger(function(err) {
var triggering = false;
lookupIntervalId = setInterval(function() {
if (triggering) return;
triggering = true;
globalSerialDeviceLoader.trigger(function() {
triggering = false;
});
}, interval);
if (err && !err.name) {
err = new Error(err);
}
if (callback) { callback(err); }
});
}
|
javascript
|
{
"resource": ""
}
|
|
q9667
|
cpy32
|
train
|
function cpy32 (d, s) {
for (var i = 0; i < 32; i++)
d[i] = s[i];
}
|
javascript
|
{
"resource": ""
}
|
q9668
|
forLeftButton
|
train
|
function forLeftButton(props) {
const { position, scene, scenes } = props;
const interpolate = getSceneIndicesForInterpolationInputRange(props);
if (!interpolate) return { opacity: 0 };
const { first, last } = interpolate;
const index = scene.index;
return {
opacity: position.interpolate({
inputRange: [
first,
first + Math.abs(index - first) / 2,
index,
last - Math.abs(last - index) / 2,
last,
],
outputRange: [0, 0.5, 1, 0.5, 0],
}),
};
}
|
javascript
|
{
"resource": ""
}
|
q9669
|
all
|
train
|
function all (extent, minZoom, maxZoom) {
const tiles = []
const grid = single(extent, minZoom, maxZoom)
while (true) {
const {value, done} = grid.next()
if (done) break
tiles.push(value)
}
return tiles
}
|
javascript
|
{
"resource": ""
}
|
q9670
|
levels
|
train
|
function levels (extent, minZoom, maxZoom) {
const extents = []
if (extent === undefined) throw new Error('extent is required')
if (minZoom === undefined) throw new Error('minZoom is required')
if (maxZoom === undefined) throw new Error('maxZoom is required')
// Single Array
if (extent.length === 4 && extent[0][0] === undefined) { extents.push({bbox: extent, minZoom, maxZoom}) }
// Multiple Array
if (extent.length && extent[0][0] !== undefined) { extent.map(inner => extents.push({bbox: inner, minZoom, maxZoom})) }
// GeoJSON
featureEach(extent, feature => {
const bbox = turfBBox(feature)
const featureMinZoom = feature.properties.minZoom || feature.properties.minzoom || minZoom
const featureMaxZoom = feature.properties.maxZoom || feature.properties.maxzoom || maxZoom
extents.push({bbox, minZoom: featureMinZoom, maxZoom: featureMaxZoom})
})
const levels = []
for (const {bbox, minZoom, maxZoom} of extents) {
let [x1, y1, x2, y2] = bbox
for (const zoom of range(minZoom, maxZoom + 1)) {
if (y2 > 85) y2 = 85
if (y2 < -85) y2 = -85
const t1 = lngLatToTile([x1, y1], zoom)
const t2 = lngLatToTile([x2, y2], zoom)
// Columns
let columns = []
// Fiji - World divided into two parts
if (t1[0] > t2[0]) {
// right world +180 degrees
const maxtx = Math.pow(2, zoom) - 1
const rightColumns = range(t1[0], maxtx + 1)
rightColumns.forEach(column => columns.push(column))
// left world -180 degrees
const mintx = 0
const leftColumns = range(mintx, t2[0] + 1)
leftColumns.forEach(column => columns.push(column))
} else {
// Normal World
const mintx = Math.min(t1[0], t2[0])
const maxtx = Math.max(t1[0], t2[0])
columns = range(mintx, maxtx + 1)
}
// Rows
const minty = Math.min(t1[1], t2[1])
const maxty = Math.max(t1[1], t2[1])
const rows = range(minty, maxty + 1)
levels.push([columns, rows, zoom])
}
}
return levels
}
|
javascript
|
{
"resource": ""
}
|
q9671
|
count
|
train
|
function count (extent, minZoom, maxZoom, quick) {
quick = quick || 1000
let count = 0
// Quick count
if (quick !== -1) {
for (const [columns, rows] of levels(extent, minZoom, maxZoom)) {
count += rows.length * columns.length
}
if (count > quick) { return count }
}
// Accurate count
count = 0
const grid = single(extent, minZoom, maxZoom)
while (true) {
const {done} = grid.next()
if (done) { break }
count++
}
return count
}
|
javascript
|
{
"resource": ""
}
|
q9672
|
normalize
|
train
|
function normalize(file, fn) {
var orig = utils.extend({}, file);
// support paths
if (typeof fn === 'string') {
file.type = 'path';
file.path = fn;
file.origPath = fn;
file = resolve(file, file.options);
// support functions
} else if (typeof fn === 'function') {
file.type = 'function';
file.path = file.name;
file.fn = fn;
// support instances
} else if (utils.isAppArg(file.app)) {
file.type = 'app';
file.path = file.name;
file.app = fn;
} else {
throw new TypeError('expected env to be a string or function');
}
if (file === null) {
var name = typeof fn === 'string' ? fn : orig.key;
throw new Error('cannot resolve: ' + util.inspect(name));
}
return file;
}
|
javascript
|
{
"resource": ""
}
|
q9673
|
genTypePartial
|
train
|
function genTypePartial(gen, field, fieldIndex, ref) {
return field.resolvedType.group ?
gen('types[%i].encode(%s,w.uint32(%i)).uint32(%i)', fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0) :
gen('types[%i].encode(%s,w.uint32(%i).fork()).ldelim()', fieldIndex, ref, (field.id << 3 | 2) >>> 0);
}
|
javascript
|
{
"resource": ""
}
|
q9674
|
patch
|
train
|
function patch(element, previous, attrs) {
if (!previous && !attrs) {
return attrs;
}
var name, value;
previous = previous || {};
attrs = attrs || {};
for (name in previous) {
if (previous[name] && !attrs[name]) {
unset(name, element, previous);
}
}
for (name in attrs) {
if (previous[name] === attrs[name]) {
continue;
}
if (attrs[name] || attrs[name] === '') {
set(name, element, previous, attrs);
}
}
return attrs;
}
|
javascript
|
{
"resource": ""
}
|
q9675
|
set
|
train
|
function set(name, element, previous, attrs) {
if (set.handlers[name]) {
set.handlers[name](name, element, previous, attrs);
} else if (attrs[name] != null && previous[name] !== attrs[name]) {
element.setAttribute(name, attrs[name]);
}
}
|
javascript
|
{
"resource": ""
}
|
q9676
|
unset
|
train
|
function unset(name, element, previous) {
if (unset.handlers[name]) {
unset.handlers[name](name, element, previous);
} else {
element.removeAttribute(name);
}
}
|
javascript
|
{
"resource": ""
}
|
q9677
|
getParent
|
train
|
function getParent(tile) {
// top left
if (tile[0] % 2 === 0 && tile[1] % 2 === 0) {
return [tile[0] / 2, tile[1] / 2, tile[2] - 1];
}
// bottom left
if ((tile[0] % 2 === 0) && (!tile[1] % 2 === 0)) {
return [tile[0] / 2, (tile[1] - 1) / 2, tile[2] - 1];
}
// top right
if ((!tile[0] % 2 === 0) && (tile[1] % 2 === 0)) {
return [(tile[0] - 1) / 2, (tile[1]) / 2, tile[2] - 1];
}
// bottom right
return [(tile[0] - 1) / 2, (tile[1] - 1) / 2, tile[2] - 1];
}
|
javascript
|
{
"resource": ""
}
|
q9678
|
copyFile
|
train
|
function copyFile (src, dest) {
return new Promise((resolve, reject) => {
const read = fs.createReadStream(src);
read.on('error', reject);
const write = fs.createWriteStream(dest);
write.on('error', reject);
write.on('finish', resolve);
read.pipe(write);
})
}
|
javascript
|
{
"resource": ""
}
|
q9679
|
parseCMS
|
train
|
function parseCMS(fileString) {
var intObj = txtToIntObj(fileString);
var result = cmsObjConverter.convertToBBModel(intObj);
return result;
}
|
javascript
|
{
"resource": ""
}
|
q9680
|
clean
|
train
|
function clean(cmsString) {
if (cmsString.indexOf('\r\n') >= 0) {
cmsString = cmsString.replace(/\r\n/g, '\n');
cmsString = cmsString.replace(/\r/g, '\n');
}
cmsString = cmsString.replace(/\n{5,}/g, '\n\n\n\n'); //more than 5 line breaks breaks the parser
return cmsString;
}
|
javascript
|
{
"resource": ""
}
|
q9681
|
separateSections
|
train
|
function separateSections(data) {
//Separated regular expression into many distinct pieces
//specical metaMatchCode goes first.
// 1st regular expression for meta, need to do
var metaMatchCode = '^(-).[\\S\\s]+?(\\n){2,}'; //this isn't used anywhere...
/* 2nd regular expression for claims, because the structure of claims is
unique */
var claimsHeaderMatchCode = '(-){4,}(\\n)*Claim Summary(\\n){2,}(-){4,}';
var claimsBodyMatchCode = '([\\S\\s]+Claim[\\S\\s]+)+';
var claimsEndMatchCode = '(?=((-){4,}))';
var claimsMatchCode = claimsHeaderMatchCode +
claimsBodyMatchCode + claimsEndMatchCode;
//this match code is for all other sections
var headerMatchCode = '(-){4,}[\\S\\s]+?(\\n){2,}(-){4,}';
var bodyMatchCode = '[\\S\\s]+?';
var endMatchCode = '(?=((-){4,}))';
var sectionMatchCode = headerMatchCode + bodyMatchCode + endMatchCode;
/* The regular expression for everything, search globally and
ignore capitalization */
var totalMatchCode = claimsMatchCode + "|" + sectionMatchCode;
var totalRegExp = new RegExp(totalMatchCode, 'gi');
var matchArray = data.match(totalRegExp);
return matchArray;
}
|
javascript
|
{
"resource": ""
}
|
q9682
|
cleanUpTitle
|
train
|
function cleanUpTitle(rawTitleString) {
/*dashChar is most commonly the dash of the title string, or a
the first repeating character surrounding the title */
var dashChar = rawTitleString.charAt(0);
//beginning and ending index of the dash
var dashBegIndex = 0;
var dashEndIndex = rawTitleString.lastIndexOf(dashChar);
//loop through to find indicies without continous dashes
while (rawTitleString.charAt(dashBegIndex) === (dashChar || '\n')) {
dashBegIndex++;
}
while (rawTitleString.charAt(dashEndIndex) === (dashChar || '\n')) {
dashEndIndex--;
}
var titleString = rawTitleString.slice(dashBegIndex + 1, dashEndIndex - 1);
titleString = trimStringEnds(titleString, ['\n', '-']);
return titleString;
}
|
javascript
|
{
"resource": ""
}
|
q9683
|
processClaimsLineChild
|
train
|
function processClaimsLineChild(objectString) {
var claimLineObj = {};
var obj = {};
var objArray = [];
var keyValuePairRegExp = /(\n){1,}[\S\s,]+?(:)[\S\s]+?(?=((\n){1,})|$)/gi;
var keyValuePairArray = objectString.match(keyValuePairRegExp);
//unusual steps are required to parse meta data and claims summary
for (var s = 0; s < keyValuePairArray.length; s++) {
//clean up the key value pair
var keyValuePairString = trimStringEnds(keyValuePairArray[s], ['\n']);
//split each string by the :, the result is an array of size two
var keyValuePair = keyValuePairString.split(/:(.*)/);
var key = removeUnwantedCharacters(keyValuePair[0].trim(), ['\n', '-']);
key = key.toLowerCase();
var value = keyValuePair[1].trim();
var claimLineCheckRegExp = /claim lines/i;
if (claimLineCheckRegExp.test(key)) {
claimLineObj.claimNumber = value;
continue;
}
if (value.length === 0) {
value = null;
}
//create a new object for line number
if (key in obj) {
objArray.push(obj);
obj = {};
}
obj[key] = value;
}
objArray.push(obj);
claimLineObj.data = objArray;
return claimLineObj;
}
|
javascript
|
{
"resource": ""
}
|
q9684
|
getSectionBody
|
train
|
function getSectionBody(sectionString) {
/*first, use regular expressions to parse the section body into different
objects */
var sectionBody = {};
var sectionBodyData = [];
var objectFromBodyRegExp = /-*(\n){2,}(?!-{4,})[\S\s,]+?((?=((\n){3,}?))|\n\n$)/gi;
//or go to the end of the string.
var objectStrings = sectionString.match(objectFromBodyRegExp);
//process each section object (from string to an actual object)
for (var obj = 0; obj < objectStrings.length; obj++) {
var sectionChild = processSectionChild(objectStrings[obj]);
if (!isEmpty(sectionChild)) {
if ('source' in sectionChild) {
sectionBody.source = sectionChild.source;
} else {
sectionBodyData.push(sectionChild);
}
}
}
sectionBody.data = sectionBodyData;
return sectionBody;
}
|
javascript
|
{
"resource": ""
}
|
q9685
|
getMetaBody
|
train
|
function getMetaBody(sectionString) {
var sectionBody = {};
var sectionBodyObj = {};
var metaBodyCode = /-{2,}((\n*?\*{3,}[\S\s]+\*{3,})|(\n{2,}))[\S\s]+?\n{3,}/gi;
var objectStrings = sectionString.match(metaBodyCode);
for (var obj = 0; obj < objectStrings.length; obj++) {
var sectionChild = processMetaChild(objectStrings[obj]);
if (!isEmpty(sectionChild)) {
sectionBodyObj.type = 'cms';
//get only the number from version
var versionRegExp = /\(v[\S\s]+?\)/;
var version = sectionChild[0].match(versionRegExp)[0];
version = trimStringEnds(version, ['(', ')', 'v']);
sectionBodyObj.version = version;
sectionBodyObj.timestamp = sectionChild[1];
}
}
sectionBody.data = [sectionBodyObj];
return sectionBody;
}
|
javascript
|
{
"resource": ""
}
|
q9686
|
convertToObject
|
train
|
function convertToObject(sectionString) {
var sectionObj = {};
//get the section title(get it raw, clean it)
var sectionTitleRegExp = /(-){3,}([\S\s]+?)(-){3,}/;
var sectionRawTitle = sectionString.match(sectionTitleRegExp)[0];
var sectionTitle = cleanUpTitle(sectionRawTitle).toLowerCase();
//get the section body
var sectionBody;
sectionObj.sectionTitle = sectionTitle;
//these are very special "edge" cases
//meta data/information about document in the beginning of the doc
if (sectionTitle.toLowerCase().indexOf("personal health information") >= 0) {
delete sectionObj.sectionTitle;
sectionObj.sectionTitle = 'meta';
sectionBody = getMetaBody(sectionString);
} else if (sectionTitle.toLowerCase().indexOf("claim") >= 0) {
sectionBody = getClaimsBody(sectionString);
} else {
sectionBody = getSectionBody(sectionString);
}
sectionObj.sectionBody = sectionBody;
return sectionObj;
}
|
javascript
|
{
"resource": ""
}
|
q9687
|
getTitles
|
train
|
function getTitles(fileString) {
var headerMatchCode = '(-){4,}[\\S\\s]+?(\\n){2,}(-){4,}';
var headerRegExp = new RegExp(headerMatchCode, 'gi');
var rawTitleArray = fileString.match(headerRegExp);
var titleArray = [];
if (rawTitleArray === null) {
return null;
}
for (var i = 0, len = rawTitleArray.length; i < len; i++) {
var tempTitle = cleanUpTitle(rawTitleArray[i]);
//exception to the rule, claim lines
if (tempTitle.toLowerCase().indexOf("claim lines for claim number") < 0 &&
tempTitle.length > 0) {
titleArray[i] = tempTitle;
}
}
return titleArray;
}
|
javascript
|
{
"resource": ""
}
|
q9688
|
Socket
|
train
|
function Socket (options) {
this.$ipaddress = ip.address();
this.$port = options.port;
this.$host = options.host || '224.1.1.1';
this.$ttl = options.ttl || 128;
this.$dispatcher = options.dispatcher;
//
// The native socket implementation.
// Will be filled on opening the socket.
//
this.$impl = null;
}
|
javascript
|
{
"resource": ""
}
|
q9689
|
patch
|
train
|
function patch(element, previous, style) {
if (!previous && !style) {
return style;
}
var rule;
if (typeof style === 'object') {
if (typeof previous === 'object') {
for (rule in previous) {
if (!style[rule]) {
domElementCss(element, rule, null);
}
}
domElementCss(element, style);
} else {
if (previous) {
element.setAttribute('style', '');
}
domElementCss(element, style);
}
} else {
element.setAttribute('style', style || '');
}
}
|
javascript
|
{
"resource": ""
}
|
q9690
|
patch
|
train
|
function patch(element, previous, props) {
if (!previous && !props) {
return props;
}
var name, value;
previous = previous || {};
props = props || {};
for (name in previous) {
if (previous[name] === undefined || props[name] !== undefined) {
continue;
}
unset(name, element, previous);
}
for (name in props) {
set(name, element, previous, props);
}
return props;
}
|
javascript
|
{
"resource": ""
}
|
q9691
|
set
|
train
|
function set(name, element, previous, props) {
if (set.handlers[name]) {
set.handlers[name](name, element, previous, props);
} else if (previous[name] !== props[name]) {
element[name] = props[name];
}
}
|
javascript
|
{
"resource": ""
}
|
q9692
|
unset
|
train
|
function unset(name, element, previous) {
if (unset.handlers[name]) {
unset.handlers[name](name, element, previous);
} else {
element[name] = null;
}
}
|
javascript
|
{
"resource": ""
}
|
q9693
|
$cond
|
train
|
function $cond(params) {
if (
Array.isArray(params) &&
params.length === 3 &&
typeof params[0] === 'boolean'
) {
return params[0] ? params[1] : params[2];
}
throw new Error(
'$cond expects an array of three elements of which the first must be a boolean'
);
}
|
javascript
|
{
"resource": ""
}
|
q9694
|
broadcastInserted
|
train
|
function broadcastInserted(node) {
if (node.hooks && node.hooks.inserted) {
return node.hooks.inserted(node, node.element);
}
if (node.children) {
for (var i = 0, len = node.children.length; i < len; i++) {
if (node.children[i]) {
broadcastInserted(node.children[i]);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q9695
|
walk
|
train
|
function walk(dir, before, after, handler, name = null, depth = 0) {
const listed = fs.readdirAsync(
dir
).then((list) => Promise.map(list, (item) => {
const child = path.resolve(dir, item);
const result = fs.lstatAsync(
child
).then((stat) => ({
path: child,
name: item,
isFile: stat.isFile(),
enterDir: stat.isDirectory()
}));
return(result);
}));
const result = listed.then(
(items) => before(items, depth)
).then((items) => Promise.map(
items,
(item) => item.enterDir && walk(item.path, before, after, handler, item.name, depth + 1)
)).then(
(children) => after(listed.value(), children)
).then((dependencyList) => {
handler(dir, dependencyList, name, depth);
return(dependencyList);
}).catch((err) => {});
return(result);
}
|
javascript
|
{
"resource": ""
}
|
q9696
|
filterChildren
|
train
|
function filterChildren(children, depth) {
if(depth == 1) {
let found = false;
for(let item of children) {
if(item.name == 'package.json') found = true;
if(item.name != 'src') item.enterDir = false;
}
if(!found) throw(new Error());
}
return(children);
}
|
javascript
|
{
"resource": ""
}
|
q9697
|
random
|
train
|
function random(min, max, float) {
if (min === undefined) {
return Math.random();
}
if (max === undefined) {
max = min;
min = 0;
}
if (max < min) {
var tmp = max;
max = min;
min = tmp;
}
if (float) {
var result = Math.random() * (max - min) + min;
if (float === true) {
return result;
} else if (typeof float === 'number') {
var str = result.toString();
var index = str.indexOf('.');
str = str.substr(0, index + 1 + float);
if (str[str.length - 1] === '0') {
str = str.substr(0, str.length - 1) + random(1, 9);
}
return parseFloat(str);
}
}
return Math.floor(Math.random() * (max - min + 1) + min);
}
|
javascript
|
{
"resource": ""
}
|
q9698
|
checkName
|
train
|
function checkName(name, cb) {
request(`https://registry.npmjs.org/${name}/latest`, {}, function(err, res, msg) {
if (err) return cb(err);
if (typeof msg === 'string' && msg === 'Package not found') {
cb(null, false);
return;
}
if (res && res.statusCode === 404) {
return cb(null, false);
}
cb(null, true);
});
}
|
javascript
|
{
"resource": ""
}
|
q9699
|
upTo
|
train
|
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
// Many DOM methods return null if they don't
// find the element they are searching for
// It would be OK to omit the following and just
// return undefined
return null;
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.