_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q22100
|
onMouseUp
|
train
|
function onMouseUp(e) {
// Cancel the timeout preventing the click event from triggering
clearTimeout(preventClickTimeout);
let eventType = EVENTS.MOUSE_UP;
if (isClickEvent) {
eventType = EVENTS.MOUSE_CLICK;
}
// Calculate our current points in page and image coordinates
const currentPoints = {
page: external.cornerstoneMath.point.pageToPoint(e),
image: external.cornerstone.pageToPixel(element, e.pageX, e.pageY),
client: {
x: e.clientX,
y: e.clientY,
},
};
currentPoints.canvas = external.cornerstone.pixelToCanvas(
element,
currentPoints.image
);
// Calculate delta values in page and image coordinates
const deltaPoints = {
page: external.cornerstoneMath.point.subtract(
currentPoints.page,
lastPoints.page
),
image: external.cornerstoneMath.point.subtract(
currentPoints.image,
lastPoints.image
),
client: external.cornerstoneMath.point.subtract(
currentPoints.client,
lastPoints.client
),
canvas: external.cornerstoneMath.point.subtract(
currentPoints.canvas,
lastPoints.canvas
),
};
logger.log('mouseup: %o', getEventButtons(e));
const eventData = {
event: e,
buttons: getEventButtons(e),
viewport: external.cornerstone.getViewport(element),
image: enabledElement.image,
element,
startPoints,
lastPoints,
currentPoints,
deltaPoints,
type: eventType,
};
triggerEvent(eventData.element, eventType, eventData);
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
element.addEventListener('mousemove', mouseMove);
isClickEvent = true;
}
|
javascript
|
{
"resource": ""
}
|
q22101
|
removeFromList
|
train
|
function removeFromList(imageIdIndex) {
const index = stackPrefetch.indicesToRequest.indexOf(imageIdIndex);
if (index > -1) {
// Don't remove last element if imageIdIndex not found
stackPrefetch.indicesToRequest.splice(index, 1);
}
}
|
javascript
|
{
"resource": ""
}
|
q22102
|
clearImageIdSpecificToolStateManager
|
train
|
function clearImageIdSpecificToolStateManager(element) {
const enabledElement = external.cornerstone.getEnabledElement(element);
if (
!enabledElement.image ||
toolState.hasOwnProperty(enabledElement.image.imageId) === false
) {
return;
}
delete toolState[enabledElement.image.imageId];
}
|
javascript
|
{
"resource": ""
}
|
q22103
|
stopClip
|
train
|
function stopClip(element) {
const playClipToolData = getToolState(element, toolType);
if (
!playClipToolData ||
!playClipToolData.data ||
!playClipToolData.data.length
) {
return;
}
stopClipWithData(playClipToolData.data[0]);
}
|
javascript
|
{
"resource": ""
}
|
q22104
|
removeEnabledElementCallback
|
train
|
function removeEnabledElementCallback(enabledElement) {
if (!external.cornerstone) {
return;
}
const cornerstoneEnabledElement = external.cornerstone.getEnabledElement(
enabledElement
);
const enabledElementUID = cornerstoneEnabledElement.uuid;
const colormap = external.cornerstone.colors.getColormap(state.colorMapId);
const numberOfColors = colormap.getNumberOfColors();
// Remove enabledElement specific data.
delete state.visibleSegmentations[enabledElementUID];
delete state.imageBitmapCache[enabledElementUID];
}
|
javascript
|
{
"resource": ""
}
|
q22105
|
_getNextColorPair
|
train
|
function _getNextColorPair() {
const indexPair = [colorPairIndex];
if (colorPairIndex < distinctColors.length - 1) {
colorPairIndex++;
indexPair.push(colorPairIndex);
} else {
colorPairIndex = 0;
indexPair.push(colorPairIndex);
}
return indexPair;
}
|
javascript
|
{
"resource": ""
}
|
q22106
|
train
|
function(enabledElement) {
// Note: We may want to `setToolDisabled` before removing from store
// Or take other action to remove any lingering eventListeners/state
store.state.tools = store.state.tools.filter(
tool => tool.element !== enabledElement
);
}
|
javascript
|
{
"resource": ""
}
|
|
q22107
|
train
|
function(enabledElement) {
if (store.modules) {
_cleanModulesOnElement(enabledElement);
}
const foundElementIndex = store.state.enabledElements.findIndex(
element => element === enabledElement
);
if (foundElementIndex > -1) {
store.state.enabledElements.splice(foundElementIndex, 1);
} else {
logger.warn('unable to remove element');
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22108
|
_cleanModulesOnElement
|
train
|
function _cleanModulesOnElement(enabledElement) {
const modules = store.modules;
Object.keys(modules).forEach(function(key) {
if (typeof modules[key].removeEnabledElementCallback === 'function') {
modules[key].removeEnabledElementCallback(enabledElement);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q22109
|
_drawImageBitmap
|
train
|
function _drawImageBitmap(evt, imageBitmap, alwaysVisible) {
const eventData = evt.detail;
const context = getNewContext(eventData.canvasContext.canvas);
const canvasTopLeft = external.cornerstone.pixelToCanvas(eventData.element, {
x: 0,
y: 0,
});
const canvasTopRight = external.cornerstone.pixelToCanvas(eventData.element, {
x: eventData.image.width,
y: 0,
});
const canvasBottomRight = external.cornerstone.pixelToCanvas(
eventData.element,
{
x: eventData.image.width,
y: eventData.image.height,
}
);
const cornerstoneCanvasWidth = external.cornerstoneMath.point.distance(
canvasTopLeft,
canvasTopRight
);
const cornerstoneCanvasHeight = external.cornerstoneMath.point.distance(
canvasTopRight,
canvasBottomRight
);
const canvas = eventData.canvasContext.canvas;
const viewport = eventData.viewport;
context.imageSmoothingEnabled = false;
context.globalAlpha = getLayerAlpha(alwaysVisible);
transformCanvasContext(context, canvas, viewport);
const canvasViewportTranslation = {
x: viewport.translation.x * viewport.scale,
y: viewport.translation.y * viewport.scale,
};
context.drawImage(
imageBitmap,
canvas.width / 2 - cornerstoneCanvasWidth / 2 + canvasViewportTranslation.x,
canvas.height / 2 -
cornerstoneCanvasHeight / 2 +
canvasViewportTranslation.y,
cornerstoneCanvasWidth,
cornerstoneCanvasHeight
);
context.globalAlpha = 1.0;
resetCanvasContextTransform(context);
}
|
javascript
|
{
"resource": ""
}
|
q22110
|
getDefaultFreehandSculpterMouseToolConfiguration
|
train
|
function getDefaultFreehandSculpterMouseToolConfiguration() {
return {
mouseLocation: {
handles: {
start: {
highlight: true,
active: true,
},
},
},
minSpacing: 1,
currentTool: null,
dragColor: toolColors.getActiveColor(),
hoverColor: toolColors.getToolColor(),
/* --- Hover options ---
showCursorOnHover: Shows a preview of the sculpting radius on hover.
limitRadiusOutsideRegion: Limit max toolsize outside the subject ROI based
on subject ROI area.
hoverCursorFadeAlpha: Alpha to fade to when tool very distant from
subject ROI.
hoverCursorFadeDistance: Distance from ROI in which to fade the hoverCursor
(in units of radii).
*/
showCursorOnHover: true,
limitRadiusOutsideRegion: true,
hoverCursorFadeAlpha: 0.5,
hoverCursorFadeDistance: 1.2,
};
}
|
javascript
|
{
"resource": ""
}
|
q22111
|
setToolCursor
|
train
|
function setToolCursor(element, svgCursor) {
if (!globalConfiguration.state.showSVGCursors) {
return;
}
// TODO: (state vs options) Exit if cursor wasn't updated
// TODO: Exit if invalid options to create cursor
// Note: Max size of an SVG cursor is 128x128, default is 32x32.
const cursorBlob = svgCursor.getIconWithPointerSVG();
const mousePoint = svgCursor.mousePoint;
const svgCursorUrl = window.URL.createObjectURL(cursorBlob);
element.style.cursor = `url('${svgCursorUrl}') ${mousePoint}, auto`;
state.svgCursorUrl = svgCursorUrl;
}
|
javascript
|
{
"resource": ""
}
|
q22112
|
_getEllipseImageCoordinates
|
train
|
function _getEllipseImageCoordinates(startHandle, endHandle) {
return {
left: Math.round(Math.min(startHandle.x, endHandle.x)),
top: Math.round(Math.min(startHandle.y, endHandle.y)),
width: Math.round(Math.abs(startHandle.x - endHandle.x)),
height: Math.round(Math.abs(startHandle.y - endHandle.y)),
};
}
|
javascript
|
{
"resource": ""
}
|
q22113
|
train
|
function(enabledElement) {
store.state.enabledElements.push(enabledElement);
if (store.modules) {
_initModulesOnElement(enabledElement);
}
_addGlobalToolsToElement(enabledElement);
_repeatGlobalToolHistory(enabledElement);
}
|
javascript
|
{
"resource": ""
}
|
|
q22114
|
_initModulesOnElement
|
train
|
function _initModulesOnElement(enabledElement) {
const modules = store.modules;
Object.keys(modules).forEach(function(key) {
if (typeof modules[key].enabledElementCallback === 'function') {
modules[key].enabledElementCallback(enabledElement);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q22115
|
_addGlobalToolsToElement
|
train
|
function _addGlobalToolsToElement(enabledElement) {
if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) {
return;
}
Object.keys(store.state.globalTools).forEach(function(key) {
const { tool, configuration } = store.state.globalTools[key];
addToolForElement(enabledElement, tool, configuration);
});
}
|
javascript
|
{
"resource": ""
}
|
q22116
|
_repeatGlobalToolHistory
|
train
|
function _repeatGlobalToolHistory(enabledElement) {
if (!store.modules.globalConfiguration.state.globalToolSyncEnabled) {
return;
}
const setToolModeFns = {
active: setToolActiveForElement,
passive: setToolPassiveForElement,
enabled: setToolEnabledForElement,
disabled: setToolDisabledForElement,
};
store.state.globalToolChangeHistory.forEach(historyEvent => {
const args = historyEvent.args.slice(0);
args.unshift(enabledElement);
setToolModeFns[historyEvent.mode].apply(null, args);
});
}
|
javascript
|
{
"resource": ""
}
|
q22117
|
fireEvent
|
train
|
function fireEvent(sourceElement, eventData) {
const isDisabled = !that.enabled;
const noElements = !sourceElements.length || !targetElements.length;
if (isDisabled || noElements) {
return;
}
ignoreFiredEvents = true;
targetElements.forEach(function(targetElement) {
const targetIndex = targetElements.indexOf(targetElement);
if (targetIndex === -1) {
return;
}
const targetImageId = initialData.imageIds.targetElements[targetIndex];
const sourceIndex = sourceElements.indexOf(sourceElement);
if (sourceIndex === -1) {
return;
}
const sourceImageId = initialData.imageIds.sourceElements[sourceIndex];
let positionDifference;
if (sourceImageId === targetImageId) {
positionDifference = 0;
} else if (initialData.distances[sourceImageId] !== undefined) {
positionDifference =
initialData.distances[sourceImageId][targetImageId];
}
eventHandler(
that,
sourceElement,
targetElement,
eventData,
positionDifference
);
});
ignoreFiredEvents = false;
}
|
javascript
|
{
"resource": ""
}
|
q22118
|
onEvent
|
train
|
function onEvent(e) {
const eventData = e.detail;
if (ignoreFiredEvents === true) {
return;
}
fireEvent(e.currentTarget, eventData);
}
|
javascript
|
{
"resource": ""
}
|
q22119
|
disableHandler
|
train
|
function disableHandler(e) {
const element = e.detail.element;
that.remove(element);
clearToolOptionsByElement(element);
}
|
javascript
|
{
"resource": ""
}
|
q22120
|
createVisualization
|
train
|
function createVisualization(data) {
var json = buildHierarchy(data);
// Basic setup of page elements.
initializeBreadcrumbTrail();
// Bounding circle underneath the sunburst, to make it easier to detect
// when the mouse leaves the parent g.
vis.append("svg:circle")
.attr("r", radius)
.style("opacity", 0);
// For efficiency, filter nodes to keep only those large enough to see.
var nodes = partition.nodes(json)
.filter(function(d) {
return (d.dx > 0.005); // 0.005 radians = 0.29 degrees
});
var path = vis.data([json]).selectAll("path")
.data(nodes)
.enter().append("svg:path")
.attr("display", function(d) { return d.depth ? null : "none"; })
.attr("d", arc)
.attr("fill-rule", "evenodd")
.style("fill", function(d) { return colors[d.depth]; })
.style("opacity", 1)
.on("mouseover", mouseover);
// Add the mouseleave handler to the bounding circle.
d3.select("#container").on("mouseleave", mouseleave);
// Get total size of the tree = value of root node from partition.
totalSize = path.node().__data__.value;
}
|
javascript
|
{
"resource": ""
}
|
q22121
|
mouseover
|
train
|
function mouseover(d) {
var percentage = (100 * d.value / totalSize).toPrecision(3);
var percentageString = percentage + "%";
if (percentage < 0.1) {
percentageString = "< 0.1%";
}
d3.select("#percentage")
.text(percentageString);
d3.select("#explanation")
.style("visibility", "");
var sequenceArray = getAncestors(d);
updateBreadcrumbs(sequenceArray, percentageString);
// Fade all the segments.
d3.selectAll("path")
.style("opacity", 0.3);
// Then highlight only those that are an ancestor of the current segment.
vis.selectAll("path")
.filter(function(node) {
return (sequenceArray.indexOf(node) >= 0);
})
.style("opacity", 1);
}
|
javascript
|
{
"resource": ""
}
|
q22122
|
mouseleave
|
train
|
function mouseleave(d) {
// Hide the breadcrumb trail
d3.select("#trail")
.style("visibility", "hidden");
// Deactivate all segments during transition.
d3.selectAll("path").on("mouseover", null);
// Transition each segment to full opacity and then reactivate it.
d3.selectAll("path")
.transition()
.duration(250)
.style("opacity", 1)
.each("end", function() {
d3.select(this).on("mouseover", mouseover);
});
d3.select("#explanation")
.style("visibility", "hidden");
}
|
javascript
|
{
"resource": ""
}
|
q22123
|
getAncestors
|
train
|
function getAncestors(node) {
var path = [];
var current = node;
while (current.parent) {
path.unshift(current);
current = current.parent;
}
return path;
}
|
javascript
|
{
"resource": ""
}
|
q22124
|
breadcrumbPoints
|
train
|
function breadcrumbPoints(d, i) {
var points = [];
points.push("0,0");
points.push(b.w + ",0");
points.push(b.w + b.t + "," + (b.h / 2));
points.push(b.w + "," + b.h);
points.push("0," + b.h);
if (i > 0) { // Leftmost breadcrumb; don't include 6th vertex.
points.push(b.t + "," + (b.h / 2));
}
return points.join(" ");
}
|
javascript
|
{
"resource": ""
}
|
q22125
|
updateBreadcrumbs
|
train
|
function updateBreadcrumbs(nodeArray, percentageString) {
// Data join; key function combines name and depth (= position in sequence).
var g = d3.select("#trail")
.selectAll("g")
.data(nodeArray, function(d) { return d.name + d.depth; });
// Add breadcrumb and label for entering nodes.
var entering = g.enter().append("svg:g");
entering.append("svg:polygon")
.attr("points", breadcrumbPoints)
.style("fill", function(d) { return colors[d.name]; });
entering.append("svg:text")
.attr("x", (b.w + b.t) / 2)
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; });
// Set position for entering and updating nodes.
g.attr("transform", function(d, i) {
return "translate(" + i * (b.w + b.s) + ", 0)";
});
// Remove exiting nodes.
g.exit().remove();
// Now move and update the percentage at the end.
d3.select("#trail").select("#endlabel")
.attr("x", (nodeArray.length + 0.5) * (b.w + b.s))
.attr("y", b.h / 2)
.attr("dy", "0.35em")
.attr("text-anchor", "middle")
.text(percentageString);
// Make the breadcrumb trail visible, if it's hidden.
d3.select("#trail")
.style("visibility", "");
}
|
javascript
|
{
"resource": ""
}
|
q22126
|
buildHierarchy
|
train
|
function buildHierarchy(csv) {
var root = {"name": "root", "children": []};
for (var i = 0; i < csv.length; i++) {
var sequence = csv[i][0];
var size = +csv[i][1];
if (isNaN(size)) { // e.g. if this is a header row
continue;
}
var parts = sequence.split("/");
var currentNode = root;
for (var j = 0; j < parts.length; j++) {
var children = currentNode["children"];
var nodeName = parts[j];
var childNode;
if (j + 1 < parts.length) {
// Not yet at the end of the sequence; move down the tree.
var foundChild = false;
for (var k = 0; k < children.length; k++) {
if (children[k]["name"] == nodeName) {
childNode = children[k];
foundChild = true;
break;
}
}
// If we don't already have a child node for this branch, create it.
if (!foundChild) {
childNode = {"name": nodeName, "children": []};
children.push(childNode);
}
currentNode = childNode;
} else {
// Reached the end of the sequence; create a leaf node.
childNode = {"name": nodeName, "size": size};
children.push(childNode);
}
}
}
return root;
}
|
javascript
|
{
"resource": ""
}
|
q22127
|
queryResource
|
train
|
function queryResource (req, res, next, dataStore) {
let resource = new Resource(req.path);
dataStore.get(resource, (err, result) => {
if (err) {
next(err);
}
else if (!result) {
let defaultValue = getDefaultValue(res);
if (defaultValue === undefined) {
util.debug("ERROR! 404 - %s %s does not exist", req.method, req.path);
err = ono({ status: 404 }, "%s Not Found", resource.toString());
next(err);
}
else {
// There' a default value, so use it instead of sending a 404
util.debug(
"%s %s does not exist, but the response schema defines a fallback value. So, using the fallback value",
req.method, req.path
);
res.swagger.lastModified = new Date();
res.body = defaultValue;
next();
}
}
else {
res.swagger.lastModified = result.modifiedOn;
// Set the response body (unless it's already been set by other middleware)
res.body = res.body || result.data;
next();
}
});
}
|
javascript
|
{
"resource": ""
}
|
q22128
|
createMiddleware
|
train
|
function createMiddleware (swagger, router, callback) {
// Shift args if needed
if (util.isExpressRouter(swagger)) {
router = swagger;
swagger = callback = undefined;
}
else if (!util.isExpressRouter(router)) {
callback = router;
router = undefined;
}
let middleware = new module.exports.Middleware(router);
if (swagger) {
middleware.init(swagger, callback);
}
return middleware;
}
|
javascript
|
{
"resource": ""
}
|
q22129
|
mergeResource
|
train
|
function mergeResource (req, res, next, dataStore) {
let resource = createResource(req);
// Save/Update the resource
util.debug("Saving data at %s", resource.toString());
dataStore.save(resource, sendResponse(req, res, next, dataStore));
}
|
javascript
|
{
"resource": ""
}
|
q22130
|
overwriteResource
|
train
|
function overwriteResource (req, res, next, dataStore) {
let resource = createResource(req);
// Delete the existing resource, if any
dataStore.delete(resource, (err) => {
if (err) {
next(err);
}
else {
// Save the new resource
util.debug("Saving data at %s", resource.toString());
dataStore.save(resource, sendResponse(req, res, next, dataStore));
}
});
}
|
javascript
|
{
"resource": ""
}
|
q22131
|
deleteResource
|
train
|
function deleteResource (req, res, next, dataStore) { // jshint ignore:line
let resource = createResource(req);
// Delete the resource
dataStore.delete(resource, (err, deletedResource) => {
// Respond with the deleted resource, if possible; otherwise, use the empty resource we just created.
sendResponse(req, res, next, dataStore)(err, deletedResource || resource);
});
}
|
javascript
|
{
"resource": ""
}
|
q22132
|
Middleware
|
train
|
function Middleware (sharedRouter) {
sharedRouter = util.isExpressRouter(sharedRouter) ? sharedRouter : undefined;
let self = this;
let context = new MiddlewareContext(sharedRouter);
/**
* Initializes the middleware with the given Swagger API.
* This method can be called again to re-initialize with a new or modified API.
*
* @param {string|object} [swagger]
* - The file path or URL of a Swagger 2.0 API spec, in YAML or JSON format.
* Or a valid Swagger API object (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object).
*
* @param {function} [callback]
* - It will be called when the API has been parsed, validated, and dereferenced, or when an error occurs.
*/
this.init = function (swagger, callback) {
// the swagger variable should only ever be a string or a populated object.
let invalidSwagger = _.isFunction(swagger) || _.isDate(swagger) || _.isEmpty(swagger);
if (invalidSwagger) {
throw new Error("Expected a Swagger file or object");
}
// Need to retrieve the Swagger API and metadata from the Swagger .yaml or .json file.
let parser = new SwaggerParser();
parser.dereference(swagger, (err, api) => {
if (err) {
util.warn(err);
}
context.error = err;
context.api = api;
context.parser = parser;
context.emit("change");
if (_.isFunction(callback)) {
callback(err, self, context.api, context.parser);
}
});
};
/**
* Serves the Swagger API file(s) in JSON and YAML formats,
* so they can be used with third-party front-end tools like Swagger UI and Swagger Editor.
*
* @param {express#Router} [router]
* - Express routing options (e.g. `caseSensitive`, `strict`).
* If an Express Application or Router is passed, then its routing settings will be used.
*
* @param {fileServer.defaultOptions} [options]
* - Options for how the files are served (see {@link fileServer.defaultOptions})
*
* @returns {function[]}
*/
this.files = function (router, options) {
if (arguments.length === 1 && !util.isExpressRouter(router) && !util.isExpressRoutingOptions(router)) {
// Shift arguments
options = router;
router = sharedRouter;
}
return fileServer(context, router, options);
};
/**
* Annotates the HTTP request (the `req` object) with Swagger metadata.
* This middleware populates {@link Request#swagger}.
*
* @param {express#Router} [router]
* - Express routing options (e.g. `caseSensitive`, `strict`).
* If an Express Application or Router is passed, then its routing settings will be used.
*
* @returns {function[]}
*/
this.metadata = function (router) {
return requestMetadata(context, router);
};
/**
* Handles CORS preflight requests and sets CORS headers for all requests
* according the Swagger API definition.
*
* @returns {function[]}
*/
this.CORS = function () {
return CORS();
};
/**
* Parses the HTTP request into typed values.
* This middleware populates {@link Request#params}, {@link Request#headers}, {@link Request#cookies},
* {@link Request#signedCookies}, {@link Request#query}, {@link Request#body}, and {@link Request#files}.
*
* @param {express#Router} [router]
* - An Express Application or Router. If provided, this will be used to register path-param middleware
* via {@link Router#param} (see http://expressjs.com/4x/api.html#router.param).
* If not provided, then path parameters will always be parsed as strings.
*
* @param {requestParser.defaultOptions} [options]
* - Options for each of the request-parsing middleware (see {@link requestParser.defaultOptions})
*
* @returns {function[]}
*/
this.parseRequest = function (router, options) {
if (arguments.length === 1 && !util.isExpressRouter(router) && !util.isExpressRoutingOptions(router)) {
// Shift arguments
options = router;
router = sharedRouter;
}
return requestParser(options)
.concat(paramParser())
.concat(pathParser(context, router));
};
/**
* Validates the HTTP request against the Swagger API.
* An error is sent downstream if the request is invalid for any reason.
*
* @returns {function[]}
*/
this.validateRequest = function () {
return requestValidator(context);
};
/**
* Implements mock behavior for HTTP requests, based on the Swagger API.
*
* @param {express#Router} [router]
* - Express routing options (e.g. `caseSensitive`, `strict`).
* If an Express Application or Router is passed, then its routing settings will be used.
*
* @param {DataStore} [dataStore]
* - The data store that will be used to persist REST resources.
* If `router` is an Express Application, then you can set/get the data store
* using `router.get("mock data store")`.
*
* @returns {function[]}
*/
this.mock = function (router, dataStore) {
if (arguments.length === 1 &&
router instanceof DataStore) {
// Shift arguments
dataStore = router;
router = undefined;
}
return mock(context, router, dataStore);
};
}
|
javascript
|
{
"resource": ""
}
|
q22133
|
Resource
|
train
|
function Resource (path, name, data) {
switch (arguments.length) {
case 0:
this.collection = "";
this.name = "/";
this.data = undefined;
break;
case 1:
this.collection = getCollectionFromPath(path);
this.name = getNameFromPath(path);
this.data = undefined;
break;
case 2:
this.merge(name);
this.collection = getCollectionFromPath(path);
this.name = getNameFromPath(path);
break;
default:
this.collection = normalizeCollection(path);
this.name = normalizeName(name);
this.merge(data);
}
this.createdOn = null;
this.modifiedOn = null;
}
|
javascript
|
{
"resource": ""
}
|
q22134
|
getCollectionFromPath
|
train
|
function getCollectionFromPath (path) {
path = _(path).toString();
let lastSlash = path.substring(0, path.length - 1).lastIndexOf("/");
if (lastSlash === -1) {
return "";
}
else {
return normalizeCollection(path.substring(0, lastSlash));
}
}
|
javascript
|
{
"resource": ""
}
|
q22135
|
getNameFromPath
|
train
|
function getNameFromPath (path) {
path = _(path).toString();
let lastSlash = path.substring(0, path.length - 1).lastIndexOf("/");
if (lastSlash === -1) {
return normalizeName(path);
}
else {
return normalizeName(path.substring(lastSlash));
}
}
|
javascript
|
{
"resource": ""
}
|
q22136
|
normalizeCollection
|
train
|
function normalizeCollection (collection) {
// Normalize the root path as an empty string
collection = _(collection).toString();
if (_.isEmpty(collection) || collection === "/" || collection === "//") {
return "";
}
// Add a leading slash
if (!_.startsWith(collection, "/")) {
collection = "/" + collection;
}
// Remove a trailing slash
if (_.endsWith(collection, "/")) {
collection = collection.substring(0, collection.length - 1);
}
return collection;
}
|
javascript
|
{
"resource": ""
}
|
q22137
|
normalizeName
|
train
|
function normalizeName (name) {
// Normalize directories as a single slash
name = _(name).toString();
if (_.isEmpty(name) || name === "/" || name === "//") {
return "/";
}
// Add a leading slash
if (!_.startsWith(name, "/")) {
name = "/" + name;
}
// Don't allow slashes in the middle
if (_.includes(name.substring(1, name.length - 1), "/")) {
throw ono("Resource names cannot contain slashes");
}
return name;
}
|
javascript
|
{
"resource": ""
}
|
q22138
|
save
|
train
|
function save (dataStore, collectionName, resources, callback) {
// Open the data store
dataStore.__openDataStore(collectionName, (err, existingResources) => {
if (err) {
return callback(err);
}
resources.forEach((resource) => {
// Set the timestamp properties
let now = Date.now();
resource.createdOn = new Date(now);
resource.modifiedOn = new Date(now);
// Does the resource already exist?
let existing = _.find(existingResources, resource.filter(dataStore.__router));
if (existing) {
// Merge the new data into the existing resource
util.debug("%s already exists. Merging new data with existing data.", resource.toString());
existing.merge(resource);
// Update the calling code's reference to the resource
_.extend(resource, existing);
}
else {
existingResources.push(resource);
}
});
// Save the changes
dataStore.__saveDataStore(collectionName, existingResources, (err) => {
callback(err, resources);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q22139
|
remove
|
train
|
function remove (dataStore, collectionName, resources, callback) {
// Open the data store
dataStore.__openDataStore(collectionName, (err, existingResources) => {
if (err) {
return callback(err);
}
// Remove the resources from the existing resources
let removedResources = [];
resources.forEach((resource) => {
let removed = _.remove(existingResources, resource.filter(dataStore.__router));
removedResources = removedResources.concat(removed);
});
if (removedResources.length > 0) {
// Save the changes
dataStore.__saveDataStore(collectionName, existingResources, (err) => {
if (err) {
callback(err);
}
else {
callback(null, removedResources);
}
});
}
else {
callback(null, []);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q22140
|
openCollection
|
train
|
function openCollection (dataStore, collection, callback) {
if (_.isString(collection)) {
collection = new Resource(collection, "", "");
}
else if (!(collection instanceof Resource)) {
throw ono("Expected a string or Resource object. Got a %s instead.", typeof (collection));
}
// Normalize the collection name
let collectionName = collection.valueOf(dataStore.__router, true);
// Open the data store
dataStore.__openDataStore(collectionName, (err, resources) => {
callback(err, collection, resources);
});
}
|
javascript
|
{
"resource": ""
}
|
q22141
|
doCallback
|
train
|
function doCallback (callback, err, arg) {
if (_.isFunction(callback)) {
callback(err, arg);
}
}
|
javascript
|
{
"resource": ""
}
|
q22142
|
parseSimpleParams
|
train
|
function parseSimpleParams (req, res, next) {
let params = getParams(req);
if (params.length > 0) {
util.debug("Parsing %d request parameters...", params.length);
params.forEach((param) => {
// Get the raw value of the parameter
switch (param.in) {
case "query":
util.debug(' Parsing the "%s" query parameter', param.name);
req.query[param.name] = parseParameter(param, req.query[param.name], param);
break;
case "header":
// NOTE: req.headers properties are always lower-cased
util.debug(' Parsing the "%s" header parameter', param.name);
req.headers[param.name.toLowerCase()] = parseParameter(param, req.header(param.name), param);
break;
}
});
}
next();
}
|
javascript
|
{
"resource": ""
}
|
q22143
|
parseFormDataParams
|
train
|
function parseFormDataParams (req, res, next) {
getParams(req).forEach((param) => {
if (param.in === "formData") {
util.debug(' Parsing the "%s" form-data parameter', param.name);
if (param.type === "file") {
// Validate the file (min/max size, etc.)
req.files[param.name] = parseParameter(param, req.files[param.name], param);
}
else {
// Parse the body parameter
req.body[param.name] = parseParameter(param, req.body[param.name], param);
}
}
});
next();
}
|
javascript
|
{
"resource": ""
}
|
q22144
|
parseBodyParam
|
train
|
function parseBodyParam (req, res, next) {
let params = getParams(req);
params.some((param) => {
if (param.in === "body") {
util.debug(' Parsing the "%s" body parameter', param.name);
if (_.isPlainObject(req.body) && _.isEmpty(req.body)) {
if (param.type === "string" || (param.schema && param.schema.type === "string")) {
// Convert {} to ""
req.body = "";
}
else {
// Convert {} to undefined
req.body = undefined;
}
}
// Parse the body
req.body = parseParameter(param, req.body, param.schema);
// There can only be one "body" parameter, so skip the rest
return true;
}
});
// If there are no body/formData parameters, then reset `req.body` to undefined
if (params.length > 0) {
let hasBody = params.some((param) => {
return param.in === "body" || param.in === "formData";
});
if (!hasBody) {
req.body = undefined;
}
}
next();
}
|
javascript
|
{
"resource": ""
}
|
q22145
|
parseParameter
|
train
|
function parseParameter (param, value, schema) {
if (value === undefined) {
if (param.required) {
// The parameter is required, but was not provided, so throw a 400 error
let errCode = 400;
if (param.in === "header" && param.name.toLowerCase() === "content-length") {
// Special case for the Content-Length header. It has it's own HTTP error code.
errCode = 411; // (Length Required)
}
// noinspection ExceptionCaughtLocallyJS
throw ono({ status: errCode }, 'Missing required %s parameter "%s"', param.in, param.name);
}
else if (schema.default === undefined) {
// The parameter is optional, and there's no default value
return undefined;
}
}
// Special case for the Content-Length header. It has it's own HTTP error code (411 Length Required)
if (value === "" && param.in === "header" && param.name.toLowerCase() === "content-length") {
throw ono({ status: 411 }, 'Missing required header parameter "%s"', param.name);
}
try {
return new JsonSchema(schema).parse(value);
}
catch (e) {
throw ono(e, { status: e.status }, 'The "%s" %s parameter is invalid (%j)',
param.name, param.in, value === undefined ? param.default : value);
}
}
|
javascript
|
{
"resource": ""
}
|
q22146
|
getParams
|
train
|
function getParams (req) {
if (req.swagger && req.swagger.params) {
return req.swagger.params;
}
return [];
}
|
javascript
|
{
"resource": ""
}
|
q22147
|
getDirectory
|
train
|
function getDirectory (baseDir, collection) {
let dir = collection.substring(0, collection.lastIndexOf("/"));
dir = dir.toLowerCase();
return path.normalize(path.join(baseDir, dir));
}
|
javascript
|
{
"resource": ""
}
|
q22148
|
getFilePath
|
train
|
function getFilePath (baseDir, collection) {
let directory = getDirectory(baseDir, collection);
let fileName = collection.substring(collection.lastIndexOf("/") + 1) + ".json";
fileName = fileName.toLowerCase();
return path.join(directory, fileName);
}
|
javascript
|
{
"resource": ""
}
|
q22149
|
requestValidator
|
train
|
function requestValidator (context) {
return [http500, http401, http404, http405, http406, http413, http415];
/**
* Throws an HTTP 500 error if the Swagger API is invalid.
* Calling {@link Middleware#init} again with a valid Swagger API will clear the error.
*/
function http500 (req, res, next) {
if (context.error) {
context.error.status = 500;
throw context.error;
}
next();
}
}
|
javascript
|
{
"resource": ""
}
|
q22150
|
queryCollection
|
train
|
function queryCollection (req, res, next, dataStore) {
dataStore.getCollection(req.path, (err, resources) => {
if (!err) {
resources = filter(resources, req);
if (resources.length === 0) {
// There is no data, so use the current date/time as the "last-modified" header
res.swagger.lastModified = new Date();
// Use the default/example value, if there is one
if (res.swagger.schema) {
resources = res.swagger.schema.default || res.swagger.schema.example || [];
}
}
else {
// Determine the max "modifiedOn" date of the remaining items
res.swagger.lastModified = _.maxBy(resources, "modifiedOn").modifiedOn;
// Extract the "data" of each Resource
resources = _.map(resources, "data");
}
// Set the response body (unless it's already been set by other middleware)
res.body = res.body || resources;
}
next(err);
});
}
|
javascript
|
{
"resource": ""
}
|
q22151
|
deleteCollection
|
train
|
function deleteCollection (req, res, next, dataStore) {
dataStore.getCollection(req.path, (err, resources) => {
if (err) {
next(err);
}
else {
// Determine which resources to delete, based on query params
let resourcesToDelete = filter(resources, req);
if (resourcesToDelete.length === 0) {
sendResponse(null, []);
}
else if (resourcesToDelete.length === resources.length) {
// Delete the whole collection
dataStore.deleteCollection(req.path, sendResponse);
}
else {
// Only delete the matching resources
dataStore.delete(resourcesToDelete, sendResponse);
}
}
});
// Responds with the deleted resources
function sendResponse (err, resources) {
// Extract the "data" of each Resource
resources = _.map(resources, "data");
// Use the current date/time as the "last-modified" header
res.swagger.lastModified = new Date();
// Set the response body (unless it's already been set by other middleware)
if (err || res.body) {
next(err);
}
else if (!res.swagger.isCollection) {
// Response body is a single value, so only return the first item in the collection
res.body = _.first(resources);
next();
}
else {
// Response body is the resource that was created/update/deleted
res.body = resources;
next();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22152
|
sendResponse
|
train
|
function sendResponse (err, resources) {
// Extract the "data" of each Resource
resources = _.map(resources, "data");
// Use the current date/time as the "last-modified" header
res.swagger.lastModified = new Date();
// Set the response body (unless it's already been set by other middleware)
if (err || res.body) {
next(err);
}
else if (!res.swagger.isCollection) {
// Response body is a single value, so only return the first item in the collection
res.body = _.first(resources);
next();
}
else {
// Response body is the resource that was created/update/deleted
res.body = resources;
next();
}
}
|
javascript
|
{
"resource": ""
}
|
q22153
|
setDeepProperty
|
train
|
function setDeepProperty (obj, propName, propValue) {
propName = propName.split(".");
for (let i = 0; i < propName.length - 1; i++) {
obj = obj[propName[i]] = obj[propName[i]] || {};
}
obj[propName[propName.length - 1]] = propValue;
}
|
javascript
|
{
"resource": ""
}
|
q22154
|
swaggerApiMetadata
|
train
|
function swaggerApiMetadata (req, res, next) {
// Only set req.swagger.api if the request is under the API's basePath
if (context.api) {
let basePath = util.normalizePath(context.api.basePath, router);
let reqPath = util.normalizePath(req.path, router);
if (_.startsWith(reqPath, basePath)) {
req.swagger.api = context.api;
}
}
next();
}
|
javascript
|
{
"resource": ""
}
|
q22155
|
swaggerPathMetadata
|
train
|
function swaggerPathMetadata (req, res, next) {
if (req.swagger.api) {
let relPath = getRelativePath(req);
let relPathNormalized = util.normalizePath(relPath, router);
// Search for a matching path
Object.keys(req.swagger.api.paths).some((swaggerPath) => {
let swaggerPathNormalized = util.normalizePath(swaggerPath, router);
if (swaggerPathNormalized === relPathNormalized) {
// We found an exact match (i.e. a path with no parameters)
req.swagger.path = req.swagger.api.paths[swaggerPath];
req.swagger.pathName = swaggerPath;
return true;
}
else if (req.swagger.path === null && pathMatches(relPathNormalized, swaggerPathNormalized)) {
// We found a possible match, but keep searching in case we find an exact match
req.swagger.path = req.swagger.api.paths[swaggerPath];
req.swagger.pathName = swaggerPath;
}
});
if (req.swagger.path) {
util.debug("%s %s matches Swagger path %s", req.method, req.path, req.swagger.pathName);
}
else {
util.warn('WARNING! Unable to find a Swagger path that matches "%s"', req.path);
}
}
next();
}
|
javascript
|
{
"resource": ""
}
|
q22156
|
swaggerMetadata
|
train
|
function swaggerMetadata (req, res, next) {
/**
* The Swagger Metadata that is added to each HTTP request.
* This object is exposed as `req.swagger`.
*
* @name Request#swagger
*/
req.swagger = {
/**
* The complete Swagger API object.
* (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object)
* @type {SwaggerObject|null}
*/
api: null,
/**
* The Swagger path name, as it appears in the Swagger API.
* (e.g. "/users/{username}/orders/{orderId}")
* @type {string}
*/
pathName: "",
/**
* The Path object from the Swagger API.
* (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#pathItemObject)
* @type {object|null}
*/
path: null,
/**
* The Operation object from the Swagger API.
* (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#operationObject)
* @type {object|null}
*/
operation: null,
/**
* The Parameter objects that apply to this request.
* (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#parameter-object-)
* @type {object[]}
*/
params: [],
/**
* The Security Requirement objects that apply to this request.
* (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#securityRequirementObject)
* @type {object[]}
*/
security: []
};
next();
}
|
javascript
|
{
"resource": ""
}
|
q22157
|
swaggerOperationMetadata
|
train
|
function swaggerOperationMetadata (req, res, next) {
if (req.swagger.path) {
let method = req.method.toLowerCase();
if (method in req.swagger.path) {
req.swagger.operation = req.swagger.path[method];
}
else {
util.warn("WARNING! Unable to find a Swagger operation that matches %s %s", req.method.toUpperCase(), req.path);
}
}
next();
}
|
javascript
|
{
"resource": ""
}
|
q22158
|
swaggerParamsMetadata
|
train
|
function swaggerParamsMetadata (req, res, next) {
req.swagger.params = util.getParameters(req.swagger.path, req.swagger.operation);
next();
}
|
javascript
|
{
"resource": ""
}
|
q22159
|
swaggerSecurityMetadata
|
train
|
function swaggerSecurityMetadata (req, res, next) {
if (req.swagger.operation) {
// Get the security requirements for this operation (or the global API security)
req.swagger.security = req.swagger.operation.security || req.swagger.api.security || [];
}
else if (req.swagger.api) {
// Get the global security requirements for the API
req.swagger.security = req.swagger.api.security || [];
}
next();
}
|
javascript
|
{
"resource": ""
}
|
q22160
|
getRelativePath
|
train
|
function getRelativePath (req) {
if (!req.swagger.api.basePath) {
return req.path;
}
else {
return req.path.substr(req.swagger.api.basePath.length);
}
}
|
javascript
|
{
"resource": ""
}
|
q22161
|
pathMatches
|
train
|
function pathMatches (path, swaggerPath) {
// Convert the Swagger path to a RegExp
let pathPattern = swaggerPath.replace(util.swaggerParamRegExp, (match, paramName) => {
return "([^/]+)";
});
// NOTE: This checks for an EXACT, case-sensitive match
let pathRegExp = new RegExp("^" + pathPattern + "$");
return pathRegExp.test(path);
}
|
javascript
|
{
"resource": ""
}
|
q22162
|
corsHeaders
|
train
|
function corsHeaders (req, res, next) {
// Get the default CORS response headers as specified in the Swagger API
let responseHeaders = getResponseHeaders(req);
// Set each CORS header
_.each(accessControl, (header) => {
if (responseHeaders[header] !== undefined) {
// Set the header to the default value from the Swagger API
res.set(header, responseHeaders[header]);
}
else {
// Set the header to a sensible default
switch (header) {
case accessControl.allowOrigin:
// By default, allow the origin host. Fallback to wild-card.
res.set(header, req.get("Origin") || "*");
break;
case accessControl.allowMethods:
if (req.swagger && req.swagger.path) {
// Return the allowed methods for this Swagger path
res.set(header, util.getAllowedMethods(req.swagger.path));
}
else {
// By default, allow all of the requested methods. Fallback to ALL methods.
res.set(header, req.get("Access-Control-Request-Method") || swaggerMethods.join(", ").toUpperCase());
}
break;
case accessControl.allowHeaders:
// By default, allow all of the requested headers
res.set(header, req.get("Access-Control-Request-Headers") || "");
break;
case accessControl.allowCredentials:
// By default, allow credentials
res.set(header, true);
break;
case accessControl.maxAge:
// By default, access-control expires immediately.
res.set(header, 0);
break;
}
}
});
if (res.get(accessControl.allowOrigin) === "*") {
// If Access-Control-Allow-Origin is wild-carded, then Access-Control-Allow-Credentials must be false
res.set("Access-Control-Allow-Credentials", "false");
}
else {
// If Access-Control-Allow-Origin is set (not wild-carded), then "Vary: Origin" must be set
res.vary("Origin");
}
next();
}
|
javascript
|
{
"resource": ""
}
|
q22163
|
corsPreflight
|
train
|
function corsPreflight (req, res, next) {
if (req.method === "OPTIONS") {
util.debug("OPTIONS %s is a CORS preflight request. Sending HTTP 200 response.", req.path);
res.send();
}
else {
next();
}
}
|
javascript
|
{
"resource": ""
}
|
q22164
|
getResponseHeaders
|
train
|
function getResponseHeaders (req) {
let corsHeaders = {};
if (req.swagger) {
let headers = [];
if (req.method !== "OPTIONS") {
// This isn't a preflight request, so the operation's response headers take precedence over the OPTIONS headers
headers = getOperationResponseHeaders(req.swagger.operation);
}
if (req.swagger.path) {
// Regardless of whether this is a preflight request, append the OPTIONS response headers
headers = headers.concat(getOperationResponseHeaders(req.swagger.path.options));
}
// Add the headers to the `corsHeaders` object. First one wins.
headers.forEach((header) => {
if (corsHeaders[header.name] === undefined) {
corsHeaders[header.name] = header.value;
}
});
}
return corsHeaders;
}
|
javascript
|
{
"resource": ""
}
|
q22165
|
JsonSchema
|
train
|
function JsonSchema (schema) {
if (!schema) {
throw ono({ status: 500 }, "Missing JSON schema");
}
if (schema.type !== undefined && dataTypes.indexOf(schema.type) === -1) {
throw ono({ status: 500 }, "Invalid JSON schema type: %s", schema.type);
}
this.schema = schema;
}
|
javascript
|
{
"resource": ""
}
|
q22166
|
getValueToValidate
|
train
|
function getValueToValidate (schema, value) {
// Is the value empty?
if (value === undefined || value === "" ||
(schema.type === "object" && _.isObject(value) && _.isEmpty(value))) {
// It's blank, so return the default/example value (if there is one)
if (schema.default !== undefined) {
value = schema.default;
}
else if (schema.example !== undefined) {
value = schema.example;
}
}
// Special case for Buffers
if (value && value.type === "Buffer" && _.isArray(value.data)) {
value = new Buffer(value.data);
}
// It's not empty, so return the existing value
return value;
}
|
javascript
|
{
"resource": ""
}
|
q22167
|
registerPathParamMiddleware
|
train
|
function registerPathParamMiddleware () {
let pathParams = getAllPathParamNames();
pathParams.forEach((param) => {
if (!alreadyRegistered(param)) {
router.param(param, pathParamMiddleware);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q22168
|
getAllPathParamNames
|
train
|
function getAllPathParamNames () {
let params = [];
function addParam (param) {
if (param.in === "path") {
params.push(param.name);
}
}
if (context.api) {
_.each(context.api.paths, (path) => {
// Add each path parameter
_.each(path.parameters, addParam);
// Add each operation parameter
_.each(path, (operation) => {
_.each(operation.parameters, addParam);
});
});
}
return _.uniq(params);
}
|
javascript
|
{
"resource": ""
}
|
q22169
|
alreadyRegistered
|
train
|
function alreadyRegistered (paramName) {
let params = router.params;
if (!params && router._router) {
params = router._router.params;
}
return params && params[paramName] &&
(params[paramName].indexOf(pathParamMiddleware) >= 0);
}
|
javascript
|
{
"resource": ""
}
|
q22170
|
serveDereferencedSwaggerFile
|
train
|
function serveDereferencedSwaggerFile (req, res, next) {
if (req.method === "GET" || req.method === "HEAD") {
let configPath = getConfiguredPath(options.apiPath);
configPath = util.normalizePath(configPath, router);
let reqPath = util.normalizePath(req.path, router);
if (reqPath === configPath) {
if (context.api) {
util.debug("%s %s => Sending the Swagger API as JSON", req.method, req.path);
res.json(context.api);
}
else {
util.warn("WARNING! The Swagger API is empty. Sending an HTTP 500 response to %s %s", req.method, req.path);
res.status(500).json({});
}
return;
}
}
next();
}
|
javascript
|
{
"resource": ""
}
|
q22171
|
getConfiguredPath
|
train
|
function getConfiguredPath (path) {
if (options.useBasePath && context.api && context.api.basePath) {
return context.api.basePath + path;
}
else {
return path;
}
}
|
javascript
|
{
"resource": ""
}
|
q22172
|
mockImplementation
|
train
|
function mockImplementation (req, res, next) {
if (res.swagger) {
// Determine the semantics of this request
let request = new SemanticRequest(req);
// Determine which mock to run
let mock;
if (request.isCollection) {
mock = queryCollection[req.method] || editCollection[req.method];
}
else {
mock = queryResource[req.method] || editResource[req.method];
}
// Get the current DataStore (this can be changed at any time by third-party code)
let db = util.isExpressApp(router) ? router.get("mock data store") || dataStore : dataStore;
db.__router = router;
// Run the mock
util.debug("Running the %s mock", mock.name);
mock(req, res, next, db);
}
else {
next();
}
}
|
javascript
|
{
"resource": ""
}
|
q22173
|
mockResponseHeaders
|
train
|
function mockResponseHeaders (req, res, next) {
if (res.swagger) {
util.debug("Setting %d response headers...", _.keys(res.swagger.headers).length);
if (res.swagger.headers) {
_.forEach(res.swagger.headers, (header, name) => {
// Set all HTTP headers that are defined in the Swagger API.
// If a default value is specified in the Swagger API, then use it; otherwise generate a value.
if (res.get(name) !== undefined) {
util.debug(" %s: %s (already set)", name, res.get(name));
}
else if (header.default !== undefined) {
res.set(name, header.default);
util.debug(" %s: %s (default)", name, header.default);
}
else {
switch (name.toLowerCase()) {
case "location":
res.location(req.baseUrl + (res.swagger.location || req.path));
break;
case "last-modified":
res.set(name, util.rfc1123(res.swagger.lastModified));
break;
case "content-disposition":
res.set(name, 'attachment; filename="' + path.basename(res.swagger.location || req.path) + '"');
break;
case "set-cookie":
// Generate a random "swagger" cookie, or re-use it if it already exists
if (req.cookies.swagger === undefined) {
res.cookie("swagger", _.uniqueId("random") + _.random(99999999999.9999));
}
else {
res.cookie("swagger", req.cookies.swagger);
}
break;
default:
// Generate a sample value from the schema
let sample = new JsonSchema(header).sample();
if (_.isDate(sample)) {
res.set(name, util.rfc1123(sample));
}
else {
res.set(name, _(sample).toString());
}
}
util.debug(" %s: %s", name, res.get(name));
}
});
}
}
next();
}
|
javascript
|
{
"resource": ""
}
|
q22174
|
mockResponseBody
|
train
|
function mockResponseBody (req, res, next) {
if (res.swagger) {
if (res.swagger.isEmpty) {
// There is no response schema, so send an empty response
util.debug("%s %s does not have a response schema. Sending an empty response", req.method, req.path);
res.send();
}
else {
// Serialize the response body according to the response schema
let schema = new JsonSchema(res.swagger.schema);
let serialized = schema.serialize(res.swagger.wrap(res.body));
switch (res.swagger.schema.type) {
case "object":
case "array":
case undefined:
sendObject(req, res, next, serialized);
break;
case "file":
sendFile(req, res, next, serialized);
break;
default:
sendText(req, res, next, serialized);
}
}
}
else {
next();
}
}
|
javascript
|
{
"resource": ""
}
|
q22175
|
sendText
|
train
|
function sendText (req, res, next, data) {
setContentType(req, res,
["text", "html", "text/*", "application/*"], // allow these types
["json", "*/json", "+json", "application/octet-stream"]); // don't allow these types
util.debug("Serializing the response as a string");
res.send(_(data).toString());
}
|
javascript
|
{
"resource": ""
}
|
q22176
|
setContentType
|
train
|
function setContentType (req, res, supported, excluded) {
// Get the MIME types that this operation produces
let produces = req.swagger.operation.produces || req.swagger.api.produces || [];
if (produces.length === 0) {
// No MIME types were specified, so just use the first one
util.debug('No "produces" MIME types are specified in the Swagger API, so defaulting to %s', supported[0]);
res.type(supported[0]);
}
else {
// Find the first MIME type that we support
let match = _.find(produces, (mimeType) => {
return typeIs.is(mimeType, supported) &&
(!excluded || !typeIs.is(mimeType, excluded));
});
if (match) {
util.debug("Using %s MIME type, which is allowed by the Swagger API", match);
res.type(match);
}
else {
util.warn(
'WARNING! %s %s produces the MIME types that are not supported (%s). Using "%s" instead',
req.method, req.path, produces.join(", "), supported[0]
);
res.type(supported[0]);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22177
|
isCollectionRequest
|
train
|
function isCollectionRequest (req) {
let isCollection = responseIsCollection(req);
if (isCollection === undefined) {
isCollection = !lastPathSegmentIsAParameter(req);
}
return isCollection;
}
|
javascript
|
{
"resource": ""
}
|
q22178
|
responseIsCollection
|
train
|
function responseIsCollection (req) {
let getter = req.swagger.path.get || req.swagger.path.head;
if (getter) {
let responses = util.getResponsesBetween(getter, 200, 299);
if (responses.length > 0) {
let response = new SemanticResponse(responses[0].api, req.swagger.path);
if (!response.isEmpty) {
return response.isCollection;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q22179
|
lastPathSegmentIsAParameter
|
train
|
function lastPathSegmentIsAParameter (req) {
let lastSlash = req.swagger.pathName.lastIndexOf("/");
let lastParam = req.swagger.pathName.lastIndexOf("{");
return (lastParam > lastSlash);
}
|
javascript
|
{
"resource": ""
}
|
q22180
|
SemanticResponse
|
train
|
function SemanticResponse (response, path) {
/**
* The JSON schema of the response
* @type {object|null}
*/
this.schema = response.schema || null;
/**
* The response headers, from the Swagger API
* @type {object|null}
*/
this.headers = response.headers || null;
/**
* If true, then an empty response should be sent.
* @type {boolean}
*/
this.isEmpty = !response.schema;
/**
* Indicates whether the response should be a single resource, or a collection.
* @type {boolean}
*/
this.isCollection = false;
/**
* Indicates whether the response schema is a wrapper around the actual resource data.
* It's common for RESTful APIs to include a response wrapper with additional metadata,
* and one of the properties of the wrapper is the actual resource data.
* @type {boolean}
*/
this.isWrapped = false;
/**
* If the response is wrapped, then this is the name of the wrapper property that
* contains the actual resource data.
* @type {string}
*/
this.wrapperProperty = "";
/**
* The date/time that the response data was last modified.
* This is used to set the Last-Modified HTTP header (if defined in the Swagger API)
*
* Each mock implementation sets this to the appropriate value.
*
* @type {Date}
*/
this.lastModified = null;
/**
* The location (URL) of the REST resource.
* This is used to set the Location HTTP header (if defined in the Swagger API)
*
* Some mocks implementations set this value. If left blank, then the Location header
* will be set to the current path.
*
* @type {string}
*/
this.location = "";
if (!this.isEmpty) {
this.setWrapperInfo(response, path);
}
}
|
javascript
|
{
"resource": ""
}
|
q22181
|
getResourceSchemas
|
train
|
function getResourceSchemas (path) {
let schemas = [];
["post", "put", "patch"].forEach((operation) => {
if (path[operation]) {
schemas.push(util.getRequestSchema(path, path[operation]));
}
});
return schemas;
}
|
javascript
|
{
"resource": ""
}
|
q22182
|
schemasMatch
|
train
|
function schemasMatch (schemasToMatch, schemaToTest) {
let propertiesToTest = 0;
if (schemaToTest.properties) {
propertiesToTest = Object.keys(schemaToTest.properties).length;
}
return schemasToMatch.some((schemaToMatch) => {
let propertiesToMatch = 0;
if (schemaToMatch.properties) {
propertiesToMatch = Object.keys(schemaToMatch.properties).length;
}
// Make sure both schemas are the same type and have the same number of properties
if (schemaToTest.type === schemaToMatch.type && propertiesToTest === propertiesToMatch) {
// Compare each property in both schemas
return _.every(schemaToMatch.properties, (propertyToMatch, propName) => {
let propertyToTest = schemaToTest.properties[propName];
return propertyToTest && propertyToMatch.type === propertyToTest.type;
});
}
});
}
|
javascript
|
{
"resource": ""
}
|
q22183
|
mergeCollection
|
train
|
function mergeCollection (req, res, next, dataStore) {
let collection = req.path;
let resources = createResources(req);
// Set the "Location" HTTP header.
// If the operation allows saving multiple resources, then use the collection path.
// If the operation only saves a single resource, then use the resource's path.
res.swagger.location = _.isArray(req.body) ? collection : resources[0].toString();
// Save/Update the resources
util.debug("Saving data at %s", res.swagger.location);
dataStore.save(resources, sendResponse(req, res, next, dataStore));
}
|
javascript
|
{
"resource": ""
}
|
q22184
|
getResourceName
|
train
|
function getResourceName (data, schema) {
// Try to find the "name" property using several different methods
let propInfo =
getResourceNameByValue(data, schema) ||
getResourceNameByName(data, schema) ||
getResourceNameByRequired(data, schema) ||
getResourceNameByFile(data, schema);
if (propInfo) {
util.debug('The "%s" property (%j) appears to be the REST resource\'s name', propInfo.name, propInfo.value);
if (propInfo.value === undefined) {
propInfo.value = new JsonSchema(propInfo.schema).sample();
util.debug('Generated new value (%j) for the "%s" property', propInfo.value, propInfo.name);
}
return propInfo;
}
else {
util.debug("Unable to determine the unique name for the REST resource. Generating a unique value instead");
return {
name: "",
schema: { type: "string" },
value: _.uniqueId()
};
}
}
|
javascript
|
{
"resource": ""
}
|
q22185
|
getResourceNameByName
|
train
|
function getResourceNameByName (data, schema) {
/** @name PropertyInfo */
let propInfo = {
name: "",
schema: {
type: ""
},
value: undefined
};
// Get a list of all existing and possible properties of the resource
let propNames = _.union(_.keys(schema.properties), _.keys(data));
// Lowercase property names, for comparison
let lowercasePropNames = propNames.map((propName) => { return propName.toLowerCase(); });
// These properties are assumed to be unique IDs.
// If we find any of them in the schema, then use it as the REST resource's name.
let nameProperties = ["id", "key", "slug", "code", "number", "num", "nbr", "username", "name"];
let foundMatch = nameProperties.some((lowercasePropName) => {
let index = lowercasePropNames.indexOf(lowercasePropName);
if (index >= 0) {
// We found a property that appears to be the resource's name. Get its info.
propInfo.name = propNames[index];
propInfo.value = data ? data[propInfo.name] : undefined;
if (schema.properties[propInfo.name]) {
propInfo.schema = schema.properties[propInfo.name];
}
else if (_.isDate(data[propInfo.name])) {
propInfo.schema = {
type: "string",
format: "date-time"
};
}
else {
propInfo.schema.type = typeof (data[propInfo.name]);
}
// If the property is valid, then we're done
return isValidResourceName(propInfo);
}
});
return foundMatch ? propInfo : undefined;
}
|
javascript
|
{
"resource": ""
}
|
q22186
|
getResourceNameByRequired
|
train
|
function getResourceNameByRequired (data, schema) {
let propInfo = {
name: "",
schema: {
type: ""
},
value: undefined
};
let foundMatch = _.some(schema.required, (propName) => {
propInfo.name = propName;
propInfo.schema = schema.properties[propName];
propInfo.value = data[propName];
// If the property is valid, then we're done
return isValidResourceName(propInfo);
});
return foundMatch ? propInfo : undefined;
}
|
javascript
|
{
"resource": ""
}
|
q22187
|
round
|
train
|
function round(value, digits)
{
if (! digits) { digits = 0; }
var scale = Math.pow(10, digits);
return Math.round(value * scale) / scale;
}
|
javascript
|
{
"resource": ""
}
|
q22188
|
fibonacciretracement
|
train
|
function fibonacciretracement(start, end) {
let levels = [0, 23.6, 38.2, 50, 61.8, 78.6, 100, 127.2, 161.8, 261.8, 423.6];
let retracements;
if (start < end) {
retracements = levels.map(function (level) {
let calculated = end - Math.abs(start - end) * (level) / 100;
return calculated > 0 ? calculated : 0;
});
}
else {
retracements = levels.map(function (level) {
let calculated = end + Math.abs(start - end) * (level) / 100;
return calculated > 0 ? calculated : 0;
});
}
return retracements;
}
|
javascript
|
{
"resource": ""
}
|
q22189
|
train
|
function (x, y, w, h) {
this.gl.viewport(x, y, w, h);
}
|
javascript
|
{
"resource": ""
}
|
|
q22190
|
train
|
function (unit, image, filter, repeat, w, h, b, premultipliedAlpha) {
var gl = this.gl;
repeat = repeat || "no-repeat";
var isPOT = me.Math.isPowerOfTwo(w || image.width) && me.Math.isPowerOfTwo(h || image.height);
var texture = gl.createTexture();
var rs = (repeat.search(/^repeat(-x)?$/) === 0) && isPOT ? gl.REPEAT : gl.CLAMP_TO_EDGE;
var rt = (repeat.search(/^repeat(-y)?$/) === 0) && isPOT ? gl.REPEAT : gl.CLAMP_TO_EDGE;
gl.activeTexture(gl.TEXTURE0 + unit);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, rs);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, rt);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, (typeof premultipliedAlpha === "boolean") ? premultipliedAlpha : true);
if (w || h || b) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, w, h, b, gl.RGBA, gl.UNSIGNED_BYTE, image);
}
else {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
}
return texture;
}
|
javascript
|
{
"resource": ""
}
|
|
q22191
|
train
|
function () {
var indices = [
0, 1, 2,
2, 1, 3
];
// ~384KB index buffer
var data = new Array(MAX_LENGTH * INDICES_PER_QUAD);
for (var i = 0; i < data.length; i++) {
data[i] = indices[i % INDICES_PER_QUAD] +
~~(i / INDICES_PER_QUAD) * ELEMENTS_PER_QUAD;
}
return new Uint16Array(data);
}
|
javascript
|
{
"resource": ""
}
|
|
q22192
|
train
|
function () {
this.sbSize <<= 1;
var stream = new Float32Array(this.sbSize * ELEMENT_SIZE * ELEMENTS_PER_QUAD);
stream.set(this.stream);
this.stream = stream;
}
|
javascript
|
{
"resource": ""
}
|
|
q22193
|
train
|
function () {
if (this.length) {
var gl = this.gl;
// Copy data into stream buffer
var len = this.length * ELEMENT_SIZE * ELEMENTS_PER_QUAD;
gl.bufferData(
gl.ARRAY_BUFFER,
this.stream.subarray(0, len),
gl.STREAM_DRAW
);
// Draw the stream buffer
gl.drawElements(
gl.TRIANGLES,
this.length * INDICES_PER_QUAD,
gl.UNSIGNED_SHORT,
0
);
this.sbIndex = 0;
this.length = 0;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22194
|
train
|
function (col, opaque) {
this.save();
this.resetTransform();
this.backBufferContext2D.globalCompositeOperation = opaque ? "copy" : "source-over";
this.backBufferContext2D.fillStyle = (col instanceof me.Color) ? col.toRGBA() : col;
this.fillRect(0, 0, this.backBufferCanvas.width, this.backBufferCanvas.height);
this.restore();
}
|
javascript
|
{
"resource": ""
}
|
|
q22195
|
train
|
function (image, sx, sy, sw, sh, dx, dy, dw, dh) {
if (this.backBufferContext2D.globalAlpha < 1 / 255) {
// Fast path: don't draw fully transparent
return;
}
if (typeof sw === "undefined") {
sw = dw = image.width;
sh = dh = image.height;
dx = sx;
dy = sy;
sx = 0;
sy = 0;
}
else if (typeof dx === "undefined") {
dx = sx;
dy = sy;
dw = sw;
dh = sh;
sw = image.width;
sh = image.height;
sx = 0;
sy = 0;
}
if (this.settings.subPixel === false) {
// clamp to pixel grid
dx = ~~dx;
dy = ~~dy;
}
this.backBufferContext2D.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);
}
|
javascript
|
{
"resource": ""
}
|
|
q22196
|
train
|
function (x, y, w, h) {
this.strokeEllipse(x, y, w, h, true);
}
|
javascript
|
{
"resource": ""
}
|
|
q22197
|
train
|
function (poly, fill) {
var context = this.backBufferContext2D;
if (context.globalAlpha < 1 / 255) {
// Fast path: don't draw fully transparent
return;
}
this.translate(poly.pos.x, poly.pos.y);
context.beginPath();
context.moveTo(poly.points[0].x, poly.points[0].y);
var point;
for (var i = 1; i < poly.points.length; i++) {
point = poly.points[i];
context.lineTo(point.x, point.y);
}
context.lineTo(poly.points[0].x, poly.points[0].y);
context[fill === true ? "fill" : "stroke"]();
context.closePath();
this.translate(-poly.pos.x, -poly.pos.y);
}
|
javascript
|
{
"resource": ""
}
|
|
q22198
|
train
|
function (x, y) {
if (this.settings.subPixel === false) {
this.backBufferContext2D.translate(~~x, ~~y);
} else {
this.backBufferContext2D.translate(x, y);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q22199
|
train
|
function (renderer, dx, dy, tmxTile) {
// check if any transformation is required
if (tmxTile.flipped) {
renderer.save();
// apply the tile current transform
renderer.translate(dx, dy);
renderer.transform(tmxTile.currentTransform);
// reset both values as managed through transform();
dx = dy = 0;
}
// check if the tile has an associated image
if (this.isCollection === true) {
// draw the tile
renderer.drawImage(
this.imageCollection[tmxTile.tileId],
0, 0,
tmxTile.width, tmxTile.height,
dx, dy,
tmxTile.width, tmxTile.height
);
} else {
// use the tileset texture
var offset = this.atlas[this.getViewTileId(tmxTile.tileId)].offset;
// draw the tile
renderer.drawImage(
this.image,
offset.x, offset.y,
this.tilewidth, this.tileheight,
dx, dy,
this.tilewidth + renderer.uvOffset, this.tileheight + renderer.uvOffset
);
}
if (tmxTile.flipped) {
// restore the context to the previous state
renderer.restore();
}
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.