_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q51000
|
acceptable
|
train
|
function acceptable(value) {
return vowels.test(value.charAt(0))
? value.length > 1
: value.length > 2 && vowels.test(value)
}
|
javascript
|
{
"resource": ""
}
|
q51001
|
train
|
function (value) {
if (! _defined(value)) return defaults;
angular.forEach(value, function (val, key) {
if (defaults.hasOwnProperty(key)) defaults[key] = val;
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51002
|
train
|
function (key, value, def) {
if (! this.has(key)) {
this.put(key, value, def);
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q51003
|
train
|
function (key, def) {
if (angular.isArray(key)) {
var items = {};
angular.forEach(key, function (k) {
if (this.has(k)) items[k] = this._getItem(k);
}, this);
return items;
}
if (! this.has(key)) return arguments.length === 2 ? def : void 0;
return this._getItem(key);
}
|
javascript
|
{
"resource": ""
}
|
|
q51004
|
transformJSX
|
train
|
function transformJSX(fileStream, fileName, opts, cb){
// Allow omitting filename
if (typeof fileName === "object"){
cb = opts;
opts = fileName;
fileName = fileStream;
}
if (!babel && (opts['--babel'] || opts['--babel-experimental'])) {
throw new Error("Optional babel parser not installed. Please `npm install [-g] babel-core`.");
}
// Allow passing strings into this method e.g. when using it as a lib
if (typeof fileStream === "string"){
fileStream = fs.createReadStream(fileStream, {encoding: "utf8"});
}
return utils.drainStream(fileStream)
.then(function processFile(source) {
var hasExtension = /\.jsx$/.exec(fileName) || fileName === "stdin";
// console.error('has extension', hasExtension);
// console.log(fileName);
if ((opts['--jsx-only'] && hasExtension) || !opts['--jsx-only']) {
try {
return transformSource(source, opts);
} catch(e) {
// Seems that esprima has some problems with some js syntax.
if (opts['--transform-errors'] === 'always' ||
(opts['--transform-errors'] !== 'never' && hasExtension)) {
console.error("Error while transforming file " + fileName + "\n", e.stack);
throw utils.transformError(fileName, e, opts);
}
}
}
return source;
})
.nodeify(cb);
}
|
javascript
|
{
"resource": ""
}
|
q51005
|
showHelp
|
train
|
function showHelp(){
var jshint_proc = fork(require.resolve('jshint/bin/jshint'), ['-h'], {silent: true});
var ts = through(function write(chunk){
this.queue(chunk.toString().replace(/(jshint)\b/g, 'jsxhint'));
}, function end() {
// This feels like a hack. There might be a better way to do this.
this.queue('\nThe above options are native to JSHint, which JSXHint extends.\n');
this.queue('\x1b[1m'); // bold
this.queue('\nJSXHint Options:\n');
this.queue('\x1b[0m');
this.queue(' --jsx-only Only transform files with the .jsx extension.\n' +
' Will run somewhat faster.\n');
this.queue(' --babel Use babel (6to5) instead of react esprima.\n' +
' Useful if you are using es6-module, etc. You must \n' +
' install the module `babel` manually with npm.\n');
this.queue(' --babel-experimental Use babel with experimental support for ES7.\n' +
' Useful if you are using es7-async, etc.\n');
this.queue(' --harmony Use react esprima with ES6 transformation support.\n' +
' Useful if you are using both es6-class and react.\n');
this.queue(' --es6module Pass the --es6module flag to react tools.\n');
this.queue(' --non-strict-es6module Pass this flag to react tools.\n');
this.queue(' --transform-errors STRING Whether to fail on transform errors.\n' +
' Valid: always, jsx, never (default: jsx)');
});
jshint_proc.stderr.pipe(ts).pipe(process.stderr);
}
|
javascript
|
{
"resource": ""
}
|
q51006
|
showVersion
|
train
|
function showVersion(){
var jshint_proc = fork(__dirname + '/node_modules/jshint/bin/jshint', ['-v'], {silent: true});
var ts = through(function write(chunk){
this.queue("JSXHint v" + require('./package.json').version + " (" +
chunk.toString().replace("\n", "") + ")\n");
});
jshint_proc.stderr.pipe(ts).pipe(process.stderr);
}
|
javascript
|
{
"resource": ""
}
|
q51007
|
runGlob
|
train
|
function runGlob(args, opts, cb) {
var dotIdx = args.indexOf('.');
if (dotIdx !== -1) {
args.splice(dotIdx, 1);
}
glob(args, opts, function(err, globbed) {
if (Array.isArray(globbed) && dotIdx !== -1) globbed.push('.');
cb(err, globbed);
});
}
|
javascript
|
{
"resource": ""
}
|
q51008
|
run
|
train
|
function run(opts, cb){
opts.extensions = opts.extensions ? opts.extensions + ',.jsx' : '.jsx';
// glob-all fixes windows glob issues and provides array support
// i.e. jsxhint ['jsx/**/*','!scripts/**/*','scripts/outlier.jsx']
runGlob(opts.args, {nodir: true}, function(err, globbed) {
if (err) return cb(err);
// Reassign the globbed files back to opts.args, so it looks like we just
// fed jshint a big list of files.
opts.args = globbed;
var files = jshintcli.gather(opts);
if (opts.useStdin) {
jsxhint.transformStream(process.stdin, jsxhintOptions, opts, cb);
} else {
jsxhint.transformFiles(files, jsxhintOptions, opts, cb);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51009
|
interceptReporter
|
train
|
function interceptReporter(reporter, filesMap){
if(!reporter) reporter = require('jshint/src/reporters/default').reporter;
return function(results, data, opts){
if (filesMap) {
results.forEach(function(result){
result.file = filesMap[result.file];
});
}
return reporter(results, data, opts);
};
}
|
javascript
|
{
"resource": ""
}
|
q51010
|
train
|
function (dimensions) {
var _this = this;
return new Promise(function (resolve, reject) {
_this._paneDimensions = dimensions;
_this.paneDimensions.next(dimensions);
resolve();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51011
|
train
|
function (positions) {
var _this = this;
this._points = positions;
positions.forEach(function (position) {
_this.positionChange(position);
});
this.repositionEvent.next(positions);
}
|
javascript
|
{
"resource": ""
}
|
|
q51012
|
train
|
function (positionChangeData) {
var _this = this;
// update positions according to current position change
this.updatePosition(positionChangeData);
// for each direction:
// 1. filter the _points that have a role as the direction's limit
// 2. for top and left find max x | y values, and min for right and bottom
this.limitDirections.forEach(function (direction) {
/** @type {?} */
var relevantPoints = _this._points.filter(function (point) {
return point.roles.includes(direction);
})
.map(function (point) {
return point[_this.getDirectionAxis(direction)];
});
/** @type {?} */
var limit;
if (direction === 'top' || direction === 'left') {
limit = Math.max.apply(Math, __spread(relevantPoints));
}
if (direction === 'right' || direction === 'bottom') {
limit = Math.min.apply(Math, __spread(relevantPoints));
}
_this._limits[direction] = limit;
});
this.limits.next(this._limits);
this.positions.next(Array.from(this._points));
}
|
javascript
|
{
"resource": ""
}
|
|
q51013
|
train
|
function (positionChange) {
var _this = this;
// finds the current position of the point by it's roles, than splices it for the new position or pushes it if it's not yet in the array
/** @type {?} */
var index = this._points.findIndex(function (point) {
return _this.compareArray(positionChange.roles, point.roles);
});
if (index === -1) {
this._points.push(positionChange);
}
else {
this._points.splice(index, 1, positionChange);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51014
|
train
|
function (positionChange) {
var _this = this;
/** @type {?} */
var pointLimits = this.limitDirections.filter(function (direction) {
return !positionChange.roles.includes(direction);
});
/** @type {?} */
var limitException = {
exceeds: false,
resetCoefficients: {
x: 0,
y: 0
},
resetCoordinates: {
x: positionChange.x,
y: positionChange.y
}
};
// limit directions are the opposite sides of the point's roles
pointLimits.forEach(function (direction) {
/** @type {?} */
var directionAxis = _this.getDirectionAxis(direction);
if (direction === 'top' || direction === 'left') {
if (positionChange[directionAxis] < _this._limits[direction]) {
limitException.resetCoefficients[directionAxis] = 1;
limitException.resetCoordinates[directionAxis] = _this._limits[direction];
}
}
else if (direction === 'right' || direction === 'bottom') {
if (positionChange[directionAxis] > _this._limits[direction]) {
limitException.resetCoefficients[directionAxis] = -1;
limitException.resetCoordinates[directionAxis] = _this._limits[direction];
}
}
});
if (limitException.resetCoefficients.x !== 0 || limitException.resetCoefficients.y !== 0) {
limitException.exceeds = true;
}
return limitException;
}
|
javascript
|
{
"resource": ""
}
|
|
q51015
|
train
|
function (resizeRatios, initialPreviewDimensions, initialPositions) {
var _this = this;
// convert positions to ratio between position to initial pane dimension
initialPositions = initialPositions.map(function (point) {
return new PositionChangeData({
x: point.x / initialPreviewDimensions.width,
y: point.y / initialPreviewDimensions.height,
}, point.roles);
});
this.repositionPoints(initialPositions.map(function (point) {
return _this.rotateCornerClockwise(point);
}));
}
|
javascript
|
{
"resource": ""
}
|
|
q51016
|
train
|
function (corner) {
var _this = this;
/** @type {?} */
var rotated = {
x: this._paneDimensions.width * (1 - corner.y),
y: this._paneDimensions.height * corner.x,
roles: []
};
// rotates corner according to order
/** @type {?} */
var order = [
['bottom', 'left'],
['top', 'left'],
['top', 'right'],
['bottom', 'right'],
['bottom', 'left']
];
rotated.roles = order[order.findIndex(function (roles) {
return _this.compareArray(roles, corner.roles);
}) + 1];
return rotated;
}
|
javascript
|
{
"resource": ""
}
|
|
q51017
|
train
|
function (array1, array2) {
return array1.every(function (element) {
return array2.includes(element);
}) && array1.length === array2.length;
}
|
javascript
|
{
"resource": ""
}
|
|
q51018
|
train
|
function (position) {
/** @type {?} */
var positionChangeData = new PositionChangeData(position, this.limitRoles);
/** @type {?} */
var limitException = this.limitsService.exceedsLimit(positionChangeData);
if (limitException.exceeds) {
// if exceeds limits, reposition
this.resetPosition = limitException.resetCoordinates;
}
else {
this.limitsService.positionChange(positionChangeData);
this._currentPosition = position;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51019
|
train
|
function (limitException) {
/** @type {?} */
var newPosition = {
x: 0,
y: 0
};
Object.keys(this.startPosition).forEach(function (axis) {
newPosition[axis] = limitException.resetCoordinates[axis] + limitException.resetCoefficients[axis];
});
this.position = newPosition;
this.limitsService.positionChange(new PositionChangeData(this.position, this.limitRoles));
}
|
javascript
|
{
"resource": ""
}
|
|
q51020
|
train
|
function (position) {
/** @type {?} */
var positionChangeData = new PositionChangeData(position, this.limitRoles);
/** @type {?} */
var limitException = this.limitsService.exceedsLimit(positionChangeData);
if (limitException.exceeds) {
this.resetPosition = limitException.resetCoordinates;
if (limitException.exceeds) {
this.adjustPosition(limitException);
positionChangeData = new PositionChangeData(this.position, this.limitRoles);
this.limitsService.updatePosition(positionChangeData);
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51021
|
train
|
function (dimensions) {
return {
x: this.limitRoles.includes('left') ? 0 : dimensions.width - this.width / 2,
y: this.limitRoles.includes('top') ? 0 : dimensions.height - this.height / 2
};
}
|
javascript
|
{
"resource": ""
}
|
|
q51022
|
train
|
function (position) {
if (this._paneDimensions.width === 0 || this._paneDimensions.height === 0) {
return position;
}
else {
if (position.x > this._paneDimensions.width) {
position.x = this._paneDimensions.width;
}
if (position.x < 0) {
position.x = 1;
}
if (position.y > this._paneDimensions.height) {
position.y = this._paneDimensions.height;
}
if (position.y < 0) {
position.y = 1;
}
}
return position;
}
|
javascript
|
{
"resource": ""
}
|
|
q51023
|
train
|
function () {
/** @type {?} */
var canvas = this.canvas.nativeElement;
/** @type {?} */
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, this.dimensions.width, this.dimensions.height);
}
|
javascript
|
{
"resource": ""
}
|
|
q51024
|
train
|
function () {
var _this = this;
/** @type {?} */
var _points = Array.from(this._points);
/** @type {?} */
var sortedPoints = [];
/** @type {?} */
var sortOrder = {
vertical: ['top', 'top', 'bottom', 'bottom'],
horizontal: ['left', 'right', 'right', 'left']
};
var _loop_1 = function (i) {
/** @type {?} */
var roles = Array.from([sortOrder.vertical[i], sortOrder.horizontal[i]]);
sortedPoints.push(_points.filter(function (point) {
return _this.limitsService.compareArray(point.roles, roles);
})[0]);
};
for (var i = 0; i < 4; i++) {
_loop_1(i);
}
this._sortedPoints = sortedPoints;
}
|
javascript
|
{
"resource": ""
}
|
|
q51025
|
train
|
function () {
var _this = this;
/** @type {?} */
var canvas = this.canvas.nativeElement;
/** @type {?} */
var ctx = canvas.getContext('2d');
ctx.lineWidth = this.weight;
ctx.strokeStyle = this.color;
ctx.beginPath();
this._sortedPoints.forEach(function (point, index) {
if (index === 0) {
ctx.moveTo(point.x, point.y);
}
if (index !== _this._sortedPoints.length - 1) {
/** @type {?} */
var nextPoint = _this._sortedPoints[index + 1];
ctx.lineTo(nextPoint.x, nextPoint.y);
}
else {
ctx.closePath();
}
});
ctx.stroke();
}
|
javascript
|
{
"resource": ""
}
|
|
q51026
|
train
|
function () {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.applyFilter(false)];
case 1:
_a.sent();
if (this.options.maxImageDimensions) {
this.resize(this.editedImage)
.then(function (resizeResult) {
resizeResult.toBlob(function (blob) {
_this.editResult.emit(blob);
_this.processing.emit(false);
}, _this.originalImage.type);
});
}
else {
this.editedImage.toBlob(function (blob) {
_this.editResult.emit(blob);
_this.processing.emit(false);
}, this.originalImage.type);
}
return [2 /*return*/];
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51027
|
train
|
function () {
var _this = this;
/** @type {?} */
var data = { filter: this.selectedFilter };
/** @type {?} */
var bottomSheetRef = this.bottomSheet.open(NgxFilterMenuComponent, {
data: data
});
bottomSheetRef.afterDismissed().subscribe(function () {
_this.selectedFilter = data.filter;
_this.applyFilter(true);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51028
|
train
|
function (file) {
var _this = this;
return new Promise(function (resolve, reject) {
return __awaiter(_this, void 0, void 0, function () {
var imageSrc, err_3, img;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, readFile()];
case 1:
imageSrc = _a.sent();
return [3 /*break*/, 3];
case 2:
err_3 = _a.sent();
reject(err_3);
return [3 /*break*/, 3];
case 3:
img = new Image();
img.onload = function () {
return __awaiter(_this, void 0, void 0, function () {
var ctx, width, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
// set edited image canvas and dimensions
this.editedImage = ( /** @type {?} */(document.createElement('canvas')));
this.editedImage.width = img.width;
this.editedImage.height = img.height;
ctx = this.editedImage.getContext('2d');
ctx.drawImage(img, 0, 0);
// resize image if larger than max image size
width = img.width > img.height ? img.height : img.width;
if (!(width > this.options.maxImageDimensions.width))
return [3 /*break*/, 2];
_a = this;
return [4 /*yield*/, this.resize(this.editedImage)];
case 1:
_a.editedImage = _b.sent();
_b.label = 2;
case 2:
this.imageDimensions.width = this.editedImage.width;
this.imageDimensions.height = this.editedImage.height;
this.setPreviewPaneDimensions(this.editedImage);
resolve();
return [2 /*return*/];
}
});
});
};
img.src = imageSrc;
return [2 /*return*/];
}
});
});
});
/**
* read file from input field
* @return {?}
*/
function readFile() {
return new Promise(function (resolve, reject) {
/** @type {?} */
var reader = new FileReader();
reader.onload = function (event) {
resolve(reader.result);
};
reader.onerror = function (err) {
reject(err);
};
reader.readAsDataURL(file);
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51029
|
readFile
|
train
|
function readFile() {
return new Promise(function (resolve, reject) {
/** @type {?} */
var reader = new FileReader();
reader.onload = function (event) {
resolve(reader.result);
};
reader.onerror = function (err) {
reject(err);
};
reader.readAsDataURL(file);
});
}
|
javascript
|
{
"resource": ""
}
|
q51030
|
train
|
function () {
var _this = this;
return new Promise(function (resolve, reject) {
_this.processing.emit(true);
setTimeout(function () {
// load the image and compute the ratio of the old height to the new height, clone it, and resize it
/** @type {?} */
var processingResizeRatio = 0.5;
/** @type {?} */
var dst = cv.imread(_this.editedImage);
/** @type {?} */
var dsize = new cv.Size(dst.rows * processingResizeRatio, dst.cols * processingResizeRatio);
/** @type {?} */
var ksize = new cv.Size(5, 5);
// convert the image to grayscale, blur it, and find edges in the image
cv.cvtColor(dst, dst, cv.COLOR_RGBA2GRAY, 0);
cv.GaussianBlur(dst, dst, ksize, 0, 0, cv.BORDER_DEFAULT);
cv.Canny(dst, dst, 75, 200);
// find contours
cv.threshold(dst, dst, 120, 200, cv.THRESH_BINARY);
/** @type {?} */
var contours = new cv.MatVector();
/** @type {?} */
var hierarchy = new cv.Mat();
cv.findContours(dst, contours, hierarchy, cv.RETR_CCOMP, cv.CHAIN_APPROX_SIMPLE);
/** @type {?} */
var rect = cv.boundingRect(dst);
dst.delete();
hierarchy.delete();
contours.delete();
// transform the rectangle into a set of points
Object.keys(rect).forEach(function (key) {
rect[key] = rect[key] * _this.imageResizeRatio;
});
/** @type {?} */
var contourCoordinates = [
new PositionChangeData({ x: rect.x, y: rect.y }, ['left', 'top']),
new PositionChangeData({ x: rect.x + rect.width, y: rect.y }, ['right', 'top']),
new PositionChangeData({ x: rect.x + rect.width, y: rect.y + rect.height }, ['right', 'bottom']),
new PositionChangeData({ x: rect.x, y: rect.y + rect.height }, ['left', 'bottom']),
];
_this.limitsService.repositionPoints(contourCoordinates);
// this.processing.emit(false);
resolve();
}, 30);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51031
|
train
|
function () {
var _this = this;
return new Promise(function (resolve, reject) {
_this.processing.emit(true);
setTimeout(function () {
/** @type {?} */
var dst = cv.imread(_this.editedImage);
// create source coordinates matrix
/** @type {?} */
var sourceCoordinates = [
_this.getPoint(['top', 'left']),
_this.getPoint(['top', 'right']),
_this.getPoint(['bottom', 'right']),
_this.getPoint(['bottom', 'left'])
].map(function (point) {
return [point.x / _this.imageResizeRatio, point.y / _this.imageResizeRatio];
});
// get max width
/** @type {?} */
var bottomWidth = _this.getPoint(['bottom', 'right']).x - _this.getPoint(['bottom', 'left']).x;
/** @type {?} */
var topWidth = _this.getPoint(['top', 'right']).x - _this.getPoint(['top', 'left']).x;
/** @type {?} */
var maxWidth = Math.max(bottomWidth, topWidth) / _this.imageResizeRatio;
// get max height
/** @type {?} */
var leftHeight = _this.getPoint(['bottom', 'left']).y - _this.getPoint(['top', 'left']).y;
/** @type {?} */
var rightHeight = _this.getPoint(['bottom', 'right']).y - _this.getPoint(['top', 'right']).y;
/** @type {?} */
var maxHeight = Math.max(leftHeight, rightHeight) / _this.imageResizeRatio;
// create dest coordinates matrix
/** @type {?} */
var destCoordinates = [
[0, 0],
[maxWidth - 1, 0],
[maxWidth - 1, maxHeight - 1],
[0, maxHeight - 1]
];
// convert to open cv matrix objects
/** @type {?} */
var Ms = cv.matFromArray(4, 1, cv.CV_32FC2, [].concat.apply([], __spread(sourceCoordinates)));
/** @type {?} */
var Md = cv.matFromArray(4, 1, cv.CV_32FC2, [].concat.apply([], __spread(destCoordinates)));
/** @type {?} */
var transformMatrix = cv.getPerspectiveTransform(Ms, Md);
// set new image size
/** @type {?} */
var dsize = new cv.Size(maxWidth, maxHeight);
// perform warp
cv.warpPerspective(dst, dst, transformMatrix, dsize, cv.INTER_LINEAR, cv.BORDER_CONSTANT, new cv.Scalar());
cv.imshow(_this.editedImage, dst);
dst.delete();
Ms.delete();
Md.delete();
transformMatrix.delete();
_this.setPreviewPaneDimensions(_this.editedImage);
_this.showPreview().then(function () {
_this.processing.emit(false);
resolve();
});
}, 30);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51032
|
train
|
function (image) {
var _this = this;
return new Promise(function (resolve, reject) {
_this.processing.emit(true);
setTimeout(function () {
/** @type {?} */
var src = cv.imread(image);
/** @type {?} */
var currentDimensions = {
width: src.size().width,
height: src.size().height
};
/** @type {?} */
var resizeDimensions = {
width: 0,
height: 0
};
if (currentDimensions.width > _this.options.maxImageDimensions.width) {
resizeDimensions.width = _this.options.maxImageDimensions.width;
resizeDimensions.height = _this.options.maxImageDimensions.width / currentDimensions.width * currentDimensions.height;
if (resizeDimensions.height > _this.options.maxImageDimensions.height) {
resizeDimensions.height = _this.options.maxImageDimensions.height;
resizeDimensions.width = _this.options.maxImageDimensions.height / currentDimensions.height * currentDimensions.width;
}
/** @type {?} */
var dsize = new cv.Size(Math.floor(resizeDimensions.width), Math.floor(resizeDimensions.height));
cv.resize(src, src, dsize, 0, 0, cv.INTER_AREA);
/** @type {?} */
var resizeResult = ( /** @type {?} */(document.createElement('canvas')));
cv.imshow(resizeResult, src);
src.delete();
_this.processing.emit(false);
resolve(resizeResult);
}
else {
_this.processing.emit(false);
resolve(image);
}
}, 30);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51033
|
train
|
function (width, height) {
/** @type {?} */
var ratio = width / height;
/** @type {?} */
var maxWidth = this.screenDimensions.width > this.maxPreviewWidth ?
this.maxPreviewWidth : this.screenDimensions.width - 40;
/** @type {?} */
var maxHeight = this.screenDimensions.height - 240;
/** @type {?} */
var calculated = {
width: maxWidth,
height: Math.round(maxWidth / ratio),
ratio: ratio
};
if (calculated.height > maxHeight) {
calculated.height = maxHeight;
calculated.width = Math.round(maxHeight * ratio);
}
return calculated;
}
|
javascript
|
{
"resource": ""
}
|
|
q51034
|
train
|
function (roles) {
var _this = this;
return this.points.find(function (point) {
return _this.limitsService.compareArray(point.roles, roles);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51035
|
longpollStream
|
train
|
function longpollStream(http, mutable) {
return asyncMapRecover(function(creds) {
return http({
timeout: LONGPOLL_TIMEOUT,
url: makeUrl(assign({}, creds, mutable))
}).then(function(body) {
return JSON.parse(body);
}).catch((error) => {
return Promise.reject({
type: ERROR_TYPE_UNKNOWN,
error: error
});
}).then(function(response) {
switch (response.failed) {
case LP_ERROR_FAIL_TS:
mutable.ts = response.ts;
return Promise.reject({ type: ERROR_TYPE_TS })
case LP_ERROR_FAIL_KEY:
return Promise.reject({ type: ERROR_TYPE_CREDS })
default:
mutable.ts = response.ts;
return response.updates;
}
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51036
|
cacher
|
train
|
function cacher() {
let cache = false;
return function(read) {
return function readable(end, cb) {
if (end === null && cache) {
cb(null, cache);
} else {
read(end, function (end, data) {
cache = data;
cb(end, data)
});
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51037
|
safe3
|
train
|
function safe3(fn) {
var queue = Queue.new();
var safe = true;
function checkQueue() {
var next = queue.shift();
safe = false;
fn(next[0], next[1], next[2], function (error, result) {
next[3](error, result);
if (queue.length > 0) {
checkQueue();
} else {
safe = true;
}
});
}
return function (arg1, arg2, arg3, callback) {
queue.push(arguments);
if (safe) {
checkQueue();
}
};
}
|
javascript
|
{
"resource": ""
}
|
q51038
|
removeNestedBlocks
|
train
|
function removeNestedBlocks (ast) {
var tagged;
while((tagged = findNestedBlocks(ast)).length) {
fast.forEach(tagged, function (item) {
var node = item[0],
parent = item[1],
index = parent.body.indexOf(node);
fast.apply(Array.prototype.splice, parent.body, fast.concat([index, 1], node.body));
});
}
return ast;
}
|
javascript
|
{
"resource": ""
}
|
q51039
|
findNestedBlocks
|
train
|
function findNestedBlocks (ast) {
var tagged = [];
traverse.traverse(ast, {
enter: function (node, parent) {
if (node.type === 'BlockStatement' && parent && parent.type === 'BlockStatement') {
tagged.push([node, parent]);
}
}
});
return tagged;
}
|
javascript
|
{
"resource": ""
}
|
q51040
|
findHoistableFunctionDeclarations
|
train
|
function findHoistableFunctionDeclarations (ast) {
var tagged = [];
traverse.traverse(ast, {
enter: function (node, parent) {
if (node.type === 'FunctionDeclaration' && ~node.id.name.indexOf('$')) {
tagged.push([node, parent]);
}
}
});
return tagged;
}
|
javascript
|
{
"resource": ""
}
|
q51041
|
combineContiguousOutputStatements
|
train
|
function combineContiguousOutputStatements (ast) {
traverse.traverse(ast, {
enter: function (node, parent) {
if (node.type !== 'BlockStatement') {
return;
}
var prev = false;
node.body = fast.reduce(node.body, function (body, statement) {
if (
!body.length ||
statement.type !== 'ExpressionStatement' ||
statement.expression.type !== 'AssignmentExpression' ||
statement.expression.operator !== '+=' ||
statement.expression.left.type !== 'Identifier' ||
statement.expression.left.name !== 'html'
) {
prev = false;
body.push(statement);
return body;
}
else if (!prev) {
prev = statement;
body.push(statement);
return body;
}
prev.expression.right = {
type: 'BinaryExpression',
operator: '+',
left: prev.expression.right,
right: statement.expression.right
};
return body;
}, []);
}
});
return ast;
}
|
javascript
|
{
"resource": ""
}
|
q51042
|
removeUnusedAssignmentExpressions
|
train
|
function removeUnusedAssignmentExpressions (ast) {
var unused = findUnusedAssignmentExpressions(ast);
traverse.traverse(ast, {
enter: function (node, parent) {
if (node.type !== 'BlockStatement') {
return;
}
node.body = fast.filter(node.body, function (item) {
return !~fast.indexOf(unused, item);
});
}
});
return ast;
}
|
javascript
|
{
"resource": ""
}
|
q51043
|
removeUnusedVariableDeclarators
|
train
|
function removeUnusedVariableDeclarators (ast) {
var unused = findUnusedVariableDeclarators(ast);
traverse.traverse(ast, {
enter: function (node, parent) {
if (node.type !== 'VariableDeclaration') {
return;
}
node.declarations = fast.filter(node.declarations, function (item) {
return !~fast.indexOf(unused, item);
});
}
});
return ast;
}
|
javascript
|
{
"resource": ""
}
|
q51044
|
findUnusedVariableDeclarators
|
train
|
function findUnusedVariableDeclarators (ast) {
var unused = [];
traverse.traverse(ast, {
enter: function (node, parent) {
var scope, refs;
if (node.type === 'VariableDeclarator' && (scope = findScope(ast, node))) {
refs = fast.filter(findVariableReferences(scope, node.id), function (item) {
return item !== node.id;
});
if (!refs.length) {
unused.push(node);
}
}
}
});
return unused;
}
|
javascript
|
{
"resource": ""
}
|
q51045
|
findVariableReferences
|
train
|
function findVariableReferences (ast, identifier, skip) {
var references = [];
traverse.traverse(ast, {
enter: function (node, parent) {
if (node === skip) {
this.skip();
}
else if (
node.type === 'Identifier' &&
node.name === identifier.name &&
(parent.type !== 'MemberExpression' || parent.left !== node)
) {
references.push(node);
}
}
});
return references;
}
|
javascript
|
{
"resource": ""
}
|
q51046
|
findScope
|
train
|
function findScope (ast, item) {
var scopes = [],
found = false;
traverse.traverse(ast, {
enter: function (node, parent) {
if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') {
scopes.push(node);
}
else if (node === item) {
found = scopes[scopes.length - 1];
this.break();
}
},
leave: function (node, parent) {
if (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') {
scopes.pop();
}
}
});
return found ? found.body : false;
}
|
javascript
|
{
"resource": ""
}
|
q51047
|
getBumpType
|
train
|
function getBumpType(){
if (args.patch && args.minor || args.minor && args.major || args.major && args.patch) {
throw '\nYou can not use more than one version bump type at a time\n';
}
if (args.patch){
return 'patch';
} else if (args.minor){
return 'minor';
} else if (args.major) {
return 'major';
} else {
return false;
}
}
|
javascript
|
{
"resource": ""
}
|
q51048
|
bumpVersion
|
train
|
function bumpVersion(importance){
return function bump_version (done){
if (!importance) throw new Error(`
An importance must be specified for a version bump to occur.
Valid importances: "--patch", "--minor", "--major"
`);
// get all the files to bump version in
return gulp.src('./package.json')
// bump the version number in those files
.pipe(bump({type: importance}))
// save it back to filesystem
.pipe(gulp.dest('./'))
//commit the changed version number
.pipe(git.commit(`${importance} version bump`))
}
}
|
javascript
|
{
"resource": ""
}
|
q51049
|
tag_version
|
train
|
function tag_version(){
return new Promise((resolve, reject)=>{
const pkg = reload('../../package.json');
const tag = `v${pkg.version}`;
gutil.log('Tagging as: '+gutil.colors.cyan(tag));
git.tag(tag, `Tagging as ${tag}`, (err)=>{
checkError(err);
resolve(tag);
})
})
}
|
javascript
|
{
"resource": ""
}
|
q51050
|
release
|
train
|
function release(importance) {
const version_bump = done => importance !== false ? gulp.series(bumpVersion(importance))(done) : done();
return done => gulp.series(
() => check_out('develop'),
version_bump,
finish_release
)(done);
}
|
javascript
|
{
"resource": ""
}
|
q51051
|
validateMetaType
|
train
|
function validateMetaType(name, metaType) {
assert(_.isObject(metaType), ERR_METATYPE_OBJECT, { name: name });
assert(metaType.name, ERR_REQUIRE_FIELD, { metaType: metaType, field: "name" });
assert(metaType.kind === "enum" || metaType.kind === "class", ERR_METATYPE_KIND, { metaType: metaType });
// Enum MetaType
if (metaType.kind === "enum") {
var lits = metaType.literals;
assert(Array.isArray(lits) && lits.length > 0, ERR_ENUM_HAS_LITERALS, { metaType: metaType });
// Check duplicated literal
_.each(lits, function (lit1) {
var len = _.filter(lits, function (lit2) { return lit2 === lit1; }).length;
assert(len === 1, ERR_DUPLICATED_LITERAL, { metaType: metaType, literal: lit1 });
});
}
// Class MetaType
if (metaType.kind === "class") {
// Check .super
if (metaType.super) {
assert(metaType.super && _global.meta[metaType.super], ERR_TYPE_NOT_FOUND, { metaType: metaType, type: metaType.super, field: "super" });
}
// Check Attributes
if (metaType.attributes) {
assert(Array.isArray(metaType.attributes), ERR_FIELD_TYPE, { metaType: metaType, field: "attributes", type: "Array" });
_.each(metaType.attributes, function (attribute) {
// check 'name'
assert(attribute.name, ERR_UNNAMED_ATTRIBUTE, { metaType: metaType });
// Check 'kind'
assert(_.contains(["prim", "enum", "var", "ref", "refs", "obj", "objs", "custom"], attribute.kind), ERR_ATTRIBUTE_KIND, { metaType: metaType, attribute: attribute });
// Check 'type'
if (attribute.kind === "prim") {
assert(_.contains(["Integer", "String", "Boolean", "Real"], attribute.type), ERR_ATTRIBUTE_PRIM_TYPE, { metaType: metaType, attribute: attribute });
} else if (attribute.kind !== "custom") {
assert(_global.meta[attribute.type], ERR_TYPE_NOT_FOUND, { metaType: metaType, type: attribute.type, field: attribute.name + ".type" });
}
// Check duplicated attribute in all inherited attributes
var len = _.filter(getMetaAttributes(metaType.name), function (attr) { return attr.name === attribute.name; }).length;
assert(len === 1, ERR_DUPLICATED_ATTRIBUTE, { metaType: metaType, attribute: attribute });
});
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51052
|
register
|
train
|
function register(metamodel) {
var name, metaType;
// Registering MetaTypes to global.meta
for (name in metamodel) {
if (metamodel.hasOwnProperty(name)) {
metaType = metamodel[name];
metaType.name = name;
// Check duplicated MetaType
if (_global.meta[name]) {
delete metamodel[name];
console.error("[MetaModelManager] MetaType '" + name + "' is already exists.");
} else {
_global.meta[name] = metaType;
}
}
}
// Validate MetaTypes
for (name in metamodel) {
if (metamodel.hasOwnProperty(name)) {
metaType = metamodel[name];
try {
validateMetaType(name, metaType);
} catch (err) {
console.error(err);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51053
|
getMetaAttributes
|
train
|
function getMetaAttributes(typeName) {
var metaClass = _global.meta[typeName],
attrs = [];
if (metaClass.super) {
attrs = getMetaAttributes(metaClass.super);
}
if (metaClass.attributes) {
var i, len, item;
for (i = 0, len = metaClass.attributes.length; i < len; i++) {
item = metaClass.attributes[i];
attrs.push(item);
}
}
return attrs;
}
|
javascript
|
{
"resource": ""
}
|
q51054
|
getViewTypeOf
|
train
|
function getViewTypeOf(typeName) {
var metaClass = _global.meta[typeName];
if (metaClass) {
return metaClass.view || null;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q51055
|
getAvailableViewTypes
|
train
|
function getAvailableViewTypes(diagramTypeName) {
var metaClass = _global.meta[diagramTypeName],
views = [];
if (metaClass.super) {
views = getAvailableViewTypes(metaClass.super);
}
if (metaClass.views) {
var i, len, item;
for (i = 0, len = metaClass.views.length; i < len; i++) {
item = metaClass.views[i];
views.push(item);
}
}
return views;
}
|
javascript
|
{
"resource": ""
}
|
q51056
|
callAPI
|
train
|
function callAPI(session, path, data, subdomain = 'api', isJson = true, headers = null) {
const authorization = 'Bearer ' + session.token;
const reqOptions = {
url: `https://${subdomain}.dropboxapi.com/2${path}`,
method: 'POST',
headers: {
'Authorization': authorization,
'User-Agent': 'Unifile'
},
json: isJson,
encoding: null
};
if(data && Object.keys(data).length !== 0) reqOptions.body = data;
if(headers) {
for(const header in headers) {
reqOptions.headers[header] = headers[header];
}
}
return new Promise(function(resolve, reject) {
request(reqOptions, function(err, res, body) {
if(err) {
reject(err);
} else if(res.statusCode >= 400) {
let errorMessage = null;
// In case of users/get_current_account, Dropbox return a String with the error
// Since isJson = true, it gets parsed by request
if(Buffer.isBuffer(body)) {
try {
errorMessage = JSON.parse(body.toString()).error_summary;
} catch (e) {
errorMessage = body.toString();
}
} else {
errorMessage = (isJson ? body : JSON.parse(body)).error_summary;
}
// Dropbox only uses 409 for endpoints specific errors
let filename = null;
try {
filename = res.request.headers.hasOwnProperty('Dropbox-API-Arg') ?
JSON.parse(res.request.headers['Dropbox-API-Arg']).path
: JSON.parse(res.request.body).path;
} catch (e) {}
if(errorMessage.includes('/not_found/')) {
reject(new UnifileError(UnifileError.ENOENT, `Not Found: ${filename}`));
} else if(errorMessage.startsWith('path/conflict/')) {
reject(new UnifileError(UnifileError.EINVAL, `Creation failed due to conflict: ${filename}`));
} else if(errorMessage.startsWith('path/not_file/')) {
reject(new UnifileError(UnifileError.EINVAL, `Path is a directory: ${filename}`));
} else if(res.statusCode === 401) {
reject(new UnifileError(UnifileError.EACCES, errorMessage));
} else {
reject(new UnifileError(UnifileError.EIO, errorMessage));
}
} else resolve(body);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51057
|
safeStringify
|
train
|
function safeStringify(v) {
return JSON.stringify(v).replace(charsToEncode,
function(c) {
return '\\u' + ('000' + c.charCodeAt(0).toString(16)).slice(-4);
}
);
}
|
javascript
|
{
"resource": ""
}
|
q51058
|
exportToHTML
|
train
|
function exportToHTML(targetDir, exportDiagram) {
fs.ensureDirSync(targetDir);
fs.ensureDirSync(targetDir + "/contents");
fs.ensureDirSync(targetDir + "/diagrams");
fs.copySync(__dirname + "/../resources/html/assets", targetDir + "/assets");
// Generate html documents
try {
var root = mdjson.getRoot();
mdjson.render(__dirname + "/../resources/html/templates/index.ejs", targetDir + "/index.html", root, { filters: filters });
mdjson.render(__dirname + "/../resources/html/templates/navigation.ejs", targetDir + "/contents/navigation.html", root, { filters: filters });
mdjson.render(__dirname + "/../resources/html/templates/diagrams.ejs", targetDir + "/contents/diagrams.html", root, { filters: filters });
mdjson.render(__dirname + "/../resources/html/templates/element_index.ejs", targetDir + "/contents/element_index.html", root, { filters: filters });
mdjson.renderBulk(__dirname + "/../resources/html/templates/content.ejs", targetDir + "/contents/<%=: element | toFilename %>.html", "@Model", { filters: filters }, function (err, file, elem) {
if (err) {
console.error(err);
}
});
} catch (err) {
console.error(err);
}
// Export diagram images
if (exportDiagram) {
var diagrams = mdjson.Repository.getInstancesOf("Diagram");
_.each(diagrams, function (d) {
mdjson.exportDiagramAsSVG(d, targetDir + "/diagrams/" + toFilename(d) + ".svg");
});
}
}
|
javascript
|
{
"resource": ""
}
|
q51059
|
addRules
|
train
|
function addRules(rules) {
_.each(rules, function (rule) {
_global.rules[rule.id] = rule;
});
}
|
javascript
|
{
"resource": ""
}
|
q51060
|
getImageData
|
train
|
function getImageData(diagram, type) {
// Make a new canvas element for making image data
var canvasElement = new Canvas(500, 500, type),
canvas = new mdjson.Graphics.Canvas(canvasElement.getContext("2d")),
boundingBox = diagram.getBoundingBox(canvas),
rectExpand = 10;
// Initialize new canvas
boundingBox.expand(rectExpand);
canvas.origin = new mdjson.Graphics.Point(-boundingBox.x1, -boundingBox.y1);
canvas.zoomFactor = new mdjson.Graphics.ZoomFactor(1, 1);
canvasElement.width = boundingBox.getWidth();
canvasElement.height = boundingBox.getHeight();
// Draw diagram to the new canvas
diagram.drawDiagram(canvas);
return canvasElement.toBuffer();
}
|
javascript
|
{
"resource": ""
}
|
q51061
|
ScrapeError
|
train
|
function ScrapeError(msg, response, bodyString) {
Error.call(this, msg);
this.response = response;
this.bodyString = bodyString;
}
|
javascript
|
{
"resource": ""
}
|
q51062
|
scrape
|
train
|
function scrape(url, model, options, cb) {
/**
* Make `options` argument optional
*/
if ('function' === typeof options) {
/**
* Interchange `cb`'s position and fill `options` with nice defaults
*/
cb = options;
options = _.cloneDeep(DEFAULTS);
} else {
/**
* Merge all options from `DEFAULTS` not present in `options`
*/
_.defaultsDeep(options, DEFAULTS);
}
/**
* Set `request`'s Uniform Resource Identifier to provied `url`
* @type {string}
*/
options.requestOptions.uri = url;
/**
* Call `request()` to get the resource
*/
request(options.requestOptions, processResponse);
/**
* Handle `request()`'s result: Chain `err` or proceed to parse the resource.
*/
function processResponse(err, res, body) {
if (err) { return cb(err); }
if (res.statusCode !== 200) {
return cb(new ScrapeError('Not OK response from server.', res, body));
}
parseBody(body, model, options, cb);
}
}
|
javascript
|
{
"resource": ""
}
|
q51063
|
parseBody
|
train
|
function parseBody(bodyString, model, options, cb) {
var result;
var dom;
/**
* Load the HTML and parse it with cheerio to create a DOM
*/
try {
dom = cheerio.load(bodyString, options.cheerioOptions);
} catch (err) {
err.bodyString = bodyString;
return cb(err);
}
result = getItem(dom, model, options.itemOptions);
if (result instanceof Error) {
result.bodyString = bodyString;
return cb(result);
}
return cb(null, result);
}
|
javascript
|
{
"resource": ""
}
|
q51064
|
getItem
|
train
|
function getItem(dom, item, defaults) {
var data;
var get;
var trim;
var nodes;
var selector;
/**
* If the `item` itself is a selector, grab it as `selector` and set item to
* a new empty object.
*/
if ('string' === typeof item) {
selector = item;
item = {};
/**
* If not, it should be an object.
* If it has no `selector`, it means it is an embedded document, so resolve it
* recursively.
*/
} else if (!item.selector) {
data = {};
for (var embedded in item) {
data[embedded] = getItem(dom, item[embedded], defaults);
if (data[embedded] instanceof Error) {
return data[embedded];
}
}
return data;
/**
* If it does have a `selector`, use it!
*/
} else { selector = item.selector; }
/**
* Then fulfill the `item` with nice `defaults`.
*/
_.defaultsDeep(item, defaults);
/**
* This is an array of cheerio objects. Always an array.
* @type {Object}
*/
nodes = dom(selector);
/**
* If there are no matches for the given `selector` set the result as `null`
* Ohterwise, proceed to process the result.
*/
if (!nodes.length) {
data = null;
} else {
/**
* Configure the `trim` function based on the item.trim options.
* If `false`, simply return the same value.
*/
switch (item.trim) {
case true:
trim = String.prototype.trim;
break;
case false:
trim = function() { return this; };
break;
case 'left':
trim = String.prototype.trimLeft;
break;
case 'right':
trim = String.prototype.trimRight;
break;
}
/**
* Configure transformation function.
*/
if ('function' === typeof item.transform) {
transform = item.transform;
} else {
transform = function() { return this.toString(); };
}
/**
* The text of a node is what you probably are looking for. Scraping is all
* about content.
* Cheerio has the `.text()` method to get it, this is the default.
* If you are looking for something else, it must be an attribute, like a
* link's `href` or an image/script's `src` or a form's `action`.
* @type {Function}
*/
get = (function(i){
if (i.get === 'text')
return function(node) { return transform.apply(item.prefix + trim.apply(node.text()) + item.suffix); };
else if (i.get === 'html')
return function(node) { return transform.apply(item.prefix + trim.apply(node.html()) + item.suffix); };
else
return function(node) { return transform.apply(item.prefix + trim.apply(node.attr(item.get)) + item.suffix); };
})(item);
/**
* When `unique` is set to `true`, only the first match will be returned, no
* matter how many elements actually matched the `selector`.
* When set to `false`, it will return the results into an array, even when
* only one element matched the `selector`.
* When set to `'auto'`, (scrapy's default) an unwrapped result will be returned
* when a single element matched the `selector`, an array if many.
*/
switch (item.unique) {
case true:
data = get(nodes.eq(0));
break;
case 'auto':
if (nodes.length === 1) {
data = get(nodes.eq(0));
break;
}
case false:
data = [];
for (var i = nodes.length - 1; i >= 0; i--) {
data[i] = get(nodes.eq(i));
}
break;
}
}
/**
* When no element is found for the given `selector` but it was explicitly
* `required`, return an `Error` instead of `data`.
*/
if (!data && item.required) {
return new Error('Item [' + selector + '] set as REQUIRED and NOT found');
}
return data;
}
|
javascript
|
{
"resource": ""
}
|
q51065
|
getSuperType
|
train
|
function getSuperType(subType) {
if (subType) {
return _global.type[_global.meta[subType.name].super];
} else {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
q51066
|
getCommonType
|
train
|
function getCommonType(elems) {
if (elems && elems.length > 0) {
var commonType = elems[0].getClass();
while (!_.every(elems, function (e) { return (e instanceof commonType); })) {
commonType = getSuperType(commonType);
}
return commonType;
} else {
return null;
}
}
|
javascript
|
{
"resource": ""
}
|
q51067
|
findByName
|
train
|
function findByName(array, name) {
if (array && array.length > 0) {
for (var i = 0, len = array.length; i < len; i++) {
var elem = array[i];
if (elem.name == name) {
return elem;
}
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q51068
|
_getBase
|
train
|
function _getBase(name) {
var operation = {
id: IdGenerator.generateGuid(),
time: getTimestamp(),
name: name,
bypass: false,
ops: []
};
return operation;
}
|
javascript
|
{
"resource": ""
}
|
q51069
|
_getArray
|
train
|
function _getArray(elem, field) {
var f = elem._id + "." + field;
if (!_currentArray[f]) {
_currentArray[f] = _.clone(elem[field]);
}
return _currentArray[f];
}
|
javascript
|
{
"resource": ""
}
|
q51070
|
begin
|
train
|
function begin(name, bypass) {
_currentOperation = _getBase(name);
if (bypass === true) {
_currentOperation.bypass = true;
}
}
|
javascript
|
{
"resource": ""
}
|
q51071
|
insert
|
train
|
function insert(elem) {
try {
$(exports).triggerHandler('insert', [elem]);
} catch (err) {
console.error(err);
}
var writer = new Writer();
elem.save(writer);
_currentOperation.ops.push({op: OP_INSERT, arg: writer.current});
}
|
javascript
|
{
"resource": ""
}
|
q51072
|
remove
|
train
|
function remove(elem) {
try {
$(exports).triggerHandler('remove', [elem]);
} catch (err) {
console.error(err);
}
var writer = new Writer();
elem.save(writer);
_currentOperation.ops.push({op: OP_REMOVE, arg: writer.current});
}
|
javascript
|
{
"resource": ""
}
|
q51073
|
fieldAssign
|
train
|
function fieldAssign(elem, field, val) {
try {
$(exports).triggerHandler('fieldAssign', [elem, field, val]);
} catch (err) {
console.error(err);
}
var isCustomField = (elem[field] && elem[field].__read);
var oldVal;
if (isCustomField) {
oldVal = elem[field].__write();
} else {
oldVal = elem[field];
}
_currentOperation.ops.push({
op: OP_FIELD_ASSIGN,
arg: {
_id: elem._id,
f: field,
n: val,
o: oldVal
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51074
|
fieldInsert
|
train
|
function fieldInsert(elem, field, val) {
try {
$(exports).triggerHandler('fieldInsert', [elem, field, val]);
} catch (err) {
console.error(err);
}
var array = _getArray(elem, field);
array.push(val);
_currentOperation.ops.push({
op: OP_FIELD_INSERT,
arg: {
_id: elem._id,
f: field,
e: val._id,
i: array.indexOf(val)
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51075
|
fieldReorder
|
train
|
function fieldReorder(elem, field, val, pos) {
try {
$(exports).triggerHandler('fieldReorder', [elem, field, val, pos]);
} catch (err) {
console.error(err);
}
_currentOperation.ops.push({
op: OP_FIELD_REORDER,
arg: {
_id: elem._id,
f: field,
e: val._id,
i: pos
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51076
|
fieldRelocate
|
train
|
function fieldRelocate(elem, field, oldParent, newParent) {
try {
$(exports).triggerHandler('fieldRelocate', [elem, field, oldParent, newParent]);
} catch (err) {
console.error(err);
}
_currentOperation.ops.push({
op: OP_FIELD_RELOCATE,
arg: {
_id: elem._id,
f: field,
op: oldParent._id,
np: newParent._id
}
});
}
|
javascript
|
{
"resource": ""
}
|
q51077
|
paginate
|
train
|
function paginate(reqOptions, link, memo) {
const links = link.split(/,\s*/);
let matches;
links.some(function(link) {
matches = link.trim().match(/<(.+)>;\s*rel="next"/);
return matches !== null;
});
// End of pagination
if(!matches) {
return Promise.resolve(memo);
}
return new Promise(function(resolve, reject) {
reqOptions.url = matches[1];
request(reqOptions, function(err, res, body) {
paginate(reqOptions, res.headers.link, memo.concat(JSON.parse(body))).then(resolve);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51078
|
move
|
train
|
function move(src, dest, treeRes) {
return treeRes.tree.map(function(file) {
const regex = new RegExp('^' + src + '$|^' + src + '(/)');
// Overrides file path
return Object.assign({}, file, {path: file.path.replace(regex, dest + '$1')});
});
}
|
javascript
|
{
"resource": ""
}
|
q51079
|
validate
|
train
|
function validate(schema) {
var key, item;
for (key in schema) {
if (schema.hasOwnProperty(key)) {
item = schema[key];
if (!item.text) {
console.error("[PreferenceManager] missing required field: 'text' of '" + key + "'");
}
if (!item.type) {
console.error("[PreferenceManager] missing required field: 'type' of '" + key + "'");
}
if (item.type !== "Section" && typeof item['default'] === "undefined") {
console.error("[PreferenceManager] missing required field: 'default' of '" + key + "'");
}
if (item.type === "Combo" || item.type === "Dropdown") {
if (item.options && item.options.length > 0) {
var i, len;
for (i = 0, len = item.options.length; i < len; i++) {
if (typeof item.options[i].value === "undefined") {
console.error("[PreferenceManager] missing required field of option item: 'value' of '" + key + "'");
}
if (typeof item.options[i].text === "undefined") {
console.error("[PreferenceManager] missing required field of option item: 'text' of '" + key + "'");
}
}
} else {
console.error("[PreferenceManager] missing required field or no items: 'options' of '" + key + "'");
}
}
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q51080
|
register
|
train
|
function register(id, name, schema) {
if (!id || !name || !schema) {
console.error("register(): missing required parameters: id, name, or schema");
return;
}
if (validate(schema)) {
_schemaMap[id] = {
id: id,
name: name,
schema: schema
};
// Build Preference Item Map
_.each(schema, function (item, key) {
if (item) {
_itemMap[key] = item;
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
q51081
|
get
|
train
|
function get(key, defaultValue) {
defaultValue = typeof defaultValue === "undefined" ? null : defaultValue;
if (global.localStorage) {
var _value = global.localStorage.getItem(key),
value = null;
if (_value) {
try {
value = JSON.parse(_value);
} catch (e) {
console.error("[PreferenceManager] Failed to read preference value of key: " + key);
}
} else {
// if not stored in localStorage, return default value from schema
if (_itemMap[key] && typeof _itemMap[key]['default'] !== "undefined") {
value = _itemMap[key]['default'];
} else {
value = defaultValue;
}
}
return value;
} else {
return defaultValue;
}
}
|
javascript
|
{
"resource": ""
}
|
q51082
|
set
|
train
|
function set(key, value) {
if (global.localStorage) {
var _value;
try {
_value = JSON.stringify(value);
global.localStorage.setItem(key, _value);
$(exports).triggerHandler("change", [key, value]);
} catch (e) {
console.error("[PreferenceManager] Failed to write preference value of key: " + key);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51083
|
render
|
train
|
function render(templatePath, outputPath, element, options) {
var template = fs.readFileSync(templatePath, 'utf8'),
rendered = "",
renderedOutput = "";
element = element || null;
options = options || {};
_.extend(options, {
mdjson : mdjson,
filename : templatePath, // to avoid "include" error
root : mdjson.getRoot(),
element : element
});
// Append predefined filters
if (!options.filters) {
options.filters = {};
}
_.extend(options.filters, filters);
rendered = ejs.render(template, options);
renderedOutput = ejs.render(outputPath, options);
fs.ensureFileSync(renderedOutput);
fs.writeFileSync(renderedOutput, rendered);
}
|
javascript
|
{
"resource": ""
}
|
q51084
|
renderBulk
|
train
|
function renderBulk(templatePath, outputPath, elements, options, fn) {
var template = fs.readFileSync(templatePath, 'utf8'),
rendered = "",
renderedOutput = "";
elements = elements || [];
options = options || {};
// if elements parameter is selector expression, retrieve them from Repository.
if (_.isString(elements)) {
elements = mdjson.Repository.select(elements) || [];
}
_.extend(options, {
mdjson : mdjson,
filename : templatePath, // to avoid "include" error
root : mdjson.getRoot()
});
// Append predefined filters
if (!options.filters) {
options.filters = {};
}
_.extend(options.filters, filters);
for (var i = 0, len = elements.length; i < len; i++) {
try {
options.element = elements[i];
rendered = ejs.render(template, options);
renderedOutput = ejs.render(outputPath, options);
fs.ensureFileSync(renderedOutput);
fs.writeFileSync(renderedOutput, rendered);
if (_.isFunction(fn)) {
fn(null, renderedOutput, options.element);
}
} catch (err) {
if (_.isFunction(fn)) {
fn(err);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51085
|
train
|
function () {
var tagArray = [];
if (this.tags && this.tags.length > 0) {
var i, len, tag;
for (i = 0, len = this.tags.length; i < len; i++) {
tag = this.tags[i];
switch (tag.kind) {
case Core.TK_STRING:
tagArray.push(tag.name + '="' + tag.value + '"');
break;
case Core.TK_REFERENCE:
if (tag.reference instanceof Core.Model) {
tagArray.push(tag.name + '=' + tag.reference.name);
} else {
tagArray.push(tag.name + '=null');
}
break;
case Core.TK_BOOLEAN:
tagArray.push(tag.name + '=' + tag.checked);
break;
case Core.TK_NUMBER:
tagArray.push(tag.name + '=' + tag.number);
break;
// TK_HIDDEN is not shown in Diagram.
}
}
}
return tagArray;
}
|
javascript
|
{
"resource": ""
}
|
|
q51086
|
registerFont
|
train
|
function registerFont(folder) {
var data = fs.readFileSync(folder + "/font.json", {encoding: "utf8"});
var fontArray = JSON.parse(data);
for (var i = 0, len = fontArray.length; i < len; i++) {
var font = fontArray[i];
font.path = folder;
mdjson.Font.registerFont(font);
}
}
|
javascript
|
{
"resource": ""
}
|
q51087
|
exportToPDF
|
train
|
function exportToPDF(diagrams, fullPath, options) {
var doc = new PDFDocument(options);
_.each(mdjson.Font.files, function (path, name) {
doc.registerFont(name, path);
});
doc.pipe(fs.createWriteStream(fullPath));
var canvas = new mdjson.PDFGraphics.Canvas(doc);
var i, len;
for (i = 0, len = diagrams.length; i < len; i++) {
if (i > 0) {
doc.addPage(options);
}
var diagram = diagrams[i],
box = diagram.getBoundingBox(canvas),
w = doc.page.width - PDF_MARGIN * 2,
h = doc.page.height - PDF_MARGIN * 2,
zoom = Math.min(w / box.x2, h / box.y2);
canvas.zoomFactor.numer = Math.min(zoom, PDF_DEFAULT_ZOOM);
canvas.origin.x = PDF_MARGIN;
canvas.origin.y = PDF_MARGIN;
_.each(diagram.ownedViews, function (v) {
v.setup(canvas);
v.update(canvas);
v.size(canvas);
v.arrange(canvas);
});
diagram.drawDiagram(canvas, false);
if (options.showName) {
doc.fontSize(10);
doc.font("Helvetica");
doc.text(diagram.getPathname(), PDF_MARGIN, PDF_MARGIN-10);
}
}
doc.end();
}
|
javascript
|
{
"resource": ""
}
|
q51088
|
writeObject
|
train
|
function writeObject(elem) {
var writer = new Core.Writer();
elem.save(writer);
var data = JSON.stringify(writer.current, null, "\t");
return data;
}
|
javascript
|
{
"resource": ""
}
|
q51089
|
extractChanged
|
train
|
function extractChanged(operation) {
var i, len, op, elem, changed = [];
if (operation.ops.length > 0) {
for (i = 0, len = operation.ops.length; i < len; i++) {
op = operation.ops[i];
if (op._elem && op._elem._id) {
elem = get(op._elem._id);
if (elem && !_.contains(changed, elem)) {
changed.push(elem);
}
}
if (op.arg && op.arg._id) {
elem = get(op.arg._id);
if (elem && !_.contains(changed, elem)) {
changed.push(elem);
}
}
}
}
return changed;
}
|
javascript
|
{
"resource": ""
}
|
q51090
|
doOperation
|
train
|
function doOperation(operation) {
if (operation.ops.length > 0) {
try {
$(exports).triggerHandler('beforeExecuteOperation', [operation]);
_applyOperation(operation);
if (operation.bypass !== true) {
_undoStack.push(operation);
_redoStack.clear();
$(exports).triggerHandler('operationExecuted', [operation]);
}
} catch (err) {
console.error(err);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51091
|
select
|
train
|
function select(selector) {
selector = selector || "";
// Parse selector into an array of terms
var interm = selector
.replace(/::/g, "\n::\n")
.replace(/@/g, "\n@")
.replace(/\./g, "\n.")
.replace(/\[/g, "\n[");
var i, len,
sliced = interm.split("\n"),
terms = [];
for (i = 0, len = sliced.length; i < len; i++) {
var item = sliced[i].trim(), arg;
// children selector
if (item === "::") {
terms.push({ op: "::" });
// type selector
} else if (item.charAt(0) === "@") {
arg = item.substring(1, item.length).trim();
if (arg.length === 0) {
throw "[Selector] Type selector requires type name after '@'";
}
terms.push({ op: "@", type: arg });
// field selector
} else if (item.charAt(0) === ".") {
arg = item.substring(1, item.length).trim();
if (arg.length === 0) {
throw "[Selector] Field selector requires field name after '.'";
}
terms.push({ op: ".", field: arg});
// value selector
} else if (item.charAt(0) === "[") {
arg = item.substring(1, item.length - 1);
var fv = arg.split("="), f = fv[0] || "", v = fv[1] || "";
if (!(item.charAt(item.length - 1) === "]" && fv.length === 2 && f.trim().length > 0 && v.trim().length > 0)) {
throw "[Selector] Value selector should be format of '[field=value]'";
}
terms.push({ op: "[]", field: f.trim(), value: v.trim()});
// name selector
} else if (item.length > 0) {
terms.push({ op: "name", name: item });
}
}
// Process terms sequentially
var current = _.values(_idMap),
term,
elems;
for (i = 0, len = terms.length; i < len; i++) {
term = terms[i];
elems = [];
switch (term.op) {
case "::":
current.forEach(function (e) {
elems = _.union(elems, e.getChildren());
});
current = elems;
break;
case "@":
current.forEach(function (e) {
if (type[term.type] && e instanceof type[term.type]) {
elems.push(e);
}
});
current = elems;
break;
case ".":
current.forEach(function (e) {
if (typeof e[term.field] !== "undefined") {
var val = e[term.field];
if (isElement(val)) {
elems.push(val);
}
if (Array.isArray(val)) {
val.forEach(function (e2) {
if (isElement(e2)) {
elems.push(e2);
}
});
}
}
});
current = elems;
break;
case "[]":
current.forEach(function (e) {
if (typeof e[term.field] !== "undefined") {
var val = e[term.field];
if (term.value == val) {
elems.push(e);
}
}
});
current = elems;
break;
case "name":
current.forEach(function (e) {
if (e.name === term.name) {
elems.push(e);
}
});
current = elems;
break;
}
}
return current;
}
|
javascript
|
{
"resource": ""
}
|
q51092
|
find
|
train
|
function find(predicate) {
var key, elem;
for (key in _idMap) {
if (_idMap.hasOwnProperty(key)) {
elem = _idMap[key];
if (predicate(elem)) {
return elem;
}
}
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q51093
|
findAll
|
train
|
function findAll(predicate) {
var key,
elem,
result = [];
for (key in _idMap) {
if (_idMap.hasOwnProperty(key)) {
elem = _idMap[key];
if (predicate(elem)) {
result.push(elem);
}
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q51094
|
search
|
train
|
function search(keyword, typeFilter) {
keyword = keyword.toLowerCase();
typeFilter = typeFilter || type.Element;
var results = findAll(function (elem) {
var name = elem.name ? elem.name.toLowerCase() : "";
return (name.indexOf(keyword) > -1 && elem instanceof typeFilter);
});
return results;
}
|
javascript
|
{
"resource": ""
}
|
q51095
|
getRefsTo
|
train
|
function getRefsTo(elem, iterator) {
var id,
ref,
obj,
list = [];
if (elem) {
obj = _refMap[elem._id];
if (obj) {
for (id in obj) {
if (obj.hasOwnProperty(id)) {
ref = _idMap[id];
if (iterator) {
if (iterator(ref)) { list.push(ref); }
} else {
list.push(ref);
}
}
}
}
}
return list;
}
|
javascript
|
{
"resource": ""
}
|
q51096
|
getRelationshipsOf
|
train
|
function getRelationshipsOf(model, iterator) {
var i,
len,
ref,
refs = getRefsTo(model),
results = [];
function _add(rel) {
if (!_.contains(results, rel)) {
results.push(rel);
}
}
for (i = 0, len = refs.length; i < len; i++) {
ref = refs[i];
// for DirectedRelationship
if ((ref instanceof Core.DirectedRelationship) && (ref.source === model || ref.target === model)) {
if (iterator) {
if (iterator(ref)) {
_add(ref);
}
} else {
_add(ref);
}
}
// for UndirectedRelationship
if ((ref instanceof Core.RelationshipEnd) && (ref.reference === model)) {
if (iterator) {
if (iterator(ref._parent)) {
_add(ref._parent);
}
} else {
_add(ref._parent);
}
}
}
return results;
}
|
javascript
|
{
"resource": ""
}
|
q51097
|
getViewsOf
|
train
|
function getViewsOf(model) {
return getRefsTo(model, function (ref) {
return (ref instanceof Core.View) && (ref.model === model);
});
}
|
javascript
|
{
"resource": ""
}
|
q51098
|
getEdgeViewsOf
|
train
|
function getEdgeViewsOf(view) {
return getRefsTo(view, function (ref) {
return (ref instanceof Core.EdgeView) &&
(ref.head === view || ref.tail === view);
});
}
|
javascript
|
{
"resource": ""
}
|
q51099
|
getClient
|
train
|
function getClient(credentials) {
return new Promise((resolve, reject) => {
const ftp = new Ftp(credentials);
ftp.once('connect', () => {
resolve(ftp);
});
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.