_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q44400
|
removeClosingReturnPoints
|
train
|
function removeClosingReturnPoints(contours) {
return _.map(contours, function (contour) {
var length = contour.length;
if (length > 1 &&
contour[0].x === contour[length - 1].x &&
contour[0].y === contour[length - 1].y) {
contour.splice(length - 1);
}
return contour;
});
}
|
javascript
|
{
"resource": ""
}
|
q44401
|
compactFlags
|
train
|
function compactFlags(flags) {
var result = [];
var prevFlag = -1;
var firstRepeat = false;
_.forEach(flags, function (flag) {
if (prevFlag === flag) {
if (firstRepeat) {
result[result.length - 1] += 8; //current flag repeats previous one, need to set 3rd bit of previous flag and set 1 to the current one
result.push(1);
firstRepeat = false;
} else {
result[result.length - 1]++; //when flag is repeating second or more times, we need to increase the last flag value
}
} else {
firstRepeat = true;
prevFlag = flag;
result.push(flag);
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q44402
|
glyphDataSize
|
train
|
function glyphDataSize(glyph) {
// Ignore glyphs without outlines. These will get a length of zero in the “loca” table
if (!glyph.contours.length) {
return 0;
}
var result = 12; //glyph fixed properties
result += glyph.contours.length * 2; //add contours
_.forEach(glyph.ttf_x, function (x) {
//add 1 or 2 bytes for each coordinate depending of its size
result += ((-0xFF <= x && x <= 0xFF)) ? 1 : 2;
});
_.forEach(glyph.ttf_y, function (y) {
//add 1 or 2 bytes for each coordinate depending of its size
result += ((-0xFF <= y && y <= 0xFF)) ? 1 : 2;
});
// Add flags length to glyph size.
result += glyph.ttf_flags.length;
if (result % 4 !== 0) { // glyph size must be divisible by 4.
result += 4 - result % 4;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q44403
|
ucs2encode
|
train
|
function ucs2encode(array) {
return _.map(array, function (value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += String.fromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += String.fromCharCode(value);
return output;
}).join('');
}
|
javascript
|
{
"resource": ""
}
|
q44404
|
toSfntCoutours
|
train
|
function toSfntCoutours(svgPath) {
var resContours = [];
var resContour = [];
svgPath.iterate(function (segment, index, x, y) {
//start new contour
if (index === 0 || segment[0] === 'M') {
resContour = [];
resContours.push(resContour);
}
var name = segment[0];
if (name === 'Q') {
//add control point of quad spline, it is not on curve
resContour.push({ x: segment[1], y: segment[2], onCurve: false });
}
// add on-curve point
if (name === 'H') {
// vertical line has Y coordinate only, X remains the same
resContour.push({ x: segment[1], y: y, onCurve: true });
} else if (name === 'V') {
// horizontal line has X coordinate only, Y remains the same
resContour.push({ x: x, y: segment[1], onCurve: true });
} else if (name !== 'Z') {
// for all commands (except H and V) X and Y are placed in the end of the segment
resContour.push({ x: segment[segment.length - 2], y: segment[segment.length - 1], onCurve: true });
}
});
return resContours;
}
|
javascript
|
{
"resource": ""
}
|
q44405
|
createFeatureList
|
train
|
function createFeatureList() {
var header = (0
+ 2 // FeatureCount
+ 4 // FeatureTag[0]
+ 2 // Feature Offset[0]
);
var length = (0
+ header
+ 2 // FeatureParams[0]
+ 2 // LookupCount[0]
+ 2 // Lookup[0] LookupListIndex[0]
);
var buffer = new ByteBuffer(length);
// FeatureCount
buffer.writeUint16(1);
// FeatureTag[0]
buffer.writeUint32(identifier('liga'));
// Feature Offset[0]
buffer.writeUint16(header);
// FeatureParams[0]
buffer.writeUint16(0);
// LookupCount[0]
buffer.writeUint16(1);
// Index into lookup table. Since we only have ligatures, the index is always 0
buffer.writeUint16(0);
return buffer;
}
|
javascript
|
{
"resource": ""
}
|
q44406
|
createLookupList
|
train
|
function createLookupList(font) {
var ligatures = font.ligatures;
var groupedLigatures = {};
// Group ligatures by first code point
_.forEach(ligatures, function (ligature) {
var first = ligature.unicode[0];
if (!_.has(groupedLigatures, first)) {
groupedLigatures[first] = [];
}
groupedLigatures[first].push(ligature);
});
var ligatureGroups = [];
_.forEach(groupedLigatures, function (ligatures, codePoint) {
codePoint = parseInt(codePoint, 10);
// Order ligatures by length, descending
// “Ligatures with more components must be stored ahead of those with fewer components in order to be found”
// From: http://partners.adobe.com/public/developer/opentype/index_tag7.html#liga
ligatures.sort(function (ligA, ligB) {
return ligB.unicode.length - ligA.unicode.length;
});
ligatureGroups.push({
codePoint: codePoint,
ligatures: ligatures,
startGlyph: font.codePoints[codePoint]
});
});
ligatureGroups.sort(function (a, b) {
return a.startGlyph.id - b.startGlyph.id;
});
var offset = (0
+ 2 // Lookup count
+ 2 // Lookup[0] offset
);
var set = createLigatureList(font, ligatureGroups);
var length = (0
+ offset
+ set.length
);
var buffer = new ByteBuffer(length);
// Lookup count
buffer.writeUint16(1);
// Lookup[0] offset
buffer.writeUint16(offset);
// Lookup[0]
buffer.writeBytes(set.buffer);
return buffer;
}
|
javascript
|
{
"resource": ""
}
|
q44407
|
getMaxPoints
|
train
|
function getMaxPoints(font) {
return _.max(_.map(font.glyphs, function (glyph) {
return _.reduce(glyph.ttfContours, function (sum, ctr) { return sum + ctr.length; }, 0);
}));
}
|
javascript
|
{
"resource": ""
}
|
q44408
|
selectScenario
|
train
|
function selectScenario(data, scenario) {
return _execute('PUT', '/mocks', {
identifier: _getIdentifier(data),
scenario: scenario || null
}, 'Could not select scenario [' + scenario + ']');
}
|
javascript
|
{
"resource": ""
}
|
q44409
|
echoRequest
|
train
|
function echoRequest(data, echo) {
return _execute('PUT', '/mocks', {
identifier: _getIdentifier(data),
echo: echo || false
}, 'Could not echo the request');
}
|
javascript
|
{
"resource": ""
}
|
q44410
|
_execute
|
train
|
function _execute(httpMethod, urlSuffix, options, errorMessage) {
const opts = {
headers: {
'Content-Type': 'application/json',
'ngapimockid': ngapimockid
}
};
if (options !== undefined) {
opts.json = options;
}
return _handleRequest(httpMethod, urlSuffix, opts, errorMessage);
}
|
javascript
|
{
"resource": ""
}
|
q44411
|
_getIdentifier
|
train
|
function _getIdentifier(data) {
let identifier;
if (typeof data === 'string') { // name of the mock
identifier = data;
} else if (data.name) { // the data containing the name of the mock
identifier = data.name;
} else {
identifier = data.expression + '$$' + data.method;
}
return identifier;
}
|
javascript
|
{
"resource": ""
}
|
q44412
|
fetchMocks
|
train
|
function fetchMocks() {
mockService.get({}, function (response) {
vm.mocks = response.mocks.map(function(mock){
Object.keys(mock.responses).forEach(function(response) {
mock.responses[response].name = response;
});
return mock;
});
vm.selections = response.selections;
vm.delays = response.delays;
vm.echos = response.echos;
vm.recordings = response.recordings;
vm.record = response.record;
if (vm.record) {
interval = $interval(refreshMocks, 5000);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q44413
|
refreshMocks
|
train
|
function refreshMocks() {
mockService.get({}, function (response) {
angular.merge(vm.mocks, response.mocks);
vm.selections = response.selections;
});
}
|
javascript
|
{
"resource": ""
}
|
q44414
|
echoMock
|
train
|
function echoMock(mock, echo) {
mockService.update({'identifier': mock.identifier, 'echo': echo}, function () {
vm.echos[mock.identifier] = echo;
});
}
|
javascript
|
{
"resource": ""
}
|
q44415
|
delayMock
|
train
|
function delayMock(mock, delay) {
mockService.update({'identifier': mock.identifier, 'delay': delay}, function () {
vm.delays[mock.identifier] = delay;
});
}
|
javascript
|
{
"resource": ""
}
|
q44416
|
toggleRecording
|
train
|
function toggleRecording() {
mockService.toggleRecord({}, function (response) {
vm.record = response.record;
if (vm.record) {
interval = $interval(refreshMocks, 5000);
} else {
$interval.cancel(interval);
refreshMocks();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q44417
|
selectMock
|
train
|
function selectMock(mock, selection) {
mockService.update({'identifier': mock.identifier, 'scenario': selection || 'passThrough'}, function () {
vm.selections[mock.identifier] = selection;
});
}
|
javascript
|
{
"resource": ""
}
|
q44418
|
addVariable
|
train
|
function addVariable() {
variableService.addOrUpdate(vm.variable, function () {
vm.variables[vm.variable.key] = vm.variable.value;
vm.variable = {
key: undefined,
value: undefined
};
});
}
|
javascript
|
{
"resource": ""
}
|
q44419
|
updateVariable
|
train
|
function updateVariable(key, value) {
variableService.addOrUpdate({key: key, value: value}, function () {
vm.variables[key] = value;
vm.variable = {
key: undefined,
value: undefined
};
});
}
|
javascript
|
{
"resource": ""
}
|
q44420
|
searchFilter
|
train
|
function searchFilter(mock) {
if (!vm.searchUrl || !mock.expression) {
return true;
}
return vm.searchUrl.match(mock.expression);
}
|
javascript
|
{
"resource": ""
}
|
q44421
|
discover
|
train
|
function discover(target) {
var both = false;
if (!target) {
target = 'googlecast';
both = true;
}
return new Promise( function(resolve, reject) {
var updateCounter=0;
var discovered = [];
try {
if (getNetworkIp) {
var browser = mdns.createBrowser(mdns.tcp(target));
var exception;
browser.on('error', function(error) {
log('debug', 'discover()', 'mdns browser error: ' + error);
})
browser.on('ready', function(){
browser.discover();
});
browser.on('update', function(service){
//try {
updateCounter++;
log('debug', 'discover()', 'update received, service: ' + JSON.stringify(service));
if (target=='googlecast' && service.type[0].name==target) {
var currentDevice = {
id: getId(service.txt[0]),
name: getFriendlyName(service.txt),
address: {
host: service.addresses[0],
port: service.port
}
}
if (!duplicateDevice(discovered, currentDevice) && currentDevice.name!=null ) {
log('debug', 'discover()', 'found device: '+ JSON.stringify(currentDevice));
discovered.push(currentDevice);
updateExistingCastDeviceAddress(currentDevice);
if ( !deviceExists(currentDevice.id) ) {
log('info', 'discover()', 'added device name: '+ currentDevice.name +', address: '+ JSON.stringify(currentDevice.address), currentDevice.id);
devices.push( new CastDevice( currentDevice.id, currentDevice.address, currentDevice.name ) ); //TODO: addDevice
}
} else {
log('debug', 'discover()', 'duplicate, googlezone device or empy name: ' + JSON.stringify(currentDevice));
}
}
if (target=='googlezone' && service.type[0].name==target) {
var currentGroupMembership = {
id: getId(service.txt[0]).replace(/-/g, ''),
groups: getGroupIds(service.txt)
}
log('debug', 'discover()', 'found googlezone: ' + JSON.stringify(currentGroupMembership) );
discovered.push(currentGroupMembership);
}
// } catch (e) {
// log('error', 'discover()', 'exception while prcessing service: '+e);
// }
});
}
} catch (e) {
reject('Exception caught: ' + e);
}
setTimeout(() => {
try{
browser.stop();
} catch (e) {
//reject('Exception caught: ' + e)
}
log('debug', 'discover()', 'updateCounter: ' + updateCounter);
resolve(discovered);
}, timeoutDiscovery);
});
}
|
javascript
|
{
"resource": ""
}
|
q44422
|
train
|
function (success, error, nativeMethodName, args) {
var fail;
// args checking
_checkCallbacks(success, error);
// By convention a failure callback should always receive an instance
// of a JavaScript Error object.
fail = function(err) {
// provide default message if no details passed to callback
if (typeof err === 'undefined') {
error(new Error('Error occured while executing native method.'));
} else {
// wrap string to Error instance if necessary
error(_isString(err) ? new Error(err) : err);
}
};
cordova.exec(success, fail, 'SecureStorage', nativeMethodName, args);
}
|
javascript
|
{
"resource": ""
}
|
|
q44423
|
filterMatrix
|
train
|
function filterMatrix(matrix, filter) {
const filtered = [];
if (matrix.length === 0) {
return matrix;
}
for (let row = 0; row < matrix.length; row++) {
if (matrix.length !== 0) {
for (let column = 0; column < matrix[0].length; column++) {
const cell = matrix[row][column];
if (cell && cell.value.includes(filter)) {
if (!filtered[0]) {
filtered[0] = [];
}
if (filtered[0].length < column) {
filtered[0].length = column + 1;
}
if (!filtered[row]) {
filtered[row] = [];
}
filtered[row][column] = cell;
}
}
}
}
return filtered;
}
|
javascript
|
{
"resource": ""
}
|
q44424
|
start
|
train
|
function start() {
exec(function (a) {
var tempListeners = listeners.slice(0);
accel = new Acceleration(a.x, a.y, a.z, a.timestamp);
for (var i = 0, l = tempListeners.length; i < l; i++) {
tempListeners[i].win(accel);
}
}, function (e) {
var tempListeners = listeners.slice(0);
for (var i = 0, l = tempListeners.length; i < l; i++) {
tempListeners[i].fail(e);
}
}, "Accelerometer", "start", []);
running = true;
}
|
javascript
|
{
"resource": ""
}
|
q44425
|
touchStart
|
train
|
function touchStart(e) {
$this = $(e.currentTarget);
$this.data('callee1', touchStart);
originalCoord.x = (e.originalEvent.targetTouches) ? e.originalEvent.targetTouches[0].pageX : e.pageX;
originalCoord.y = (e.originalEvent.targetTouches) ? e.originalEvent.targetTouches[0].pageY : e.pageY;
finalCoord.x = originalCoord.x;
finalCoord.y = originalCoord.y;
started = true;
var origEvent = e.originalEvent;
// Read event data into our startEvt:
startEvnt = {
'position': {
'x': (settings.touch_capable) ? origEvent.touches[0].screenX : e.screenX,
'y': (settings.touch_capable) ? origEvent.touches[0].screenY : e.screenY
},
'offset': {
'x': (settings.touch_capable) ? Math.round(origEvent.changedTouches[0].pageX - ($this.offset() ? $this.offset().left : 0)) : Math.round(e.pageX - ($this.offset() ? $this.offset().left : 0)),
'y': (settings.touch_capable) ? Math.round(origEvent.changedTouches[0].pageY - ($this.offset() ? $this.offset().top : 0)) : Math.round(e.pageY - ($this.offset() ? $this.offset().top : 0))
},
'time': Date.now(),
'target': e.target
};
}
|
javascript
|
{
"resource": ""
}
|
q44426
|
train
|
function(packet) {
packet.status = packet.readInt(8);
packet.oskType = packet.readInt(12);
// TODO: for some reason, the way we decode it
// gives an extra 16 bytes of garbage here. We
// should really figure out why that's happening
// ... and fix it
if (packet.buf.length > 36) {
packet.max = packet.readInt(32);
packet.initial = packet.readString(36);
}
this.emit('start_osk_result', packet);
}
|
javascript
|
{
"resource": ""
}
|
|
q44427
|
train
|
function(packet) {
packet._index = 8;
packet.preEditIndex = packet.readInt();
packet.preEditLength = packet.readInt();
// TODO: see above about how how we're skipping
// 16 bytes here for some reason and how hacky
// this is
if (packet.buf.length > 36) {
packet._index += 16;
packet.editIndex = packet.readInt();
packet.editLength = packet.readInt();
packet.caretIndex = packet.readInt();
packet.string = packet.readString(packet._index);
}
this.emit('osk_string_changed', packet);
}
|
javascript
|
{
"resource": ""
}
|
|
q44428
|
train
|
function(packet) {
packet.commandId = packet.readInt();
packet.command = packet.commandId === 0
? 'return'
: 'close';
this.emit('osk_command', packet);
}
|
javascript
|
{
"resource": ""
}
|
|
q44429
|
Packet
|
train
|
function Packet(length) {
this._index = 0;
if (length instanceof Buffer) {
this.buf = length;
} else {
this.buf = Buffer.alloc(length, 0);
this.writeInt32LE(length);
}
}
|
javascript
|
{
"resource": ""
}
|
q44430
|
findClosestPoint
|
train
|
function findClosestPoint (sources, target) {
const distances = [];
let minDistance;
sources.forEach(function (source, index) {
const d = distance(source, target);
distances.push(d);
if (index === 0) {
minDistance = d;
} else {
minDistance = Math.min(d, minDistance);
}
});
const index = distances.indexOf(minDistance);
return sources[index];
}
|
javascript
|
{
"resource": ""
}
|
q44431
|
rectToPoints
|
train
|
function rectToPoints (rect) {
const rectPoints = {
topLeft: {
x: rect.left,
y: rect.top
},
bottomRight: {
x: rect.left + rect.width,
y: rect.top + rect.height
}
};
return rectPoints;
}
|
javascript
|
{
"resource": ""
}
|
q44432
|
doesIntersect
|
train
|
function doesIntersect (rect1, rect2) {
let intersectLeftRight;
let intersectTopBottom;
const rect1Points = rectToPoints(rect1);
const rect2Points = rectToPoints(rect2);
if (rect1.width >= 0) {
if (rect2.width >= 0) {
intersectLeftRight = !((rect1Points.bottomRight.x <= rect2Points.topLeft.x) || (rect2Points.bottomRight.x <= rect1Points.topLeft.x));
} else {
intersectLeftRight = !((rect1Points.bottomRight.x <= rect2Points.bottomRight.x) || (rect2Points.topLeft.x <= rect1Points.topLeft.x));
}
} else if (rect2.width >= 0) {
intersectLeftRight = !((rect1Points.topLeft.x <= rect2Points.topLeft.x) || (rect2Points.bottomRight.x <= rect1Points.bottomRight.x));
} else {
intersectLeftRight = !((rect1Points.topLeft.x <= rect2Points.bottomRight.x) || (rect2Points.topLeft.x <= rect1Points.bottomRight.x));
}
if (rect1.height >= 0) {
if (rect2.height >= 0) {
intersectTopBottom = !((rect1Points.bottomRight.y <= rect2Points.topLeft.y) || (rect2Points.bottomRight.y <= rect1Points.topLeft.y));
} else {
intersectTopBottom = !((rect1Points.bottomRight.y <= rect2Points.bottomRight.y) || (rect2Points.topLeft.y <= rect1Points.topLeft.y));
}
} else if (rect2.height >= 0) {
intersectTopBottom = !((rect1Points.topLeft.y <= rect2Points.topLeft.y) || (rect2Points.bottomRight.y <= rect1Points.bottomRight.y));
} else {
intersectTopBottom = !((rect1Points.topLeft.y <= rect2Points.bottomRight.y) || (rect2Points.top <= rect1Points.bottomRight.y));
}
return intersectLeftRight && intersectTopBottom;
}
|
javascript
|
{
"resource": ""
}
|
q44433
|
getIntersectionRect
|
train
|
function getIntersectionRect (rect1, rect2) {
const intersectRect = {
topLeft: {},
bottomRight: {}
};
if (!doesIntersect(rect1, rect2)) {
return;
}
const rect1Points = rectToPoints(rect1);
const rect2Points = rectToPoints(rect2);
if (rect1.width >= 0) {
if (rect2.width >= 0) {
intersectRect.topLeft.x = Math.max(rect1Points.topLeft.x, rect2Points.topLeft.x);
intersectRect.bottomRight.x = Math.min(rect1Points.bottomRight.x, rect2Points.bottomRight.x);
} else {
intersectRect.topLeft.x = Math.max(rect1Points.topLeft.x, rect2Points.bottomRight.x);
intersectRect.bottomRight.x = Math.min(rect1Points.bottomRight.x, rect2Points.topLeft.x);
}
} else if (rect2.width >= 0) {
intersectRect.topLeft.x = Math.min(rect1Points.topLeft.x, rect2Points.bottomRight.x);
intersectRect.bottomRight.x = Math.max(rect1Points.bottomRight.x, rect2Points.topLeft.x);
} else {
intersectRect.topLeft.x = Math.min(rect1Points.topLeft.x, rect2Points.topLeft.x);
intersectRect.bottomRight.x = Math.max(rect1Points.bottomRight.x, rect2Points.bottomRight.x);
}
if (rect1.height >= 0) {
if (rect2.height >= 0) {
intersectRect.topLeft.y = Math.max(rect1Points.topLeft.y, rect2Points.topLeft.y);
intersectRect.bottomRight.y = Math.min(rect1Points.bottomRight.y, rect2Points.bottomRight.y);
} else {
intersectRect.topLeft.y = Math.max(rect1Points.topLeft.y, rect2Points.bottomRight.y);
intersectRect.bottomRight.y = Math.min(rect1Points.bottomRight.y, rect2Points.topLeft.y);
}
} else if (rect2.height >= 0) {
intersectRect.topLeft.y = Math.min(rect1Points.topLeft.y, rect2Points.bottomRight.y);
intersectRect.bottomRight.y = Math.max(rect1Points.bottomRight.y, rect2Points.topLeft.y);
} else {
intersectRect.topLeft.y = Math.min(rect1Points.topLeft.y, rect2Points.topLeft.y);
intersectRect.bottomRight.y = Math.max(rect1Points.bottomRight.y, rect2Points.bottomRight.y);
}
// Returns top-left and bottom-right points of intersected rectangle
return intersectRect;
}
|
javascript
|
{
"resource": ""
}
|
q44434
|
clamp
|
train
|
function clamp (x, a, b) {
return (x < a) ? a : ((x > b) ? b : x);
}
|
javascript
|
{
"resource": ""
}
|
q44435
|
intersectLine
|
train
|
function intersectLine (lineSegment1, lineSegment2) {
const intersectionPoint = {};
let x1 = lineSegment1.start.x,
y1 = lineSegment1.start.y,
x2 = lineSegment1.end.x,
y2 = lineSegment1.end.y,
x3 = lineSegment2.start.x,
y3 = lineSegment2.start.y,
x4 = lineSegment2.end.x,
y4 = lineSegment2.end.y;
// Coefficients of line equations
let a1, a2, b1, b2, c1, c2;
// Sign values
let r1, r2, r3, r4;
// Intermediate values
let denom, num;
// Compute a1, b1, c1, where line joining points 1 and 2 is "a1 x + b1 y + c1 = 0"
a1 = y2 - y1;
b1 = x1 - x2;
c1 = x2 * y1 - x1 * y2;
// Compute r3 and r4
r3 = a1 * x3 + b1 * y3 + c1;
r4 = a1 * x4 + b1 * y4 + c1;
/* Check signs of r3 and r4. If both point 3 and point 4 lie on
* same side of line 1, the line segments do not intersect.
*/
if (r3 !== 0 &&
r4 !== 0 &&
sign(r3) === sign(r4)) {
return;
}
// Compute a2, b2, c2
a2 = y4 - y3;
b2 = x3 - x4;
c2 = x4 * y3 - x3 * y4;
// Compute r1 and r2
r1 = a2 * x1 + b2 * y1 + c2;
r2 = a2 * x2 + b2 * y2 + c2;
/* Check signs of r1 and r2. If both point 1 and point 2 lie
* on same side of second line segment, the line segments do
* not intersect.
*/
if (r1 !== 0 &&
r2 !== 0 &&
sign(r1) === sign(r2)) {
return;
}
/* Line segments intersect: compute intersection point.
*/
denom = (a1 * b2) - (a2 * b1);
/* The denom/2 is to get rounding instead of truncating. It
* is added or subtracted to the numerator, depending upon the
* sign of the numerator.
*/
num = (b1 * c2) - (b2 * c1);
const x = parseFloat(num / denom);
num = (a2 * c1) - (a1 * c2);
const y = parseFloat(num / denom);
intersectionPoint.x = x;
intersectionPoint.y = y;
return intersectionPoint;
}
|
javascript
|
{
"resource": ""
}
|
q44436
|
train
|
function (bytes) {
var s = '';
for (var i = 0, l = bytes.length; i < l; i++) {
s += String.fromCharCode(bytes[i]);
}
return s;
}
|
javascript
|
{
"resource": ""
}
|
|
q44437
|
calcCFFSubroutineBias
|
train
|
function calcCFFSubroutineBias(subrs) {
var bias;
if (subrs.length < 1240) {
bias = 107;
}
else if (subrs.length < 33900) {
bias = 1131;
}
else {
bias = 32768;
}
return bias;
}
|
javascript
|
{
"resource": ""
}
|
q44438
|
getRawTag
|
train
|
function getRawTag(value) {
var isOwn = hasOwnProperty$1.call(value, symToStringTag$1),
tag = value[symToStringTag$1];
try {
value[symToStringTag$1] = undefined;
var unmasked = true;
} catch (e) {}
var result = nativeObjectToString.call(value);
if (unmasked) {
if (isOwn) {
value[symToStringTag$1] = tag;
} else {
delete value[symToStringTag$1];
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q44439
|
default_deduplicator
|
train
|
function default_deduplicator(objectA, objectB) {
// default deduplication handler:
// if object versions differ, use highest available version
if ((objectA.version || objectB.version) &&
(objectA.version !== objectB.version)) {
return (+objectA.version || 0) > (+objectB.version || 0)
? objectA
: objectB;
}
// otherwise: return merged obj properties
return _.merge(objectA, objectB);
}
|
javascript
|
{
"resource": ""
}
|
q44440
|
has_interesting_tags
|
train
|
function has_interesting_tags(t, ignore_tags) {
if (typeof ignore_tags !== "object")
ignore_tags={};
if (typeof options.uninterestingTags === "function")
return !options.uninterestingTags(t, ignore_tags);
for (var k in t)
if (!(options.uninterestingTags[k]===true) &&
!(ignore_tags[k]===true || ignore_tags[k]===t[k]))
return true;
return false;
}
|
javascript
|
{
"resource": ""
}
|
q44441
|
build_meta_information
|
train
|
function build_meta_information(object) {
var res = {
"timestamp": object.timestamp,
"version": object.version,
"changeset": object.changeset,
"user": object.user,
"uid": object.uid
};
for (var k in res)
if (res[k] === undefined)
delete res[k];
return res;
}
|
javascript
|
{
"resource": ""
}
|
q44442
|
join
|
train
|
function join(ways) {
var _first = function(arr) {return arr[0]};
var _last = function(arr) {return arr[arr.length-1]};
var _fitTogether = function(n1, n2) {
return n1 !== undefined && n2 !== undefined && n1.id === n2.id;
}
// stolen from iD/relation.js
var joined = [], current, first, last, i, how, what;
while (ways.length) {
current = ways.pop().nodes.slice();
joined.push(current);
while (ways.length && !_fitTogether(_first(current), _last(current))) {
first = _first(current);
last = _last(current);
for (i = 0; i < ways.length; i++) {
what = ways[i].nodes;
if (_fitTogether(last, _first(what))) {
how = current.push;
what = what.slice(1);
break;
} else if (_fitTogether(last, _last(what))) {
how = current.push;
what = what.slice(0, -1).reverse();
break;
} else if (_fitTogether(first, _last(what))) {
how = current.unshift;
what = what.slice(0, -1);
break;
} else if (_fitTogether(first, _first(what))) {
how = current.unshift;
what = what.slice(1).reverse();
break;
} else {
what = how = null;
}
}
if (!what)
break; // Invalid geometry (dangling way, unclosed ring)
ways.splice(i, 1);
how.apply(current, what);
}
}
return joined;
}
|
javascript
|
{
"resource": ""
}
|
q44443
|
train
|
function () {
var deferred = Q.defer();
var parser = new xml2js.Parser();
fs.readFile(settings.CONFIG_FILE, function (err, data) {
if (err) {
deferred.reject(err);
}
parser.parseString(data, function (err, result) {
if (err) {
deferred.reject(err);
}
var projectName = result.widget.name[0];
deferred.resolve(projectName);
});
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q44444
|
train
|
function (platform, splash) {
var deferred = Q.defer();
var srcPath = settings.SPLASH_FILE;
var platformPath = srcPath.replace(/\.png$/, '-' + platform.name + '.png');
if (fs.existsSync(platformPath)) {
srcPath = platformPath;
}
var dstPath = platform.splashPath + splash.name;
var dst = path.dirname(dstPath);
if (!fs.existsSync(dst)) {
fs.mkdirsSync(dst);
}
ig.crop({
srcPath: srcPath,
dstPath: dstPath,
quality: 1,
format: 'png',
width: splash.width,
height: splash.height
} , function(err, stdout, stderr){
if (err) {
deferred.reject(err);
} else {
deferred.resolve();
display.success(splash.name + ' created');
}
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q44445
|
train
|
function (platform) {
var deferred = Q.defer();
display.header('Generating splash screen for ' + platform.name);
var all = [];
var splashes = platform.splash;
splashes.forEach(function (splash) {
all.push(generateSplash(platform, splash));
});
Q.all(all).then(function () {
deferred.resolve();
}).catch(function (err) {
console.log(err);
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q44446
|
train
|
function (platforms) {
var deferred = Q.defer();
var sequence = Q();
var all = [];
_(platforms).where({ isAdded : true }).forEach(function (platform) {
sequence = sequence.then(function () {
return generateSplashForPlatform(platform);
});
all.push(sequence);
});
Q.all(all).then(function () {
deferred.resolve();
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q44447
|
train
|
function () {
var deferred = Q.defer();
getPlatforms().then(function (platforms) {
var activePlatforms = _(platforms).where({ isAdded : true });
if (activePlatforms.length > 0) {
display.success('platforms found: ' + _(activePlatforms).pluck('name').join(', '));
deferred.resolve();
} else {
display.error(
'No cordova platforms found. ' +
'Make sure you are in the root folder of your Cordova project ' +
'and add platforms with \'cordova platform add\''
);
deferred.reject();
}
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q44448
|
train
|
function () {
var deferred = Q.defer();
fs.exists(settings.SPLASH_FILE, function (exists) {
if (exists) {
display.success(settings.SPLASH_FILE + ' exists');
deferred.resolve();
} else {
display.error(settings.SPLASH_FILE + ' does not exist');
deferred.reject();
}
});
return deferred.promise;
}
|
javascript
|
{
"resource": ""
}
|
|
q44449
|
syncMaps
|
train
|
function syncMaps () {
var maps;
var argLen = arguments.length;
if (argLen === 1) {
maps = arguments[0];
} else {
maps = [];
for (var i = 0; i < argLen; i++) {
maps.push(arguments[i]);
}
}
// Create all the movement functions, because if they're created every time
// they wouldn't be the same and couldn't be removed.
var fns = [];
maps.forEach(function (map, index) {
fns[index] = sync.bind(null, map, maps.filter(function (o, i) { return i !== index; }));
});
function on () {
maps.forEach(function (map, index) {
map.on('move', fns[index]);
});
}
function off () {
maps.forEach(function (map, index) {
map.off('move', fns[index]);
});
}
// When one map moves, we turn off the movement listeners
// on all the maps, move it, then turn the listeners on again
function sync (master, clones) {
off();
moveToMapPosition(master, clones);
on();
}
on();
}
|
javascript
|
{
"resource": ""
}
|
q44450
|
writeFile
|
train
|
function writeFile(path,content) {
return when.promise(function(resolve,reject) {
var stream = fs.createWriteStream(path);
stream.on('open',function(fd) {
stream.end(content,'utf8',function() {
fs.fsync(fd,resolve);
});
});
stream.on('error',function(err) {
reject(err);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q44451
|
train
|
function( result, message ) {
message = message || ( result ? "okay" : "failed, expected argument to be truthy, was: " +
QUnit.dump.parse( result ) );
if ( !!result ) {
this.push( true, result, true, message );
} else {
this.test.pushFailure( message, null, result );
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44452
|
handler
|
train
|
function handler(e) {
if (!vNode.context) return
// some components may have related popup item, on which we shall prevent the click outside event handler.
var elements = e.path || (e.composedPath && e.composedPath())
elements && elements.length > 0 && elements.unshift(e.target)
if (el.contains(e.target) || isPopup(vNode.context.popupItem, elements)) return
el.__vueClickOutside__.callback(e)
}
|
javascript
|
{
"resource": ""
}
|
q44453
|
wrapClass
|
train
|
function wrapClass(Controller) {
let proto = Controller.prototype;
const ret = {};
// tracing the prototype chain
while (proto !== Object.prototype) {
const keys = Object.getOwnPropertyNames(proto);
for (const key of keys) {
// getOwnPropertyNames will return constructor
// that should be ignored
if (key === 'constructor') {
continue;
}
// skip getter, setter & non-function properties
const d = Object.getOwnPropertyDescriptor(proto, key);
// prevent to override sub method
if (is.function(d.value) && !ret.hasOwnProperty(key)) {
ret[key] = methodToMiddleware(Controller, key);
ret[key][FULLPATH] = Controller.prototype.fullPath + '#' + Controller.name + '.' + key + '()';
}
}
proto = Object.getPrototypeOf(proto);
}
return ret;
function methodToMiddleware(Controller, key) {
return function classControllerMiddleware(...args) {
const controller = new Controller(this);
if (!this.app.config.controller || !this.app.config.controller.supportParams) {
args = [ this ];
}
return utils.callFn(controller[key], args, controller);
};
}
}
|
javascript
|
{
"resource": ""
}
|
q44454
|
wrapObject
|
train
|
function wrapObject(obj, path, prefix) {
const keys = Object.keys(obj);
const ret = {};
for (const key of keys) {
if (is.function(obj[key])) {
const names = utility.getParamNames(obj[key]);
if (names[0] === 'next') {
throw new Error(`controller \`${prefix || ''}${key}\` should not use next as argument from file ${path}`);
}
ret[key] = functionToMiddleware(obj[key]);
ret[key][FULLPATH] = `${path}#${prefix || ''}${key}()`;
} else if (is.object(obj[key])) {
ret[key] = wrapObject(obj[key], path, `${prefix || ''}${key}.`);
}
}
return ret;
function functionToMiddleware(func) {
const objectControllerMiddleware = async function(...args) {
if (!this.app.config.controller || !this.app.config.controller.supportParams) {
args = [ this ];
}
return await utils.callFn(func, args, this);
};
for (const key in func) {
objectControllerMiddleware[key] = func[key];
}
return objectControllerMiddleware;
}
}
|
javascript
|
{
"resource": ""
}
|
q44455
|
getGasPrice
|
train
|
function getGasPrice(toWei) {
return axios.get("https://ethgasstation.info/json/ethgasAPI.json").then(response => {
//ethgasstation returns 10x the actual average for some odd reason
let actualAverage = response.data.average / 10
winston.debug(`gas price actualAverage: ${actualAverage}`)
//We want to just add a bit more than average to be speedy
let safeAmount = actualAverage + 0.1
winston.debug(`gas price safeAmount: ${safeAmount}`)
//We want to round to the tenthousandth precision
let rounded = Math.round(safeAmount * 10000) / 10000
winston.debug(`gas price rounded: ${rounded}`)
//Lets save the gas price in wei, rather than gwei, since that is how web3 expects it.
let wei = toWei(`${rounded}`, 'gwei')
winston.debug(`gas price wei: ${wei}`)
return parseInt(wei)
})
}
|
javascript
|
{
"resource": ""
}
|
q44456
|
cssnext
|
train
|
function cssnext (tagName, css) {
// A small hack: it passes :scope as :root to PostCSS.
// This make it easy to use css variables inside tags.
css = css.replace(/:scope/g, ':root')
css = postcss([postcssCssnext]).process(css).css
css = css.replace(/:root/g, ':scope')
return css
}
|
javascript
|
{
"resource": ""
}
|
q44457
|
makeLocalizeFunction
|
train
|
function makeLocalizeFunction(localization, nested) {
return function localizeFunction(key) {
return nested ? byString(localization, key) : localization[key];
};
}
|
javascript
|
{
"resource": ""
}
|
q44458
|
byString
|
train
|
function byString(localization, nestedKey) {
// remove a leading dot and split by dot
const keys = nestedKey.replace(/^\./, '').split('.');
// loop through the keys to find the nested value
for (let i = 0, length = keys.length; i < length; ++i) {
const key = keys[i];
if (!(key in localization)) { return; }
localization = localization[key];
}
return localization;
}
|
javascript
|
{
"resource": ""
}
|
q44459
|
Delegator
|
train
|
function Delegator(proto, target) {
if (!(this instanceof Delegator)) return new Delegator(proto, target);
this.proto = proto;
this.target = target;
this.methods = [];
this.getters = [];
this.setters = [];
this.fluents = [];
}
|
javascript
|
{
"resource": ""
}
|
q44460
|
issued
|
train
|
function issued(err, val) {
if (err) { return self.error(err); }
res.cookie(self._key, val, self._opts);
return self.success(user, info);
}
|
javascript
|
{
"resource": ""
}
|
q44461
|
gotData
|
train
|
function gotData() {
var currentString = serial.readLine(); // read the incoming data
trim(currentString); // trim off trailing whitespace
if (!currentString) return; // if the incoming string is empty, do no more
console.log(currentString);
if (!isNaN(currentString)) { // make sure the string is a number (i.e. NOT Not a Number (NaN))
textXpos = currentString; // save the currentString to use for the text position in draw()
}
}
|
javascript
|
{
"resource": ""
}
|
q44462
|
setup
|
train
|
function setup() {
createCanvas(windowWidth, windowHeight);
// Instantiate our SerialPort object
serial = new p5.SerialPort();
// Get a list the ports available
// You should have a callback defined to see the results
serial.list();
// Assuming our Arduino is connected, let's open the connection to it
// Change this to the name of your arduino's serial port
serial.open("/dev/cu.usbmodem1411");
// Here are the callbacks that you can register
// When we connect to the underlying server
serial.on('connected', serverConnected);
// When we get a list of serial ports that are available
serial.on('list', gotList);
// OR
//serial.onList(gotList);
// When we some data from the serial port
serial.on('data', gotData);
// OR
//serial.onData(gotData);
// When or if we get an error
serial.on('error', gotError);
// OR
//serial.onError(gotError);
// When our serial port is opened and ready for read/write
serial.on('open', gotOpen);
// OR
//serial.onOpen(gotOpen);
// Callback to get the raw data, as it comes in for handling yourself
//serial.on('rawdata', gotRawData);
// OR
//serial.onRawData(gotRawData);
}
|
javascript
|
{
"resource": ""
}
|
q44463
|
gotData
|
train
|
function gotData() {
var currentString = serial.readLine(); // read the incoming string
trim(currentString); // remove any trailing whitespace
if (!currentString) return; // if the string is empty, do no more
console.log(currentString); // println the string
latestData = currentString; // save it for the draw method
}
|
javascript
|
{
"resource": ""
}
|
q44464
|
train
|
function (f) {
var filename = path.basename(f);
var extension = path.extname(f),
allowedExtensions = lessWatchCompilerUtilsModule.config.allowedExtensions || defaultAllowedExtensions;
if (filename.substr(0, 1) == '_' ||
filename.substr(0, 1) == '.' ||
filename == '' ||
allowedExtensions.indexOf(extension) == -1
)
return true;
else {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44465
|
train
|
function (list) {
var items = [];
var i = 0;
var listLength = list.length;
for (; i < listLength; i++) {
items.push(list[i]);
}
return items;
}
|
javascript
|
{
"resource": ""
}
|
|
q44466
|
train
|
function (stylesheet) {
var sheetMedia = stylesheet.media && stylesheet.media.mediaText;
var sheetHost;
// if this sheet is cross-origin and option is set skip it
if (objectFit.disableCrossDomain == 'true') {
sheetHost = getCSSHost(stylesheet.href);
if ((sheetHost !== window.location.host)) {
return [];
}
}
// if this sheet is disabled skip it
if (stylesheet.disabled) {
return [];
}
if (!window.matchMedia) {
if (sheetMedia && sheetMedia.length) {
return [];
}
}
// if this sheet's media is specified and doesn't match the viewport then skip it
else if (sheetMedia && sheetMedia.length && ! window.matchMedia(sheetMedia).matches) {
return [];
}
// get the style rules of this sheet
return toArray(stylesheet.cssRules);
}
|
javascript
|
{
"resource": ""
}
|
|
q44467
|
train
|
function (selector) {
var score = [0, 0, 0];
var parts = selector.split(' ');
var part;
var match;
//TODO: clean the ':not' part since the last ELEMENT_RE will pick it up
while (part = parts.shift(), typeof part === 'string') {
// find all pseudo-elements
match = _find(part, PSEUDO_ELEMENTS_RE);
score[2] = match;
// and remove them
match && (part = part.replace(PSEUDO_ELEMENTS_RE, ''));
// find all pseudo-classes
match = _find(part, PSEUDO_CLASSES_RE);
score[1] = match;
// and remove them
match && (part = part.replace(PSEUDO_CLASSES_RE, ''));
// find all attributes
match = _find(part, ATTR_RE);
score[1] += match;
// and remove them
match && (part = part.replace(ATTR_RE, ''));
// find all IDs
match = _find(part, ID_RE);
score[0] = match;
// and remove them
match && (part = part.replace(ID_RE, ''));
// find all classes
match = _find(part, CLASS_RE);
score[1] += match;
// and remove them
match && (part = part.replace(CLASS_RE, ''));
// find all elements
score[2] += _find(part, ELEMENT_RE);
}
return parseInt(score.join(''), 10);
}
|
javascript
|
{
"resource": ""
}
|
|
q44468
|
train
|
function (a, b) {
return getSpecificityScore(element, b.selectorText) - getSpecificityScore(element, a.selectorText);
}
|
javascript
|
{
"resource": ""
}
|
|
q44469
|
tms2zxy
|
train
|
function tms2zxy(zxys) {
return zxys.split(',').map(function(tms) {
var zxy = tms.split('/').map(function(v) { return parseInt(v, 10); });
zxy[2] = (1 << zxy[0]) - 1 - zxy[2];
return zxy.join('/');
});
}
|
javascript
|
{
"resource": ""
}
|
q44470
|
train
|
function(properties) {
if (this instanceof User) {
for (var property in (properties || {})) {
if (Array.prototype.hasOwnProperty.call(properties, property)) {
this[property] = properties[property];
}
}
}
else {
return(new User(properties));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44471
|
train
|
function(url, baseDN, username, password, defaults) {
if (this instanceof ActiveDirectory) {
this.opts = {};
if (typeof(url) === 'string') {
this.opts.url = url;
this.baseDN = baseDN;
this.opts.bindDN = username;
this.opts.bindCredentials = password;
if (typeof((defaults || {}).entryParser) === 'function') {
this.opts.entryParser = defaults.entryParser;
}
}
else {
this.opts = _.defaults({}, url);
this.baseDN = this.opts.baseDN;
if (! this.opts.bindDN) this.opts.bindDN = this.opts.username;
if (! this.opts.bindCredentials) this.opts.bindCredentials = this.opts.password;
if (this.opts.logging) {
log = bunyan.createLogger(_.defaults({}, this.opts.logging));
delete(this.opts.logging);
}
}
defaultAttributes = _.extend({}, originalDefaultAttributes, (this.opts || {}).attributes || {}, (defaults || {}).attributes || {});
defaultReferrals = _.extend({}, originalDefaultReferrals, (this.opts || {}).referrals || {}, (defaults || {}).referrals || {});
log.info('Using username/password (%s/%s) to bind to ActiveDirectory (%s).', this.opts.bindDN,
isPasswordLoggingEnabled ? this.opts.bindCredentials : '********', this.opts.url);
log.info('Referrals are %s', defaultReferrals.enabled ? 'enabled. Exclusions: '+JSON.stringify(defaultReferrals.exclude): 'disabled');
log.info('Default user attributes: %j', defaultAttributes.user || []);
log.info('Default group attributes: %j', defaultAttributes.group || []);
// Enable connection pooling
// TODO: To be disabled / removed in future release of ldapjs > 0.7.1
if (typeof(this.opts.maxConnections) === 'undefined') {
this.opts.maxConnections = 20;
}
events.EventEmitter.call(this);
}
else {
return(new ActiveDirectory(url, baseDN, username, password, defaults));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44472
|
truncateLogOutput
|
train
|
function truncateLogOutput(output, maxLength) {
if (typeof(maxLength) === 'undefined') maxLength = maxOutputLength;
if (! output) return(output);
if (typeof(output) !== 'string') output = output.toString();
var length = output.length;
if ((! length) || (length < (maxLength + 3))) return(output);
var prefix = Math.ceil((maxLength - 3)/2);
var suffix = Math.floor((maxLength - 3)/2);
return(output.slice(0, prefix)+ '...' +
output.slice(length-suffix));
}
|
javascript
|
{
"resource": ""
}
|
q44473
|
isDistinguishedName
|
train
|
function isDistinguishedName(value) {
log.trace('isDistinguishedName(%s)', value);
if ((! value) || (value.length === 0)) return(false);
re.isDistinguishedName.lastIndex = 0; // Reset the regular expression
return(re.isDistinguishedName.test(value));
}
|
javascript
|
{
"resource": ""
}
|
q44474
|
getUserQueryFilter
|
train
|
function getUserQueryFilter(username) {
log.trace('getUserQueryFilter(%s)', username);
var self = this;
if (! username) return('(objectCategory=User)');
if (isDistinguishedName.call(self, username)) {
return('(&(objectCategory=User)(distinguishedName='+parseDistinguishedName(username)+'))');
}
return('(&(objectCategory=User)(|(sAMAccountName='+username+')(userPrincipalName='+username+')))');
}
|
javascript
|
{
"resource": ""
}
|
q44475
|
getGroupQueryFilter
|
train
|
function getGroupQueryFilter(groupName) {
log.trace('getGroupQueryFilter(%s)', groupName);
var self = this;
if (! groupName) return('(objectCategory=Group)');
if (isDistinguishedName.call(self, groupName)) {
return('(&(objectCategory=Group)(distinguishedName='+parseDistinguishedName(groupName)+'))');
}
return('(&(objectCategory=Group)(cn='+groupName+'))');
}
|
javascript
|
{
"resource": ""
}
|
q44476
|
isGroupResult
|
train
|
function isGroupResult(item) {
log.trace('isGroupResult(%j)', item);
if (! item) return(false);
if (item.groupType) return(true);
if (item.objectCategory) {
re.isGroupResult.lastIndex = 0; // Reset the regular expression
return(re.isGroupResult.test(item.objectCategory));
}
if ((item.objectClass) && (item.objectClass.length > 0)) {
return(_.any(item.objectClass, function(c) { return(c.toLowerCase() === 'group'); }));
}
return(false);
}
|
javascript
|
{
"resource": ""
}
|
q44477
|
isUserResult
|
train
|
function isUserResult(item) {
log.trace('isUserResult(%j)', item);
if (! item) return(false);
if (item.userPrincipalName) return(true);
if (item.objectCategory) {
re.isUserResult.lastIndex = 0; // Reset the regular expression
return(re.isUserResult.test(item.objectCategory));
}
if ((item.objectClass) && (item.objectClass.length > 0)) {
return(_.any(item.objectClass, function(c) { return(c.toLowerCase() === 'user'); }));
}
return(false);
}
|
javascript
|
{
"resource": ""
}
|
q44478
|
createClient
|
train
|
function createClient(url, opts) {
// Attempt to get Url from this instance.
url = url || this.url || (this.opts || {}).url || (opts || {}).url;
if (! url) {
throw 'No url specified for ActiveDirectory client.';
}
log.trace('createClient(%s)', url);
var opts = getLdapClientOpts(_.defaults({}, { url: url }, opts, this.opts));
log.debug('Creating ldapjs client for %s. Opts: %j', opts.url, _.omit(opts, 'url', 'bindDN', 'bindCredentials'));
var client = ldap.createClient(opts);
return(client);
}
|
javascript
|
{
"resource": ""
}
|
q44479
|
isAllowedReferral
|
train
|
function isAllowedReferral(referral) {
log.trace('isAllowedReferral(%j)', referral);
if (! defaultReferrals.enabled) return(false);
if (! referral) return(false);
return(! _.any(defaultReferrals.exclude, function(exclusion) {
var re = new RegExp(exclusion, "i");
return(re.test(referral));
}));
}
|
javascript
|
{
"resource": ""
}
|
q44480
|
removeReferral
|
train
|
function removeReferral(client) {
if (! client) return;
client.unbind();
var indexOf = pendingReferrals.indexOf(client);
if (indexOf >= 0) {
pendingReferrals.splice(indexOf, 1);
}
}
|
javascript
|
{
"resource": ""
}
|
q44481
|
onSearchEntry
|
train
|
function onSearchEntry(entry) {
log.trace('onSearchEntry(%j)', entry);
var result = entry.object;
delete result.controls; // Remove the controls array returned as part of the SearchEntry
// Some attributes can have range attributes (paging). Execute the query
// again to get additional items.
pendingRangeRetrievals++;
parseRangeAttributes.call(self, result, opts, function(err, item) {
pendingRangeRetrievals--;
if (err) item = entry.object;
entryParser(item, entry.raw, function(item) {
if (item) results.push(item);
if ((! pendingRangeRetrievals) && (isDone)) {
onSearchEnd();
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q44482
|
onReferralError
|
train
|
function onReferralError(err) {
log.error(err, '[%s] An error occurred chasing the LDAP referral on %s (%j)',
(err || {}).errno, referralBaseDn, opts);
removeReferral(referralClient);
}
|
javascript
|
{
"resource": ""
}
|
q44483
|
onSearchEnd
|
train
|
function onSearchEnd(result) {
if ((! pendingRangeRetrievals) && (pendingReferrals.length <= 0)) {
client.unbind();
log.info('Active directory search (%s) for "%s" returned %d entries.',
baseDN, truncateLogOutput(opts.filter),
(results || []).length);
if (callback) callback(null, results);
}
}
|
javascript
|
{
"resource": ""
}
|
q44484
|
parseRangeAttributes
|
train
|
function parseRangeAttributes(result, opts, callback) {
log.trace('parseRangeAttributes(%j,%j)', result, opts);
var self = this;
// Check to see if any of the result attributes have range= attributes.
// If not, return immediately.
if (! RangeRetrievalSpecifierAttribute.prototype.hasRangeAttributes(result)) {
callback(null, result);
return;
}
// Parse the range attributes that were provided. If the range attributes are null
// or indicate that the range is complete, return the result.
var rangeAttributes = RangeRetrievalSpecifierAttribute.prototype.getRangeAttributes(result);
if ((! rangeAttributes) || (rangeAttributes.length <= 0)) {
callback(null, result);
return;
}
// Parse each of the range attributes. Merge the range attributes into
// the properly named property.
var queryAttributes = [];
_.each(rangeAttributes, function(rangeAttribute, index) {
// Merge existing range into the properly named property.
if (! result[rangeAttribute.attributeName]) result[rangeAttribute.attributeName] = [];
Array.prototype.push.apply(result[rangeAttribute.attributeName], result[rangeAttribute.toString()]);
delete(result[rangeAttribute.toString()]);
// Build our ldap query attributes with the proper attribute;range= tags to
// get the next sequence of data.
var queryAttribute = rangeAttribute.next();
if ((queryAttribute) && (! queryAttribute.isComplete())) {
queryAttributes.push(queryAttribute.toString());
}
});
// If we're at the end of the range (i.e. all items retrieved), return the result.
if (queryAttributes.length <= 0) {
log.debug('All attribute ranges %j retrieved for %s', rangeAttributes, result.dn);
callback(null, result);
return;
}
log.debug('Attribute range retrieval specifiers %j found for "%s". Next range: %j',
rangeAttributes, result.dn, queryAttributes);
// Execute the query again with the query attributes updated.
opts = _.defaults({ filter: '(distinguishedName='+parseDistinguishedName(result.dn)+')',
attributes: queryAttributes }, opts);
search.call(self, opts, function onSearch(err, results) {
if (err) {
callback(err);
return;
}
// Should be only one result
var item = (results || [])[0];
for(var property in item) {
if (item.hasOwnProperty(property)) {
if (! result[property]) result[property] = [];
if (_.isArray(result[property])) {
Array.prototype.push.apply(result[property], item[property]);
}
}
}
callback(null, result);
});
}
|
javascript
|
{
"resource": ""
}
|
q44485
|
pickAttributes
|
train
|
function pickAttributes(result, attributes) {
if (shouldIncludeAllAttributes(attributes)) {
attributes = function() {
return(true);
};
}
return(_.pick(result, attributes));
}
|
javascript
|
{
"resource": ""
}
|
q44486
|
chunk
|
train
|
function chunk(arr, chunkSize) {
var result = [];
for (var index = 0, length = arr.length; index < length; index += chunkSize) {
result.push(arr.slice(index,index + chunkSize));
}
return(result);
}
|
javascript
|
{
"resource": ""
}
|
q44487
|
includeGroupMembershipFor
|
train
|
function includeGroupMembershipFor(opts, name) {
if (typeof(opts) === 'string') {
name = opts;
opts = this.opts;
}
var lowerCaseName = (name || '').toLowerCase();
return(_.any(((opts || this.opts || {}).includeMembership || []), function(i) {
i = i.toLowerCase();
return((i === 'all') || (i === lowerCaseName));
}));
}
|
javascript
|
{
"resource": ""
}
|
q44488
|
onClientError
|
train
|
function onClientError(err) {
// Ignore ECONNRESET errors
if ((err || {}).errno !== 'ECONNRESET') {
log.error('An unhandled error occured when searching for the root DSE at "%s". Error: %j', url, err);
if (hasEvents.call(self, 'error')) self.emit('error', err)
}
}
|
javascript
|
{
"resource": ""
}
|
q44489
|
parseRangeRetrievalSpecifierAttribute
|
train
|
function parseRangeRetrievalSpecifierAttribute(attribute) {
var re = new RegExp(pattern, 'i');
var match = re.exec(attribute);
return({
attributeName: match[1],
low: parseInt(match[2]),
high: parseInt(match[3]) || null
});
}
|
javascript
|
{
"resource": ""
}
|
q44490
|
train
|
function(attribute) {
if (this instanceof RangeRetrievalSpecifierAttribute) {
if (! attribute) throw new Error('No attribute provided to create a range retrieval specifier.');
if (typeof(attribute) === 'string') {
attribute = parseRangeRetrievalSpecifierAttribute(attribute);
}
for(var property in attribute) {
if (Array.prototype.hasOwnProperty.call(attribute, property)) {
this[property] = attribute[property];
}
}
}
else {
return(new RangeRetrievalSpecifierAttribute(attribute));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q44491
|
train
|
function(items, config) {
config = config || {};
config.searchableFields = config.searchableFields || [];
this.items = items;
// creating index
this.idx = lunr(function () {
// currently schema hardcoded
this.field('name', { boost: 10 });
var self = this;
_.forEach(config.searchableFields, function(field) {
self.field(field);
});
this.ref('id');
})
//var items2 = _.clone(items)
var i = 1;
_.map(items, (doc) => {
if (!doc.id) {
doc.id = i;
++i;
}
this.idx.add(doc)
})
this.store = _.mapKeys(items, (doc) => {
return doc.id;
})
}
|
javascript
|
{
"resource": ""
}
|
|
q44492
|
train
|
function(input) {
input = input || {};
/**
* merge configuration aggregation with user input
*/
input.aggregations = helpers.mergeAggregations(configuration.aggregations, input);
return service.search(items, input, configuration, fulltext);
}
|
javascript
|
{
"resource": ""
}
|
|
q44493
|
serve
|
train
|
function serve (options = { contentBase: '' }) {
if (Array.isArray(options) || typeof options === 'string') {
options = { contentBase: options }
}
options.contentBase = Array.isArray(options.contentBase) ? options.contentBase : [options.contentBase]
options.host = options.host || 'localhost'
options.port = options.port || 10001
options.headers = options.headers || {}
options.https = options.https || false
options.openPage = options.openPage || ''
mime.default_type = 'text/plain'
const requestListener = (request, response) => {
// Remove querystring
const urlPath = decodeURI(request.url.split('?')[0])
Object.keys(options.headers).forEach((key) => {
response.setHeader(key, options.headers[key])
})
readFileFromContentBase(options.contentBase, urlPath, function (error, content, filePath) {
if (!error) {
return found(response, filePath, content)
}
if (error.code !== 'ENOENT') {
response.writeHead(500)
response.end('500 Internal Server Error' +
'\n\n' + filePath +
'\n\n' + Object.values(error).join('\n') +
'\n\n(rollup-plugin-serve)', 'utf-8')
return
}
if (options.historyApiFallback) {
var fallbackPath = typeof options.historyApiFallback === 'string' ? options.historyApiFallback : '/index.html'
readFileFromContentBase(options.contentBase, fallbackPath, function (error, content, filePath) {
if (error) {
notFound(response, filePath)
} else {
found(response, filePath, content)
}
})
} else {
notFound(response, filePath)
}
})
}
// release previous server instance if rollup is reloading configuration in watch mode
if (server) {
server.close()
}
// If HTTPS options are available, create an HTTPS server
if (options.https) {
server = createHttpsServer(options.https, requestListener).listen(options.port, options.host)
} else {
server = createServer(requestListener).listen(options.port, options.host)
}
closeServerOnTermination(server)
var running = options.verbose === false
return {
name: 'serve',
generateBundle () {
if (!running) {
running = true
// Log which url to visit
const url = (options.https ? 'https' : 'http') + '://' + options.host + ':' + options.port
options.contentBase.forEach(base => {
console.log(green(url) + ' -> ' + resolve(base))
})
// Open browser
if (options.open) {
opener(url + options.openPage)
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q44494
|
Hotkey
|
train
|
function Hotkey (combo, description, callback, action, allowIn, persistent) {
// TODO: Check that the values are sane because we could
// be trying to instantiate a new Hotkey with outside dev's
// supplied values
this.combo = combo instanceof Array ? combo : [combo];
this.description = description;
this.callback = callback;
this.action = action;
this.allowIn = allowIn;
this.persistent = persistent;
this._formated = null;
}
|
javascript
|
{
"resource": ""
}
|
q44495
|
_add
|
train
|
function _add (combo, description, callback, action, allowIn, persistent) {
// used to save original callback for "allowIn" wrapping:
var _callback;
// these elements are prevented by the default Mousetrap.stopCallback():
var preventIn = ['INPUT', 'SELECT', 'TEXTAREA'];
// Determine if object format was given:
var objType = Object.prototype.toString.call(combo);
if (objType === '[object Object]') {
description = combo.description;
callback = combo.callback;
action = combo.action;
persistent = combo.persistent;
allowIn = combo.allowIn;
combo = combo.combo;
}
// no duplicates please
_del(combo);
// description is optional:
if (description instanceof Function) {
action = callback;
callback = description;
description = '$$undefined$$';
} else if (angular.isUndefined(description)) {
description = '$$undefined$$';
}
// any items added through the public API are for controllers
// that persist through navigation, and thus undefined should mean
// true in this case.
if (persistent === undefined) {
persistent = true;
}
// if callback is defined, then wrap it in a function
// that checks if the event originated from a form element.
// the function blocks the callback from executing unless the element is specified
// in allowIn (emulates Mousetrap.stopCallback() on a per-key level)
if (typeof callback === 'function') {
// save the original callback
_callback = callback;
// make sure allowIn is an array
if (!(allowIn instanceof Array)) {
allowIn = [];
}
// remove anything from preventIn that's present in allowIn
var index;
for (var i=0; i < allowIn.length; i++) {
allowIn[i] = allowIn[i].toUpperCase();
index = preventIn.indexOf(allowIn[i]);
if (index !== -1) {
preventIn.splice(index, 1);
}
}
// create the new wrapper callback
callback = function(event) {
var shouldExecute = true;
// if the callback is executed directly `hotkey.get('w').callback()`
// there will be no event, so just execute the callback.
if (event) {
var target = event.target || event.srcElement; // srcElement is IE only
var nodeName = target.nodeName.toUpperCase();
// check if the input has a mousetrap class, and skip checking preventIn if so
if ((' ' + target.className + ' ').indexOf(' mousetrap ') > -1) {
shouldExecute = true;
} else {
// don't execute callback if the event was fired from inside an element listed in preventIn
for (var i=0; i<preventIn.length; i++) {
if (preventIn[i] === nodeName) {
shouldExecute = false;
break;
}
}
}
}
if (shouldExecute) {
wrapApply(_callback.apply(this, arguments));
}
};
}
if (typeof(action) === 'string') {
Mousetrap.bind(combo, wrapApply(callback), action);
} else {
Mousetrap.bind(combo, wrapApply(callback));
}
var hotkey = new Hotkey(combo, description, callback, action, allowIn, persistent);
scope.hotkeys.push(hotkey);
return hotkey;
}
|
javascript
|
{
"resource": ""
}
|
q44496
|
_del
|
train
|
function _del (hotkey) {
var combo = (hotkey instanceof Hotkey) ? hotkey.combo : hotkey;
Mousetrap.unbind(combo);
if (angular.isArray(combo)) {
var retStatus = true;
var i = combo.length;
while (i--) {
retStatus = _del(combo[i]) && retStatus;
}
return retStatus;
} else {
var index = scope.hotkeys.indexOf(_get(combo));
if (index > -1) {
// if the combo has other combos bound, don't unbind the whole thing, just the one combo:
if (scope.hotkeys[index].combo.length > 1) {
scope.hotkeys[index].combo.splice(scope.hotkeys[index].combo.indexOf(combo), 1);
} else {
// remove hotkey from bound scopes
angular.forEach(boundScopes, function (boundScope) {
var scopeIndex = boundScope.indexOf(scope.hotkeys[index]);
if (scopeIndex !== -1) {
boundScope.splice(scopeIndex, 1);
}
});
scope.hotkeys.splice(index, 1);
}
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q44497
|
_get
|
train
|
function _get (combo) {
if (!combo) {
return scope.hotkeys;
}
var hotkey;
for (var i = 0; i < scope.hotkeys.length; i++) {
hotkey = scope.hotkeys[i];
if (hotkey.combo.indexOf(combo) > -1) {
return hotkey;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q44498
|
bindTo
|
train
|
function bindTo (scope) {
// Only initialize once to allow multiple calls for same scope.
if (!(scope.$id in boundScopes)) {
// Add the scope to the list of bound scopes
boundScopes[scope.$id] = [];
scope.$on('$destroy', function () {
var i = boundScopes[scope.$id].length;
while (i--) {
_del(boundScopes[scope.$id].pop());
}
});
}
// return an object with an add function so we can keep track of the
// hotkeys and their scope that we added via this chaining method
return {
add: function (args) {
var hotkey;
if (arguments.length > 1) {
hotkey = _add.apply(this, arguments);
} else {
hotkey = _add(args);
}
boundScopes[scope.$id].push(hotkey);
return this;
}
};
}
|
javascript
|
{
"resource": ""
}
|
q44499
|
create
|
train
|
function create(method, options = {}) {
options = Object.assign(exports.defaults, options);
exports.results.set(method, new lru_cache_1.default(options));
return exports.results.get(method);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.