_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q2600
|
train
|
function (key, n) {
var int;
var numeral;
try {
int = key.getInterval(n);
} catch (err) {
try {
int = key.getInterval(n.clean());
} catch (err2) {
int = key.getInterval(n.toggleAccidental());
}
}
// Although dim7, for example, is a valid interval, we don't want a bbVII in our symbol
if (!interval.isPerfect(int.number) && int.quality === 'dim') {
int = interval.parse((int.number - 1).toString());
}
numeral = romanNumeral[int.number];
if (int.quality === 'm' || int.quality === 'dim') numeral = 'b' + numeral;
if (int.quality === 'aug') numeral = '#' + numeral;
return numeral;
}
|
javascript
|
{
"resource": ""
}
|
|
q2601
|
train
|
function (numeral) {
var matches = numeral.match(/([b#]?)([iIvV]+)/);
var halfSteps = interval.parse(_.indexOf(romanNumeral, matches[2]).toString()).halfSteps();
if (matches[1] === 'b') halfSteps -= 1;
if (matches[1] === '#') halfSteps += 1;
return halfSteps;
}
|
javascript
|
{
"resource": ""
}
|
|
q2602
|
train
|
function (numeral, quality) {
// Roman numeral representing chord
this.numeral = numeral;
// Chord quality: M, m, x, o, ø, s
this.quality = quality;
if (!_.contains(['M', 'm', 'x', 'o', 'ø', 's'], quality)) {
throw new Error('Invalid chord quality');
}
// The number of half-steps between the key and the chord
// e.g. I => 0, bIV => 6
this.interval = getHalfSteps(numeral);
this.toString = function () {
return this.numeral + this.quality;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q2603
|
train
|
function (key, ch) {
key = note.create(key || 'C');
ch = chord.create(ch);
return new Mehegan(getNumeral(key, ch.root), getQuality(ch));
}
|
javascript
|
{
"resource": ""
}
|
|
q2604
|
train
|
function (mehegan, cache) {
if (mehegan instanceof Mehegan) return mehegan;
// If no cache is provided, return string as Mehegan symbol
if (!cache) return fromString(mehegan);
// Otherwise, try to retrieve symbol from cache, creating a new symbol if it's not found
if (!cache[mehegan]) cache[mehegan] = fromString(mehegan);
return cache[mehegan];
}
|
javascript
|
{
"resource": ""
}
|
|
q2605
|
train
|
function (interval) {
var quality;
var number;
if (interval instanceof Interval) return interval;
quality = interval.replace(/\d/g, ''); // Remove digits
number = parseInt(interval.replace(/\D/g, ''), 10); // Remove non-digits
if (!quality) { // No quality given, assume major or perfect
quality = isPerfect(number) ? 'P' : 'M';
}
return new Interval(number, quality);
}
|
javascript
|
{
"resource": ""
}
|
|
q2606
|
train
|
function (scale, note) {
return _.findIndex(scale.scale, function (scaleNote) {
return scaleNote.enharmonic(note);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2607
|
train
|
function (chord) {
var noteRegex = '[A-Ga-g][#b]{0,2}';
var root = chord.match(new RegExp('^' + noteRegex))[0];
var bass = null;
var symbol;
root = note.create(root);
// Strip note, strip spaces, strip bass
symbol = chord.replace(/[\s]/g, '')
.replace(new RegExp('^' + noteRegex), '')
.replace(new RegExp('/' + noteRegex + '$'), '');
bass = chord.match(new RegExp('/' + noteRegex + '$'));
if (bass) bass = note.create(bass[0].slice(1));
return { root: root, symbol: symbol, bass: bass };
}
|
javascript
|
{
"resource": ""
}
|
|
q2608
|
train
|
function (interval) {
return _.find(notes, function (n) {
return root.transpose(interval).enharmonic(n);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2609
|
train
|
function (root, bass, intervals) {
var chord = _.chain(intervals)
.map(function (quality, number) {
var int;
if (quality) {
// #9 is stored as b10, so special case this
if (number === 10 && quality === 'm') {
int = interval.create(9, 'aug');
}
else {
int = interval.create(number, quality);
}
return root.transpose(int);
}
})
.compact()
.value();
var bassIndex;
// Handle slash chords
if (bass && !root.enharmonic(bass)) {
bassIndex = _.findIndex(chord, bass.enharmonic.bind(bass));
if (bassIndex > -1) { // Rotate chord so bass is first
chord = rotateArr(chord, bassIndex);
}
else { // Otherwise, add bass to beginning
chord.unshift(bass);
}
}
return chord;
}
|
javascript
|
{
"resource": ""
}
|
|
q2610
|
train
|
function (root, symbol, bass) {
var name = root.name + symbol;
var octave = bass ? bass.octave : root.octave;
if (bass) name += '/' + bass.name;
return new Chord(name, octave);
}
|
javascript
|
{
"resource": ""
}
|
|
q2611
|
train
|
function (scales, chord) {
// Exclude scales with a particular interval
var exclude = function (int) {
scales = _.filter(scales, function (scale) {
return !scale.hasInterval(int);
});
};
// Add a scale at a particular index
var include = function (index, scaleId) {
scales.splice(index, 0, scale.create(chord.root, scaleId));
};
if (_.includes(['m', 'm6', 'm7', 'm9', 'm11', 'm13'], chord.formattedSymbol)) {
exclude('M3');
}
if (_.includes(['7', '9', '11', '13', 'm7', 'm9', 'm11', 'm13'], chord.formattedSymbol)) {
exclude('M7');
}
if (_.includes(['M7', 'M9', 'M11', 'M13'], chord.formattedSymbol)) {
exclude('m7');
}
if (chord.formattedSymbol[0] === '6' || chord.formattedSymbol.slice(0, 2) === 'M6') {
exclude('m7');
}
if (_.includes(['7', '7#9', '7+9', '7#11', '7+11'], chord.formattedSymbol)) {
include(2, 'blues');
}
return scales;
}
|
javascript
|
{
"resource": ""
}
|
|
q2612
|
train
|
function (index, scaleId) {
scales.splice(index, 0, scale.create(chord.root, scaleId));
}
|
javascript
|
{
"resource": ""
}
|
|
q2613
|
train
|
function (obj, octave) {
var lastNote = obj.chord[0];
obj.chord = _.map(obj.chord, function (n) {
// Every time a note is "lower" than the last note, we're in a new octave
if (n.lowerThan(lastNote)) octave += 1;
// As a side-effect, update the octaves for root and bass
if (n.enharmonic(obj.root)) {
obj.root = obj.root.inOctave(octave);
}
if (obj.bass && n.enharmonic(obj.bass)) {
obj.bass = obj.bass.inOctave(octave);
}
lastNote = n;
return n.inOctave(octave);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q2614
|
train
|
function (num, totalBytes) {
var numBytes = Math.floor(Math.log(num) / Math.log(0xff)) + 1;
var buffer = new Buffer(totalBytes);
buffer.fill(0);
buffer.writeUIntBE(num, totalBytes - numBytes, numBytes);
return buffer;
}
|
javascript
|
{
"resource": ""
}
|
|
q2615
|
train
|
function (format, numTracks) {
var chunklen = padNumber(6, 4); // MIDI header is always 6 bytes long
var ntracks = padNumber(numTracks, 2);
var tickdiv = padNumber(ticksPerBeat, 2);
format = padNumber(format, 2); // Usually format 1 MIDI file (multuple overlayed tracks)
return Buffer.concat([midiHeader, chunklen, format, ntracks, tickdiv]);
}
|
javascript
|
{
"resource": ""
}
|
|
q2616
|
train
|
function (settings) {
var tempo = 60e6 / settings.tempo; // Microseconds per beat
var setTempo = Buffer.concat([new Buffer([0, 0xFF, 0x51, 0x03]), padNumber(tempo, 3)]);
var length = setTempo.length + trackFooter.length;
return Buffer.concat([trackHeader, padNumber(length, 4), setTempo, trackFooter]);
}
|
javascript
|
{
"resource": ""
}
|
|
q2617
|
train
|
function (deltaTime, on, channel, note, velocity) {
var status = on ? 0x90 : 0x80;
status += channel;
deltaTime = makeVLQ(deltaTime);
return Buffer.concat([deltaTime, new Buffer([status, note, velocity])]);
}
|
javascript
|
{
"resource": ""
}
|
|
q2618
|
train
|
function (deltaTime, on, firstChannel, chord, velocity) {
var arr = [];
// Make note event for first note after appropriate time
arr.push(makeNoteEvent(deltaTime, on, firstChannel, noteValue(_.first(chord)), velocity));
// Make note event for rest of the notes
_.each(_.rest(chord), function (note, i) {
arr.push(makeNoteEvent(0, on, i + firstChannel, noteValue(note), velocity));
});
return Buffer.concat(arr);
}
|
javascript
|
{
"resource": ""
}
|
|
q2619
|
train
|
function (duration, settings) {
// If there's no swing ratio, assume straight eighths
var ratio = settings && settings.swingRatio ? settings.swingRatio : 1;
return Math.round(ticksPerBeat * duration.value(ratio));
}
|
javascript
|
{
"resource": ""
}
|
|
q2620
|
train
|
function (notes, settings) {
var restBuffer = 0;
var events = _.reduce(notes, function (arr, obj) {
var time = noteLength(obj.duration, settings);
if (obj.note) {
arr.push(makeNoteEvent(restBuffer, true, 0, noteValue(obj.note), settings.noteVelocity)); // On
arr.push(makeNoteEvent(time, false, 0, noteValue(obj.note), settings.noteVelocity)); // Off
restBuffer = 0;
}
else {
restBuffer += time;
}
return arr;
}, []);
return Buffer.concat(events);
}
|
javascript
|
{
"resource": ""
}
|
|
q2621
|
train
|
function (chords, settings) {
var events = _.reduce(chords, function (arr, obj) {
var time = noteLength(obj.duration, settings);
var chord = obj.chord.inOctave(settings.chordOctave).chord;
arr.push(makeChordEvent(0, true, 1, chord, settings.chordVelocity)); // On
arr.push(makeChordEvent(time, false, 1, chord, settings.chordVelocity)); // Off
return arr;
}, []);
return Buffer.concat(events);
}
|
javascript
|
{
"resource": ""
}
|
|
q2622
|
train
|
function (notes, settings) {
var noteEvents = makeNoteEvents(notes, settings);
var setPatch = makePatchEvent(0, settings.melodyPatch);
var length = setPatch.length + noteEvents.length + trackFooter.length;
return Buffer.concat([trackHeader, padNumber(length, 4), setPatch, noteEvents, trackFooter]);
}
|
javascript
|
{
"resource": ""
}
|
|
q2623
|
train
|
function (chords, settings) {
var chordEvents = makeChordEvents(chords, settings);
// Set all channels
var setPatches = _.reduce(_.range(0xf), function (buffer, channel) {
return Buffer.concat([buffer, makePatchEvent(channel, settings.chordPatch)]);
}, new Buffer(0));
var length = setPatches.length + chordEvents.length + trackFooter.length;
return Buffer.concat([trackHeader, padNumber(length, 4), setPatches, chordEvents, trackFooter]);
}
|
javascript
|
{
"resource": ""
}
|
|
q2624
|
getAxesPosition
|
train
|
function getAxesPosition(axes, buttons) {
if (axes.length === 10) {
return Math.round(axes[9] / (2 / 7) + 3.5);
}
const [right, left, down, up] = [...buttons].reverse();
const buttonValues = [up, right, down, left]
.map((pressed, i) => (pressed.value ? i * 2 : false))
.filter(val => val !== false);
if (buttonValues.length === 0) return 8;
if (buttonValues.length === 2 && buttonValues[0] === 0 && buttonValues[1] === 6) return 7;
return buttonValues.reduce((prev, curr) => prev + curr, 0) / buttonValues.length;
}
|
javascript
|
{
"resource": ""
}
|
q2625
|
Unswitch
|
train
|
function Unswitch(settings) {
const buttonState = {};
let axesPosition = 8;
for (let i = buttonMappings.length - 1; i >= 0; i -= 1) {
buttonState[buttonMappings[i]] = { pressed: false };
}
this.update = () => {
const gamepads = navigator.getGamepads();
for (let i = Object.keys(gamepads).length - 1; i >= 0; i -= 1) {
if (gamepads[i] && gamepads[i].id && gamepads[i].id.indexOf(settings.side) !== -1) {
this.observe(gamepads[i]);
break;
}
}
};
this.observe = (pad) => {
const { buttons, axes } = pad;
for (let j = buttonMappings.length - 1; j >= 0; j -= 1) {
const button = buttonMappings[j];
if (buttonState[button].pressed !== buttons[j].pressed) {
buttonState[button].pressed = buttons[j].pressed;
if (settings[button]) {
settings[button](buttonState[button].pressed);
}
if (settings.buttons) {
settings.buttons(button, buttonState[button].pressed, settings.side);
}
}
}
if (settings.axes) {
const position = getAxesPosition(axes, buttons);
if (position !== axesPosition) {
settings.axes(position);
axesPosition = position;
}
}
};
}
|
javascript
|
{
"resource": ""
}
|
q2626
|
createHandler
|
train
|
function createHandler(to, except, pathFunc, protocol) {
return function(req, res, next) {
var host = req.hostname || '';
var url = req.url;
if (host in except) {
next();
} else {
var target = new URIjs(pathFunc(host, url))
.host(to)
.protocol(protocol || '')
.href();
res.redirect(301, target);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q2627
|
CDNUp
|
train
|
function CDNUp(bucket, options) {
options = options || {};
this.sharding = !!options.sharding;
this.urls = arrayify(options.url || options.urls);
this.mime = options.mime || {};
this.check = options.check;
this.bucket = bucket;
this.client = pkgcloud.storage.createClient(options.pkgcloud || {});
this.acl = options.acl;
this.subdomain = options.subdomain;
}
|
javascript
|
{
"resource": ""
}
|
q2628
|
arrayify
|
train
|
function arrayify(urls) {
var tmp = Array.isArray(urls) ? urls : [urls];
return tmp.filter(Boolean);
}
|
javascript
|
{
"resource": ""
}
|
q2629
|
generateMakefile
|
train
|
function generateMakefile(testFiles, targetPath, callback) {
var template = new templates.Template('Makefile.magic');
var fullPath = path.join(targetPath, 'Makefile');
var context = {
test_files: testFiles.join(' \\\n ')
};
if (path.existsSync(fullPath)) {
callback(new Error(sprintf('File "%s" already exists', fullPath)));
return;
}
async.waterfall([
template.load.bind(template),
function render(template, callback) {
template.render(context, callback);
},
function save(output, callback) {
fs.writeFile(fullPath, output.join(''), callback);
}
], callback);
}
|
javascript
|
{
"resource": ""
}
|
q2630
|
checkSavedData
|
train
|
function checkSavedData(dbName, objStore, data) {
const keyValueContainer = Object.prototype.isPrototypeOf.call(skladKeyValueContainer, data);
const value = keyValueContainer ? data.value : data;
const objStoreMeta = objStoresMeta.get(dbName).get(objStore.name);
let key = keyValueContainer ? data.key : undefined;
const keyPath = objStore.keyPath || objStoreMeta.keyPath;
const autoIncrement = objStore.autoIncrement || objStoreMeta.autoIncrement;
if (keyPath === null) {
if (!autoIncrement && key === undefined) {
key = uuid();
}
} else {
if (typeof data !== 'object') {
return false;
}
// TODO: support dot-separated and array keyPaths
if (!autoIncrement && data[keyPath] === undefined) {
data[keyPath] = uuid();
}
}
return key ? [value, key] : [value];
}
|
javascript
|
{
"resource": ""
}
|
q2631
|
checkContainingStores
|
train
|
function checkContainingStores(objStoreNames) {
return objStoreNames.every(function (storeName) {
return (indexOf.call(this.database.objectStoreNames, storeName) !== -1);
}, this);
}
|
javascript
|
{
"resource": ""
}
|
q2632
|
getObjStoresMeta
|
train
|
function getObjStoresMeta(db, objStoreNames) {
const dbMeta = objStoresMeta.get(db.name);
const promises = [];
objStoreNames.forEach(objStoreName => {
if (dbMeta.has(objStoreName)) {
return;
}
const promise = new Promise(resolve => {
const transaction = db.transaction([objStoreName], TRANSACTION_READWRITE);
transaction.oncomplete = resolve;
transaction.onabort = resolve;
const objStore = transaction.objectStore(objStoreName);
if (objStore.autoIncrement !== undefined) {
dbMeta.set(objStoreName, {
autoIncrement: objStore.autoIncrement,
keyPath: objStore.keyPath
});
return;
}
let autoIncrement;
if (objStore.keyPath !== null) {
// if key path is defined it's possible to insert only objects
// but if key generator (autoIncrement) is not defined the inserted objects
// must contain field(s) described in keyPath value otherwise IDBObjectStore.add op fails
// so if we run ODBObjectStore.add with an empty object and it fails, this means that
// autoIncrement property was false. Otherwise - true
// if key path is array autoIncrement property can't be true
if (Array.isArray(objStore.keyPath)) {
autoIncrement = false;
} else {
try {
objStore.add({});
autoIncrement = true;
} catch (ex) {
autoIncrement = false;
}
}
} else {
// if key path is not defined it's possible to insert any kind of data
// but if key generator (autoIncrement) is not defined you should set it explicitly
// so if we run ODBObjectStore.add with one argument and it fails, this means that
// autoIncrement property was false. Otherwise - true
try {
objStore.add('some value');
autoIncrement = true;
} catch (ex) {
autoIncrement = false;
}
}
// save meta properties
dbMeta.set(objStoreName, {
autoIncrement: autoIncrement,
keyPath: objStore.keyPath
});
// and abort transaction so that new record is forgotten
transaction.abort();
});
promises.push(promise);
});
return Promise.all(promises);
}
|
javascript
|
{
"resource": ""
}
|
q2633
|
createProgram
|
train
|
function createProgram(
gl, shaders, opt_attribs, opt_locations, opt_errorCallback) {
var errFn = opt_errorCallback || error;
var program = gl.createProgram();
shaders.forEach(function(shader) {
gl.attachShader(program, shader);
});
if (opt_attribs) {
opt_attribs.forEach(function(attrib, ndx) {
gl.bindAttribLocation(
program,
opt_locations ? opt_locations[ndx] : ndx,
attrib);
});
}
gl.linkProgram(program);
// Check the link status
var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!linked) {
// something went wrong with the link
var lastError = gl.getProgramInfoLog(program);
errFn("Error in program linking:" + lastError);
gl.deleteProgram(program);
return null;
}
return program;
}
|
javascript
|
{
"resource": ""
}
|
q2634
|
getBindPointForSamplerType
|
train
|
function getBindPointForSamplerType(gl, type) {
if (type === gl.SAMPLER_2D) return gl.TEXTURE_2D; // eslint-disable-line
if (type === gl.SAMPLER_CUBE) return gl.TEXTURE_CUBE_MAP; // eslint-disable-line
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q2635
|
getExtensionWithKnownPrefixes
|
train
|
function getExtensionWithKnownPrefixes(gl, name) {
for (var ii = 0; ii < browserPrefixes.length; ++ii) {
var prefixedName = browserPrefixes[ii] + name;
var ext = gl.getExtension(prefixedName);
if (ext) {
return ext;
}
}
return undefined;
}
|
javascript
|
{
"resource": ""
}
|
q2636
|
resizeCanvasToDisplaySize
|
train
|
function resizeCanvasToDisplaySize(canvas, multiplier) {
multiplier = multiplier || 1;
var width = canvas.clientWidth * multiplier | 0;
var height = canvas.clientHeight * multiplier | 0;
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q2637
|
getNumElementsFromNonIndexedArrays
|
train
|
function getNumElementsFromNonIndexedArrays(arrays) {
var key = Object.keys(arrays)[0];
var array = arrays[key];
if (isArrayBuffer(array)) {
return array.numElements;
} else {
return array.data.length / array.numComponents;
}
}
|
javascript
|
{
"resource": ""
}
|
q2638
|
createBuffersFromArrays
|
train
|
function createBuffersFromArrays(gl, arrays) {
var buffers = { };
Object.keys(arrays).forEach(function(key) {
var type = key === "indices" ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;
var array = makeTypedArray(arrays[key], name);
buffers[key] = createBufferFromTypedArray(gl, array, type);
});
// hrm
if (arrays.indices) {
buffers.numElements = arrays.indices.length;
} else if (arrays.position) {
buffers.numElements = arrays.position.length / 3;
}
return buffers;
}
|
javascript
|
{
"resource": ""
}
|
q2639
|
drawBufferInfo
|
train
|
function drawBufferInfo(gl, bufferInfo, primitiveType, count, offset) {
var indices = bufferInfo.indices;
primitiveType = primitiveType === undefined ? gl.TRIANGLES : primitiveType;
var numElements = count === undefined ? bufferInfo.numElements : count;
offset = offset === undefined ? offset : 0;
if (indices) {
gl.drawElements(primitiveType, numElements, gl.UNSIGNED_SHORT, offset);
} else {
gl.drawArrays(primitiveType, offset, numElements);
}
}
|
javascript
|
{
"resource": ""
}
|
q2640
|
getLogger
|
train
|
function getLogger(name) {
name = name || '';
if (!name) {
return Manager.root;
} else {
return Manager.getLogger(name);
}
}
|
javascript
|
{
"resource": ""
}
|
q2641
|
train
|
function(filename){
// resolve by symlink if possible
for (var from in this.symlinks)
if (filename.indexOf(from) === 0 && (filename === from || filename[from.length] === '/'))
return this.symlinks[from] + filename.substr(from.length);
return path.resolve(this.fsBaseURI, filename.replace(/^[\\\/]/, ''));
}
|
javascript
|
{
"resource": ""
}
|
|
q2642
|
train
|
function(fileRef){
var filename;
var file;
if (fileRef instanceof File)
{
file = fileRef;
filename = file.filename;
}
else
{
filename = abspath(this.baseURI, fileRef);
file = this.map[filename];
if (!file)
{
this.flow.warn({
file: filename,
message: 'File `' + fileRef + '` not found in map'
});
return;
}
}
// remove links
for (var i = file.linkTo.length, linkTo; linkTo = file.linkTo[i]; i--)
file.unlink(linkTo);
for (var i = file.linkBack.length, linkBack; linkBack = file.linkBack[i]; i--)
linkBack.unlink(file);
// remove from queue
var index = this.queue.indexOf(file);
if (index != -1)
this.queue.splice(index, 1);
// remove from map
if (filename)
delete this.map[filename];
}
|
javascript
|
{
"resource": ""
}
|
|
q2643
|
train
|
function(data, options) {
var configs = [];
if (_.isArray(data)) {
data.forEach(function(block) {
configs.push(new BlockConfig(block.name, block, options));
});
} else if (_.isPlainObject(data)) {
_.forOwn(data, function(value, name) {
configs.push(new BlockConfig(name, value, options));
});
} else {
grunt.warn('Block configuration must be an array or object.');
}
return configs;
}
|
javascript
|
{
"resource": ""
}
|
|
q2644
|
ConsoleHandler
|
train
|
function ConsoleHandler(level, grouping, collapsed) {
grouping = typeof grouping !== 'undefined' ? grouping : true;
collapsed = typeof collapsed !== 'undefined' ? collapsed : false;
Handler.call(this, level);
this._grouping = grouping;
this._groupMethod = collapsed ? 'groupCollapsed' : 'group';
this._openGroup = '';
}
|
javascript
|
{
"resource": ""
}
|
q2645
|
ScrapinodeError
|
train
|
function ScrapinodeError(message){
Error.call(this);
Error.captureStackTrace(this,arguments.callee);
this.name = 'ScrapinodeError';
this.message = message;
}
|
javascript
|
{
"resource": ""
}
|
q2646
|
FileHandler
|
train
|
function FileHandler(filename, mode, encoding, delay) {
mode = mode || 'a';
encoding = typeof encoding !== 'undefined' ? encoding : 'utf8';
delay = typeof delay !== 'undefined' ? delay : false;
/**
* @private
* @type {string}
*/
this._filename = filename;
/**
* @private
* @type {string}
*/
this._mode = mode;
/**
* @private
* @type {string}
*/
this._encoding = encoding;
if (delay) {
StreamHandler.call(this);
this._stream = null;
} else {
StreamHandler.call(this, this._open());
}
}
|
javascript
|
{
"resource": ""
}
|
q2647
|
RotatingFileHandler
|
train
|
function RotatingFileHandler(filename, mode, maxBytes, backupCount,
encoding, delay) {
mode = mode || 'a';
maxBytes = typeof maxBytes !== 'undefined' ? maxBytes : 0;
backupCount = typeof backupCount !== 'undefined' ? backupCount : 0;
encoding = typeof encoding !== 'undefined' ? encoding : 'utf8';
delay = typeof delay !== 'undefined' ? delay : false;
if (maxBytes > 0) {
mode = 'a';
}
FileHandler.call(this, filename, mode, encoding, delay);
/**
* @private
* @type {number}
*/
this._maxBytes = maxBytes;
/**
* @private
* @type {number}
*/
this._backupCount = backupCount;
/**
* @private
* @type {Promise}
*/
this._chain = Promise.resolve();
}
|
javascript
|
{
"resource": ""
}
|
q2648
|
accepts
|
train
|
function accepts(func, validator, message) {
message = messageBuilder(message || 'vet/utils/accepts error!');
return function wrapper(){
var args = arguments;
if (validator.apply(this, args)) {
return func.apply(this, args);
} else {
throw new Error(message.apply(this, args));
}
};
}
|
javascript
|
{
"resource": ""
}
|
q2649
|
toRepoUrl
|
train
|
function toRepoUrl(url) {
if (url.startsWith('git@')) {
if (argv.useSSH) {
return url;
}
// have an ssh url need an http url
const m = url.match(/(https?:\/\/([^/]+)\/|git@(.+):)([\w\d-_/]+)(.git)?/);
return `https://${m[3]}/${m[4]}.git`;
}
if (url.startsWith('http')) {
if (!argv.useSSH) {
return url;
}
// have a http url need an ssh url
const m = url.match(/(https?:\/\/([^/]+)\/|git@(.+):)([\w\d-_/]+)(.git)?/);
return `git@${m[2]}:${m[4]}.git`;
}
if (!url.includes('/')) {
url = `Caleydo/${url}`;
}
if (argv.useSSH) {
return `[email protected]:${url}.git`;
}
return `https://github.com/${url}.git`;
}
|
javascript
|
{
"resource": ""
}
|
q2650
|
guessUserName
|
train
|
function guessUserName(repo) {
// extract the host
const host = repo.match(/:\/\/([^/]+)/)[1];
const hostClean = host.replace(/\./g, '_').toUpperCase();
// e.g. GITHUB_COM_CREDENTIALS
const envVar = process.env[`${hostClean}_CREDENTIALS`];
if (envVar) {
return envVar;
}
return process.env.PHOVEA_GITHUB_CREDENTIALS;
}
|
javascript
|
{
"resource": ""
}
|
q2651
|
spawn
|
train
|
function spawn(cmd, args, opts) {
const spawn = require('child_process').spawn;
const _ = require('lodash');
return new Promise((resolve, reject) => {
const p = spawn(cmd, typeof args === 'string' ? args.split(' ') : args, _.merge({stdio: argv.quiet ? ['ignore', 'pipe', 'pipe'] : ['ignore', 1, 2]}, opts));
const out = [];
if (p.stdout) {
p.stdout.on('data', (chunk) => out.push(chunk));
}
if (p.stderr) {
p.stderr.on('data', (chunk) => out.push(chunk));
}
p.on('close', (code, signal) => {
if (code === 0) {
console.info(cmd, 'ok status code', code, signal);
resolve(code);
} else {
console.error(cmd, 'status code', code, signal);
if (args.quiet) {
// log output what has been captured
console.log(out.join('\n'));
}
reject(`${cmd} failed with status code ${code} ${signal}`);
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q2652
|
npm
|
train
|
function npm(cwd, cmd) {
console.log(cwd, chalk.blue('running npm', cmd));
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
return spawn(npm, (cmd || 'install').split(' '), {cwd, env});
}
|
javascript
|
{
"resource": ""
}
|
q2653
|
docker
|
train
|
function docker(cwd, cmd) {
console.log(cwd, chalk.blue('running docker', cmd));
return spawn('docker', (cmd || 'build .').split(' '), {cwd, env});
}
|
javascript
|
{
"resource": ""
}
|
q2654
|
yo
|
train
|
function yo(generator, options, cwd) {
const yeoman = require('yeoman-environment');
// call yo internally
const yeomanEnv = yeoman.createEnv([], {cwd, env}, quiet ? createQuietTerminalAdapter() : undefined);
yeomanEnv.register(require.resolve('generator-phovea/generators/' + generator), 'phovea:' + generator);
return new Promise((resolve, reject) => {
try {
console.log(cwd, chalk.blue('running yo phovea:' + generator));
yeomanEnv.run('phovea:' + generator, options, resolve);
} catch (e) {
console.error('error', e, e.stack);
reject(e);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q2655
|
train
|
function (job, config, callback) {
var task = {
job: job,
config: config,
callback: callback || function () {
}
};
task.id = task.job._id;
// Tasks with identical keys will be prevented from being scheduled concurrently.
task.key = task.job.project + branchFromJob(task.job);
this.tasks.push(task);
// Defer task execution to the next event loop tick to ensure that the push() function's
// callback is *always* invoked asynchronously.
// http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony
process.nextTick(this.drain.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q2656
|
train
|
function () {
var self = this;
// See how much capacity we have left to fill.
var launchCount = this.concurrency - Object.keys(this.active).length;
// Identify up to launchCount eligible tasks, giving priority to those earlier in the queue.
var offset = 0;
var launchTasks = [];
while (launchTasks.length < launchCount && this.tasks.length > offset) {
var task = this.tasks[offset];
if (task.key in this.active) {
// This task cannot run right now, so skip it.
offset += 1;
} else {
// This task is eligible to run. Remove it from the queue and prepare it to launch.
this.tasks.splice(offset, 1);
launchTasks.push(task);
}
}
// Create a task completion callback. Remove the task from the active set, invoke the tasks'
// push() callback, then drain() again to see if another task is ready to run.
function makeTaskHandler(task) {
return function (err) {
delete self.active[task.key];
task.callback(err);
// Defer the next drain() call again in case the task's callback was synchronous.
process.nextTick(self.drain.bind(self));
};
}
// Launch the queue handler for each chosen task.
for (var i = 0; i < launchTasks.length; i++) {
var each = launchTasks[i];
this.active[each.key] = each;
this.handler(each.job, each.config, makeTaskHandler(each));
}
// Fire and unset the drain callback if one has been registered.
if (this.drainCallback) {
var lastCallback = this.drainCallback;
this.drainCallback = null;
lastCallback();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2657
|
train
|
function (id) {
for (var key in this.active) {
if (this.active.hasOwnProperty(key) && this.active[key].id === id) {
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q2658
|
train
|
function (opts) {
var paths = es.through();
var files = es.through();
paths.pipe(es.writeArray(function (err, srcs) {
gulp.src(srcs, opts).pipe(files);
}));
return es.duplex(paths, files);
}
|
javascript
|
{
"resource": ""
}
|
|
q2659
|
train
|
function (block) {
es.readArray([
'<!--',
' processed by htmlbuild',
'-->'
].map(function (str) {
return block.indent + str;
})).pipe(block);
}
|
javascript
|
{
"resource": ""
}
|
|
q2660
|
train
|
function (template) {
var pattern = _.template(template)(fileReplace);
pattern = pattern.replace(/\//g, '\\/');
pattern = pattern.replace(/\s+/g, '\\s*');
pattern = '\\s*' + pattern + '\\s*';
return new RegExp(pattern);
}
|
javascript
|
{
"resource": ""
}
|
|
q2661
|
train
|
function (line, block) {
if (!block.template) {
return;
}
var regex = getRegExp(block.template);
var match = regex.exec(line);
return match ? match[1] : match;
}
|
javascript
|
{
"resource": ""
}
|
|
q2662
|
scrapDescription
|
train
|
function scrapDescription(window){
var $ = window.$;
var descriptions = [];
// Open Graph protocol by Facebook <meta property="og:description" content="(*)"/>
$('meta[property="og:description"]').each(function(){
var content = $(this).attr('content');
if(content) descriptions.push(content);
});
// Schema.org : <* itemprop="description">(*)</*>
$('[itemprop="description"]').each(function(){
var text = $(this).text();
if(text) descriptions.push(text);
});
// Meta tag description: <meta property="description" content="(*)" />
$('meta[name="description"]').each(function(){
var description = utils.inline($(this).attr('content')).trim();
if(description) descriptions.push(description);
});
// Random text in div and p tags. Oriented product informations
if(descriptions.length === 0){
$('div,p').each(function(){
if( ($(this).attr('class') && $(this).attr('class').toLowerCase() === 'productdesc') || ($(this).attr('id') && $(this).attr('id').toLowerCase() === 'productdesc')){
var description = utils.inline($(this).text()).trim();
if(description) descriptions.push(description);
}
});
}
return descriptions;
}
|
javascript
|
{
"resource": ""
}
|
q2663
|
isValidExtension
|
train
|
function isValidExtension(src){
var extension = src.split('.').pop();
var isValid = ENUM_INVALID_EXTENSIONS[extension] === false ? false : true;
return isValid;
}
|
javascript
|
{
"resource": ""
}
|
q2664
|
scrapImage
|
train
|
function scrapImage(window){
var $ = window.$;
var url = window.url;
var thumbs = [];
var thumbsRejected = [];
var title = scrapTitle(window);
var addToThumbs = function(image,beginning){
var src = $(image).attr('src');
if(src && isValidExtension(src) ){
src = utils.toURL(src,url);
if(beginning){
thumbs.unshift(src);
}else{
thumbs.push(src);
}
}else if(src){
thumbsRejected.push(src);
}
};
// Open Graph protocol by Facebook: <meta property="og:image" content="(*)"/>
$('meta[property="og:image"]').each(function(){
var content = $(this).attr('content');
if(content) thumbs.push(utils.toURL(content));
});
// Schema.org: <img itemprop="image" src="(*)"/>
$('img[itemprop="image"]').each(function(){
addToThumbs(this);
});
// Oriented product informations
if(thumbs.length < 1){
$('img[id*="product"]').each(function(){
addToThumbs(this);
});
$('img[class*="product"]').each(function(){
addToThumbs(this);
});
}
// Grab all images
if(thumbs.length < 10){
$('img').each(function(){
if($(this).attr('itemprop') === 'image') return;
var alt = $(this).attr('alt');
// Leave this test alone
// the selector 'img[alt="title"]' will not work if the title is like LG 42PT35342" PLASMA TV. Escaping issues.
// Image where the title of the page is equal to the content of the alt attribute of the image tag.
if(alt === title){
addToThumbs(this,true);
}else{
addToThumbs(this);
}
});
}
if(thumbs.length === 0){
thumbs = thumbsRejected;
}
return thumbs;
}
|
javascript
|
{
"resource": ""
}
|
q2665
|
scrapTitle
|
train
|
function scrapTitle(window){
var $ = window.$;
var url = window.location.href;
// Tags or attributes whom can contain a nice title for the page
var titleTag = $('title').text().trim();
var metaTitleTag = $('meta[name="title"]').attr('content');
var openGraphTitle = $('meta[property="og:title"]').attr('content');
var h1Tag = $('h1').eq(0).text().trim();
var itempropNameTag = $('[itemprop="name"]').text().trim();
var titles = [titleTag, metaTitleTag, openGraphTitle, h1Tag, itempropNameTag];
// Regex of the web site name
var nameWebsite = utils.getWebsiteName(url);
var regex = new RegExp(nameWebsite,'i');
// Sort to find the best title
var titlesNotEmpty = titles.filter(function(value){
return !!value;
});
var titlesBest = titlesNotEmpty.filter(function(value){
return !regex.test(value);
});
var bestTitle = (titlesBest && titlesBest[0]) || (titlesNotEmpty && titlesNotEmpty[0]) || '';
return utils.inline(bestTitle);
}
|
javascript
|
{
"resource": ""
}
|
q2666
|
scrapVideo
|
train
|
function scrapVideo(window){
var $ = window.$;
var url = window.location.href;
var thumbs = [];
// Open Graph protocol by Facebook: <meta property="og:video" content="(*)"/>
$('meta').each(function(){
var property = $(this).attr('property');
var content = $(this).attr('content');
if(property === 'og:video' && content){
thumbs.push(utils.toURL(content));
}
});
$('video, embed').each(function(){
var src = $(this).attr('src');
if(src) thumbs.push(utils.toURL(src,url));
});
return thumbs;
}
|
javascript
|
{
"resource": ""
}
|
q2667
|
parseRequirements
|
train
|
function parseRequirements(file) {
if (!file) {
return {};
}
file = file.trim();
if (file === '') {
return {};
}
const versions = {};
file.split('\n').forEach((line) => {
line = line.trim();
if (line.startsWith('-e')) {
// editable special dependency
const branchSeparator = line.indexOf('@');
const name = line.slice(0, branchSeparator).trim();
versions[name] = line.slice(branchSeparator).trim();
return;
}
if (line.startsWith('#') || line.startsWith('-')) {
return; // skip
}
const versionSeparator = line.search(/[\^~=>!]/);
if (versionSeparator >= 0) {
const name = line.slice(0, versionSeparator).trim();
versions[name] = line.slice(versionSeparator).trim();
} else {
versions[line] = '';
}
});
return versions;
}
|
javascript
|
{
"resource": ""
}
|
q2668
|
train
|
function(func, context, args, callback) {
try {
func.apply(context, args);
}
catch (err) {}
if (callback) {
callback();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2669
|
fireOnce
|
train
|
function fireOnce(fn) {
var fired = false;
return function wrapped() {
if (!fired) {
fired = true;
fn.apply(null, arguments);
}
};
}
|
javascript
|
{
"resource": ""
}
|
q2670
|
handleClientLoad
|
train
|
function handleClientLoad() {
(async ()=> {
await config.load()
await config.api.google.load()
gapi.load('client:auth2', initClient)
})().catch(console.error)
}
|
javascript
|
{
"resource": ""
}
|
q2671
|
initClient
|
train
|
function initClient() {
gapi.client.init({
apiKey: config.api.google.web.key,
clientId: config.api.google.web.client_id,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
|
javascript
|
{
"resource": ""
}
|
q2672
|
updateSigninStatus
|
train
|
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listFiles();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
|
javascript
|
{
"resource": ""
}
|
q2673
|
appendPre
|
train
|
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
|
javascript
|
{
"resource": ""
}
|
q2674
|
listFiles
|
train
|
function listFiles() {
gapi.client.drive.files.list({
'pageSize': 10,
'fields': "nextPageToken, files(id, name)"
}).then(function(response) {
appendPre('Files:');
var files = response.result.files;
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
appendPre(file.name + ' (' + file.id + ')');
}
} else {
appendPre('No files found.');
}
});
}
|
javascript
|
{
"resource": ""
}
|
q2675
|
Formatter
|
train
|
function Formatter(format, timeFormat) {
format = format || '%(message)';
timeFormat = timeFormat || '%Y-%m-%d %H:%M:%S';
/**
* @private
* @type {string}
*/
this._format = format;
/**
* @private
* @type {string}
*/
this._timeFormat = timeFormat;
}
|
javascript
|
{
"resource": ""
}
|
q2676
|
stringifyString
|
train
|
function stringifyString( v , runtime , isTemplateSentence ) {
var maybeDollar = '' ;
if ( isTemplateSentence ) {
if ( v.key ) {
v = v.key ;
maybeDollar = '$' ;
}
else {
runtime.str += runtime.depth ? ' <Sentence>' : '<Sentence>' ;
return ;
}
}
if ( runtime.preferQuotes ) {
return stringifyStringMaybeQuotes( v , runtime , maybeDollar ) ;
}
return stringifyStringMaybeStringLine( v , runtime , maybeDollar ) ;
}
|
javascript
|
{
"resource": ""
}
|
q2677
|
t
|
train
|
function t(time, done) {
if (arguments.length === 1) {
done = time;
time = 2000;
}
var error = new Error(`Callback took too long (max: ${time})`);
var waiting = true;
var timeout = setTimeout(function () {
if (!waiting) return;
waiting = false;
done(error);
}, time);
function handler() {
if (!waiting) return;
clearTimeout(timeout);
waiting = false;
done.apply(this, arguments);
}
return handler;
}
|
javascript
|
{
"resource": ""
}
|
q2678
|
getRequest
|
train
|
function getRequest(options,callback){
var destroyed = false;
var req = request.get(options.url)
.set(options.headers)
.timeout(options.timeout)
.redirects(options.redirects)
.buffer(false)
.end(function(err,res){
if(err && !err.status) return onError(err);
// Check HTTP status code
var isHTTPError = isRedirect(res.status) || isClientError(res.status) || isServerError(res.status);
if(isHTTPError) {
var reqFormated = req.req;
var resFormated = err.response.res;
return onError(new HTTPError(reqFormated, resFormated));
}
// Attach event handlers and build the body
var body = '';
res.on('data',function(chunk){
body += chunk;
});
res.on('end',function(){
if(destroyed) return;
// Check if a HTTP refresh/redirection is present into the HTML page, if yes refreshes/redirects.
var matches = body.match(/<meta[ ]*http-equiv="REFRESH"[ ]*content="[0-9]{1,};[ ]*URL=(.*?)"[ ]*\/?>/i);
if(matches && matches[1]){
options.url = matches[1];
return getRequest(options,callback);
}
callback(null,body);
});
res.on('error',onError);
// Check if content-type is an image, if yes destroy the response and build a HTML page with the image in it
if(isImage(res.headers)){
res.destroy();
destroyed = true;
body = '<!DOCTYPE html><html><head></head><body><img src="' + options.url + '" /></body></html>';
return callback(null,body);
}
});
// Error event handler
function onError(err){
if(options.retries--) return getRequest(options,callback);
callback(err);
}
return req;
}
|
javascript
|
{
"resource": ""
}
|
q2679
|
buildDOM
|
train
|
function buildDOM(body,engine,url,callback){
if(!body){
return callback(new ScrapinodeError('The HTTP response contains an empty body: "' + body +'"'));
}
if(engine === 'jsdom' || engine === 'jsdom+zepto'){
var library = engine === 'jsdom+zepto' ? zepto : jquery;
try{
jsdom.env({
html: body,
src : [library],
done : function(err,window){
if(err) return callback(err);
if(!window) return callback(new ScrapinodeError('The "window" provides by JSDOM is falsy: ' + window));
window.location.href = url;
callback(err,window);
window.close();
}
});
}catch(err){
callback(err);
}
}else if(engine === 'cheerio'){
try{
var $ = cheerio.load(body);
var window = {
$ : $,
location : {
href : url
}
};
callback(null,window);
}catch(err){
callback(err);
}
}else{
callback(new ScrapinodeError('The engine "' + engine + '" is not supported. Scrapinode only supports jsdom and cheerio.'));
}
}
|
javascript
|
{
"resource": ""
}
|
q2680
|
isImage
|
train
|
function isImage(headers){
var regexImage = /image\//i;
var contentType = headers ? headers['content-type'] : '';
return regexImage.test(contentType);
}
|
javascript
|
{
"resource": ""
}
|
q2681
|
Schema
|
train
|
function Schema(options) {
this.options = options || {};
this.data = new Data();
this.isSchema = true;
this.utils = utils;
this.initSchema();
this.addFields(this.options);
var only = utils.arrayify(this.options.pick || this.options.only);
utils.define(this.options, 'only', only);
}
|
javascript
|
{
"resource": ""
}
|
q2682
|
rewriteDockerCompose
|
train
|
function rewriteDockerCompose(compose) {
const services = compose.services;
if (!services) {
return compose;
}
const host = services._host;
delete services._host;
Object.keys(services).forEach((k) => {
if (!isHelperContainer(k)) {
mergeWith(services[k], host);
}
});
return compose;
}
|
javascript
|
{
"resource": ""
}
|
q2683
|
train
|
function(token, this_, args, scope){
//fconsole.log('extend', arguments);
if (this.file.jsScope == basisScope)
{
var arg0 = token.arguments[0];
if (arg0 && arg0.type == 'Identifier' && arg0.name == 'Object')
flow.exit('Too old basis.js (prior 1.0) detected! Current tools doesn\'t support it. Use basisjs-tools 1.3 or lower.');
}
astExtend(scope, args[0], args[1]);
token.obj = args[0];
}
|
javascript
|
{
"resource": ""
}
|
|
q2684
|
train
|
function(token, this_, args){
//fconsole.log('getNamespace', arguments);
var namespace = args[0];
if (namespace && namespace.type == 'Literal')
{
var ns = getNamespace(namespace.value);
token.obj = ns.obj;
token.ref_ = ns.ref_;
if (args[1])
token.obj.setWrapper.run(token, this_, [args[1]]);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2685
|
getReferenceIndexedByCSS
|
train
|
function getReferenceIndexedByCSS(ref) {
var newRef = {};
for (var symb in ref.symbolizers) {
for (var property in ref.symbolizers[symb]) {
newRef[ref.symbolizers[symb][property].css] = ref.symbolizers[symb][property];
}
}
return newRef;
}
|
javascript
|
{
"resource": ""
}
|
q2686
|
getOpacityOverride
|
train
|
function getOpacityOverride(sceneDrawGroup, isFill) {
var opacity;
if (isFill) {
opacity = sceneDrawGroup._hidden['opacity:fill'];
} else {
opacity = sceneDrawGroup._hidden['opacity:outline'];
}
if (sceneDrawGroup._hidden['opacity:general'] !== undefined) {
opacity = sceneDrawGroup._hidden['opacity:general'];
}
return opacity;
}
|
javascript
|
{
"resource": ""
}
|
q2687
|
getFunctionFromDefaultAndShaderValue
|
train
|
function getFunctionFromDefaultAndShaderValue(sceneDrawGroup, ccssProperty, defaultValue, shaderValue) {
if (referenceCSS[ccssProperty].type === 'color') {
defaultValue = `'${color.normalize(defaultValue, tangramReference)}'`;
}
var fn = `var _value=${defaultValue};`;
shaderValue.js.forEach(function (code) {
if (code.search(/data\['mapnik::\S+'\]/) >= 0) {
throw new Error('mapnik selector present in the CartoCSS');
}
fn += code;
});
if (referenceCSS[ccssProperty].type === 'color') {
fn += getColorOverrideCode(sceneDrawGroup, ccssProperty.indexOf('fill') >= 0);
}
if (ccssProperty === 'line-width') {
fn += '_value=_value*$meters_per_pixel;';
}
fn += 'return _value;';
return wrapFn(fn);
}
|
javascript
|
{
"resource": ""
}
|
q2688
|
translateValue
|
train
|
function translateValue(sceneDrawGroup, ccssProperty, ccssValue) {
if (ccssProperty.indexOf('comp-op') >= 0) {
switch (ccssValue) {
case 'src-over':
return 'overlay';
case 'plus':
return 'add';
default:
return ccssValue;
}
}
if (referenceCSS[ccssProperty].type === 'color') {
return getColorFromLiteral(sceneDrawGroup, ccssValue, ccssProperty.indexOf('fill') >= 0);
}
if (ccssProperty.indexOf('width') >= 0) {
ccssValue += 'px';
}
if (ccssProperty.indexOf('allow-overlap') >= 0) {
ccssValue = !ccssValue;
}
return ccssValue;
}
|
javascript
|
{
"resource": ""
}
|
q2689
|
getFilterFn
|
train
|
function getFilterFn(layer, symbolizer) {
const symbolizers = Object.keys(layer.shader)
.filter(property => layer.shader[property].symbolizer === symbolizer);
//No need to set a callback when at least one property is not filtered (i.e. it always activates the symbolizer)
const alwaysActive = symbolizers
.reduce((a, property) => a || !layer.shader[property].filtered, false);
if (alwaysActive) {
return undefined;
}
const fn = symbolizers
.map((property) => layer.shader[property].js)
.reduce((all, arr) => all.concat(arr), [])
.join('');
return wrapFn(`var _value = null; ${fn} return _value !== null;`);
}
|
javascript
|
{
"resource": ""
}
|
q2690
|
getGlob
|
train
|
function getGlob() {
if (isNode) {
return loader.import("@node-require", { name: module.id })
.then(function(nodeRequire) {
return nodeRequire("glob");
});
}
return Promise.resolve();
}
|
javascript
|
{
"resource": ""
}
|
q2691
|
getModuleName
|
train
|
function getModuleName(nameWithConditional, variation) {
var modName;
var conditionIndex = nameWithConditional.search(conditionalRegEx);
// look for any "/" after the condition
var lastSlashIndex = nameWithConditional.indexOf("/",
nameWithConditional.indexOf("}"));
// substitution of a folder name
if (lastSlashIndex !== -1) {
modName = nameWithConditional.substr(0, conditionIndex) + variation;
}
else {
modName = nameWithConditional.replace(conditionalRegEx, variation);
}
return modName;
}
|
javascript
|
{
"resource": ""
}
|
q2692
|
train
|
function(m) {
var conditionValue = (typeof m === "object") ?
readMemberExpression(conditionExport, m) : m;
if (substitution) {
if (typeof conditionValue !== "string") {
throw new TypeError(
"The condition value for " +
conditionalMatch[0] +
" doesn't resolve to a string."
);
}
name = name.replace(conditionalRegEx, conditionValue);
}
else {
if (typeof conditionValue !== "boolean") {
throw new TypeError(
"The condition value for " +
conditionalMatch[0] +
" isn't resolving to a boolean."
);
}
if (booleanNegation) {
conditionValue = !conditionValue;
}
if (!conditionValue) {
name = "@empty";
} else {
name = name.replace(conditionalRegEx, "");
}
}
if (name === "@empty") {
return normalize.call(loader, name, parentName, parentAddress, pluginNormalize);
} else {
// call the full normalize in case the module name
// is an npm package (that needs to be normalized)
return loader.normalize.call(loader, name, parentName, parentAddress, pluginNormalize);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q2693
|
Handler
|
train
|
function Handler(level) {
level = level || Logger.NOTSET;
if (Logger.getLevelName(level) === '') {
throw new Error('Argument 1 of Handler.constructor has unsupported'
+ ' value \'' + level + '\'');
}
Filterer.call(this);
/**
* @private
* @type {number}
*/
this._level = level;
/**
* @private
* @type {Object}
*/
this._formatter = null;
}
|
javascript
|
{
"resource": ""
}
|
q2694
|
baseParse
|
train
|
function baseParse(text, strict) {
const lines = String(text).replace(/(?:\r?\n)+$/, '').split(/\r?\n/);
const records = [];
for (let i = 0, len = lines.length; i < len; ++i) {
records[i] = baseParseLine(lines[i], strict);
}
return records;
}
|
javascript
|
{
"resource": ""
}
|
q2695
|
baseParseLine
|
train
|
function baseParseLine(line, strict) {
const fields = String(line).replace(/(?:\r?\n)+$/, '').split('\t');
const record = {};
for (let i = 0, len = fields.length; i < len; ++i) {
const _splitField = splitField(fields[i], strict),
label = _splitField.label,
value = _splitField.value;
record[label] = value;
}
return record;
}
|
javascript
|
{
"resource": ""
}
|
q2696
|
train
|
function(params) {
const order = this;
if (!params) {
params = {};
}
// the standards attributes
this.id = params.id;
this.dateCreated = params.dateCreated;
this.lastUpdated = params.lastUpdated;
this.version = params.version;
this.customer = params.customer;
this.orderDate = params.orderDate;
this.total = params.total;
this.items = params.items;
this.calcTotal = function() {
order.total = 0;
order.items.forEach(function(item) {
order.total += item.price;
});
return order.total;
};
}
|
javascript
|
{
"resource": ""
}
|
|
q2697
|
customOverrider
|
train
|
function customOverrider (a, b, propertyName) {
if (b == null) {
return a
}
if (a == null) {
// Invoke default overrider
return undefined
}
// Some objects have custom overriders
if (b._customize_custom_overrider && b._customize_custom_overrider instanceof Function) {
return b._customize_custom_overrider(a, b, propertyName)
}
// Arrays should be concatenated
if (Array.isArray(a)) {
return a.concat(b)
}
// Merge values resolving promises, if they are not leaf-promises
if (isPromiseAlike(a) || isPromiseAlike(b)) {
return Promise.all([a, b]).then(function ([_a, _b]) {
// Merge the promise results
return mergeWith({}, { x: _a }, { x: _b }, customOverrider).x
})
}
// None of these options apply. Implicit "undefined" return value to invoke default overrider.
}
|
javascript
|
{
"resource": ""
}
|
q2698
|
MultiLine
|
train
|
function MultiLine( type , fold , applicable , options ) {
this.type = type ;
this.fold = !! fold ;
this.applicable = !! applicable ;
this.options = options ;
this.lines = [] ;
}
|
javascript
|
{
"resource": ""
}
|
q2699
|
train
|
function(callback) {
self._getConnection(function(err, connection) {
if (err) {
callback(new Error('Unable to establish connection with the master ' +
'process'));
return;
}
self._connection = connection;
callback();
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.