_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q28200
processReceivedData
train
function processReceivedData() { if (dataReceived || queueItem.fetched) { return; } responseBuffer = responseBuffer.slice(0, responseLengthReceived); dataReceived = true; timeDataReceived = Date.now(); crawler.queue.update(queueItem.id, { stateData: { downloadTime: timeDataReceived - timeHeadersReceived, requestTime: timeDataReceived - timeCommenced, actualDataSize: responseBuffer.length, sentIncorrectSize: responseBuffer.length !== responseLength } }, function (error, queueItem) { if (error) { // Remove this request from the open request map crawler._openRequests.splice( crawler._openRequests.indexOf(response.req), 1); return crawler.emit("queueerror", error, queueItem); } // First, save item to cache (if we're using a cache!) if (crawler.cache && crawler.cache.setCacheData instanceof Function) { crawler.cache.setCacheData(queueItem, responseBuffer); } // No matter the value of `crawler.decompressResponses`, we still // decompress the response if it's gzipped or deflated. This is // because we always provide the discoverResources method with a // decompressed buffer if (/(gzip|deflate)/.test(queueItem.stateData.headers["content-encoding"])) { zlib.unzip(responseBuffer, function(error, decompressedBuffer) { if (error) { /** * Fired when an error was encountered while unzipping the response data * @event Crawler#gziperror * @param {QueueItem} queueItem The queue item for which the unzipping failed * @param {String|Buffer} responseBody If {@link Crawler#decodeResponses} is true, this will be the decoded HTTP response. Otherwise it will be the raw response buffer. * @param {http.IncomingMessage} response The [http.IncomingMessage]{@link https://nodejs.org/api/http.html#http_class_http_incomingmessage} for the request's response */ crawler.emit("gziperror", queueItem, error, responseBuffer); emitFetchComplete(responseBuffer); } else { var responseBody = crawler.decompressResponses ? decompressedBuffer : responseBuffer; emitFetchComplete(responseBody, decompressedBuffer); } }); } else { emitFetchComplete(responseBuffer); } }); }
javascript
{ "resource": "" }
q28201
addPathHandle
train
function addPathHandle($canvas, parent, xProp, yProp) { var handle = $.extend({ cursors: { mouseover: 'grab', mousedown: 'grabbing', mouseup: 'grab' } }, parent.handle, { // Define constant properties for handle layer: true, draggable: true, x: parent[xProp], y: parent[yProp], _parent: parent, _xProp: xProp, _yProp: yProp, fromCenter: true, // Adjust line path when dragging a handle dragstart: function (layer) { $(this).triggerLayerEvent(layer._parent, 'handlestart'); }, drag: function (layer) { var parent = layer._parent; parent[layer._xProp] = layer.x - parent.x; parent[layer._yProp] = layer.y - parent.y; updatePathGuides(parent); $(this).triggerLayerEvent(parent, 'handlemove'); }, dragstop: function (layer) { $(this).triggerLayerEvent(layer._parent, 'handlestop'); }, dragcancel: function (layer) { $(this).triggerLayerEvent(layer._parent, 'handlecancel'); } }); $canvas.draw(handle); // Add handle to parent layer's list of handles parent._handles.push($canvas.getLayer(-1)); }
javascript
{ "resource": "" }
q28202
train
function (layer) { var parent = layer._parent; if (parent.width + (layer.dx * layer._px) < parent.minWidth) { parent.width = parent.minWidth; layer.dx = 0; } if (parent.height + (layer.dy * layer._py) < parent.minHeight) { parent.height = parent.minHeight; layer.dy = 0; } if (!parent.resizeFromCenter) { // Optionally constrain proportions if (parent.constrainProportions) { if (layer._py === 0) { // Manage handles whose y is at layer's center parent.height = parent.width / parent.aspectRatio; } else { // Manage every other handle parent.width = parent.height * parent.aspectRatio; layer.dx = layer.dy * parent.aspectRatio * layer._py * layer._px; } } // Optionally resize rectangle from corner if (parent.fromCenter) { parent.width += layer.dx * layer._px; parent.height += layer.dy * layer._py; } else { // This is simplified version based on math. Also you can write this using an if statement for each handle parent.width += layer.dx * layer._px; if (layer._px !== 0) { parent.x += layer.dx * ((1 - layer._px) && (1 - layer._px) / Math.abs((1 - layer._px))); } parent.height += layer.dy * layer._py; if (layer._py !== 0) { parent.y += layer.dy * ((1 - layer._py) && (1 - layer._py) / Math.abs((1 - layer._py))); } } // Ensure diagonal handle does not move if (parent.fromCenter) { if (layer._px !== 0) { parent.x += layer.dx / 2; } if (layer._py !== 0) { parent.y += layer.dy / 2; } } } else { // Otherwise, resize rectangle from center parent.width += layer.dx * layer._px * 2; parent.height += layer.dy * layer._py * 2; // Optionally constrain proportions if (parent.constrainProportions) { if (layer._py === 0) { // Manage handles whose y is at layer's center parent.height = parent.width / parent.aspectRatio; } else { // Manage every other handle parent.width = parent.height * parent.aspectRatio; } } } updateRectHandles(parent); $(this).triggerLayerEvent(parent, 'handlemove'); }
javascript
{ "resource": "" }
q28203
addRectHandles
train
function addRectHandles($canvas, parent) { var handlePlacement = parent.handlePlacement; // Store current width-to-height ratio if (parent.aspectRatio === null && parent.height !== 0) { parent.aspectRatio = parent.width / parent.height; } // Optionally add handles to corners if (handlePlacement === 'corners' || handlePlacement === 'both') { addRectHandle($canvas, parent, -1, -1); addRectHandle($canvas, parent, 1, -1); addRectHandle($canvas, parent, 1, 1); addRectHandle($canvas, parent, -1, 1); } // Optionally add handles to sides if (handlePlacement === 'sides' || handlePlacement === 'both') { addRectHandle($canvas, parent, 0, -1); addRectHandle($canvas, parent, 1, 0); addRectHandle($canvas, parent, 0, 1); addRectHandle($canvas, parent, -1, 0); } // Optionally add handle guides if (parent.guide) { addRectGuides($canvas, parent); } }
javascript
{ "resource": "" }
q28204
updateRectGuides
train
function updateRectGuides(parent) { var guide = parent._guide; if (guide) { guide.x = parent.x; guide.y = parent.y; guide.width = parent.width; guide.height = parent.height; guide.fromCenter = parent.fromCenter; } }
javascript
{ "resource": "" }
q28205
addRectGuides
train
function addRectGuides($canvas, parent) { var guideProps, guide; guideProps = $.extend({}, parent.guide, { layer: true, draggable: false, type: 'rectangle', handle: null }); $canvas.addLayer(guideProps); guide = $canvas.getLayer(-1); parent._guide = guide; $canvas.moveLayer(guide, -parent._handles.length - 1); updateRectGuides(parent); }
javascript
{ "resource": "" }
q28206
addPathHandles
train
function addPathHandles($canvas, parent) { var key, xProp, yProp; for (key in parent) { if (Object.prototype.hasOwnProperty.call(parent, key)) { // If property is a control point if (key.match(/c?x(\d+)/gi) !== null) { // Get the x and y coordinates for that control point xProp = key; yProp = key.replace('x', 'y'); // Add handle at control point addPathHandle($canvas, parent, xProp, yProp); } } } // Add guides connecting handles if (parent.guide) { addPathGuides($canvas, parent); } }
javascript
{ "resource": "" }
q28207
updatePathGuides
train
function updatePathGuides(parent) { var handles = parent._handles, guides = parent._guides, handle, h, guide, g; if (parent._method === $.fn.drawQuadratic) { if (handles) { guide = parent._guide; if (guide) { for (h = 0; h < handles.length; h += 1) { handle = parent._handles[h]; guide['x' + (h + 1)] = handle.x; guide['y' + (h + 1)] = handle.y; } } } } else if (parent._method === $.fn.drawBezier) { if (guides) { for (g = 0; g < guides.length; g += 1) { guide = guides[g]; handles = guide._handles; if (guide && handles) { for (h = 0; h < handles.length; h += 1) { handle = handles[h]; guide['x' + (h + 1)] = handle.x; guide['y' + (h + 1)] = handle.y; } } } } } }
javascript
{ "resource": "" }
q28208
addPathGuides
train
function addPathGuides($canvas, parent) { var handles = parent._handles, prevHandle, nextHandle, otherHandle, handle, h, guide, guideProps; guideProps = $.extend({}, parent.guide, { layer: true, draggable: false, type: 'line' }); if (parent._method === $.fn.drawQuadratic) { $canvas.addLayer(guideProps); parent._guide = $canvas.getLayer(-1); $canvas.moveLayer(parent._guide, -handles.length - 1); } else if (parent._method === $.fn.drawBezier) { parent._guides = []; for (h = 0; h < handles.length; h += 1) { handle = handles[h]; nextHandle = handles[h + 1]; prevHandle = handles[h - 1]; otherHandle = null; if (nextHandle !== undefined) { // If handle is a start/end point and next handle is a control point if (handle._xProp.indexOf('x') === 0 && nextHandle._xProp.indexOf('cx') === 0) { otherHandle = nextHandle; } } else if (prevHandle !== undefined) { if (prevHandle._xProp.indexOf('cx') === 0 && handle._xProp.indexOf('x') === 0) { otherHandle = prevHandle; } } if (otherHandle !== null) { $canvas.addLayer(guideProps); guide = $canvas.getLayer(-1); guide._handles = [handle, otherHandle]; parent._guides.push(guide); $canvas.moveLayer(guide, -handles.length - 1); } } } updatePathGuides(parent); }
javascript
{ "resource": "" }
q28209
updateRectHandles
train
function updateRectHandles(parent) { var handle, h; if (parent._handles) { // Move handles when dragging for (h = 0; h < parent._handles.length; h += 1) { handle = parent._handles[h]; handle.x = parent.x + ((parent.width / 2 * handle._px) + ((parent.fromCenter) ? 0 : parent.width / 2)); handle.y = parent.y + ((parent.height / 2 * handle._py) + ((parent.fromCenter) ? 0 : parent.height / 2)); } } updateRectGuides(parent); }
javascript
{ "resource": "" }
q28210
updatePathHandles
train
function updatePathHandles(parent) { var handles = parent._handles, handle, h; if (handles) { // Move handles when dragging for (h = 0; h < handles.length; h += 1) { handle = handles[h]; handle.x = parent[handle._xProp] + parent.x; handle.y = parent[handle._yProp] + parent.y; } } updatePathGuides(parent); }
javascript
{ "resource": "" }
q28211
addHandles
train
function addHandles(parent) { var $canvas = $(parent.canvas); // If parent's list of handles doesn't exist if (parent._handles === undefined) { // Create list to store handles parent._handles = []; } if (isRectLayer(parent)) { // Add four handles to corners of a rectangle/ellipse/image addRectHandles($canvas, parent); } else if (isPathLayer(parent)) { // Add two or more handles to a line path addPathHandles($canvas, parent); } }
javascript
{ "resource": "" }
q28212
removeHandles
train
function removeHandles(layer) { var $canvas = $(layer.canvas), handle, h; if (layer._handles) { // Remove handles from layer for (h = 0; h < layer._handles.length; h += 1) { handle = layer._handles[h]; $canvas.removeLayer(handle); } layer._handles.length = 0; } }
javascript
{ "resource": "" }
q28213
train
function (layer) { var $canvas, handle, h; if (layer._handles) { $canvas = $(this); // Remove handles from layer for (h = 0; h < layer._handles.length; h += 1) { handle = layer._handles[h]; $canvas.removeLayer(handle); } layer._handles.length = 0; } }
javascript
{ "resource": "" }
q28214
train
function (layer, props) { if (props.handle || objectContainsPathCoords(props)) { // Add handles if handle property was added removeHandles(layer); addHandles(layer); } else if (props.handle === null) { removeHandles(layer); } if (isRectLayer(layer)) { // If width/height was changed if (props.width !== undefined || props.height !== undefined || props.x !== undefined || props.y !== undefined) { // Update handle positions updateRectHandles(layer); } } else if (isPathLayer(layer)) { updatePathHandles(layer); } }
javascript
{ "resource": "" }
q28215
train
function (layer, fx) { // If layer is a rectangle or ellipse layer if (isRectLayer(layer)) { // If width or height are animated if (fx.prop === 'width' || fx.prop === 'height' || fx.prop === 'x' || fx.prop === 'y') { // Update rectangular handles updateRectHandles(layer); } } else if (isPathLayer(layer)) { // If coordinates are animated if (fx.prop.match(/^c?(x|y)(\d+)/gi) !== null) { // Update path handles updatePathHandles(layer); } } }
javascript
{ "resource": "" }
q28216
jCanvasObject
train
function jCanvasObject(args) { var params = this, propName; // Copy the given parameters into new object for (propName in args) { // Do not merge defaults into parameters if (Object.prototype.hasOwnProperty.call(args, propName)) { params[propName] = args[propName]; } } return params; }
javascript
{ "resource": "" }
q28217
_coerceNumericProps
train
function _coerceNumericProps(props) { var propName, propType, propValue; // Loop through all properties in given property map for (propName in props) { if (Object.prototype.hasOwnProperty.call(props, propName)) { propValue = props[propName]; propType = typeOf(propValue); // If property is non-empty string and value is numeric if (propType === 'string' && isNumeric(propValue) && propName !== 'text') { // Convert value to number props[propName] = parseFloat(propValue); } } } // Ensure value of text property is always a string if (props.text !== undefined) { props.text = String(props.text); } }
javascript
{ "resource": "" }
q28218
_cloneTransforms
train
function _cloneTransforms(transforms) { // Clone the object itself transforms = extendObject({}, transforms); // Clone the object's masks array transforms.masks = transforms.masks.slice(0); return transforms; }
javascript
{ "resource": "" }
q28219
_saveCanvas
train
function _saveCanvas(ctx, data) { var transforms; ctx.save(); transforms = _cloneTransforms(data.transforms); data.savedTransforms.push(transforms); }
javascript
{ "resource": "" }
q28220
_restoreCanvas
train
function _restoreCanvas(ctx, data) { if (data.savedTransforms.length === 0) { // Reset transformation state if it can't be restored any more data.transforms = _cloneTransforms(baseTransforms); } else { // Restore canvas context ctx.restore(); // Restore current transform state to the last saved state data.transforms = data.savedTransforms.pop(); } }
javascript
{ "resource": "" }
q28221
_setStyle
train
function _setStyle(canvas, ctx, params, styleName) { if (params[styleName]) { if (isFunction(params[styleName])) { // Handle functions ctx[styleName] = params[styleName].call(canvas, params); } else { // Handle string values ctx[styleName] = params[styleName]; } } }
javascript
{ "resource": "" }
q28222
_setGlobalProps
train
function _setGlobalProps(canvas, ctx, params) { _setStyle(canvas, ctx, params, 'fillStyle'); _setStyle(canvas, ctx, params, 'strokeStyle'); ctx.lineWidth = params.strokeWidth; // Optionally round corners for paths if (params.rounded) { ctx.lineCap = ctx.lineJoin = 'round'; } else { ctx.lineCap = params.strokeCap; ctx.lineJoin = params.strokeJoin; ctx.miterLimit = params.miterLimit; } // Reset strokeDash if null if (!params.strokeDash) { params.strokeDash = []; } // Dashed lines if (ctx.setLineDash) { ctx.setLineDash(params.strokeDash); } ctx.webkitLineDash = params.strokeDash; ctx.lineDashOffset = ctx.webkitLineDashOffset = ctx.mozDashOffset = params.strokeDashOffset; // Drop shadow ctx.shadowOffsetX = params.shadowX; ctx.shadowOffsetY = params.shadowY; ctx.shadowBlur = params.shadowBlur; ctx.shadowColor = params.shadowColor; // Opacity and composite operation ctx.globalAlpha = params.opacity; ctx.globalCompositeOperation = params.compositing; // Support cross-browser toggling of image smoothing if (params.imageSmoothing) { ctx.imageSmoothingEnabled = params.imageSmoothing; } }
javascript
{ "resource": "" }
q28223
_enableMasking
train
function _enableMasking(ctx, data, params) { if (params.mask) { // If jCanvas autosave is enabled if (params.autosave) { // Automatically save transformation state by default _saveCanvas(ctx, data); } // Clip the current path ctx.clip(); // Keep track of current masks data.transforms.masks.push(params._args); } }
javascript
{ "resource": "" }
q28224
_closePath
train
function _closePath(canvas, ctx, params) { var data; // Optionally close path if (params.closed) { ctx.closePath(); } if (params.shadowStroke && params.strokeWidth !== 0) { // Extend the shadow to include the stroke of a drawing // Add a stroke shadow by stroking before filling ctx.stroke(); ctx.fill(); // Ensure the below stroking does not inherit a shadow ctx.shadowColor = 'transparent'; ctx.shadowBlur = 0; // Stroke over fill as usual ctx.stroke(); } else { // If shadowStroke is not enabled, stroke & fill as usual ctx.fill(); // Prevent extra shadow created by stroke (but only when fill is present) if (params.fillStyle !== 'transparent') { ctx.shadowColor = 'transparent'; } if (params.strokeWidth !== 0) { // Only stroke if the stroke is not 0 ctx.stroke(); } } // Optionally close path if (!params.closed) { ctx.closePath(); } // Restore individual shape transformation _restoreTransform(ctx, params); // Mask shape if chosen if (params.mask) { // Retrieve canvas data data = _getCanvasData(canvas); _enableMasking(ctx, data, params); } }
javascript
{ "resource": "" }
q28225
_addLayerEvents
train
function _addLayerEvents($canvas, data, layer) { var eventName; // Determine which jCanvas events need to be bound to this layer for (eventName in jCanvas.events) { if (Object.prototype.hasOwnProperty.call(jCanvas.events, eventName)) { // If layer has callback function to complement it if (layer[eventName] || (layer.cursors && layer.cursors[eventName])) { // Bind event to layer _addExplicitLayerEvent($canvas, data, layer, eventName); } } } if (!data.events.mouseout) { $canvas.bind('mouseout.jCanvas', function () { // Retrieve the layer whose drag event was canceled var layer = data.drag.layer, l; // If cursor mouses out of canvas while dragging if (layer) { // Cancel drag data.drag = {}; _triggerLayerEvent($canvas, data, layer, 'dragcancel'); } // Loop through all layers for (l = 0; l < data.layers.length; l += 1) { layer = data.layers[l]; // If layer thinks it's still being moused over if (layer._hovered) { // Trigger mouseout on layer $canvas.triggerLayerEvent(data.layers[l], 'mouseout'); } } // Redraw layers $canvas.drawLayers(); }); // Indicate that an event handler has been bound data.events.mouseout = true; } }
javascript
{ "resource": "" }
q28226
_addLayerEvent
train
function _addLayerEvent($canvas, data, layer, eventName) { // Use touch events if appropriate // eventName = _getMouseEventName(eventName); // Bind event to layer jCanvas.events[eventName]($canvas, data); layer._event = true; }
javascript
{ "resource": "" }
q28227
_enableDrag
train
function _enableDrag($canvas, data, layer) { var dragHelperEvents, eventName, i; // Only make layer draggable if necessary if (layer.draggable || layer.cursors) { // Organize helper events which enable drag support dragHelperEvents = ['mousedown', 'mousemove', 'mouseup']; // Bind each helper event to the canvas for (i = 0; i < dragHelperEvents.length; i += 1) { // Use touch events if appropriate eventName = dragHelperEvents[i]; // Bind event _addLayerEvent($canvas, data, layer, eventName); } // Indicate that this layer has events bound to it layer._event = true; } }
javascript
{ "resource": "" }
q28228
_updateLayerName
train
function _updateLayerName($canvas, data, layer, props) { var nameMap = data.layer.names; // If layer name is being added, not changed if (!props) { props = layer; } else { // Remove old layer name entry because layer name has changed if (props.name !== undefined && isString(layer.name) && layer.name !== props.name) { delete nameMap[layer.name]; } } // Add new entry to layer name map with new name if (isString(props.name)) { nameMap[props.name] = layer; } }
javascript
{ "resource": "" }
q28229
_updateLayerGroups
train
function _updateLayerGroups($canvas, data, layer, props) { var groupMap = data.layer.groups, group, groupName, g, index, l; // If group name is not changing if (!props) { props = layer; } else { // Remove layer from all of its associated groups if (props.groups !== undefined && layer.groups !== null) { for (g = 0; g < layer.groups.length; g += 1) { groupName = layer.groups[g]; group = groupMap[groupName]; if (group) { // Remove layer from its old layer group entry for (l = 0; l < group.length; l += 1) { if (group[l] === layer) { // Keep track of the layer's initial index index = l; // Remove layer once found group.splice(l, 1); break; } } // Remove layer group entry if group is empty if (group.length === 0) { delete groupMap[groupName]; } } } } } // Add layer to new group if a new group name is given if (props.groups !== undefined && props.groups !== null) { for (g = 0; g < props.groups.length; g += 1) { groupName = props.groups[g]; group = groupMap[groupName]; if (!group) { // Create new group entry if it doesn't exist group = groupMap[groupName] = []; group.name = groupName; } if (index === undefined) { // Add layer to end of group unless otherwise stated index = group.length; } // Add layer to its new layer group group.splice(index, 0, layer); } } }
javascript
{ "resource": "" }
q28230
_getIntersectingLayer
train
function _getIntersectingLayer(data) { var layer, i, mask, m; // Store the topmost layer layer = null; // Get the topmost layer whose visible area intersects event coordinates for (i = data.intersecting.length - 1; i >= 0; i -= 1) { // Get current layer layer = data.intersecting[i]; // If layer has previous masks if (layer._masks) { // Search previous masks to ensure // layer is visible at event coordinates for (m = layer._masks.length - 1; m >= 0; m -= 1) { mask = layer._masks[m]; // If mask does not intersect event coordinates if (!mask.intersects) { // Indicate that the mask does not // intersect event coordinates layer.intersects = false; // Stop searching previous masks break; } } // If event coordinates intersect all previous masks // and layer is not intangible if (layer.intersects && !layer.intangible) { // Stop searching for topmost layer break; } } } // If resulting layer is intangible if (layer && layer.intangible) { // Cursor does not intersect this layer layer = null; } return layer; }
javascript
{ "resource": "" }
q28231
_setCursor
train
function _setCursor($canvas, layer, eventType) { var cursor; if (layer.cursors) { // Retrieve cursor from cursors object if it exists cursor = layer.cursors[eventType]; } // Prefix any CSS3 cursor if ($.inArray(cursor, css.cursors) !== -1) { cursor = css.prefix + cursor; } // If cursor is defined if (cursor) { // Set canvas cursor $canvas.css({ cursor: cursor }); } }
javascript
{ "resource": "" }
q28232
_runEventCallback
train
function _runEventCallback($canvas, layer, eventType, callbacks, arg) { // Prevent callback from firing recursively if (callbacks[eventType] && layer._running && !layer._running[eventType]) { // Signify the start of callback execution for this event layer._running[eventType] = true; // Run event callback with the given arguments callbacks[eventType].call($canvas[0], layer, arg); // Signify the end of callback execution for this event layer._running[eventType] = false; } }
javascript
{ "resource": "" }
q28233
_layerCanFireEvent
train
function _layerCanFireEvent(layer, eventType) { // If events are disable and if // layer is tangible or event is not tangible return (!layer.disableEvents && (!layer.intangible || $.inArray(eventType, tangibleEvents) === -1)); }
javascript
{ "resource": "" }
q28234
_triggerLayerEvent
train
function _triggerLayerEvent($canvas, data, layer, eventType, arg) { // If layer can legally fire this event type if (_layerCanFireEvent(layer, eventType)) { // Do not set a custom cursor on layer mouseout if (eventType !== 'mouseout') { // Update cursor if one is defined for this event _setCursor($canvas, layer, eventType); } // Trigger the user-defined event callback _runEventCallback($canvas, layer, eventType, layer, arg); // Trigger the canvas-bound event hook _runEventCallback($canvas, layer, eventType, data.eventHooks, arg); // Trigger the global event hook _runEventCallback($canvas, layer, eventType, jCanvas.eventHooks, arg); } }
javascript
{ "resource": "" }
q28235
_parseEndValues
train
function _parseEndValues(canvas, layer, endValues) { var propName, propValue, subPropName, subPropValue; // Loop through all properties in map of end values for (propName in endValues) { if (Object.prototype.hasOwnProperty.call(endValues, propName)) { propValue = endValues[propName]; // If end value is function if (isFunction(propValue)) { // Call function and use its value as the end value endValues[propName] = propValue.call(canvas, layer, propName); } // If end value is an object if (typeOf(propValue) === 'object' && isPlainObject(propValue)) { // Prepare to animate properties in object for (subPropName in propValue) { if (Object.prototype.hasOwnProperty.call(propValue, subPropName)) { subPropValue = propValue[subPropName]; // Store property's start value at top-level of layer if (layer[propName] !== undefined) { layer[propName + '.' + subPropName] = layer[propName][subPropName]; // Store property's end value at top-level of end values map endValues[propName + '.' + subPropName] = subPropValue; } } } // Delete sub-property of object as it's no longer needed delete endValues[propName]; } } } return endValues; }
javascript
{ "resource": "" }
q28236
_removeSubPropAliases
train
function _removeSubPropAliases(layer) { var propName; for (propName in layer) { if (Object.prototype.hasOwnProperty.call(layer, propName)) { if (propName.indexOf('.') !== -1) { delete layer[propName]; } } } }
javascript
{ "resource": "" }
q28237
_colorToRgbArray
train
function _colorToRgbArray(color) { var originalColor, elem, rgb = [], multiple = 1; // Deal with complete transparency if (color === 'transparent') { color = 'rgba(0, 0, 0, 0)'; } else if (color.match(/^([a-z]+|#[0-9a-f]+)$/gi)) { // Deal with hexadecimal colors and color names elem = document.head; originalColor = elem.style.color; elem.style.color = color; color = $.css(elem, 'color'); elem.style.color = originalColor; } // Parse RGB string if (color.match(/^rgb/gi)) { rgb = color.match(/(\d+(\.\d+)?)/gi); // Deal with RGB percentages if (color.match(/%/gi)) { multiple = 2.55; } rgb[0] *= multiple; rgb[1] *= multiple; rgb[2] *= multiple; // Ad alpha channel if given if (rgb[3] !== undefined) { rgb[3] = parseFloat(rgb[3]); } else { rgb[3] = 1; } } return rgb; }
javascript
{ "resource": "" }
q28238
_animateColor
train
function _animateColor(fx) { var n = 3, i; // Only parse start and end colors once if (typeOf(fx.start) !== 'array') { fx.start = _colorToRgbArray(fx.start); fx.end = _colorToRgbArray(fx.end); } fx.now = []; // If colors are RGBA, animate transparency if (fx.start[3] !== 1 || fx.end[3] !== 1) { n = 4; } // Calculate current frame for red, green, blue, and alpha for (i = 0; i < n; i += 1) { fx.now[i] = fx.start[i] + ((fx.end[i] - fx.start[i]) * fx.pos); // Only the red, green, and blue values must be integers if (i < 3) { fx.now[i] = round(fx.now[i]); } } if (fx.start[3] !== 1 || fx.end[3] !== 1) { // Only use RGBA if RGBA colors are given fx.now = 'rgba(' + fx.now.join(',') + ')'; } else { // Otherwise, animate as solid colors fx.now.slice(0, 3); fx.now = 'rgb(' + fx.now.join(',') + ')'; } // Animate colors for both canvas layers and DOM elements if (fx.elem.nodeName) { fx.elem.style[fx.prop] = fx.now; } else { fx.elem[fx.prop] = fx.now; } }
javascript
{ "resource": "" }
q28239
complete
train
function complete($canvas, data, layer) { return function () { _showProps(layer); _removeSubPropAliases(layer); // Prevent multiple redraw loops if (!data.animating || data.animated === layer) { // Redraw layers on last frame $canvas.drawLayers(); } // Signify the end of an animation loop layer._animating = false; data.animating = false; data.animated = null; // If callback is defined if (args[4]) { // Run callback at the end of the animation args[4].call($canvas[0], layer); } _triggerLayerEvent($canvas, data, layer, 'animateend'); }; }
javascript
{ "resource": "" }
q28240
_supportColorProps
train
function _supportColorProps(props) { var p; for (p = 0; p < props.length; p += 1) { $.fx.step[props[p]] = _animateColor; } }
javascript
{ "resource": "" }
q28241
_getMouseEventName
train
function _getMouseEventName(eventName) { if (maps.mouseEvents[eventName]) { eventName = maps.mouseEvents[eventName]; } return eventName; }
javascript
{ "resource": "" }
q28242
_createEvent
train
function _createEvent(eventName) { jCanvas.events[eventName] = function ($canvas, data) { var helperEventName, touchEventName, eventCache; // Retrieve canvas's event cache eventCache = data.event; // Both mouseover/mouseout events will be managed by a single mousemove event helperEventName = (eventName === 'mouseover' || eventName === 'mouseout') ? 'mousemove' : eventName; touchEventName = _getTouchEventName(helperEventName); function eventCallback(event) { // Cache current mouse position and redraw layers eventCache.x = event.offsetX; eventCache.y = event.offsetY; eventCache.type = helperEventName; eventCache.event = event; // Redraw layers on every trigger of the event; don't redraw if at // least one layer is draggable and there are no layers with // explicit mouseover/mouseout/mousemove events if (event.type !== 'mousemove' || data.redrawOnMousemove || data.drag.dragging) { $canvas.drawLayers({ resetFire: true }); } // Prevent default event behavior event.preventDefault(); } // Ensure the event is not bound more than once if (!data.events[helperEventName]) { // Bind one canvas event which handles all layer events of that type if (touchEventName !== helperEventName) { $canvas.bind(helperEventName + '.jCanvas ' + touchEventName + '.jCanvas', eventCallback); } else { $canvas.bind(helperEventName + '.jCanvas', eventCallback); } // Prevent this event from being bound twice data.events[helperEventName] = true; } }; }
javascript
{ "resource": "" }
q28243
_detectEvents
train
function _detectEvents(canvas, ctx, params) { var layer, data, eventCache, intersects, transforms, x, y, angle; // Use the layer object stored by the given parameters object layer = params._args; // Canvas must have event bindings if (layer) { data = _getCanvasData(canvas); eventCache = data.event; if (eventCache.x !== null && eventCache.y !== null) { // Respect user-defined pixel ratio x = eventCache.x * data.pixelRatio; y = eventCache.y * data.pixelRatio; // Determine if the given coordinates are in the current path intersects = ctx.isPointInPath(x, y) || (ctx.isPointInStroke && ctx.isPointInStroke(x, y)); } transforms = data.transforms; // Allow callback functions to retrieve the mouse coordinates layer.eventX = eventCache.x; layer.eventY = eventCache.y; layer.event = eventCache.event; // Adjust coordinates to match current canvas transformation // Keep track of some transformation values angle = data.transforms.rotate; x = layer.eventX; y = layer.eventY; if (angle !== 0) { // Rotate coordinates if coordinate space has been rotated layer._eventX = (x * cos(-angle)) - (y * sin(-angle)); layer._eventY = (y * cos(-angle)) + (x * sin(-angle)); } else { // Otherwise, no calculations need to be made layer._eventX = x; layer._eventY = y; } // Scale coordinates layer._eventX /= transforms.scaleX; layer._eventY /= transforms.scaleY; // If layer intersects with cursor if (intersects) { // Add it to a list of layers that intersect with cursor data.intersecting.push(layer); } layer.intersects = Boolean(intersects); } }
javascript
{ "resource": "" }
q28244
_addStartArrow
train
function _addStartArrow(canvas, ctx, params, path, x1, y1, x2, y2) { if (!path._arrowAngleConverted) { path.arrowAngle *= params._toRad; path._arrowAngleConverted = true; } if (path.startArrow) { _addArrow(canvas, ctx, params, path, x1, y1, x2, y2); } }
javascript
{ "resource": "" }
q28245
_addEndArrow
train
function _addEndArrow(canvas, ctx, params, path, x1, y1, x2, y2) { if (!path._arrowAngleConverted) { path.arrowAngle *= params._toRad; path._arrowAngleConverted = true; } if (path.endArrow) { _addArrow(canvas, ctx, params, path, x1, y1, x2, y2); } }
javascript
{ "resource": "" }
q28246
_getVectorX
train
function _getVectorX(params, angle, length) { angle *= params._toRad; angle -= (PI / 2); return (length * cos(angle)); }
javascript
{ "resource": "" }
q28247
_getVectorY
train
function _getVectorY(params, angle, length) { angle *= params._toRad; angle -= (PI / 2); return (length * sin(angle)); }
javascript
{ "resource": "" }
q28248
_measureText
train
function _measureText(canvas, ctx, params, lines) { var originalSize, curWidth, l, propCache = caches.propCache; // Used cached width/height if possible if (propCache.text === params.text && propCache.fontStyle === params.fontStyle && propCache.fontSize === params.fontSize && propCache.fontFamily === params.fontFamily && propCache.maxWidth === params.maxWidth && propCache.lineHeight === params.lineHeight) { params.width = propCache.width; params.height = propCache.height; } else { // Calculate text dimensions only once // Calculate width of first line (for comparison) params.width = ctx.measureText(lines[0]).width; // Get width of longest line for (l = 1; l < lines.length; l += 1) { curWidth = ctx.measureText(lines[l]).width; // Ensure text's width is the width of its longest line if (curWidth > params.width) { params.width = curWidth; } } // Save original font size originalSize = canvas.style.fontSize; // Temporarily set canvas font size to retrieve size in pixels canvas.style.fontSize = params.fontSize; // Save text width and height in parameters object params.height = parseFloat($.css(canvas, 'fontSize')) * lines.length * params.lineHeight; // Reset font size to original size canvas.style.fontSize = originalSize; } }
javascript
{ "resource": "" }
q28249
_wrapText
train
function _wrapText(ctx, params) { var allText = String(params.text), // Maximum line width (optional) maxWidth = params.maxWidth, // Lines created by manual line breaks (\n) manualLines = allText.split('\n'), // All lines created manually and by wrapping allLines = [], // Other variables lines, line, l, text, words, w; // Loop through manually-broken lines for (l = 0; l < manualLines.length; l += 1) { text = manualLines[l]; // Split line into list of words words = text.split(' '); lines = []; line = ''; // If text is short enough initially // Or, if the text consists of only one word if (words.length === 1 || ctx.measureText(text).width < maxWidth) { // No need to wrap text lines = [text]; } else { // Wrap lines for (w = 0; w < words.length; w += 1) { // Once line gets too wide, push word to next line if (ctx.measureText(line + words[w]).width > maxWidth) { // This check prevents empty lines from being created if (line !== '') { lines.push(line); } // Start new line and repeat process line = ''; } // Add words to line until the line is too wide line += words[w]; // Do not add a space after the last word if (w !== (words.length - 1)) { line += ' '; } } // The last word should always be pushed lines.push(line); } // Remove extra space at the end of each line allLines = allLines.concat( lines .join('\n') .replace(/((\n))|($)/gi, '$2') .split('\n') ); } return allLines; }
javascript
{ "resource": "" }
q28250
getIntersection
train
function getIntersection(x0, y0, r0, x1, y1, r1) { var dx = x1 - x0, dy = y1 - y0, d = sqrt(pow(dx, 2) + pow(dy, 2)), a = (pow(d, 2) + pow(r0, 2) - pow(r1, 2)) / (2 * d), x2 = x0 + (dx * a / d), y2 = y0 + (dy * a / d), h = sqrt(pow(r0, 2) - pow(a, 2)), rx = -dy * (h / d), ry = dx * (h / d), xi = x2 + rx, yi = y2 + ry; // Check if circles do not intersect or overlap completely if (d > (r0 + r1) || d < Math.abs(r0 - r1)) { return false; } return [xi, yi]; }
javascript
{ "resource": "" }
q28251
getElementName
train
function getElementName (props, tag) { if (typeof props.id === 'string' && !placeholderRe.test(props.id)) { return camelCase(props.id) } if (typeof props.className === 'string' && !placeholderRe.test(props.className)) { return camelCase(props.className.split(' ')[0]) } return tag || 'nanohtml' }
javascript
{ "resource": "" }
q28252
convertPlaceholders
train
function convertPlaceholders (value) { // Probably AST nodes. if (typeof value !== 'string') { return [value] } const items = value.split(placeholderRe) let placeholder = true return items.map((item) => { placeholder = !placeholder return placeholder ? expressions[item] : t.stringLiteral(item) }) }
javascript
{ "resource": "" }
q28253
buildSitemapIndex
train
function buildSitemapIndex (conf) { var xml = []; var lastmod; xml.push('<?xml version="1.0" encoding="UTF-8"?>'); if (conf.xslUrl) { xml.push('<?xml-stylesheet type="text/xsl" href="' + conf.xslUrl + '"?>'); } if (!conf.xmlNs) { xml.push('<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" ' + 'xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0" ' + 'xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" ' + 'xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">'); } else { xml.push('<sitemapindex ' + conf.xmlNs + '>') } if (conf.lastmodISO) { lastmod = conf.lastmodISO; } else if (conf.lastmodrealtime) { lastmod = new Date().toISOString(); } else if (conf.lastmod) { lastmod = new Date(conf.lastmod).toISOString(); } conf.urls.forEach(url => { if (url instanceof Object) { lastmod = url.lastmod ? url.lastmod : lastmod; url = url.url; } xml.push('<sitemap>'); xml.push('<loc>' + url + '</loc>'); if (lastmod) { xml.push('<lastmod>' + lastmod + '</lastmod>'); } xml.push('</sitemap>'); }); xml.push('</sitemapindex>'); return xml.join('\n'); }
javascript
{ "resource": "" }
q28254
Headings
train
function Headings({ toc, path }) { if (!toc.length) { return null } return ( <ul> {toc.map(function(item, index) { const href = `${path}#${item.id}` return ( <li key={index}> {item.children.length > 0 && ( <input id={href} className="nav_toggle" type="checkbox" defaultChecked={false} /> )} <a className={`nav_toggle-label nav_item-name nav_sublink ${item.children.length ? '' : 'nav_childless'}`} href={href} > {item.title} </a> <Headings toc={item.children} path={path} /> </li> ) })} </ul> ) }
javascript
{ "resource": "" }
q28255
findInterfaces
train
function findInterfaces (targets) { if (!targets) targets = [] targets = targets.map(target => target.toLowerCase()) if (process.platform === 'darwin') { return findInterfacesDarwin(targets) } else if (process.platform === 'linux') { return findInterfacesLinux(targets) } else if (process.platform === 'win32') { return findInterfacesWin32(targets) } }
javascript
{ "resource": "" }
q28256
getInterfaceMAC
train
function getInterfaceMAC (device) { if (process.platform === 'darwin' || process.platform === 'linux') { let output try { output = cp.execSync(quote(['ifconfig', device]), { stdio: 'pipe' }).toString() } catch (err) { return null } const address = MAC_ADDRESS_RE.exec(output) return address && normalize(address[0]) } else if (process.platform === 'win32') { console.error('No windows support for this method yet - PR welcome!') } }
javascript
{ "resource": "" }
q28257
setInterfaceMAC
train
function setInterfaceMAC (device, mac, port) { if (!MAC_ADDRESS_RE.exec(mac)) { throw new Error(mac + ' is not a valid MAC address') } const isWirelessPort = port && port.toLowerCase() === 'wi-fi' if (process.platform === 'darwin') { if (isWirelessPort) { // Turn on the device, assuming it's an airport device. try { cp.execSync(quote(['networksetup', '-setairportpower', device, 'on'])) } catch (err) { throw new Error('Unable to power on wifi device') } } // For some reason this seems to be required even when changing a non-airport device. try { cp.execSync(quote([PATH_TO_AIRPORT, '-z'])) } catch (err) { throw new Error('Unable to disassociate from wifi networks') } // Change the MAC. try { cp.execSync(quote(['ifconfig', device, 'ether', mac])) } catch (err) { throw new Error('Unable to change MAC address') } // Restart airport so it will associate with known networks (if any) if (isWirelessPort) { try { cp.execSync(quote(['networksetup', '-setairportpower', device, 'off'])) cp.execSync(quote(['networksetup', '-setairportpower', device, 'on'])) } catch (err) { throw new Error('Unable to set restart wifi device') } } } else if (process.platform === 'linux') { // Set the device's mac address. // Handles shutting down and starting back up interface. try { cp.execSync(quote(['ifconfig', device, 'down', 'hw', 'ether', mac])) cp.execSync(quote(['ifconfig', device, 'up'])) } catch (err) { throw new Error('Unable to change MAC address') } } else if (process.platform === 'win32') { // Locate adapter's registry and update network address (mac) const regKey = new Winreg({ hive: Winreg.HKLM, key: WIN_REGISTRY_PATH }) regKey.keys((err, keys) => { if (err) { console.log('ERROR: ' + err) } else { // Loop over all available keys and find the right adapter for (let i = 0; i < keys.length; i++) { tryWindowsKey(keys[i].key, device, mac) } } }) } }
javascript
{ "resource": "" }
q28258
tryWindowsKey
train
function tryWindowsKey (key, device, mac) { // Skip the Properties key to avoid problems with permissions if (key.indexOf('Properties') > -1) { return false } const networkAdapterKeyPath = new Winreg({ hive: Winreg.HKLM, key: key }) // we need to format the MAC a bit for Windows mac = mac.replace(/:/g, '') networkAdapterKeyPath.values((err, values) => { let gotAdapter = false if (err) { console.log('ERROR: ' + err) } else { for (let x = 0; x < values.length; x++) { if (values[x].name === 'AdapterModel') { gotAdapter = true break } } if (gotAdapter) { networkAdapterKeyPath.set('NetworkAddress', 'REG_SZ', mac, () => { try { cp.execSync('netsh interface set interface "' + device + '" disable') cp.execSync('netsh interface set interface "' + device + '" enable') } catch (err) { throw new Error('Unable to restart device, is the cmd running as admin?') } }) } } }) }
javascript
{ "resource": "" }
q28259
randomize
train
function randomize (localAdmin) { // Randomly assign a VM vendor's MAC address prefix, which should // decrease chance of colliding with existing device's addresses. const vendors = [ [ 0x00, 0x05, 0x69 ], // VMware [ 0x00, 0x50, 0x56 ], // VMware [ 0x00, 0x0C, 0x29 ], // VMware [ 0x00, 0x16, 0x3E ], // Xen [ 0x00, 0x03, 0xFF ], // Microsoft Hyper-V, Virtual Server, Virtual PC [ 0x00, 0x1C, 0x42 ], // Parallels [ 0x00, 0x0F, 0x4B ], // Virtual Iron 4 [ 0x08, 0x00, 0x27 ] // Sun Virtual Box ] // Windows needs specific prefixes sometimes // http://www.wikihow.com/Change-a-Computer's-Mac-Address-in-Windows const windowsPrefixes = [ 'D2', 'D6', 'DA', 'DE' ] const vendor = vendors[random(0, vendors.length - 1)] if (process.platform === 'win32') { vendor[0] = windowsPrefixes[random(0, 3)] } const mac = [ vendor[0], vendor[1], vendor[2], random(0x00, 0x7f), random(0x00, 0xff), random(0x00, 0xff) ] if (localAdmin) { // Universally administered and locally administered addresses are // distinguished by setting the second least significant bit of the // most significant byte of the address. If the bit is 0, the address // is universally administered. If it is 1, the address is locally // administered. In the example address 02-00-00-00-00-01 the most // significant byte is 02h. The binary is 00000010 and the second // least significant bit is 1. Therefore, it is a locally administered // address.[3] The bit is 0 in all OUIs. mac[0] |= 2 } return mac .map(byte => zeroFill(2, byte.toString(16))) .join(':') .toUpperCase() }
javascript
{ "resource": "" }
q28260
logOutput
train
function logOutput(options, parts) { const msg = `${ 'Generated '.blue }${ path.resolve.apply(path, parts).cyan }` log(options, msg) }
javascript
{ "resource": "" }
q28261
generate
train
async function generate(options = {}) { options = Object.assign(DEFAULT_OPTIONS, options) // Log start let msg = `Generating font kit from ${ options.paths.length } SVG icons`.yellow log(options, msg) // Run validation over options await validateOptions(options) if (options.codepoints) { options.codepointsMap = await getCodepointsMap(options.codepoints) } // Run font generation const config = getGeneratorConfig(options) const generatorResult = await fontGenerator(config) // Clean up after generator await deleteUnspecifiedTypes(options) // If specified, generate JSON map if (options.json) { await generateJson(options, generatorResult) } // Log generated files logReport(options) }
javascript
{ "resource": "" }
q28262
getGeneratorConfig
train
function getGeneratorConfig(options) { const { tag, classNames } = parseSelector(options.baseSelector) const config = { files : options.paths, dest : options.outputDir, types : options.types, codepoints : options.codepointsMap, startCodepoint : options.startCodepoint || 0xF101, cssDest : options.cssPath, cssFontsUrl : getCssFontsUrl(options), htmlDest : options.htmlPath, cssTemplate : options.cssTemplate || TEMPLATES.css, htmlTemplate : options.htmlTemplate || TEMPLATES.html, templateOptions : { baseTag : tag || options.baseTag || 'i', baseSelector : options.baseSelector || null, baseClassNames : classNames.join(' '), classPrefix : (options.classPrefix || 'icon') + '-', htmlCssRelativePath : path.relative( path.dirname(getResolvedPath(options, 'html')), getResolvedPath(options, 'css') ) } } // Normalise and add available optional configurations OPTIONAL_PARAMS.forEach(key => { if (typeof options[key] !== 'undefined') { // Parse numeric values if (`${ parseFloat(options[key]) }` === `${ options[key] }`) { options[key] = parseFloat(options[key]) } config[key] = options[key] } }) return config }
javascript
{ "resource": "" }
q28263
parseSelector
train
function parseSelector(selector = '') { const tagMatch = selector.match(/^[a-zA-Z0-9='"[\]_-]*/g) const classNamesMatch = selector.match(/\.[a-zA-Z0-1_-]*/g) return { tag: tagMatch ? tagMatch[0] : undefined, classNames: classNamesMatch ? classNamesMatch.map(cname => cname.substr(1)) : [] } }
javascript
{ "resource": "" }
q28264
getCssFontsUrl
train
function getCssFontsUrl(options) { if (options.cssFontsUrl) { return options.cssFontsUrl } if (options.cssPath) { return path.relative(path.dirname(options.cssPath), options.outputDir) } return './' }
javascript
{ "resource": "" }
q28265
getCodepointsMap
train
async function getCodepointsMap(filepath) { const content = await fsAsync.readFile(filepath) let codepointsMap try { codepointsMap = JSON.parse(content) } catch (e) { throw new ValidationError('Codepoints map is invalid JSON') } for (let propName in codepointsMap) { codepointsMap[propName] = Number.parseInt(codepointsMap[propName]) } return codepointsMap }
javascript
{ "resource": "" }
q28266
getResolvedPath
train
function getResolvedPath(options, type = 'html') { const explicitPathKey = `${ type }Path` if (options[explicitPathKey]) { return path.resolve(options[explicitPathKey]) } return path.resolve(options.outputDir, `${ options.fontName }.${ type }`) }
javascript
{ "resource": "" }
q28267
logReport
train
function logReport(options) { const { outputDir, fontName } = options // Log font files output for (let ext of options.types) { logOutput(options, [ outputDir, `${ fontName }.${ ext }` ]) } // Log HTML file output if (options.html) { logOutput(options, [ getResolvedPath(options, 'html') ]) } // Log CSS file output if (options.css) { logOutput(options, [ getResolvedPath(options, 'css') ]) } // Log JSON map output if (options.json) { logOutput(options, [ getResolvedPath(options, 'json') ]) } // Log final message log(options, 'Done'.green) }
javascript
{ "resource": "" }
q28268
generateJson
train
async function generateJson(options, generatorResult) { const jsonPath = ( options.jsonPath || `${ path.join(options.outputDir, '/' + options.fontName) }.json` ) const css = generatorResult.generateCss() let map = {} css.replace(CSS_PARSE_REGEX, (match, name, code) => map[name] = code) await fsAsync.writeFile(jsonPath, JSON.stringify(map, null, 4)) }
javascript
{ "resource": "" }
q28269
deleteUnspecifiedTypes
train
async function deleteUnspecifiedTypes(options) { const { outputDir, fontName, types } = options for (let ext of FONT_TYPES) { if (types.indexOf(ext) !== -1) { continue } let filepath = path.resolve(outputDir, `${ fontName }.${ ext }`) if (await fsAsync.exists(filepath)) { await fsAsync.unlink(filepath) } } }
javascript
{ "resource": "" }
q28270
validateOptions
train
async function validateOptions(options) { // Check that input glob was passed if (!options.paths.length) { throw new ValidationError('No paths specified') } // Check that output path was passed if (!options.outputDir) { throw new ValidationError('Please specify an output directory with -o or --output') } // Check that the existance of output path if (!await fsAsync.exists(options.outputDir)) { throw new ValidationError('Output directory doesn\'t exist') } // Check that output path is a directory const outStat = await fsAsync.stat(options.outputDir) if (!outStat.isDirectory()) { throw new ValidationError('Output path must be a directory') } // Check existance of CSS template (If set) if (options.cssTemplate && !await fsAsync.exists(options.cssTemplate)) { throw new ValidationError('CSS template not found') } // Check existance of HTML template (If set) if (options.htmlTemplate && !await fsAsync.exists(options.htmlTemplate)) { throw new ValidationError('HTML template not found') } // Validate codepoints file if passed if (options.codepoints) { if (!await fsAsync.exists(options.codepoints)) { throw new ValidationError(`Cannot find json file @ ${options.codepoints}!`) } const codepointsStat = await fsAsync.stat(options.codepoints) if (!codepointsStat.isFile() || path.extname(options.codepoints) !== '.json') { throw new ValidationError([ 'Codepoints file must be JSON', `${options.codepoints} is not a valid file.` ].join(' ')) } } }
javascript
{ "resource": "" }
q28271
sessionMiddleware
train
function sessionMiddleware(req,res,next) { return ss.session.strategy.sessionMiddleware? ss.session.strategy.sessionMiddleware(req,res,next) : next(); }
javascript
{ "resource": "" }
q28272
loadFile
train
function loadFile(entry, opts, formatter, cb, errCb) { var type = entry.assetType || entry.bundle; formatter = formatter || ss.client.formatters[entry.ext || type]; if (!formatter) { throw new Error('Unsupported file extension \'.' + entry.ext + '\' when we were expecting some type of ' + ((type||'unknown').toUpperCase()) + ' file. Please provide a formatter for ' + (entry.file) + ' or move it to /client/static'); } if (formatter.assetType !== type) { throw new Error('Unable to render \'' + entry.file + '\' as this appears to be a ' + (type.toUpperCase()) + ' file. Expecting some type of ' + (type.toUpperCase()) + ' file in ' + (path.dirname(entry.file)) + ' instead'); } // Use the formatter to pre-process the asset before bundling try { return formatter.call(this.clientFilePath(entry.file), opts, cb, errCb); } catch (err) { return errCb(err); } }
javascript
{ "resource": "" }
q28273
train
function(paths) { function relativePath(p, dirType) { var relativeStart = p.indexOf('./') === 0 || p.indexOf('../') === 0; return relativeStart? prefixPath(options.dirs.client,p) : prefixPath(options.dirs[dirType], p); } function prefixPath(base,p) { base = base.replace(/^\//,''); if (p === '*') { return base; } p = p.replace(/\/\*$/,''); return path.join(base,p); } function entries(from, dirType) { if (from == null) { return []; } var list = (from instanceof Array)? from : [from]; return list.map(function(value) { return relativePath(value, dirType); }); } paths.css = entries(paths.css, 'css'); paths.code = entries(paths.code, 'code'); paths.tmpl = entries(paths.tmpl || paths.templates, 'templates'); if (paths.view) { paths.view = relativePath(paths.view, 'views'); } return paths; }
javascript
{ "resource": "" }
q28274
getSession
train
function getSession(sessions, sessionId) { var sess = sessions[sessionId] if (!sess) { debug('no session in MemoryStore for %s',sessionId); return; } // parse sess = JSON.parse(sess) var expires = typeof sess.cookie.expires === 'string' ? new Date(sess.cookie.expires) : sess.cookie.expires // destroy expired session if (expires && expires <= Date.now()) { debug('Session %s is Expired in MemoryStore',sessionId); delete sessions[sessionId]; return; } return sess }
javascript
{ "resource": "" }
q28275
set
train
function set(url, content, mimeType) { if (url.charAt(0) !== '/') { url = '/'+url; } var point = getPoint(url) || new KnownPoint(url); // console.info('new url:',url, mimeType); point.content = content; point.mimeType = mimeType; }
javascript
{ "resource": "" }
q28276
train
function(names, cb) { if (!cb) { cb = function() {}; } if (!session.channels) { session.channels = []; } forceArray(names).forEach(function(name) { if (session.channels.indexOf(name) === -1) { // clients can only join a channel once session.channels.push(name); return ss.log.info('i'.green + ' subscribed sessionId '.grey + session.id + ' to channel '.grey + name); } }); this._bindToSocket(); return session.save(cb); }
javascript
{ "resource": "" }
q28277
train
function(names, cb) { if (!cb) { cb = function() {}; } if (!session.channels) { session.channels = []; } forceArray(names).forEach(function(name) { var i; if ((i = session.channels.indexOf(name)) >= 0) { session.channels.splice(i, 1); subscriptions.channel.remove(name, socketId); return ss.log.info('i'.green + ' unsubscribed sessionId '.grey + session.id + ' from channel '.grey + name); } }); return session.save(cb); }
javascript
{ "resource": "" }
q28278
isDir
train
function isDir(abspath, found) { var stat = fs.statSync(abspath), abspathAry = abspath.split('/'), data, file_name; if (!found) { found = {dirs: [], files: [] } } if (stat.isDirectory() && !isHidden(abspathAry[abspathAry.length - 1])) { found.dirs.push(abspath); /* If we found a directory, recurse! */ data = exports.readDirSync(abspath); found.dirs = found.dirs.concat(data.dirs); found.files = found.files.concat(data.files); } else { abspathAry = abspath.split('/'); file_name = abspathAry[abspathAry.length - 1]; if (!isHidden(file_name)) { found.files.push(abspath); } } return found; }
javascript
{ "resource": "" }
q28279
projectOrHereRequire
train
function projectOrHereRequire(id,root) { try { return resolve.sync(id, { package: path.join(root,'package.json'), paths: [root], basedir:root }); } catch(ex) { // console.error(ex); } var here = path.join(__dirname,'..','..'); try { var p = resolve.sync(id, { package: path.join(here,'package.json'), paths: [here], basedir:here }); return p; } catch(ex) { // console.error(ex); } }
javascript
{ "resource": "" }
q28280
resolveAssetLink
train
function resolveAssetLink(client, type) { var defaultPath = '/assets/' + client.name + '/' + client.id + '.' + type, pack = options.packedAssets, link = pack !== undefined ? (pack.cdn !== undefined ? pack.cdn[type] : void 0) : void 0; if (link) { if (typeof link === 'function') { var file = { id: client.id, name: client.name, extension: type, path: defaultPath }; return link(file); } else if (typeof link === 'string') { return link; } else { throw new Error('CDN ' + type + ' param must be a Function or String'); } } else { return defaultPath; } }
javascript
{ "resource": "" }
q28281
sendToMultiple
train
function sendToMultiple(send, msg, destinations, type) { destinations = destinations instanceof Array && destinations || [destinations]; destinations.forEach(function(destination) { var set, socketIds; set = subscriptions[type]; if ((socketIds = set.members(destination))) { return socketIds.slice(0).forEach(function(socketId) { if (!send.socketId(socketId, msg, destination)) { return set.removeFromAll(socketId); } }); } }); return true; }
javascript
{ "resource": "" }
q28282
train
function(all) { var tasks = all? ['load-api']:['pack-prepare','load-api']; ss.bundler.forEach(function(bundler){ if (all) { tasks.push(bundler.client.name + ':pack'); } else if (bundler.packNeeded) { tasks.push(bundler.client.name + ':pack-needed'); tasks.push(bundler.client.name + ':pack'); } else { tasks.push(bundler.client.name + ':pack-unneeded'); } }); return tasks; }
javascript
{ "resource": "" }
q28283
suggestedId
train
function suggestedId(pth, templatesPath) { if (pth.indexOf(templatesPath) === 0) { pth = pth.substring(templatesPath.length + 1); } var sp; sp = pth.split('.'); if (pth.indexOf('.') > 0) { sp.pop(); } return sp.join('.').replace(/\//g, '-'); }
javascript
{ "resource": "" }
q28284
onChange
train
function onChange(changedPath, event) { var _ref = path.extname(changedPath), action = cssExtensions.indexOf(_ref) >= 0 ? 'updateCSS' : 'reload'; //first change is with delayTime delay , thereafter only once there has been no further changes for guardTime seconds //validate the change if (customOnChange.validate) { if (!customOnChange.validate(changedPath, event,action)) { return ;} //ignore changes if the app says-so } //avoid multiple rapid changes var delay=delayTime; if (lastRun[action].guardTime) { clearTimeout(lastRun[action].guardTime); delay=guardTime;} if (lastRun[action].delayTime) { clearTimeout(lastRun[action].delayTime); delay=delayTime;} lastRun[action].delayTime = setTimeout(function(){ onChangeFiltered(changedPath, event, action); lastRun[action].guardTime = setTimeout(function(){ lastRun[action].guardTime=null; }, delay); lastRun[action].delayTime=null; }, delay); return Date.now(); }
javascript
{ "resource": "" }
q28285
train
function(newOption) { var k, v, y, _results; if (typeof newOption !== 'object') { throw new Error('ss.client.set() takes an object e.g. {liveReload: false}'); } _results = []; for (k in newOption) { if (newOption.hasOwnProperty(k)) { v = newOption[k]; if (v instanceof Object) { //jshint -W083 _results.push((function() { var _results1, x; _results1 = []; for (x in v) { if (v.hasOwnProperty(x)) { y = v[x]; if (!options[k]) { options[k]= {}; } _results1.push(options[k][x] = y); } } return _results1; })()); } else { _results.push(options[k] = v); } } } return _results; }
javascript
{ "resource": "" }
q28286
train
function(opts) { if (opts && typeof opts !== 'object') { throw new Error('Options passed to ss.client.packAssets() must be an object'); } options.packedAssets = opts || true; options.servePacked = opts || true; options.liveReload = false; // As it's safe to assume we're running in production mode at this point, if your app is not catching uncaught // errors with its own custom error handling code, step in and prevent any exceptions from taking the server down if (options.packedAssets && process.listeners('uncaughtException').length === 0) { return process.on('uncaughtException', function(err) { log.error('Uncaught Exception!'.red); return log.error(err.stack); }); } }
javascript
{ "resource": "" }
q28287
train
function() { ss.http.cached.loadStatic(); ss.http.cached.loadAssets(); ss.bundler.updateCachedOndemandAssets(); ss.bundler.forEach(function(bundler) { bundler.updateCachedDevAssets(); }); }
javascript
{ "resource": "" }
q28288
train
function() { if (options.servePacked) { ss.bundler.forEach(function(bundler) { bundler.useLatestsPackedId(); }); } ss.bundler.load(); //TODO convert options.dirs to relative paths stripping the lead '/' if present // Cache instances of code formatters and template engines here // This may change in the future as I don't like hanging system objects // on the 'ss' internal API object, but for now it solves a problem // we were having when repl.start() would erase vars cached inside a module ss.client.formatters = this.formatters.load(); ss.client.templateEngines = this.templateEngine.load(); }
javascript
{ "resource": "" }
q28289
train
function(msg) { for (var id in openSocketsById) { if (openSocketsById.hasOwnProperty(id)) { openSocketsById[id].send('0|' + msg + '|null'); } } }
javascript
{ "resource": "" }
q28290
pattern
train
function pattern (val, pat) { if (typeof pat !== 'string') { return false } var match = pat.match(new RegExp('^/(.*?)/([gimy]*)$')); if (!match) { return false } return new RegExp(match[1], match[2]).test(val) }
javascript
{ "resource": "" }
q28291
minlength
train
function minlength (val, min) { if (typeof val === 'string') { return isInteger(min, 10) && val.length >= parseInt(min, 10) } else if (Array.isArray(val)) { return val.length >= parseInt(min, 10) } else { return false } }
javascript
{ "resource": "" }
q28292
maxlength
train
function maxlength (val, max) { if (typeof val === 'string') { return isInteger(max, 10) && val.length <= parseInt(max, 10) } else if (Array.isArray(val)) { return val.length <= parseInt(max, 10) } else { return false } }
javascript
{ "resource": "" }
q28293
validator
train
function validator ( id, def ) { if (def === undefined) { return Vue.options['validators'][id] } else { Vue.options['validators'][id] = def; if (def === null) { delete Vue.options['validators']['id']; } } }
javascript
{ "resource": "" }
q28294
addMonitoring
train
function addMonitoring(connection, probe) { aspect.around( connection, 'execute', function(target, methodName, args, probeData) { // Start the monitoring for the 'execute' method probe.metricsProbeStart(probeData, methodName, args); probe.requestProbeStart(probeData, methodName, args); // Advise the callback for 'execute'. Will do nothing if no callback is registered aspect.aroundCallback(args, probeData, function(target, callbackArgs, probeData) { // 'execute' has completed and the callback has been called, so end the monitoring // Call the transaction link with a name and the callback for strong trace var callbackPosition = aspect.findCallbackArg(args); if (typeof callbackPosition != 'undefined') { aspect.strongTraceTransactionLink('oracle: ', methodName, args[callbackPosition]); } probe.metricsProbeEnd(probeData, methodName, args); probe.requestProbeEnd(probeData, methodName, args); }); }, function(target, methodName, args, probeData, rc) { // If no callback used then end the monitoring after returning from the 'execute' method instead if (aspect.findCallbackArg(args) == undefined) { probe.metricsProbeEnd(probeData, methodName, args); probe.requestProbeEnd(probeData, methodName, args); } return rc; } ); }
javascript
{ "resource": "" }
q28295
train
function(target, methodName, methodArgs, probeData, rc) { // If no callback has been used then end the metrics after returning from the method instead if (aspect.findCallbackArg(methodArgs) === undefined) { // Need to get request method and URL again var ri = getRequestItems(methodArgs[0]); // End metrics (no response available so pass empty object) that.metricsProbeEnd(probeData, ri.requestMethod, ri.urlRequested, {}, ri.headers); that.requestProbeEnd(probeData, ri.requestMethod, ri.urlRequested, {}, ri.headers); } return rc; }
javascript
{ "resource": "" }
q28296
train
function() { var lvldownObj = target.apply(null, arguments); lvldownObj._ddProbeAttached_ = true; aspectLvldownMethod(lvldownObj, methods, that); return lvldownObj; }
javascript
{ "resource": "" }
q28297
train
function(obj, methodName, methodArgs, probeData) { // Start metrics that.metricsProbeStart(probeData); that.requestProbeStart(probeData); // End metrics aspect.aroundCallback( methodArgs, probeData, function(target, args, probeData) { // Get HTTP request method from options var ri = getRequestItems(methodArgs[0]); that.metricsProbeEnd(probeData, ri.requestMethod, ri.urlRequested, args[0], ri.headers); that.requestProbeEnd(probeData, ri.requestMethod, ri.urlRequested, args[0], ri.headers); }, function(target, args, probeData, ret) { // Don't need to do anything after the callback return ret; } ); }
javascript
{ "resource": "" }
q28298
done
train
function done(output, options, config, failures, exit) { return marge.create(output, options) .then(([ htmlFile, jsonFile ]) => { if (!htmlFile && !jsonFile) { log('No files were generated', 'warn', config); } else { jsonFile && log(`Report JSON saved to ${jsonFile}`, null, config); htmlFile && log(`Report HTML saved to ${htmlFile}`, null, config); } }) .catch(err => { log(err, 'error', config); }) .then(() => { exit && exit(failures > 0 ? 1 : 0); }); }
javascript
{ "resource": "" }
q28299
Mochawesome
train
function Mochawesome(runner, options) { // Set the config options this.config = conf(options); // Reporter options const reporterOptions = Object.assign( {}, (options.reporterOptions || {}), { reportFilename: this.config.reportFilename, saveHtml: this.config.saveHtml, saveJson: this.config.saveJson } ); // Done function will be called before mocha exits // This is where we will save JSON and generate the HTML report this.done = (failures, exit) => done( this.output, reporterOptions, this.config, failures, exit ); // Reset total tests counter totalTestsRegistered.total = 0; // Call the Base mocha reporter Base.call(this, runner); // Show the Spec Reporter in the console new Spec(runner); // eslint-disable-line let endCalled = false; // Add a unique identifier to each test/hook runner.on('test', test => { test.uuid = uuid.v4(); }); runner.on('hook', hook => { hook.uuid = uuid.v4(); }); runner.on('pending', test => { test.uuid = uuid.v4(); }); // Process the full suite runner.on('end', () => { try { /* istanbul ignore else */ if (!endCalled) { // end gets called more than once for some reason // so we ensure the suite is processed only once endCalled = true; const allSuites = mapSuites(this.runner.suite, totalTestsRegistered, this.config); const obj = { stats: this.stats, suites: allSuites, copyrightYear: new Date().getFullYear() }; obj.stats.testsRegistered = totalTestsRegistered.total; const { passes, failures, pending, tests, testsRegistered } = obj.stats; const passPercentage = Math.round((passes / (testsRegistered - pending)) * 1000) / 10; const pendingPercentage = Math.round((pending / testsRegistered) * 1000) /10; obj.stats.passPercent = passPercentage; obj.stats.pendingPercent = pendingPercentage; obj.stats.other = (passes + failures + pending) - tests; obj.stats.hasOther = obj.stats.other > 0; obj.stats.skipped = testsRegistered - tests; obj.stats.hasSkipped = obj.stats.skipped > 0; obj.stats.failures -= obj.stats.other; obj.stats.passPercentClass = getPercentClass(passPercentage); obj.stats.pendingPercentClass = getPercentClass(pendingPercentage); // Save the final output to be used in the done function this.output = obj; } } catch (e) { // required because thrown errors are not handled directly in the // event emitter pattern and mocha does not have an "on error" /* istanbul ignore next */ log(`Problem with mochawesome: ${e.stack}`, 'error'); } }); }
javascript
{ "resource": "" }