id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
30,700
resonance-audio/resonance-audio-web-sdk
examples/resources/js/treasure-hunt.js
updateAngles
function updateAngles(xAngle, yAngle, zAngle) { let deg2rad = Math.PI / 180; let euler = new THREE.Euler( xAngle * deg2rad, yAngle * deg2rad, zAngle * deg2rad, 'YXZ'); let matrix = new THREE.Matrix4().makeRotationFromEuler(euler); camera.setRotationFromMatrix(matrix); if (!audioReady) return; if (Date.now() - lastMatrixUpdate > 100) { audioScene.setListenerFromMatrix(camera.matrixWorld); } }
javascript
function updateAngles(xAngle, yAngle, zAngle) { let deg2rad = Math.PI / 180; let euler = new THREE.Euler( xAngle * deg2rad, yAngle * deg2rad, zAngle * deg2rad, 'YXZ'); let matrix = new THREE.Matrix4().makeRotationFromEuler(euler); camera.setRotationFromMatrix(matrix); if (!audioReady) return; if (Date.now() - lastMatrixUpdate > 100) { audioScene.setListenerFromMatrix(camera.matrixWorld); } }
[ "function", "updateAngles", "(", "xAngle", ",", "yAngle", ",", "zAngle", ")", "{", "let", "deg2rad", "=", "Math", ".", "PI", "/", "180", ";", "let", "euler", "=", "new", "THREE", ".", "Euler", "(", "xAngle", "*", "deg2rad", ",", "yAngle", "*", "deg2r...
Compute rotation matrix. @param {Number} xAngle @param {Number} yAngle @param {Number} zAngle @private
[ "Compute", "rotation", "matrix", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/examples/resources/js/treasure-hunt.js#L41-L56
30,701
resonance-audio/resonance-audio-web-sdk
examples/resources/js/treasure-hunt.js
getCursorPosition
function getCursorPosition(event) { let cursorX; let cursorY; let rect = htmlElement.getBoundingClientRect(); if (event.touches !== undefined) { cursorX = event.touches[0].clientX; cursorY = event.touches[0].clientY; } else { cursorX = event.clientX; cursorY = event.clientY; } return { x: cursorX - rect.left, y: cursorY - rect.top, }; }
javascript
function getCursorPosition(event) { let cursorX; let cursorY; let rect = htmlElement.getBoundingClientRect(); if (event.touches !== undefined) { cursorX = event.touches[0].clientX; cursorY = event.touches[0].clientY; } else { cursorX = event.clientX; cursorY = event.clientY; } return { x: cursorX - rect.left, y: cursorY - rect.top, }; }
[ "function", "getCursorPosition", "(", "event", ")", "{", "let", "cursorX", ";", "let", "cursorY", ";", "let", "rect", "=", "htmlElement", ".", "getBoundingClientRect", "(", ")", ";", "if", "(", "event", ".", "touches", "!==", "undefined", ")", "{", "cursor...
Get cursor position on canvas. @param {Object} event @return {Object} @private
[ "Get", "cursor", "position", "on", "canvas", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/examples/resources/js/treasure-hunt.js#L64-L79
30,702
resonance-audio/resonance-audio-web-sdk
examples/resources/js/vs-pannernode.js
selectRenderingMode
function selectRenderingMode(event) { if (!audioReady) return; switch (document.getElementById('renderingMode').value) { case 'toa': { noneGain.gain.value = 0; pannerGain.gain.value = 0; foaGain.gain.value = 0; toaGain.gain.value = 1; } break; case 'foa': { noneGain.gain.value = 0; pannerGain.gain.value = 0; foaGain.gain.value = 1; toaGain.gain.value = 0; } break; case 'panner-node': { noneGain.gain.value = 0; pannerGain.gain.value = 1; foaGain.gain.value = 0; toaGain.gain.value = 0; } break; case 'none': default: { noneGain.gain.value = 1; pannerGain.gain.value = 0; foaGain.gain.value = 0; toaGain.gain.value = 0; } break; } }
javascript
function selectRenderingMode(event) { if (!audioReady) return; switch (document.getElementById('renderingMode').value) { case 'toa': { noneGain.gain.value = 0; pannerGain.gain.value = 0; foaGain.gain.value = 0; toaGain.gain.value = 1; } break; case 'foa': { noneGain.gain.value = 0; pannerGain.gain.value = 0; foaGain.gain.value = 1; toaGain.gain.value = 0; } break; case 'panner-node': { noneGain.gain.value = 0; pannerGain.gain.value = 1; foaGain.gain.value = 0; toaGain.gain.value = 0; } break; case 'none': default: { noneGain.gain.value = 1; pannerGain.gain.value = 0; foaGain.gain.value = 0; toaGain.gain.value = 0; } break; } }
[ "function", "selectRenderingMode", "(", "event", ")", "{", "if", "(", "!", "audioReady", ")", "return", ";", "switch", "(", "document", ".", "getElementById", "(", "'renderingMode'", ")", ".", "value", ")", "{", "case", "'toa'", ":", "{", "noneGain", ".", ...
Select the desired rendering mode. @param {Object} event @private
[ "Select", "the", "desired", "rendering", "mode", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/examples/resources/js/vs-pannernode.js#L21-L60
30,703
resonance-audio/resonance-audio-web-sdk
examples/resources/js/vs-pannernode.js
updatePositions
function updatePositions(elements) { if (!audioReady) return; for (let i = 0; i < elements.length; i++) { let x = (elements[i].x - 0.5) * dimensions.width / 2; let y = 0; let z = (elements[i].y - 0.5) * dimensions.depth / 2; if (i == 0) { pannerNode.setPosition(x, y, z); foaSource.setPosition(x, y, z); toaSource.setPosition(x, y, z); } else { audioContext.listener.setPosition(x, y, z); foaScene.setListenerPosition(x, y, z); toaScene.setListenerPosition(x, y, z); } } }
javascript
function updatePositions(elements) { if (!audioReady) return; for (let i = 0; i < elements.length; i++) { let x = (elements[i].x - 0.5) * dimensions.width / 2; let y = 0; let z = (elements[i].y - 0.5) * dimensions.depth / 2; if (i == 0) { pannerNode.setPosition(x, y, z); foaSource.setPosition(x, y, z); toaSource.setPosition(x, y, z); } else { audioContext.listener.setPosition(x, y, z); foaScene.setListenerPosition(x, y, z); toaScene.setListenerPosition(x, y, z); } } }
[ "function", "updatePositions", "(", "elements", ")", "{", "if", "(", "!", "audioReady", ")", "return", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "i", "++", ")", "{", "let", "x", "=", "(", "elements", "[...
Update the audio sound objects' positions. @param {Object} elements @private
[ "Update", "the", "audio", "sound", "objects", "positions", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/examples/resources/js/vs-pannernode.js#L67-L85
30,704
resonance-audio/resonance-audio-web-sdk
src/room.js
_getCoefficientsFromMaterials
function _getCoefficientsFromMaterials(materials) { // Initialize coefficients to use defaults. let coefficients = {}; for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (Utils.DEFAULT_ROOM_MATERIALS.hasOwnProperty(property)) { coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[ Utils.DEFAULT_ROOM_MATERIALS[property]]; } } // Sanitize materials. if (materials == undefined) { materials = {}; Object.assign(materials, Utils.DEFAULT_ROOM_MATERIALS); } // Assign coefficients using provided materials. for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (Utils.DEFAULT_ROOM_MATERIALS.hasOwnProperty(property) && materials.hasOwnProperty(property)) { if (materials[property] in Utils.ROOM_MATERIAL_COEFFICIENTS) { coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[materials[property]]; } else { Utils.log('Material \"' + materials[property] + '\" on wall \"' + property + '\" not found. Using \"' + Utils.DEFAULT_ROOM_MATERIALS[property] + '\".'); } } else { Utils.log('Wall \"' + property + '\" is not defined. Default used.'); } } return coefficients; }
javascript
function _getCoefficientsFromMaterials(materials) { // Initialize coefficients to use defaults. let coefficients = {}; for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (Utils.DEFAULT_ROOM_MATERIALS.hasOwnProperty(property)) { coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[ Utils.DEFAULT_ROOM_MATERIALS[property]]; } } // Sanitize materials. if (materials == undefined) { materials = {}; Object.assign(materials, Utils.DEFAULT_ROOM_MATERIALS); } // Assign coefficients using provided materials. for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (Utils.DEFAULT_ROOM_MATERIALS.hasOwnProperty(property) && materials.hasOwnProperty(property)) { if (materials[property] in Utils.ROOM_MATERIAL_COEFFICIENTS) { coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[materials[property]]; } else { Utils.log('Material \"' + materials[property] + '\" on wall \"' + property + '\" not found. Using \"' + Utils.DEFAULT_ROOM_MATERIALS[property] + '\".'); } } else { Utils.log('Wall \"' + property + '\" is not defined. Default used.'); } } return coefficients; }
[ "function", "_getCoefficientsFromMaterials", "(", "materials", ")", "{", "// Initialize coefficients to use defaults.", "let", "coefficients", "=", "{", "}", ";", "for", "(", "let", "property", "in", "Utils", ".", "DEFAULT_ROOM_MATERIALS", ")", "{", "if", "(", "Util...
Generate absorption coefficients from material names. @param {Object} materials @return {Object}
[ "Generate", "absorption", "coefficients", "from", "material", "names", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/room.js#L36-L69
30,705
resonance-audio/resonance-audio-web-sdk
src/room.js
_sanitizeCoefficients
function _sanitizeCoefficients(coefficients) { if (coefficients == undefined) { coefficients = {}; } for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (!(coefficients.hasOwnProperty(property))) { // If element is not present, use default coefficients. coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[ Utils.DEFAULT_ROOM_MATERIALS[property]]; } } return coefficients; }
javascript
function _sanitizeCoefficients(coefficients) { if (coefficients == undefined) { coefficients = {}; } for (let property in Utils.DEFAULT_ROOM_MATERIALS) { if (!(coefficients.hasOwnProperty(property))) { // If element is not present, use default coefficients. coefficients[property] = Utils.ROOM_MATERIAL_COEFFICIENTS[ Utils.DEFAULT_ROOM_MATERIALS[property]]; } } return coefficients; }
[ "function", "_sanitizeCoefficients", "(", "coefficients", ")", "{", "if", "(", "coefficients", "==", "undefined", ")", "{", "coefficients", "=", "{", "}", ";", "}", "for", "(", "let", "property", "in", "Utils", ".", "DEFAULT_ROOM_MATERIALS", ")", "{", "if", ...
Sanitize coefficients. @param {Object} coefficients @return {Object}
[ "Sanitize", "coefficients", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/room.js#L76-L88
30,706
resonance-audio/resonance-audio-web-sdk
src/room.js
_sanitizeDimensions
function _sanitizeDimensions(dimensions) { if (dimensions == undefined) { dimensions = {}; } for (let property in Utils.DEFAULT_ROOM_DIMENSIONS) { if (!(dimensions.hasOwnProperty(property))) { dimensions[property] = Utils.DEFAULT_ROOM_DIMENSIONS[property]; } } return dimensions; }
javascript
function _sanitizeDimensions(dimensions) { if (dimensions == undefined) { dimensions = {}; } for (let property in Utils.DEFAULT_ROOM_DIMENSIONS) { if (!(dimensions.hasOwnProperty(property))) { dimensions[property] = Utils.DEFAULT_ROOM_DIMENSIONS[property]; } } return dimensions; }
[ "function", "_sanitizeDimensions", "(", "dimensions", ")", "{", "if", "(", "dimensions", "==", "undefined", ")", "{", "dimensions", "=", "{", "}", ";", "}", "for", "(", "let", "property", "in", "Utils", ".", "DEFAULT_ROOM_DIMENSIONS", ")", "{", "if", "(", ...
Sanitize dimensions. @param {Utils~RoomDimensions} dimensions @return {Utils~RoomDimensions}
[ "Sanitize", "dimensions", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/room.js#L95-L105
30,707
resonance-audio/resonance-audio-web-sdk
src/room.js
_getDurationsFromProperties
function _getDurationsFromProperties(dimensions, coefficients, speedOfSound) { let durations = new Float32Array(Utils.NUMBER_REVERB_FREQUENCY_BANDS); // Sanitize inputs. dimensions = _sanitizeDimensions(dimensions); coefficients = _sanitizeCoefficients(coefficients); if (speedOfSound == undefined) { speedOfSound = Utils.DEFAULT_SPEED_OF_SOUND; } // Acoustic constant. let k = Utils.TWENTY_FOUR_LOG10 / speedOfSound; // Compute volume, skip if room is not present. let volume = dimensions.width * dimensions.height * dimensions.depth; if (volume < Utils.ROOM_MIN_VOLUME) { return durations; } // Room surface area. let leftRightArea = dimensions.width * dimensions.height; let floorCeilingArea = dimensions.width * dimensions.depth; let frontBackArea = dimensions.depth * dimensions.height; let totalArea = 2 * (leftRightArea + floorCeilingArea + frontBackArea); for (let i = 0; i < Utils.NUMBER_REVERB_FREQUENCY_BANDS; i++) { // Effective absorptive area. let absorbtionArea = (coefficients.left[i] + coefficients.right[i]) * leftRightArea + (coefficients.down[i] + coefficients.up[i]) * floorCeilingArea + (coefficients.front[i] + coefficients.back[i]) * frontBackArea; let meanAbsorbtionArea = absorbtionArea / totalArea; // Compute reverberation using Eyring equation [1]. // [1] Beranek, Leo L. "Analysis of Sabine and Eyring equations and their // application to concert hall audience and chair absorption." The // Journal of the Acoustical Society of America, Vol. 120, No. 3. // (2006), pp. 1399-1399. durations[i] = Utils.ROOM_EYRING_CORRECTION_COEFFICIENT * k * volume / (-totalArea * Math.log(1 - meanAbsorbtionArea) + 4 * Utils.ROOM_AIR_ABSORPTION_COEFFICIENTS[i] * volume); } return durations; }
javascript
function _getDurationsFromProperties(dimensions, coefficients, speedOfSound) { let durations = new Float32Array(Utils.NUMBER_REVERB_FREQUENCY_BANDS); // Sanitize inputs. dimensions = _sanitizeDimensions(dimensions); coefficients = _sanitizeCoefficients(coefficients); if (speedOfSound == undefined) { speedOfSound = Utils.DEFAULT_SPEED_OF_SOUND; } // Acoustic constant. let k = Utils.TWENTY_FOUR_LOG10 / speedOfSound; // Compute volume, skip if room is not present. let volume = dimensions.width * dimensions.height * dimensions.depth; if (volume < Utils.ROOM_MIN_VOLUME) { return durations; } // Room surface area. let leftRightArea = dimensions.width * dimensions.height; let floorCeilingArea = dimensions.width * dimensions.depth; let frontBackArea = dimensions.depth * dimensions.height; let totalArea = 2 * (leftRightArea + floorCeilingArea + frontBackArea); for (let i = 0; i < Utils.NUMBER_REVERB_FREQUENCY_BANDS; i++) { // Effective absorptive area. let absorbtionArea = (coefficients.left[i] + coefficients.right[i]) * leftRightArea + (coefficients.down[i] + coefficients.up[i]) * floorCeilingArea + (coefficients.front[i] + coefficients.back[i]) * frontBackArea; let meanAbsorbtionArea = absorbtionArea / totalArea; // Compute reverberation using Eyring equation [1]. // [1] Beranek, Leo L. "Analysis of Sabine and Eyring equations and their // application to concert hall audience and chair absorption." The // Journal of the Acoustical Society of America, Vol. 120, No. 3. // (2006), pp. 1399-1399. durations[i] = Utils.ROOM_EYRING_CORRECTION_COEFFICIENT * k * volume / (-totalArea * Math.log(1 - meanAbsorbtionArea) + 4 * Utils.ROOM_AIR_ABSORPTION_COEFFICIENTS[i] * volume); } return durations; }
[ "function", "_getDurationsFromProperties", "(", "dimensions", ",", "coefficients", ",", "speedOfSound", ")", "{", "let", "durations", "=", "new", "Float32Array", "(", "Utils", ".", "NUMBER_REVERB_FREQUENCY_BANDS", ")", ";", "// Sanitize inputs.", "dimensions", "=", "_...
Compute frequency-dependent reverb durations. @param {Utils~RoomDimensions} dimensions @param {Object} coefficients @param {Number} speedOfSound @return {Array}
[ "Compute", "frequency", "-", "dependent", "reverb", "durations", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/room.js#L114-L156
30,708
resonance-audio/resonance-audio-web-sdk
src/room.js
_computeReflectionCoefficients
function _computeReflectionCoefficients(absorptionCoefficients) { let reflectionCoefficients = []; for (let property in Utils.DEFAULT_REFLECTION_COEFFICIENTS) { if (Utils.DEFAULT_REFLECTION_COEFFICIENTS .hasOwnProperty(property)) { // Compute average absorption coefficient (per wall). reflectionCoefficients[property] = 0; for (let j = 0; j < Utils.NUMBER_REFLECTION_AVERAGING_BANDS; j++) { let bandIndex = j + Utils.ROOM_STARTING_AVERAGING_BAND; reflectionCoefficients[property] += absorptionCoefficients[property][bandIndex]; } reflectionCoefficients[property] /= Utils.NUMBER_REFLECTION_AVERAGING_BANDS; // Convert absorption coefficient to reflection coefficient. reflectionCoefficients[property] = Math.sqrt(1 - reflectionCoefficients[property]); } } return reflectionCoefficients; }
javascript
function _computeReflectionCoefficients(absorptionCoefficients) { let reflectionCoefficients = []; for (let property in Utils.DEFAULT_REFLECTION_COEFFICIENTS) { if (Utils.DEFAULT_REFLECTION_COEFFICIENTS .hasOwnProperty(property)) { // Compute average absorption coefficient (per wall). reflectionCoefficients[property] = 0; for (let j = 0; j < Utils.NUMBER_REFLECTION_AVERAGING_BANDS; j++) { let bandIndex = j + Utils.ROOM_STARTING_AVERAGING_BAND; reflectionCoefficients[property] += absorptionCoefficients[property][bandIndex]; } reflectionCoefficients[property] /= Utils.NUMBER_REFLECTION_AVERAGING_BANDS; // Convert absorption coefficient to reflection coefficient. reflectionCoefficients[property] = Math.sqrt(1 - reflectionCoefficients[property]); } } return reflectionCoefficients; }
[ "function", "_computeReflectionCoefficients", "(", "absorptionCoefficients", ")", "{", "let", "reflectionCoefficients", "=", "[", "]", ";", "for", "(", "let", "property", "in", "Utils", ".", "DEFAULT_REFLECTION_COEFFICIENTS", ")", "{", "if", "(", "Utils", ".", "DE...
Compute reflection coefficients from absorption coefficients. @param {Object} absorptionCoefficients @return {Object}
[ "Compute", "reflection", "coefficients", "from", "absorption", "coefficients", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/room.js#L164-L185
30,709
resonance-audio/resonance-audio-web-sdk
src/source.js
_computeDistanceOutsideRoom
function _computeDistanceOutsideRoom(distance) { // We apply a linear ramp from 1 to 0 as the source is up to 1m outside. let gain = 1; if (distance > Utils.EPSILON_FLOAT) { gain = 1 - distance / Utils.SOURCE_MAX_OUTSIDE_ROOM_DISTANCE; // Clamp gain between 0 and 1. gain = Math.max(0, Math.min(1, gain)); } return gain; }
javascript
function _computeDistanceOutsideRoom(distance) { // We apply a linear ramp from 1 to 0 as the source is up to 1m outside. let gain = 1; if (distance > Utils.EPSILON_FLOAT) { gain = 1 - distance / Utils.SOURCE_MAX_OUTSIDE_ROOM_DISTANCE; // Clamp gain between 0 and 1. gain = Math.max(0, Math.min(1, gain)); } return gain; }
[ "function", "_computeDistanceOutsideRoom", "(", "distance", ")", "{", "// We apply a linear ramp from 1 to 0 as the source is up to 1m outside.", "let", "gain", "=", "1", ";", "if", "(", "distance", ">", "Utils", ".", "EPSILON_FLOAT", ")", "{", "gain", "=", "1", "-", ...
Determine the distance a source is outside of a room. Attenuate gain going to the reflections and reverb when the source is outside of the room. @param {Number} distance Distance in meters. @return {Number} Gain (linear) of source. @private
[ "Determine", "the", "distance", "a", "source", "is", "outside", "of", "a", "room", ".", "Attenuate", "gain", "going", "to", "the", "reflections", "and", "reverb", "when", "the", "source", "is", "outside", "of", "the", "room", "." ]
c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6
https://github.com/resonance-audio/resonance-audio-web-sdk/blob/c69e41dae836aea5b41cf4e9e51efcd96e5d0bb6/src/source.js#L344-L354
30,710
feedhenry/fh-forms
lib/impl/importForms/inputValidator.js
validateJSonStructure
function validateJSonStructure(filePath, cb) { fs.readFile(filePath, function(err, data) { if (err) { return cb(err); } try { var jsonObject = JSON.parse(data); cb(null, jsonObject); } catch (e) { cb('Invalid JSON file: ' + path.basename(filePath)); } }); }
javascript
function validateJSonStructure(filePath, cb) { fs.readFile(filePath, function(err, data) { if (err) { return cb(err); } try { var jsonObject = JSON.parse(data); cb(null, jsonObject); } catch (e) { cb('Invalid JSON file: ' + path.basename(filePath)); } }); }
[ "function", "validateJSonStructure", "(", "filePath", ",", "cb", ")", "{", "fs", ".", "readFile", "(", "filePath", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "try", "{"...
Checks that the received file is a well formed json @param {string} filePath path to the JSon file @param {function} cb callback
[ "Checks", "that", "the", "received", "file", "is", "a", "well", "formed", "json" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/inputValidator.js#L11-L24
30,711
feedhenry/fh-forms
lib/impl/importForms/inputValidator.js
validateMetadata
function validateMetadata(metadataPath, cb) { validateJSonStructure(metadataPath, function(err, metadataObject) { if (err) { cb(err, null); } else { cb(null, metadataObject.files); } }); }
javascript
function validateMetadata(metadataPath, cb) { validateJSonStructure(metadataPath, function(err, metadataObject) { if (err) { cb(err, null); } else { cb(null, metadataObject.files); } }); }
[ "function", "validateMetadata", "(", "metadataPath", ",", "cb", ")", "{", "validateJSonStructure", "(", "metadataPath", ",", "function", "(", "err", ",", "metadataObject", ")", "{", "if", "(", "err", ")", "{", "cb", "(", "err", ",", "null", ")", ";", "}"...
Validates the metadata.json file @param {string} metadataPath path to themetadata.json file @param {function} cb callback
[ "Validates", "the", "metadata", ".", "json", "file" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/inputValidator.js#L32-L40
30,712
feedhenry/fh-forms
lib/impl/importForms/inputValidator.js
validateForm
function validateForm(form, cb) { async.series([function(callback) { fs.exists(form, function(exists) { if (exists) { callback(null); } else { callback('File ' + path.basename(form) + ' referenced by metadata.json does not exists'); } }); }, function(callback) { validateJSonStructure(form, callback); } ], function(err, data) { cb(err, data); }); }
javascript
function validateForm(form, cb) { async.series([function(callback) { fs.exists(form, function(exists) { if (exists) { callback(null); } else { callback('File ' + path.basename(form) + ' referenced by metadata.json does not exists'); } }); }, function(callback) { validateJSonStructure(form, callback); } ], function(err, data) { cb(err, data); }); }
[ "function", "validateForm", "(", "form", ",", "cb", ")", "{", "async", ".", "series", "(", "[", "function", "(", "callback", ")", "{", "fs", ".", "exists", "(", "form", ",", "function", "(", "exists", ")", "{", "if", "(", "exists", ")", "{", "callb...
Validate the received form file. @param {string} form path to the form file to be validated @param {function} cb callback
[ "Validate", "the", "received", "form", "file", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/inputValidator.js#L48-L65
30,713
feedhenry/fh-forms
lib/impl/importForms/inputValidator.js
validate
function validate(archiveDirectory, strict, cb) { // Root validation checks fs.readdir(archiveDirectory, function(err, files) { if (err) { return cb(err); } if (files.length < 2 || (files.length !== 2 && strict)) { return cb('Root directory must contain exactly one metadata file and one forms directory'); } if (files.indexOf('forms') === -1) { return cb('A forms directory should be present in the root of the zip file'); } if (files.indexOf('metadata.json') === -1) { return cb('A metadata.json file must be present in the root of the zip file'); } var metadataPath = path.join(archiveDirectory, 'metadata.json'); async.waterfall([ function(callback) { validateMetadata(metadataPath, function(err, formFiles) { callback(err, formFiles); }); }, function(formFiles, callback) { var forms = []; _.each(formFiles, function(formFile) { forms.push(path.join(archiveDirectory, formFile.path)); }); async.each(forms, validateForm, callback); } ], function(err) { cb(err); }); }); }
javascript
function validate(archiveDirectory, strict, cb) { // Root validation checks fs.readdir(archiveDirectory, function(err, files) { if (err) { return cb(err); } if (files.length < 2 || (files.length !== 2 && strict)) { return cb('Root directory must contain exactly one metadata file and one forms directory'); } if (files.indexOf('forms') === -1) { return cb('A forms directory should be present in the root of the zip file'); } if (files.indexOf('metadata.json') === -1) { return cb('A metadata.json file must be present in the root of the zip file'); } var metadataPath = path.join(archiveDirectory, 'metadata.json'); async.waterfall([ function(callback) { validateMetadata(metadataPath, function(err, formFiles) { callback(err, formFiles); }); }, function(formFiles, callback) { var forms = []; _.each(formFiles, function(formFile) { forms.push(path.join(archiveDirectory, formFile.path)); }); async.each(forms, validateForm, callback); } ], function(err) { cb(err); }); }); }
[ "function", "validate", "(", "archiveDirectory", ",", "strict", ",", "cb", ")", "{", "// Root validation checks", "fs", ".", "readdir", "(", "archiveDirectory", ",", "function", "(", "err", ",", "files", ")", "{", "if", "(", "err", ")", "{", "return", "cb"...
Validates the content of the extracted ZIP to check that it is a valid archive to be imported. @param {string} archiveDirectory The directory where the ZIP archive has been unzipped @param {boolean} strict if true, strict checks must be performed: no extraneous files will be admitted. @param {function} cb callback
[ "Validates", "the", "content", "of", "the", "extracted", "ZIP", "to", "check", "that", "it", "is", "a", "valid", "archive", "to", "be", "imported", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/inputValidator.js#L75-L115
30,714
back4app/back4app-entity
src/back/models/attributes/Attribute.js
resolve
function resolve() { expect(arguments).to.have.length.within( 1, 4, 'Invalid arguments length when resolving an Attribute (it has to be ' + 'passed from 1 to 4 arguments)' ); var argumentArray = Array.prototype.slice.call(arguments); var TypedAttribute = attributes.types.ObjectAttribute; if (arguments.length === 1 && typeof arguments[0] !== 'string') { var attribute = objects.copy(arguments[0]); argumentArray[0] = attribute; expect(attribute).to.be.an( 'object', 'Invalid argument type when resolving an Attribute (it has to be an ' + 'object)' ); if (attribute.type) { expect(attribute.type).to.be.a( 'string', 'Invalid argument "type" when resolving an Attribute' + (attribute.name ? ' called' + attribute.name : '') + ' (it has to be a string)' ); try { TypedAttribute = attributes.types.get(attribute.type); } catch (e) { if (e instanceof errors.AttributeTypeNotFoundError) { TypedAttribute = attributes.types.AssociationAttribute; attribute.entity = attribute.type; } else { throw e; } } delete attribute.type; } } else { if (arguments.length > 1) { expect(arguments[1]).to.be.a( 'string', 'Invalid argument "type" when resolving an Attribute' + (arguments[0] ? ' called' + arguments[0] : '') + ' (it has to be a string)' ); try { TypedAttribute = attributes.types.get(arguments[1]); } catch (e) { if (e instanceof errors.AttributeTypeNotFoundError) { TypedAttribute = attributes.types.AssociationAttribute; argumentArray.splice(2, 0, arguments[1]); } else { throw e; } } argumentArray.splice(1,1); } } return new (Function.prototype.bind.apply( TypedAttribute, [null].concat(argumentArray) ))(); }
javascript
function resolve() { expect(arguments).to.have.length.within( 1, 4, 'Invalid arguments length when resolving an Attribute (it has to be ' + 'passed from 1 to 4 arguments)' ); var argumentArray = Array.prototype.slice.call(arguments); var TypedAttribute = attributes.types.ObjectAttribute; if (arguments.length === 1 && typeof arguments[0] !== 'string') { var attribute = objects.copy(arguments[0]); argumentArray[0] = attribute; expect(attribute).to.be.an( 'object', 'Invalid argument type when resolving an Attribute (it has to be an ' + 'object)' ); if (attribute.type) { expect(attribute.type).to.be.a( 'string', 'Invalid argument "type" when resolving an Attribute' + (attribute.name ? ' called' + attribute.name : '') + ' (it has to be a string)' ); try { TypedAttribute = attributes.types.get(attribute.type); } catch (e) { if (e instanceof errors.AttributeTypeNotFoundError) { TypedAttribute = attributes.types.AssociationAttribute; attribute.entity = attribute.type; } else { throw e; } } delete attribute.type; } } else { if (arguments.length > 1) { expect(arguments[1]).to.be.a( 'string', 'Invalid argument "type" when resolving an Attribute' + (arguments[0] ? ' called' + arguments[0] : '') + ' (it has to be a string)' ); try { TypedAttribute = attributes.types.get(arguments[1]); } catch (e) { if (e instanceof errors.AttributeTypeNotFoundError) { TypedAttribute = attributes.types.AssociationAttribute; argumentArray.splice(2, 0, arguments[1]); } else { throw e; } } argumentArray.splice(1,1); } } return new (Function.prototype.bind.apply( TypedAttribute, [null].concat(argumentArray) ))(); }
[ "function", "resolve", "(", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "within", "(", "1", ",", "4", ",", "'Invalid arguments length when resolving an Attribute (it has to be '", "+", "'passed from 1 to 4 arguments)'", ")"...
Resolves the arguments and create a new instance of Attribute. It tries to find the Attribute type. It it is not possible, it assumes that it is an AssociationAttribute. @memberof module:back4app-entity/models/attributes.Attribute @name resolve @param {!Object} attribute This is the attribute to be resolved. It can be passed as an Object. @param {!string} attribute.name It is the name of the attribute. @param {!string} [attribute.type='Object'] It is the type of the attribute. It is optional and if not passed it will assume 'Object' as the default value. @param {!string} [attribute.multiplicity='1'] It is the multiplicity of the attribute. It is optional and if not passed it will assume '1' as the default value. @param {?(boolean|number|string|Object|function)} [attribute.default] It is the default expression of the attribute. @returns {module:back4app-entity/models/attributes.Attribute} The new Attribute instance. @throws {module:back4app-entity/models/errors.AttributeTypeNotFoundError} @example Attribute.resolve({ name: 'attribute', type: 'String', multiplicity: '0..1', default: null }); Resolves the arguments and create a new instance of Attribute. It tries to find the Attribute type. It it is not possible, it assumes that it is an AssociationAttribute. @memberof module:back4app-entity/models/attributes.Attribute @name resolve @param {!string} name It is the name of the attribute. @param {!string} [type='Object'] It is the type of the attribute. It is optional and if not passed it will assume 'Object' as the default value. @param {!string} [multiplicity='1'] It is the multiplicity of the attribute. It is optional and if not passed it will assume '1' as the default value. @param {?(boolean|number|string|Object|function)} [default] It is the default expression of the attribute. @returns {module:back4app-entity/models/attributes.Attribute} The new Attribute instance. @throws {module:back4app-entity/models/errors.AttributeTypeNotFoundError} @example Attribute.resolve( this, 'attribute', 'String', '0..1', null );
[ "Resolves", "the", "arguments", "and", "create", "a", "new", "instance", "of", "Attribute", ".", "It", "tries", "to", "find", "the", "Attribute", "type", ".", "It", "it", "is", "not", "possible", "it", "assumes", "that", "it", "is", "an", "AssociationAttri...
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/attributes/Attribute.js#L456-L526
30,715
back4app/back4app-entity
src/back/models/attributes/Attribute.js
getDefaultValue
function getDefaultValue(entity) { expect(arguments).to.have.length( 1, 'Invalid arguments length when getting the default value of an Attribute ' + 'to an Entity instance (it has to be given 1 argument)' ); expect(entity).to.be.an.instanceOf( models.Entity, 'Invalid type of argument "entity" when getting the default value of an ' + 'Attribute to an Entity instance (it has to be an Entity)' ); if (typeof this.default === 'function') { return this.default.call(entity); } else { return this.default; } }
javascript
function getDefaultValue(entity) { expect(arguments).to.have.length( 1, 'Invalid arguments length when getting the default value of an Attribute ' + 'to an Entity instance (it has to be given 1 argument)' ); expect(entity).to.be.an.instanceOf( models.Entity, 'Invalid type of argument "entity" when getting the default value of an ' + 'Attribute to an Entity instance (it has to be an Entity)' ); if (typeof this.default === 'function') { return this.default.call(entity); } else { return this.default; } }
[ "function", "getDefaultValue", "(", "entity", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", "(", "1", ",", "'Invalid arguments length when getting the default value of an Attribute '", "+", "'to an Entity instance (it has to be given 1 ar...
Gets the default value of the current Attribute to a given Entity instance. @name module:back4app-entity/models/attributes.Attribute#getDefaultValue @function @param {!module:back4app-entity/models.Entity} entity The Entity instance to which the default value will be get. @returns {boolean|number|string|Object|function} The default value. @example var defaultValue = MyEntity.attributes.myAttribute.getDefaultValue( new MyEntity() );
[ "Gets", "the", "default", "value", "of", "the", "current", "Attribute", "to", "a", "given", "Entity", "instance", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/attributes/Attribute.js#L540-L558
30,716
back4app/back4app-entity
src/back/models/attributes/Attribute.js
getDataName
function getDataName(adapterName) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when getting the data name of an Attribute ' + '(it has to be passed less than 2 arguments)'); if (adapterName) { expect(adapterName).to.be.a( 'string', 'Invalid argument "adapterName" when getting the data name of an ' + 'Attribute (it has to be a string)' ); if ( this.dataName && typeof this.dataName === 'object' && this.dataName.hasOwnProperty(adapterName) ) { return this.dataName[adapterName]; } } if (this.dataName && typeof this.dataName === 'string') { return this.dataName; } else { return this.name; } }
javascript
function getDataName(adapterName) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when getting the data name of an Attribute ' + '(it has to be passed less than 2 arguments)'); if (adapterName) { expect(adapterName).to.be.a( 'string', 'Invalid argument "adapterName" when getting the data name of an ' + 'Attribute (it has to be a string)' ); if ( this.dataName && typeof this.dataName === 'object' && this.dataName.hasOwnProperty(adapterName) ) { return this.dataName[adapterName]; } } if (this.dataName && typeof this.dataName === 'string') { return this.dataName; } else { return this.name; } }
[ "function", "getDataName", "(", "adapterName", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "below", "(", "2", ",", "'Invalid arguments length when getting the data name of an Attribute '", "+", "'(it has to be passed less than ...
Gets the data name of an Entity attribute to be used in an adapter. @name module:back4app-entity/models/attributes.Attribute#getDataName @function @param {?string} [adapterName] The name of the adapter of which the data name is wanted. @returns {string} The data name. @example var dataName = MyEntity.attributes.myAttribute.getDataName('default');
[ "Gets", "the", "data", "name", "of", "an", "Entity", "attribute", "to", "be", "used", "in", "an", "adapter", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/attributes/Attribute.js#L694-L721
30,717
feedhenry/fh-forms
lib/impl/submissionExportHelper/csvValues.js
generateCSVSingleValue
function generateCSVSingleValue(field, val, downloadUrl, submissionId) { var line = ''; var fieldValue = val; if (!(typeof (fieldValue) === 'undefined' || fieldValue === null)) { //Value is something, add the value if (field.type === 'checkboxes') { fieldValue = val.selections; } else if (fieldTypeUtils.isFileType(field.type)) { //File types have two fields, a name and url to be added if (val.fileName) { fieldValue = val.fileName; } else { fieldValue = '<not uploaded>'; } } else if (fieldTypeUtils.isBarcodeType(field.type)) { if (val.format) { fieldValue = val.format; } else { fieldValue = "<not set>"; } } line += csvStr(fieldValue); line += ','; //If it is a file type, then the url should also be added if (fieldTypeUtils.isFileType(field.type)) { if (val.groupId) { fieldValue = downloadUrl.replace(":id", submissionId).replace(":fileId", val .groupId); } else { fieldValue = '<not uploaded>'; } line += csvStr(fieldValue); line += ','; } else if (fieldTypeUtils.isBarcodeType(field.type)) { if (val.text) { fieldValue = val.text; } else { fieldValue = "<not set>"; } line += csvStr(fieldValue); line += ','; } } else { //No value, spacers have to be added. //For file type, the file name and url are included. Therefore blank values have to be spaced twice. if (fieldTypeUtils.isFileType(field.type) || fieldTypeUtils.isBarcodeType( field.type)) { line += ',,'; } else { line += ','; } } return line; }
javascript
function generateCSVSingleValue(field, val, downloadUrl, submissionId) { var line = ''; var fieldValue = val; if (!(typeof (fieldValue) === 'undefined' || fieldValue === null)) { //Value is something, add the value if (field.type === 'checkboxes') { fieldValue = val.selections; } else if (fieldTypeUtils.isFileType(field.type)) { //File types have two fields, a name and url to be added if (val.fileName) { fieldValue = val.fileName; } else { fieldValue = '<not uploaded>'; } } else if (fieldTypeUtils.isBarcodeType(field.type)) { if (val.format) { fieldValue = val.format; } else { fieldValue = "<not set>"; } } line += csvStr(fieldValue); line += ','; //If it is a file type, then the url should also be added if (fieldTypeUtils.isFileType(field.type)) { if (val.groupId) { fieldValue = downloadUrl.replace(":id", submissionId).replace(":fileId", val .groupId); } else { fieldValue = '<not uploaded>'; } line += csvStr(fieldValue); line += ','; } else if (fieldTypeUtils.isBarcodeType(field.type)) { if (val.text) { fieldValue = val.text; } else { fieldValue = "<not set>"; } line += csvStr(fieldValue); line += ','; } } else { //No value, spacers have to be added. //For file type, the file name and url are included. Therefore blank values have to be spaced twice. if (fieldTypeUtils.isFileType(field.type) || fieldTypeUtils.isBarcodeType( field.type)) { line += ',,'; } else { line += ','; } } return line; }
[ "function", "generateCSVSingleValue", "(", "field", ",", "val", ",", "downloadUrl", ",", "submissionId", ")", "{", "var", "line", "=", "''", ";", "var", "fieldValue", "=", "val", ";", "if", "(", "!", "(", "typeof", "(", "fieldValue", ")", "===", "'undefi...
generateCSVSingleValue - Generating A Single Value For A Field @param {object} field Field Definition To Generate A CSV For @param {object/string/number} val Field Value @param {string} downloadUrl URL template for downloading files @param {object} submissionId Submission ID @return {type} description
[ "generateCSVSingleValue", "-", "Generating", "A", "Single", "Value", "For", "A", "Field" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/submissionExportHelper/csvValues.js#L14-L72
30,718
feedhenry/fh-forms
lib/impl/submissionExportHelper/csvValues.js
generateCSVFieldValues
function generateCSVFieldValues(baseField, ff, downloadUrl, sub) { var line = ''; var fieldValues = []; if (ff) { fieldValues = misc.filterOutNullData(ff.fieldValues); } if (baseField && baseField.repeating) { for (var j = 0; j < baseField.fieldOptions.definition.maxRepeat; j++) { line += generateCSVSingleValue(baseField, fieldValues[j], downloadUrl, sub._id); } } else { line += generateCSVSingleValue(baseField, fieldValues[0], downloadUrl, sub._id); } return line; }
javascript
function generateCSVFieldValues(baseField, ff, downloadUrl, sub) { var line = ''; var fieldValues = []; if (ff) { fieldValues = misc.filterOutNullData(ff.fieldValues); } if (baseField && baseField.repeating) { for (var j = 0; j < baseField.fieldOptions.definition.maxRepeat; j++) { line += generateCSVSingleValue(baseField, fieldValues[j], downloadUrl, sub._id); } } else { line += generateCSVSingleValue(baseField, fieldValues[0], downloadUrl, sub._id); } return line; }
[ "function", "generateCSVFieldValues", "(", "baseField", ",", "ff", ",", "downloadUrl", ",", "sub", ")", "{", "var", "line", "=", "''", ";", "var", "fieldValues", "=", "[", "]", ";", "if", "(", "ff", ")", "{", "fieldValues", "=", "misc", ".", "filterOut...
generateCSVFieldValues - description @param {type} baseField description @param {type} ff description @param {type} downloadUrl description @param {type} sub description @return {type} description
[ "generateCSVFieldValues", "-", "description" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/submissionExportHelper/csvValues.js#L83-L100
30,719
feedhenry/fh-forms
lib/impl/importForms/index.js
checkWorkingDir
function checkWorkingDir(workingDir, cb) { fs.stat(workingDir, function(err, stats) { var errMessage; if (err) { errMessage = "The directory " + workingDir + " does not exist."; logger.error(errMessage); return cb(errMessage); } //Checking that it is a directory if (!stats.isDirectory()) { errMessage = "Expected " + workingDir + " to be a directory"; logger.error(errMessage); return cb(errMessage); } return cb(); }); }
javascript
function checkWorkingDir(workingDir, cb) { fs.stat(workingDir, function(err, stats) { var errMessage; if (err) { errMessage = "The directory " + workingDir + " does not exist."; logger.error(errMessage); return cb(errMessage); } //Checking that it is a directory if (!stats.isDirectory()) { errMessage = "Expected " + workingDir + " to be a directory"; logger.error(errMessage); return cb(errMessage); } return cb(); }); }
[ "function", "checkWorkingDir", "(", "workingDir", ",", "cb", ")", "{", "fs", ".", "stat", "(", "workingDir", ",", "function", "(", "err", ",", "stats", ")", "{", "var", "errMessage", ";", "if", "(", "err", ")", "{", "errMessage", "=", "\"The directory \"...
checkWorkingDir - Checking that the working directory exists and is a directory. @param {string} workingDir Path to the working directory @param {function} cb
[ "checkWorkingDir", "-", "Checking", "that", "the", "working", "directory", "exists", "and", "is", "a", "directory", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/index.js#L43-L61
30,720
feedhenry/fh-forms
lib/impl/importForms/index.js
checkZipFile
function checkZipFile(zipFilePath, cb) { //Checking that it is a ZIP file mimeInspector.detectFile(zipFilePath, function(err, fileMimetype) { var errMessage; if (err) { logger.error("Error detecting ZIP file", err); return cb(err); } if (fileMimetype !== 'application/zip') { errMessage = "Expected the file MIME type to be application/zip but was " + fileMimetype; logger.error(errMessage); } return cb(errMessage); }); }
javascript
function checkZipFile(zipFilePath, cb) { //Checking that it is a ZIP file mimeInspector.detectFile(zipFilePath, function(err, fileMimetype) { var errMessage; if (err) { logger.error("Error detecting ZIP file", err); return cb(err); } if (fileMimetype !== 'application/zip') { errMessage = "Expected the file MIME type to be application/zip but was " + fileMimetype; logger.error(errMessage); } return cb(errMessage); }); }
[ "function", "checkZipFile", "(", "zipFilePath", ",", "cb", ")", "{", "//Checking that it is a ZIP file", "mimeInspector", ".", "detectFile", "(", "zipFilePath", ",", "function", "(", "err", ",", "fileMimetype", ")", "{", "var", "errMessage", ";", "if", "(", "err...
checkZipFile - Checking that the file exists and is a zip file. @param {string} zipFilePath Path to the zip file. @param {function} cb description
[ "checkZipFile", "-", "Checking", "that", "the", "file", "exists", "and", "is", "a", "zip", "file", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/index.js#L70-L86
30,721
feedhenry/fh-forms
lib/impl/importForms/index.js
importForms
function importForms(connections, params, callback) { params = params || {}; logger.debug("Importing Forms ", params); //Validating var paramsValidator = validate(params); var failed = paramsValidator.has(ZIP_FILE_PATH, WORKING_DIR); if (failed) { return callback("Validation Failed " + (failed[ZIP_FILE_PATH] || failed[WORKING_DIR])); } //Random directory name. var newDirectoryName = (new mongoose.Types.ObjectId()).toString(); var unzipDirectoryPath = path.join(params.workingDir, "/", newDirectoryName); async.waterfall([ function checkFiles(cb) { async.parallel([ async.apply(checkWorkingDir, params.workingDir), async.apply(checkZipFile, params.zipFilePath) ], function(err) { //Not interested in passing any of the results from the aync.parallel to the waterfall callback cb(err); }); }, function createUniqueDirToUnzipTo(cb) { //Need to create a new directory mkdirp(unzipDirectoryPath, function(err) { return cb(err); }); }, async.apply(unzipFile, { zipFilePath: params.zipFilePath, workingDir: unzipDirectoryPath, queueConcurrency: 5 }), function validateInput(cb) { inputValidator(unzipDirectoryPath, true, cb); }, async.apply(importFromDir, connections, unzipDirectoryPath) ], function(err, importedForms) { if (err) { logger.error("Error Importing Forms ", err); } //we always need to cleanup cleanupFiles(unzipDirectoryPath, params.zipFilePath); return callback(err, importedForms); }); }
javascript
function importForms(connections, params, callback) { params = params || {}; logger.debug("Importing Forms ", params); //Validating var paramsValidator = validate(params); var failed = paramsValidator.has(ZIP_FILE_PATH, WORKING_DIR); if (failed) { return callback("Validation Failed " + (failed[ZIP_FILE_PATH] || failed[WORKING_DIR])); } //Random directory name. var newDirectoryName = (new mongoose.Types.ObjectId()).toString(); var unzipDirectoryPath = path.join(params.workingDir, "/", newDirectoryName); async.waterfall([ function checkFiles(cb) { async.parallel([ async.apply(checkWorkingDir, params.workingDir), async.apply(checkZipFile, params.zipFilePath) ], function(err) { //Not interested in passing any of the results from the aync.parallel to the waterfall callback cb(err); }); }, function createUniqueDirToUnzipTo(cb) { //Need to create a new directory mkdirp(unzipDirectoryPath, function(err) { return cb(err); }); }, async.apply(unzipFile, { zipFilePath: params.zipFilePath, workingDir: unzipDirectoryPath, queueConcurrency: 5 }), function validateInput(cb) { inputValidator(unzipDirectoryPath, true, cb); }, async.apply(importFromDir, connections, unzipDirectoryPath) ], function(err, importedForms) { if (err) { logger.error("Error Importing Forms ", err); } //we always need to cleanup cleanupFiles(unzipDirectoryPath, params.zipFilePath); return callback(err, importedForms); }); }
[ "function", "importForms", "(", "connections", ",", "params", ",", "callback", ")", "{", "params", "=", "params", "||", "{", "}", ";", "logger", ".", "debug", "(", "\"Importing Forms \"", ",", "params", ")", ";", "//Validating", "var", "paramsValidator", "="...
importForms - Importing Form Definitions From A ZIP File. The ZIP file will be unzipped to a working directory where the forms will be imported from. @param {object} connections @param {object} connections.mongooseConnection The Mongoose Connection @param {object} params @param {string} params.zipFilePath A Path to a ZIP file on the file system. @param {string} params.workingDir A Path to a directory where the zip file can be unzipped to. @param {function} callback @return {type}
[ "importForms", "-", "Importing", "Form", "Definitions", "From", "A", "ZIP", "File", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/index.js#L102-L153
30,722
feedhenry/fh-forms
lib/impl/importForms/unzipFile.js
makeExportDirectory
function makeExportDirectory(params, callback) { var newDirPath = params.workingDir + "/" + params.entry.fileName; mkdirp(newDirPath, function(err) { if (err) { logger.debug("Error making directory " + newDirPath, err); return callback(err); } params.zipfile.readEntry(); return callback(err); }); }
javascript
function makeExportDirectory(params, callback) { var newDirPath = params.workingDir + "/" + params.entry.fileName; mkdirp(newDirPath, function(err) { if (err) { logger.debug("Error making directory " + newDirPath, err); return callback(err); } params.zipfile.readEntry(); return callback(err); }); }
[ "function", "makeExportDirectory", "(", "params", ",", "callback", ")", "{", "var", "newDirPath", "=", "params", ".", "workingDir", "+", "\"/\"", "+", "params", ".", "entry", ".", "fileName", ";", "mkdirp", "(", "newDirPath", ",", "function", "(", "err", "...
makeExportDirectory - Making a directory in the same structure as the zip file. @param {object} params @param {object} params.entry Single Zip file entry @param {object} params.zipfile Reference To THe Parent Zip File. @param {string} params.workingDir Directory being unzipped into. @param {function} callback
[ "makeExportDirectory", "-", "Making", "a", "directory", "in", "the", "same", "structure", "as", "the", "zip", "file", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/unzipFile.js#L18-L28
30,723
feedhenry/fh-forms
lib/impl/importForms/unzipFile.js
streamFileEntry
function streamFileEntry(params, callback) { params.zipfile.openReadStream(params.entry, function(err, readStream) { if (err) { return callback(err); } // ensure parent directory exists var newFilePath = params.workingDir + "/" + params.entry.fileName; mkdirp(path.dirname(newFilePath), function(err) { if (err) { logger.debug("Error making directory " + newFilePath, err); return callback(err); } readStream.pipe(fs.createWriteStream(newFilePath)); readStream.on("end", function() { params.zipfile.readEntry(); callback(); }); readStream.on('error', function(err) { callback(err); }); }); }); }
javascript
function streamFileEntry(params, callback) { params.zipfile.openReadStream(params.entry, function(err, readStream) { if (err) { return callback(err); } // ensure parent directory exists var newFilePath = params.workingDir + "/" + params.entry.fileName; mkdirp(path.dirname(newFilePath), function(err) { if (err) { logger.debug("Error making directory " + newFilePath, err); return callback(err); } readStream.pipe(fs.createWriteStream(newFilePath)); readStream.on("end", function() { params.zipfile.readEntry(); callback(); }); readStream.on('error', function(err) { callback(err); }); }); }); }
[ "function", "streamFileEntry", "(", "params", ",", "callback", ")", "{", "params", ".", "zipfile", ".", "openReadStream", "(", "params", ".", "entry", ",", "function", "(", "err", ",", "readStream", ")", "{", "if", "(", "err", ")", "{", "return", "callba...
streamFileEntry - Streaming a single uncompressed file from the zip file to the working folder. The folder structure of the zip file is maintained. @param {object} params @param {object} params.zipfile Reference to the parent zip file @param {object} params.entry Single Zip file entry @param {string} params.workingDir Directory being unzipped into. @param {function} callback @return {type} description
[ "streamFileEntry", "-", "Streaming", "a", "single", "uncompressed", "file", "from", "the", "zip", "file", "to", "the", "working", "folder", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/unzipFile.js#L43-L65
30,724
feedhenry/fh-forms
lib/impl/importForms/unzipFile.js
unzipWorker
function unzipWorker(unzipTask, workerCb) { var zipfile = unzipTask.zipfile; var entry = unzipTask.entry; var workingDir = unzipTask.workingDir; if (/\/$/.test(entry.fileName)) { // directory file names end with '/' makeExportDirectory({ entry: entry, zipfile: zipfile, workingDir: workingDir }, workerCb); } else { // file entry streamFileEntry({ zipfile: zipfile, entry: entry, workingDir: workingDir }, workerCb); } }
javascript
function unzipWorker(unzipTask, workerCb) { var zipfile = unzipTask.zipfile; var entry = unzipTask.entry; var workingDir = unzipTask.workingDir; if (/\/$/.test(entry.fileName)) { // directory file names end with '/' makeExportDirectory({ entry: entry, zipfile: zipfile, workingDir: workingDir }, workerCb); } else { // file entry streamFileEntry({ zipfile: zipfile, entry: entry, workingDir: workingDir }, workerCb); } }
[ "function", "unzipWorker", "(", "unzipTask", ",", "workerCb", ")", "{", "var", "zipfile", "=", "unzipTask", ".", "zipfile", ";", "var", "entry", "=", "unzipTask", ".", "entry", ";", "var", "workingDir", "=", "unzipTask", ".", "workingDir", ";", "if", "(", ...
unzipWorker - Async Queue worker to pipe the unzipped file to a folder. @param {object} unzipTask description @param {function} workerCb description
[ "unzipWorker", "-", "Async", "Queue", "worker", "to", "pipe", "the", "unzipped", "file", "to", "a", "folder", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/unzipFile.js#L74-L93
30,725
feedhenry/fh-forms
lib/impl/importForms/unzipFile.js
unzipToWorkingDir
function unzipToWorkingDir(params, callback) { var unzipError; var queue = async.queue(unzipWorker, params.queueConcurrency || 5); //Pushing a single file unzip to the queue. function getQueueEntry(zipfile) { return function queueEntry(entry) { queue.push({ zipfile: zipfile, workingDir: params.workingDir, entry: entry }, function(err) { if (err) { logger.debug("Error unzipping file params.zipFilePath", err); //If one of the files has failed to unzip correctly. No point in continuing to unzip. Close the zip file. zipfile.close(); } }); }; } unzip.open(params.zipFilePath, {lazyEntries: true}, function(err, zipfile) { if (err) { return callback(err); } zipfile.on("entry", getQueueEntry(zipfile)); zipfile.readEntry(); zipfile.on('error', function(err) { logger.error("Error unzipping Zip File " + params.zipFilePath, err); unzipError = err; }); zipfile.on('close', function() { //When the queue is empty and the zip file has finisihed scanning files, then the unzip is finished logger.debug("Zip File " + params.zipFilePath + " Unzipped"); callback(unzipError); }); }); }
javascript
function unzipToWorkingDir(params, callback) { var unzipError; var queue = async.queue(unzipWorker, params.queueConcurrency || 5); //Pushing a single file unzip to the queue. function getQueueEntry(zipfile) { return function queueEntry(entry) { queue.push({ zipfile: zipfile, workingDir: params.workingDir, entry: entry }, function(err) { if (err) { logger.debug("Error unzipping file params.zipFilePath", err); //If one of the files has failed to unzip correctly. No point in continuing to unzip. Close the zip file. zipfile.close(); } }); }; } unzip.open(params.zipFilePath, {lazyEntries: true}, function(err, zipfile) { if (err) { return callback(err); } zipfile.on("entry", getQueueEntry(zipfile)); zipfile.readEntry(); zipfile.on('error', function(err) { logger.error("Error unzipping Zip File " + params.zipFilePath, err); unzipError = err; }); zipfile.on('close', function() { //When the queue is empty and the zip file has finisihed scanning files, then the unzip is finished logger.debug("Zip File " + params.zipFilePath + " Unzipped"); callback(unzipError); }); }); }
[ "function", "unzipToWorkingDir", "(", "params", ",", "callback", ")", "{", "var", "unzipError", ";", "var", "queue", "=", "async", ".", "queue", "(", "unzipWorker", ",", "params", ".", "queueConcurrency", "||", "5", ")", ";", "//Pushing a single file unzip to th...
unzipToWorkingDir - Unzipping a file to a working directory. Using a queue to control the number of files decompressing at a time. @param {object} params @param {string} params.zipFilePath Path to the ZIP file to unzip. @param {number} params.queueConcurrency Concurrency Of the async queue @param {string} params.workingDir Unzip Working Directory @param {function} callback
[ "unzipToWorkingDir", "-", "Unzipping", "a", "file", "to", "a", "working", "directory", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/unzipFile.js#L107-L148
30,726
feedhenry/fh-forms
lib/impl/importForms/unzipFile.js
getQueueEntry
function getQueueEntry(zipfile) { return function queueEntry(entry) { queue.push({ zipfile: zipfile, workingDir: params.workingDir, entry: entry }, function(err) { if (err) { logger.debug("Error unzipping file params.zipFilePath", err); //If one of the files has failed to unzip correctly. No point in continuing to unzip. Close the zip file. zipfile.close(); } }); }; }
javascript
function getQueueEntry(zipfile) { return function queueEntry(entry) { queue.push({ zipfile: zipfile, workingDir: params.workingDir, entry: entry }, function(err) { if (err) { logger.debug("Error unzipping file params.zipFilePath", err); //If one of the files has failed to unzip correctly. No point in continuing to unzip. Close the zip file. zipfile.close(); } }); }; }
[ "function", "getQueueEntry", "(", "zipfile", ")", "{", "return", "function", "queueEntry", "(", "entry", ")", "{", "queue", ".", "push", "(", "{", "zipfile", ":", "zipfile", ",", "workingDir", ":", "params", ".", "workingDir", ",", "entry", ":", "entry", ...
Pushing a single file unzip to the queue.
[ "Pushing", "a", "single", "file", "unzip", "to", "the", "queue", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/unzipFile.js#L113-L127
30,727
feedhenry/fh-forms
lib/common/misc.js
filterOutNullData
function filterOutNullData(fieldValues) { return _.filter(fieldValues || [], function(val) { return val === false || val === 0 || val; }); }
javascript
function filterOutNullData(fieldValues) { return _.filter(fieldValues || [], function(val) { return val === false || val === 0 || val; }); }
[ "function", "filterOutNullData", "(", "fieldValues", ")", "{", "return", "_", ".", "filter", "(", "fieldValues", "||", "[", "]", ",", "function", "(", "val", ")", "{", "return", "val", "===", "false", "||", "val", "===", "0", "||", "val", ";", "}", "...
filterOutNullData - Utility function to remove all 'null' or 'undefined' values. 0 and false are considered valid field value entries. @param {array} fieldValues Array of field values to filter. @return {array} Filtered field values.
[ "filterOutNullData", "-", "Utility", "function", "to", "remove", "all", "null", "or", "undefined", "values", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L31-L35
30,728
feedhenry/fh-forms
lib/common/misc.js
addAdminFieldToSubmission
function addAdminFieldToSubmission(field) { //Full field object is used in the return as existing fields are populated already. var subObject = { fieldId : field, fieldValues: [] }; submission.formFields.push(subObject); }
javascript
function addAdminFieldToSubmission(field) { //Full field object is used in the return as existing fields are populated already. var subObject = { fieldId : field, fieldValues: [] }; submission.formFields.push(subObject); }
[ "function", "addAdminFieldToSubmission", "(", "field", ")", "{", "//Full field object is used in the return as existing fields are populated already.", "var", "subObject", "=", "{", "fieldId", ":", "field", ",", "fieldValues", ":", "[", "]", "}", ";", "submission", ".", ...
The field definition can either be in the submission that has a populated fieldId, Or the field definition is an admin field that is in the formSubmitted against. As this field is not included in a client submission, a scan of the formSubmitted against must be made. @param field @param formJSON
[ "The", "field", "definition", "can", "either", "be", "in", "the", "submission", "that", "has", "a", "populated", "fieldId", "Or", "the", "field", "definition", "is", "an", "admin", "field", "that", "is", "in", "the", "formSubmitted", "against", ".", "As", ...
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L51-L59
30,729
feedhenry/fh-forms
lib/common/misc.js
convertAllObjectIdsToString
function convertAllObjectIdsToString(form) { form._id = form._id ? form._id.toString() : form._id; form.pages = _.map(form.pages, function(page) { page._id = page._id ? page._id.toString() : page._id; page.fields = _.map(page.fields, function(field) { field._id = field._id ? field._id.toString() : field._id; return field; }); return page; }); return form; }
javascript
function convertAllObjectIdsToString(form) { form._id = form._id ? form._id.toString() : form._id; form.pages = _.map(form.pages, function(page) { page._id = page._id ? page._id.toString() : page._id; page.fields = _.map(page.fields, function(field) { field._id = field._id ? field._id.toString() : field._id; return field; }); return page; }); return form; }
[ "function", "convertAllObjectIdsToString", "(", "form", ")", "{", "form", ".", "_id", "=", "form", ".", "_id", "?", "form", ".", "_id", ".", "toString", "(", ")", ":", "form", ".", "_id", ";", "form", ".", "pages", "=", "_", ".", "map", "(", "form"...
Handy Function To convert All ObjectIds to strings.
[ "Handy", "Function", "To", "convert", "All", "ObjectIds", "to", "strings", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L86-L99
30,730
feedhenry/fh-forms
lib/common/misc.js
getMostRecentRefresh
function getMostRecentRefresh(formLastUpdated, dataLastUpdated) { var formTimestamp = new Date(formLastUpdated).getTime(); var dataTimestamp = new Date(dataLastUpdated).getTime(); if (!dataLastUpdated) { return formLastUpdated; } if (dataTimestamp > formTimestamp) { return dataLastUpdated; } else { return formLastUpdated; } }
javascript
function getMostRecentRefresh(formLastUpdated, dataLastUpdated) { var formTimestamp = new Date(formLastUpdated).getTime(); var dataTimestamp = new Date(dataLastUpdated).getTime(); if (!dataLastUpdated) { return formLastUpdated; } if (dataTimestamp > formTimestamp) { return dataLastUpdated; } else { return formLastUpdated; } }
[ "function", "getMostRecentRefresh", "(", "formLastUpdated", ",", "dataLastUpdated", ")", "{", "var", "formTimestamp", "=", "new", "Date", "(", "formLastUpdated", ")", ".", "getTime", "(", ")", ";", "var", "dataTimestamp", "=", "new", "Date", "(", "dataLastUpdate...
Function to compare to timestamps and return the most recent.
[ "Function", "to", "compare", "to", "timestamps", "and", "return", "the", "most", "recent", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L102-L115
30,731
feedhenry/fh-forms
lib/common/misc.js
checkId
function checkId(id) { id = id || ""; id = id.toString(); return _.isString(id) && id.length === 24; }
javascript
function checkId(id) { id = id || ""; id = id.toString(); return _.isString(id) && id.length === 24; }
[ "function", "checkId", "(", "id", ")", "{", "id", "=", "id", "||", "\"\"", ";", "id", "=", "id", ".", "toString", "(", ")", ";", "return", "_", ".", "isString", "(", "id", ")", "&&", "id", ".", "length", "===", "24", ";", "}" ]
Checking Mongo ID Param
[ "Checking", "Mongo", "ID", "Param" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L168-L172
30,732
feedhenry/fh-forms
lib/common/misc.js
buildErrorResponse
function buildErrorResponse(params) { params = params || {}; params.error = params.error || {}; var ERROR_CODES = models.CONSTANTS.ERROR_CODES; if (params.error.userDetail) { return params.error; } if (params.error) { var message = params.error.message || ""; //If the message is about validation, the return a validation http response if (message.indexOf("validation") > -1) { params.code = params.code || ERROR_CODES.FH_FORMS_INVALID_PARAMETERS; } } //Mongoose Validation Failed if (params.error && params.error.errors) { var fieldKey = _.keys(params.error.errors)[0]; params.userDetail = params.userDetail || params.error.errors[fieldKey].message; params.code = params.code || ERROR_CODES.FH_FORMS_INVALID_PARAMETERS; } var userDetail = params.userDetail || params.error.userDetail || params.error.message || "An Unexpected Error Occurred"; var systemDetail = params.systemDetail || params.error.systemDetail || params.error.stack || ""; var code = params.code || ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR; return { userDetail: userDetail, systemDetail: systemDetail, code: code }; }
javascript
function buildErrorResponse(params) { params = params || {}; params.error = params.error || {}; var ERROR_CODES = models.CONSTANTS.ERROR_CODES; if (params.error.userDetail) { return params.error; } if (params.error) { var message = params.error.message || ""; //If the message is about validation, the return a validation http response if (message.indexOf("validation") > -1) { params.code = params.code || ERROR_CODES.FH_FORMS_INVALID_PARAMETERS; } } //Mongoose Validation Failed if (params.error && params.error.errors) { var fieldKey = _.keys(params.error.errors)[0]; params.userDetail = params.userDetail || params.error.errors[fieldKey].message; params.code = params.code || ERROR_CODES.FH_FORMS_INVALID_PARAMETERS; } var userDetail = params.userDetail || params.error.userDetail || params.error.message || "An Unexpected Error Occurred"; var systemDetail = params.systemDetail || params.error.systemDetail || params.error.stack || ""; var code = params.code || ERROR_CODES.FH_FORMS_UNEXPECTED_ERROR; return { userDetail: userDetail, systemDetail: systemDetail, code: code }; }
[ "function", "buildErrorResponse", "(", "params", ")", "{", "params", "=", "params", "||", "{", "}", ";", "params", ".", "error", "=", "params", ".", "error", "||", "{", "}", ";", "var", "ERROR_CODES", "=", "models", ".", "CONSTANTS", ".", "ERROR_CODES", ...
Common Error Response builder. Thee should be a common error response from all feedhenry components. @param params - object containing error structures.
[ "Common", "Error", "Response", "builder", ".", "Thee", "should", "be", "a", "common", "error", "response", "from", "all", "feedhenry", "components", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L197-L230
30,733
feedhenry/fh-forms
lib/common/misc.js
pruneIds
function pruneIds(form) { var testForm = _.clone(form); testForm.pages = _.map(testForm.pages, function(page) { page.fields = _.map(page.fields, function(field) { return _.omit(field, '_id'); }); return _.omit(page, '_id'); }); return _.omit(testForm, '_id'); }
javascript
function pruneIds(form) { var testForm = _.clone(form); testForm.pages = _.map(testForm.pages, function(page) { page.fields = _.map(page.fields, function(field) { return _.omit(field, '_id'); }); return _.omit(page, '_id'); }); return _.omit(testForm, '_id'); }
[ "function", "pruneIds", "(", "form", ")", "{", "var", "testForm", "=", "_", ".", "clone", "(", "form", ")", ";", "testForm", ".", "pages", "=", "_", ".", "map", "(", "testForm", ".", "pages", ",", "function", "(", "page", ")", "{", "page", ".", "...
Removing All underscore ids
[ "Removing", "All", "underscore", "ids" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L233-L244
30,734
feedhenry/fh-forms
lib/common/misc.js
buildFormFileSizes
function buildFormFileSizes(submissions) { //Grouping By Form Id var fileSizesByForm = _.groupBy(submissions, 'formId'); //Getting all files associated with the submissions fileSizesByForm = _.mapObject(fileSizesByForm, function(formSubs) { //Getting File Sizes For All Entries In All Submissions Related To formId var allSubmissionSizes = _.map(formSubs, function(submission) { //For a single submission, get all file sizes var submissionFileSizes = _.map(submission.formFields, function(formField) { return _.map(_.compact(formField.fieldValues), function(fieldValue) { return fieldValue.fileSize; }); }); var totalSize = _.compact(_.flatten(submissionFileSizes)); //Adding all the file sizes for a single submission. return _.reduce(totalSize, function(memo, fileSize) { return memo + fileSize; }, 0); }); //Adding all file sizes for all submissions return _.reduce(_.flatten(allSubmissionSizes), function(memo, fileSize) { return memo + fileSize; }, 0); }); return fileSizesByForm; }
javascript
function buildFormFileSizes(submissions) { //Grouping By Form Id var fileSizesByForm = _.groupBy(submissions, 'formId'); //Getting all files associated with the submissions fileSizesByForm = _.mapObject(fileSizesByForm, function(formSubs) { //Getting File Sizes For All Entries In All Submissions Related To formId var allSubmissionSizes = _.map(formSubs, function(submission) { //For a single submission, get all file sizes var submissionFileSizes = _.map(submission.formFields, function(formField) { return _.map(_.compact(formField.fieldValues), function(fieldValue) { return fieldValue.fileSize; }); }); var totalSize = _.compact(_.flatten(submissionFileSizes)); //Adding all the file sizes for a single submission. return _.reduce(totalSize, function(memo, fileSize) { return memo + fileSize; }, 0); }); //Adding all file sizes for all submissions return _.reduce(_.flatten(allSubmissionSizes), function(memo, fileSize) { return memo + fileSize; }, 0); }); return fileSizesByForm; }
[ "function", "buildFormFileSizes", "(", "submissions", ")", "{", "//Grouping By Form Id", "var", "fileSizesByForm", "=", "_", ".", "groupBy", "(", "submissions", ",", "'formId'", ")", ";", "//Getting all files associated with the submissions", "fileSizesByForm", "=", "_", ...
Utility Function To Add All Files Storage Sizes For Submission @param submissions
[ "Utility", "Function", "To", "Add", "All", "Files", "Storage", "Sizes", "For", "Submission" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/common/misc.js#L250-L282
30,735
feedhenry/fh-forms
lib/impl/getForm.js
getDataSourceIds
function getDataSourceIds(forms) { var dataSources = _.map(forms, function(form) { return _.map(form.dataSources.formDataSources, function(dataSourceMeta) { return dataSourceMeta._id.toString(); }); }); dataSources = _.flatten(dataSources); //Only want unique data source Ids as multiple forms may use the same data source. return _.uniq(dataSources); }
javascript
function getDataSourceIds(forms) { var dataSources = _.map(forms, function(form) { return _.map(form.dataSources.formDataSources, function(dataSourceMeta) { return dataSourceMeta._id.toString(); }); }); dataSources = _.flatten(dataSources); //Only want unique data source Ids as multiple forms may use the same data source. return _.uniq(dataSources); }
[ "function", "getDataSourceIds", "(", "forms", ")", "{", "var", "dataSources", "=", "_", ".", "map", "(", "forms", ",", "function", "(", "form", ")", "{", "return", "_", ".", "map", "(", "form", ".", "dataSources", ".", "formDataSources", ",", "function",...
Extract a list of data sources from forms @param forms
[ "Extract", "a", "list", "of", "data", "sources", "from", "forms" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getForm.js#L130-L142
30,736
feedhenry/fh-forms
lib/impl/getForm.js
populateFieldDataFromDataSources
function populateFieldDataFromDataSources(populatedForms, cb) { logger.debug("populateFieldDataFromDataSources", populatedForms); var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE); //If no data source cache data is expected, then there is no need to load the Data Source Cache Data. if (!options.expectDataSourceCache) { return cb(undefined, populatedForms); } var dataSourceIds = getDataSourceIds(populatedForms); logger.debug("populateFieldDataFromDataSources", {dataSourceIds: dataSourceIds}); //If none of the forms refer to any data sources, then no need to search if (dataSourceIds.length === 0) { return cb(undefined, populatedForms); } var query = { _id: { "$in": dataSourceIds } }; //One query to populate all data sources DataSource.find(query).exec(function(err, dataSources) { if (err) { logger.error("Error Finding Data Sources", {error: err, dataSourceIds:dataSourceIds}); return cb(err); } logger.debug("populateFieldDataFromDataSources", {dataSources: dataSources}); var validatonError = _validateReturnedDataSources(dataSourceIds, dataSources); if (validatonError) { logger.error("Error Getting Form With Data Sources", {error: validatonError}); return cb(validatonError); } var cacheEntries = {}; //Assigning a lookup for cache entries _.each(dataSources, function(dataSource) { cacheEntries[dataSource._id] = dataSource.cache[0].data; }); //Overriding field options for a field with data source data if the field is defined as being sourced from a data source. populatedForms = _.map(populatedForms, function(populatedForm) { populatedForm.pages = _.map(populatedForm.pages, function(page) { page.fields = _.map(page.fields, function(field) { //If it is a data source type field, then return the data source data if (field.dataSourceType === models.FORM_CONSTANTS.DATA_SOURCE_TYPE_DATA_SOURCE) { //No guarantee these are set field.fieldOptions = field.fieldOptions || {}; field.fieldOptions.definition = field.fieldOptions.definition || {}; //Setting the data source data field.fieldOptions.definition.options = models.convertDSCacheToFieldOptions(field.type, cacheEntries[field.dataSource]); } return field; }); return page; }); return populatedForm; }); logger.debug("populateFieldDataFromDataSources", {populatedForms: JSON.stringify(populatedForms)}); //Finished, return the merged forms return cb(undefined, populatedForms); }); }
javascript
function populateFieldDataFromDataSources(populatedForms, cb) { logger.debug("populateFieldDataFromDataSources", populatedForms); var DataSource = models.get(connections.mongooseConnection, models.MODELNAMES.DATA_SOURCE); //If no data source cache data is expected, then there is no need to load the Data Source Cache Data. if (!options.expectDataSourceCache) { return cb(undefined, populatedForms); } var dataSourceIds = getDataSourceIds(populatedForms); logger.debug("populateFieldDataFromDataSources", {dataSourceIds: dataSourceIds}); //If none of the forms refer to any data sources, then no need to search if (dataSourceIds.length === 0) { return cb(undefined, populatedForms); } var query = { _id: { "$in": dataSourceIds } }; //One query to populate all data sources DataSource.find(query).exec(function(err, dataSources) { if (err) { logger.error("Error Finding Data Sources", {error: err, dataSourceIds:dataSourceIds}); return cb(err); } logger.debug("populateFieldDataFromDataSources", {dataSources: dataSources}); var validatonError = _validateReturnedDataSources(dataSourceIds, dataSources); if (validatonError) { logger.error("Error Getting Form With Data Sources", {error: validatonError}); return cb(validatonError); } var cacheEntries = {}; //Assigning a lookup for cache entries _.each(dataSources, function(dataSource) { cacheEntries[dataSource._id] = dataSource.cache[0].data; }); //Overriding field options for a field with data source data if the field is defined as being sourced from a data source. populatedForms = _.map(populatedForms, function(populatedForm) { populatedForm.pages = _.map(populatedForm.pages, function(page) { page.fields = _.map(page.fields, function(field) { //If it is a data source type field, then return the data source data if (field.dataSourceType === models.FORM_CONSTANTS.DATA_SOURCE_TYPE_DATA_SOURCE) { //No guarantee these are set field.fieldOptions = field.fieldOptions || {}; field.fieldOptions.definition = field.fieldOptions.definition || {}; //Setting the data source data field.fieldOptions.definition.options = models.convertDSCacheToFieldOptions(field.type, cacheEntries[field.dataSource]); } return field; }); return page; }); return populatedForm; }); logger.debug("populateFieldDataFromDataSources", {populatedForms: JSON.stringify(populatedForms)}); //Finished, return the merged forms return cb(undefined, populatedForms); }); }
[ "function", "populateFieldDataFromDataSources", "(", "populatedForms", ",", "cb", ")", "{", "logger", ".", "debug", "(", "\"populateFieldDataFromDataSources\"", ",", "populatedForms", ")", ";", "var", "DataSource", "=", "models", ".", "get", "(", "connections", ".",...
Any fields that require data source data need to be populated
[ "Any", "fields", "that", "require", "data", "source", "data", "need", "to", "be", "populated" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getForm.js#L145-L218
30,737
feedhenry/fh-forms
lib/impl/getForm.js
pruneDataSourceInfo
function pruneDataSourceInfo(form) { if (options.includeDataSources) { return form; } delete form.dataSources; form.pages = _.map(form.pages, function(page) { page.fields = _.map(page.fields, function(field) { delete field.dataSource; delete field.dataSourceType; return field; }); return page; }); return form; }
javascript
function pruneDataSourceInfo(form) { if (options.includeDataSources) { return form; } delete form.dataSources; form.pages = _.map(form.pages, function(page) { page.fields = _.map(page.fields, function(field) { delete field.dataSource; delete field.dataSourceType; return field; }); return page; }); return form; }
[ "function", "pruneDataSourceInfo", "(", "form", ")", "{", "if", "(", "options", ".", "includeDataSources", ")", "{", "return", "form", ";", "}", "delete", "form", ".", "dataSources", ";", "form", ".", "pages", "=", "_", ".", "map", "(", "form", ".", "p...
Removing form data source information.
[ "Removing", "form", "data", "source", "information", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getForm.js#L236-L254
30,738
flumedb/flumeview-reduce
write.js
function (state, ev) { if(state.dirtyTs + 200 < ev.ts && state.queue) { state.cleanTs = ev.ts state.writing = true state.dirty = false return {state: state, effects: {type: 'write'}} } return state }
javascript
function (state, ev) { if(state.dirtyTs + 200 < ev.ts && state.queue) { state.cleanTs = ev.ts state.writing = true state.dirty = false return {state: state, effects: {type: 'write'}} } return state }
[ "function", "(", "state", ",", "ev", ")", "{", "if", "(", "state", ".", "dirtyTs", "+", "200", "<", "ev", ".", "ts", "&&", "state", ".", "queue", ")", "{", "state", ".", "cleanTs", "=", "ev", ".", "ts", "state", ".", "writing", "=", "true", "st...
don't actually start writing immediately. incase writes are coming in fast... this will delay until they stop for 200 ms
[ "don", "t", "actually", "start", "writing", "immediately", ".", "incase", "writes", "are", "coming", "in", "fast", "...", "this", "will", "delay", "until", "they", "stop", "for", "200", "ms" ]
0c881037358af065b78842475b94eacc68e7e303
https://github.com/flumedb/flumeview-reduce/blob/0c881037358af065b78842475b94eacc68e7e303/write.js#L39-L47
30,739
feedhenry/fh-forms
lib/impl/pdfGeneration/processForm.js
function(field) { var converted = field.fieldId; converted.values = field.fieldValues; converted.sectionIndex = field.sectionIndex; return converted; }
javascript
function(field) { var converted = field.fieldId; converted.values = field.fieldValues; converted.sectionIndex = field.sectionIndex; return converted; }
[ "function", "(", "field", ")", "{", "var", "converted", "=", "field", ".", "fieldId", ";", "converted", ".", "values", "=", "field", ".", "fieldValues", ";", "converted", ".", "sectionIndex", "=", "field", ".", "sectionIndex", ";", "return", "converted", "...
Fields in submissions and fields in forms have a little bit different structure, this method converts submission field into a form field. @param field
[ "Fields", "in", "submissions", "and", "fields", "in", "forms", "have", "a", "little", "bit", "different", "structure", "this", "method", "converts", "submission", "field", "into", "a", "form", "field", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/pdfGeneration/processForm.js#L10-L15
30,740
feedhenry/fh-forms
lib/impl/pdfGeneration/processForm.js
function(section, pageFields, submittedFields) { var thisSection = section; var fieldsInSection = sectionUtils.getFieldsInSection(section._id, pageFields); var renderData = []; var addedSectionBreaks = false; var idsOfFieldsInTheSection = []; _.each(fieldsInSection, function(field) { idsOfFieldsInTheSection.push(field._id); var thisFieldInSection = _.filter(submittedFields, function(subField) { return subField.fieldId._id === field._id; }); if (!addedSectionBreaks) { _.each(thisFieldInSection, function(field, index) { var sectionForIndex = _.clone(thisSection); sectionForIndex.idx = index + 1; field.sectionIndex = field.sectionIndex || 0; renderData[field.sectionIndex] = [sectionForIndex]; }); addedSectionBreaks = true; } _.each(thisFieldInSection, function(field) { field.sectionIndex = field.sectionIndex || 0; renderData[field.sectionIndex].push(convertFieldToFormFormat(field)); }); }); renderData = _.flatten(renderData); return {renderData: renderData, fieldsInSection: idsOfFieldsInTheSection}; }
javascript
function(section, pageFields, submittedFields) { var thisSection = section; var fieldsInSection = sectionUtils.getFieldsInSection(section._id, pageFields); var renderData = []; var addedSectionBreaks = false; var idsOfFieldsInTheSection = []; _.each(fieldsInSection, function(field) { idsOfFieldsInTheSection.push(field._id); var thisFieldInSection = _.filter(submittedFields, function(subField) { return subField.fieldId._id === field._id; }); if (!addedSectionBreaks) { _.each(thisFieldInSection, function(field, index) { var sectionForIndex = _.clone(thisSection); sectionForIndex.idx = index + 1; field.sectionIndex = field.sectionIndex || 0; renderData[field.sectionIndex] = [sectionForIndex]; }); addedSectionBreaks = true; } _.each(thisFieldInSection, function(field) { field.sectionIndex = field.sectionIndex || 0; renderData[field.sectionIndex].push(convertFieldToFormFormat(field)); }); }); renderData = _.flatten(renderData); return {renderData: renderData, fieldsInSection: idsOfFieldsInTheSection}; }
[ "function", "(", "section", ",", "pageFields", ",", "submittedFields", ")", "{", "var", "thisSection", "=", "section", ";", "var", "fieldsInSection", "=", "sectionUtils", ".", "getFieldsInSection", "(", "section", ".", "_id", ",", "pageFields", ")", ";", "var"...
Builds and returns data used to render repeating sections. @param section @param pageFields @param submittedFields @returns {{renderData: Array, fieldsInSection: Array}}
[ "Builds", "and", "returns", "data", "used", "to", "render", "repeating", "sections", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/pdfGeneration/processForm.js#L24-L57
30,741
crispy1989/node-zstreams
lib/streams/request-stream.js
RequestStream
function RequestStream(requestStream, options) { var self = this; if(!options) options = {}; if(options.allowedStatusCodes === undefined) { options.allowedStatusCodes = [200, 201, 202, 203, 204, 205, 206]; } if(options.readErrorResponse === undefined) { options.readErrorResponse = true; } ClassicDuplex.call(this, requestStream, options); this._readErrorResponse = !!options.readErrorResponse; this._allowedStatusCodes = options.allowedStatusCodes; requestStream.on('response', function(response) { self._currentResponse = response; self.emit('response', response); if(Array.isArray(self._allowedStatusCodes)) { var statusCode = ''+response.statusCode; var statusCodeIsAllowed = false; for(var i = 0; i < self._allowedStatusCodes.length; i++) { if(''+self._allowedStatusCodes[i] === statusCode) { statusCodeIsAllowed = true; } } if(!statusCodeIsAllowed) { self._handleErrorInResponse(response, new Error('Received error status code: ' + statusCode)); } } }); if(requestStream.method === 'GET') { this._compoundWritable.end(); } }
javascript
function RequestStream(requestStream, options) { var self = this; if(!options) options = {}; if(options.allowedStatusCodes === undefined) { options.allowedStatusCodes = [200, 201, 202, 203, 204, 205, 206]; } if(options.readErrorResponse === undefined) { options.readErrorResponse = true; } ClassicDuplex.call(this, requestStream, options); this._readErrorResponse = !!options.readErrorResponse; this._allowedStatusCodes = options.allowedStatusCodes; requestStream.on('response', function(response) { self._currentResponse = response; self.emit('response', response); if(Array.isArray(self._allowedStatusCodes)) { var statusCode = ''+response.statusCode; var statusCodeIsAllowed = false; for(var i = 0; i < self._allowedStatusCodes.length; i++) { if(''+self._allowedStatusCodes[i] === statusCode) { statusCodeIsAllowed = true; } } if(!statusCodeIsAllowed) { self._handleErrorInResponse(response, new Error('Received error status code: ' + statusCode)); } } }); if(requestStream.method === 'GET') { this._compoundWritable.end(); } }
[ "function", "RequestStream", "(", "requestStream", ",", "options", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "options", ")", "options", "=", "{", "}", ";", "if", "(", "options", ".", "allowedStatusCodes", "===", "undefined", ")", "{", ...
This stream exists for the sole purpose of wrapping the commonly used npm module 'request' to make it act like a real duplex stream. The "stream" it returns is not a real streams2 stream, and does not work with the zstreams conversion methods. This class will emit errors from the request stream and will also emit the 'response' event proxied from the request stream. Additionally, it will emit errors if an error response code is received (see options.allowedStatusCodes) . Error emitted because of a disallowed status code will, by default, read in the entire response body before emitting the error, and will assign error.responseBody to be the response body. @class RequestStream @constructor @param {Request} requestStream - The "stream" returned from request() @param {Object} options - Options to change behavior of the stream @param {String[]|Number[]|Null} [options.allowedStatusCodes=[200, 201, 202, 203, 204, 205, 206]] - If a response is received with a HTTP status code not in this list, it is considered an error. @param {Boolean} [options.readErrorResponse=true] - If set to false, it disables unpiping the stream and reading in the full response body when an error status code is received.
[ "This", "stream", "exists", "for", "the", "sole", "purpose", "of", "wrapping", "the", "commonly", "used", "npm", "module", "request", "to", "make", "it", "act", "like", "a", "real", "duplex", "stream", ".", "The", "stream", "it", "returns", "is", "not", ...
4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd
https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/streams/request-stream.js#L25-L57
30,742
makeup-js/makeup-screenreader-trap
docs/static/bundle.js
filterAncestor
function filterAncestor(item) { return item.nodeType === 1 && item.tagName.toLowerCase() !== 'body' && item.tagName.toLowerCase() !== 'html'; }
javascript
function filterAncestor(item) { return item.nodeType === 1 && item.tagName.toLowerCase() !== 'body' && item.tagName.toLowerCase() !== 'html'; }
[ "function", "filterAncestor", "(", "item", ")", "{", "return", "item", ".", "nodeType", "===", "1", "&&", "item", ".", "tagName", ".", "toLowerCase", "(", ")", "!==", "'body'", "&&", "item", ".", "tagName", ".", "toLowerCase", "(", ")", "!==", "'html'", ...
filter function for ancestor elements
[ "filter", "function", "for", "ancestor", "elements" ]
4ce73c000f66194028d9992ee000c7c50b242148
https://github.com/makeup-js/makeup-screenreader-trap/blob/4ce73c000f66194028d9992ee000c7c50b242148/docs/static/bundle.js#L667-L669
30,743
crispy1989/node-zstreams
lib/streams/classic-duplex.js
ClassicDuplex
function ClassicDuplex(stream, options) { var readable, writable, classicReadable, classicWritable, self = this; readable = new PassThrough(); writable = new PassThrough(); CompoundDuplex.call(self, writable, readable, options); classicMixins.call(this, stream, options); classicReadable = this._internalReadable = new ClassicReadable(stream, options); classicReadable.on('error', this._duplexHandleInternalError.bind(this)); classicWritable = this._internalWritable = new ClassicWritable(stream, options); classicWritable.on('error', this._duplexHandleInternalError.bind(this)); writable.pipe(classicWritable); classicReadable.pipe(readable); }
javascript
function ClassicDuplex(stream, options) { var readable, writable, classicReadable, classicWritable, self = this; readable = new PassThrough(); writable = new PassThrough(); CompoundDuplex.call(self, writable, readable, options); classicMixins.call(this, stream, options); classicReadable = this._internalReadable = new ClassicReadable(stream, options); classicReadable.on('error', this._duplexHandleInternalError.bind(this)); classicWritable = this._internalWritable = new ClassicWritable(stream, options); classicWritable.on('error', this._duplexHandleInternalError.bind(this)); writable.pipe(classicWritable); classicReadable.pipe(readable); }
[ "function", "ClassicDuplex", "(", "stream", ",", "options", ")", "{", "var", "readable", ",", "writable", ",", "classicReadable", ",", "classicWritable", ",", "self", "=", "this", ";", "readable", "=", "new", "PassThrough", "(", ")", ";", "writable", "=", ...
ClassicDuplex wraps a "classic" duplex stream. @class ClassicDuplex @constructor @extends CompoundDuplex @uses _Classic @param {Stream} stream - The classic stream being wrapped @param {Object} [options] - Stream options
[ "ClassicDuplex", "wraps", "a", "classic", "duplex", "stream", "." ]
4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd
https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/streams/classic-duplex.js#L19-L35
30,744
back4app/back4app-entity
src/back/models/EntitySpecification.js
_loadEntity
function _loadEntity() { if (_Entity && _Entity !== models.Entity) { if (_nameValidation) { _Entity.adapter.loadEntity(_Entity); for (var attribute in _attributes) { _loadEntityAttribute(_attributes[attribute]); } } for (var method in _methods) { _loadEntityMethod(_methods[method], method); } } }
javascript
function _loadEntity() { if (_Entity && _Entity !== models.Entity) { if (_nameValidation) { _Entity.adapter.loadEntity(_Entity); for (var attribute in _attributes) { _loadEntityAttribute(_attributes[attribute]); } } for (var method in _methods) { _loadEntityMethod(_methods[method], method); } } }
[ "function", "_loadEntity", "(", ")", "{", "if", "(", "_Entity", "&&", "_Entity", "!==", "models", ".", "Entity", ")", "{", "if", "(", "_nameValidation", ")", "{", "_Entity", ".", "adapter", ".", "loadEntity", "(", "_Entity", ")", ";", "for", "(", "var"...
Loads the attributes and methods of the Entity that is associated with the current specification. @name module:back4app-entity/models.EntitySpecification~_loadEntity @function @private @example _loadEntity();
[ "Loads", "the", "attributes", "and", "methods", "of", "the", "Entity", "that", "is", "associated", "with", "the", "current", "specification", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/EntitySpecification.js#L570-L584
30,745
back4app/back4app-entity
src/back/models/EntitySpecification.js
_loadEntityAttribute
function _loadEntityAttribute(attribute) { expect(_methods).to.not.have.ownProperty( attribute.name, 'failed to load entity attribute "' + attribute.name + '" because ' + 'there is a method with same name in the current Entity and it cannot ' + 'be overloaded' ); if (_Entity.General) { expect(_Entity.General.attributes).to.not.have.ownProperty( attribute.name, 'failed to load entity attribute "' + attribute.name + '" because ' + 'there is an attribute with same name in a parent of current Entity ' + 'and it cannot be overriden' ); expect(_Entity.General.methods).to.not.respondTo( attribute.name, 'failed to load entity attribute "' + attribute.name + '" because ' + 'there is a method with same name in a parent of current Entity ' + 'and it cannot be overriden' ); } var entitySpecializations = _Entity.specializations; for (var specialization in entitySpecializations) { expect(entitySpecializations[specialization].specification.attributes) .to.not.have.ownProperty( attribute.name, 'failed to load entity attribute "' + attribute.name + '" because ' + 'there is an attribute with same name in a child of current Entity' ); expect(entitySpecializations[specialization].specification.methods) .to.not.have.ownProperty( attribute.name, 'failed to load entity attribute "' + attribute.name + '" because ' + 'there is a method with same name in a child of current Entity' ); } _Entity.adapter.loadEntityAttribute(_Entity, attribute); }
javascript
function _loadEntityAttribute(attribute) { expect(_methods).to.not.have.ownProperty( attribute.name, 'failed to load entity attribute "' + attribute.name + '" because ' + 'there is a method with same name in the current Entity and it cannot ' + 'be overloaded' ); if (_Entity.General) { expect(_Entity.General.attributes).to.not.have.ownProperty( attribute.name, 'failed to load entity attribute "' + attribute.name + '" because ' + 'there is an attribute with same name in a parent of current Entity ' + 'and it cannot be overriden' ); expect(_Entity.General.methods).to.not.respondTo( attribute.name, 'failed to load entity attribute "' + attribute.name + '" because ' + 'there is a method with same name in a parent of current Entity ' + 'and it cannot be overriden' ); } var entitySpecializations = _Entity.specializations; for (var specialization in entitySpecializations) { expect(entitySpecializations[specialization].specification.attributes) .to.not.have.ownProperty( attribute.name, 'failed to load entity attribute "' + attribute.name + '" because ' + 'there is an attribute with same name in a child of current Entity' ); expect(entitySpecializations[specialization].specification.methods) .to.not.have.ownProperty( attribute.name, 'failed to load entity attribute "' + attribute.name + '" because ' + 'there is a method with same name in a child of current Entity' ); } _Entity.adapter.loadEntityAttribute(_Entity, attribute); }
[ "function", "_loadEntityAttribute", "(", "attribute", ")", "{", "expect", "(", "_methods", ")", ".", "to", ".", "not", ".", "have", ".", "ownProperty", "(", "attribute", ".", "name", ",", "'failed to load entity attribute \"'", "+", "attribute", ".", "name", "...
Loads an attribute of the Entity that is associated with the current specification. @name module:back4app-entity/models.EntitySpecification~_loadEntityAttribute @function @param {!module:back4app-entity/models/attributes.Attribute} attribute The attribute to be loaded. @private @example _loadEntityAttribute(someAttribute);
[ "Loads", "an", "attribute", "of", "the", "Entity", "that", "is", "associated", "with", "the", "current", "specification", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/EntitySpecification.js#L598-L640
30,746
back4app/back4app-entity
src/back/models/EntitySpecification.js
_loadEntityMethod
function _loadEntityMethod(func, name) { expect(_attributes).to.not.have.ownProperty( name, 'failed to load entity method "' + name + '" because there is an ' + 'attribute with same name in the current Entity and it cannot be ' + 'overloaded' ); if (_Entity.General) { expect(_Entity.General.attributes).to.not.have.ownProperty( name, 'failed to load entity method "' + name + '" because there is an ' + 'attribute with same name in a parent of current Entity and it ' + 'cannot be overriden' ); } var entitySpecializations = _Entity.specializations; for (var specialization in entitySpecializations) { expect(entitySpecializations[specialization].specification.attributes) .to.not.have.ownProperty( name, 'failed to load entity method "' + name + '" because there is an ' + 'attribute with same name in a child of current Entity' ); } _Entity.prototype[name] = func; }
javascript
function _loadEntityMethod(func, name) { expect(_attributes).to.not.have.ownProperty( name, 'failed to load entity method "' + name + '" because there is an ' + 'attribute with same name in the current Entity and it cannot be ' + 'overloaded' ); if (_Entity.General) { expect(_Entity.General.attributes).to.not.have.ownProperty( name, 'failed to load entity method "' + name + '" because there is an ' + 'attribute with same name in a parent of current Entity and it ' + 'cannot be overriden' ); } var entitySpecializations = _Entity.specializations; for (var specialization in entitySpecializations) { expect(entitySpecializations[specialization].specification.attributes) .to.not.have.ownProperty( name, 'failed to load entity method "' + name + '" because there is an ' + 'attribute with same name in a child of current Entity' ); } _Entity.prototype[name] = func; }
[ "function", "_loadEntityMethod", "(", "func", ",", "name", ")", "{", "expect", "(", "_attributes", ")", ".", "to", ".", "not", ".", "have", ".", "ownProperty", "(", "name", ",", "'failed to load entity method \"'", "+", "name", "+", "'\" because there is an '", ...
Loads a method of the Entity that is associated with the current specification. @name module:back4app-entity/models.EntitySpecification~_loadEntityMethod @function @param {!function} func The method's function to be loaded. @param {!string} name The method's name to be loaded. @private @example _loadEntityMethod(someMethodFunction, someMethodName);
[ "Loads", "a", "method", "of", "the", "Entity", "that", "is", "associated", "with", "the", "current", "specification", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/EntitySpecification.js#L654-L682
30,747
back4app/back4app-entity
src/back/models/EntitySpecification.js
addAttribute
function addAttribute() { var attribute = arguments.length === 1 && arguments[0] instanceof attributes.Attribute ? arguments[0] : attributes.Attribute.resolve.apply( null, Array.prototype.slice.call(arguments) ); var newAttributes = attributes.AttributeDictionary.concat( _attributes, attribute ); if (_Entity) { _loadEntityAttribute(attribute); } _attributes = newAttributes; }
javascript
function addAttribute() { var attribute = arguments.length === 1 && arguments[0] instanceof attributes.Attribute ? arguments[0] : attributes.Attribute.resolve.apply( null, Array.prototype.slice.call(arguments) ); var newAttributes = attributes.AttributeDictionary.concat( _attributes, attribute ); if (_Entity) { _loadEntityAttribute(attribute); } _attributes = newAttributes; }
[ "function", "addAttribute", "(", ")", "{", "var", "attribute", "=", "arguments", ".", "length", "===", "1", "&&", "arguments", "[", "0", "]", "instanceof", "attributes", ".", "Attribute", "?", "arguments", "[", "0", "]", ":", "attributes", ".", "Attribute"...
Adds a new attribute to the attributes in the specification. @name module:back4app-entity/models.EntitySpecification#addAttribute @function @param {!module:back4app-entity/models/attributes.Attribute} attribute This is the attribute to be added. It can be passed as a {@link module:back4app-entity/models/attributes.Attribute} instance. @param {?string} [name] This is the name of the attribute. @example entitySpecification.addAttribute( new StringAttribute('attribute'), 'attribute' ); Adds a new attribute to the attributes in the specification @name module:back4app-entity/models.EntitySpecification#addAttribute @function @param {!Object} attribute This is the attribute to be added. It can be passed as an Object, as specified in {@link module:back4app-entity/models/attributes.Attribute}. @param {!string} [attribute.name] It is the name of the attribute. It is optional if it is passed as an argument in the function. @param {!string} [attribute.type='Object'] It is the type of the attribute. It is optional and if not passed it will assume 'Object' as the default value. @param {!string} [attribute.multiplicity='1'] It is the multiplicity of the attribute. It is optional and if not passed it will assume '1' as the default value. @param {?(boolean|number|string|Object|function)} [attribute.default] It is the default expression of the attribute. @param {?string} [name] This is the name of the attribute. @example entitySpecification.addAttribute({ name: 'attribute', type: 'string', multiplicity: '0..1', default: 'default' }, 'attribute'); Adds a new attribute to the attributes in the specification. @name module:back4app-entity/models.EntitySpecification#addAttribute @function @param {!string} name It is the name of the attribute. @param {!string} [type='Object'] It is the type of the attribute. It is optional and if not passed it will assume 'Object' as the default value. @param {!string} [multiplicity='1'] It is the multiplicity of the attribute. It is optional and if not passed it will assume '1' as the default value. @param {?(boolean|number|string|Object|function)} [default] It is the default expression of the attribute. @example entitySpecification.addAttribute( 'attribute', 'string', '0..1', 'default' );
[ "Adds", "a", "new", "attribute", "to", "the", "attributes", "in", "the", "specification", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/EntitySpecification.js#L744-L763
30,748
back4app/back4app-entity
src/back/models/EntitySpecification.js
addMethod
function addMethod(func, name) { var newMethods = methods.MethodDictionary.concat( _methods, func, name ); if (_Entity) { _loadEntityMethod(func, name); } _methods = newMethods; }
javascript
function addMethod(func, name) { var newMethods = methods.MethodDictionary.concat( _methods, func, name ); if (_Entity) { _loadEntityMethod(func, name); } _methods = newMethods; }
[ "function", "addMethod", "(", "func", ",", "name", ")", "{", "var", "newMethods", "=", "methods", ".", "MethodDictionary", ".", "concat", "(", "_methods", ",", "func", ",", "name", ")", ";", "if", "(", "_Entity", ")", "{", "_loadEntityMethod", "(", "func...
Adds a new method to the methods in the specification. @name module:back4app-entity/models.EntitySpecification#addMethod @function @param {!function} func This is the method's function to be added. @param {!string} name This is the name of the method. @example entitySpecification.addMethod( function () { return 'newMethod'; }, 'newMethod' );
[ "Adds", "a", "new", "method", "to", "the", "methods", "in", "the", "specification", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/EntitySpecification.js#L777-L789
30,749
crispy1989/node-zstreams
lib/mixins/_stream.js
_Stream
function _Stream(superObj) { var self = this; this._zSuperObj = superObj; this._isZStream = true; this._ignoreStreamError = false; this._zStreamId = streamIdCounter++; this._currentStreamChain = new StreamChain(true); this._currentStreamChain._addStream(this); this._zStreamRank = 0; this.on('error', function(error) { // If there are no other 'error' handlers on this stream, trigger a chainerror if(self.listeners('error').length <= 1) { self.triggerChainError(error); } }); }
javascript
function _Stream(superObj) { var self = this; this._zSuperObj = superObj; this._isZStream = true; this._ignoreStreamError = false; this._zStreamId = streamIdCounter++; this._currentStreamChain = new StreamChain(true); this._currentStreamChain._addStream(this); this._zStreamRank = 0; this.on('error', function(error) { // If there are no other 'error' handlers on this stream, trigger a chainerror if(self.listeners('error').length <= 1) { self.triggerChainError(error); } }); }
[ "function", "_Stream", "(", "superObj", ")", "{", "var", "self", "=", "this", ";", "this", ".", "_zSuperObj", "=", "superObj", ";", "this", ".", "_isZStream", "=", "true", ";", "this", ".", "_ignoreStreamError", "=", "false", ";", "this", ".", "_zStreamI...
Writable mixins for ZStream streams. This class cannot be instantiated in itself. Its prototype methods must be added to the prototype of the class it's being mixed into, and its constructor must be called from the superclass's constructor. @class _Stream @constructor @param {Function} superObj - The prototype functions of the superclass the mixin is added on top of. For example, Writable.prototype or Transform.prototype.
[ "Writable", "mixins", "for", "ZStream", "streams", "." ]
4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd
https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/mixins/_stream.js#L16-L32
30,750
feedhenry/fh-forms
lib/impl/importForms/importFromDir.js
getFormFiles
function getFormFiles(metaDataFilePath) { var formsZipMetaData = require(metaDataFilePath); if (formsZipMetaData && formsZipMetaData.files) { var formFiles = formsZipMetaData.files; return _.map(formFiles, function(formDetails) { return formDetails.path; }); } else { return []; } }
javascript
function getFormFiles(metaDataFilePath) { var formsZipMetaData = require(metaDataFilePath); if (formsZipMetaData && formsZipMetaData.files) { var formFiles = formsZipMetaData.files; return _.map(formFiles, function(formDetails) { return formDetails.path; }); } else { return []; } }
[ "function", "getFormFiles", "(", "metaDataFilePath", ")", "{", "var", "formsZipMetaData", "=", "require", "(", "metaDataFilePath", ")", ";", "if", "(", "formsZipMetaData", "&&", "formsZipMetaData", ".", "files", ")", "{", "var", "formFiles", "=", "formsZipMetaData...
Returns an array that contains the form file paths @param {String} metaDataFilePath the path to the unzipped form meta data file @return {Array} an array that contains the relative paths of the form files
[ "Returns", "an", "array", "that", "contains", "the", "form", "file", "paths" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/importForms/importFromDir.js#L15-L25
30,751
feedhenry/fh-forms
lib/impl/exportSubmissions.js
getStatusUpdater
function getStatusUpdater(connections, isAsync) { return function updateExportStatus(statusUpdate, cb) { cb = cb || _.noop; if (isAsync) { updateCSVExportStatus(connections, statusUpdate, cb); } else { return cb(); } }; }
javascript
function getStatusUpdater(connections, isAsync) { return function updateExportStatus(statusUpdate, cb) { cb = cb || _.noop; if (isAsync) { updateCSVExportStatus(connections, statusUpdate, cb); } else { return cb(); } }; }
[ "function", "getStatusUpdater", "(", "connections", ",", "isAsync", ")", "{", "return", "function", "updateExportStatus", "(", "statusUpdate", ",", "cb", ")", "{", "cb", "=", "cb", "||", "_", ".", "noop", ";", "if", "(", "isAsync", ")", "{", "updateCSVExpo...
Creating an updater function for export @param connections Mongoose and mongodb connections @param {boolean} isAsync Flag to indicated whether the CSV export is synchronous or asynchronous. @returns {function} updateExportStatus
[ "Creating", "an", "updater", "function", "for", "export" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportSubmissions.js#L22-L31
30,752
feedhenry/fh-forms
lib/impl/exportSubmissions.js
generateQuery
function generateQuery(searchParams, cb) { if (searchParams.query ) { searchSubmissions.queryBuilder(searchParams.query, cb); } else { return cb(undefined, buildQuery(searchParams)); } }
javascript
function generateQuery(searchParams, cb) { if (searchParams.query ) { searchSubmissions.queryBuilder(searchParams.query, cb); } else { return cb(undefined, buildQuery(searchParams)); } }
[ "function", "generateQuery", "(", "searchParams", ",", "cb", ")", "{", "if", "(", "searchParams", ".", "query", ")", "{", "searchSubmissions", ".", "queryBuilder", "(", "searchParams", ".", "query", ",", "cb", ")", ";", "}", "else", "{", "return", "cb", ...
generateQuery - Generating either a basic query or advanced search query @param {object} searchParams params to search submissions by @param {array} searchParams.formId Array of form IDs to search for @param {array} searchParams.subid Array of submission IDs to search for @param {string} searchParams.filter A string value to filter the submissions by metadata @param {string} searchParams.query An advanced submission query object @param {array} searchParams.appId Array of Project IDs to search for @param {function} cb @return {object} Generated mongo query
[ "generateQuery", "-", "Generating", "either", "a", "basic", "query", "or", "advanced", "search", "query" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportSubmissions.js#L45-L51
30,753
feedhenry/fh-forms
lib/impl/exportSubmissions.js
buildCompositeForm
function buildCompositeForm(formSubmissionModel, formId, singleFormQuery, statusUpdaterFunction, cb) { var mergedFields = {}; mergedFields[formId] = {}; logger.debug("buildCompositeForm start"); statusUpdaterFunction({ message: "Creating form metadata for submissions with form ID: " + formId }); var mapReduceOptions = { map: function() { //The only difference will be the "lastUpdated" timestamp. emit(this.formSubmittedAgainst.lastUpdated, this.formSubmittedAgainst); // eslint-disable-line no-undef }, reduce: function(lastUpdatedTimestamp, formEntries) { //Only want one of each form definition for each different timestamp var formEntry = formEntries[0]; //Only need the pages, _id and name if (formEntry && formEntry.pages) { return { _id: formEntry._id, name: formEntry.name, pages: formEntry.pages }; } else { return null; } }, query: singleFormQuery }; formSubmissionModel.mapReduce(mapReduceOptions, function(err, subFormsSubmittedAgainst) { if (err) { logger.error("Error Using mapReduce ", err); return cb(err); } statusUpdaterFunction({ message: "Finished Creating form metadata for submissions with form ID: " + formId }); logger.debug("buildCompositeForm finish"); var formName = ""; _.each(subFormsSubmittedAgainst, function(subFormSubmittedAgainst) { formName = formName || subFormSubmittedAgainst.value.name; mergedFields[formId] = mergeFormFields(mergedFields[formId] || {}, subFormSubmittedAgainst.value); }); return cb(null, mergedFields, formName); }); }
javascript
function buildCompositeForm(formSubmissionModel, formId, singleFormQuery, statusUpdaterFunction, cb) { var mergedFields = {}; mergedFields[formId] = {}; logger.debug("buildCompositeForm start"); statusUpdaterFunction({ message: "Creating form metadata for submissions with form ID: " + formId }); var mapReduceOptions = { map: function() { //The only difference will be the "lastUpdated" timestamp. emit(this.formSubmittedAgainst.lastUpdated, this.formSubmittedAgainst); // eslint-disable-line no-undef }, reduce: function(lastUpdatedTimestamp, formEntries) { //Only want one of each form definition for each different timestamp var formEntry = formEntries[0]; //Only need the pages, _id and name if (formEntry && formEntry.pages) { return { _id: formEntry._id, name: formEntry.name, pages: formEntry.pages }; } else { return null; } }, query: singleFormQuery }; formSubmissionModel.mapReduce(mapReduceOptions, function(err, subFormsSubmittedAgainst) { if (err) { logger.error("Error Using mapReduce ", err); return cb(err); } statusUpdaterFunction({ message: "Finished Creating form metadata for submissions with form ID: " + formId }); logger.debug("buildCompositeForm finish"); var formName = ""; _.each(subFormsSubmittedAgainst, function(subFormSubmittedAgainst) { formName = formName || subFormSubmittedAgainst.value.name; mergedFields[formId] = mergeFormFields(mergedFields[formId] || {}, subFormSubmittedAgainst.value); }); return cb(null, mergedFields, formName); }); }
[ "function", "buildCompositeForm", "(", "formSubmissionModel", ",", "formId", ",", "singleFormQuery", ",", "statusUpdaterFunction", ",", "cb", ")", "{", "var", "mergedFields", "=", "{", "}", ";", "mergedFields", "[", "formId", "]", "=", "{", "}", ";", "logger",...
buildCompositeForm - Building a merged list of fields based on the @param {Model} formSubmissionModel The Submission mongoose Model @param {string} formId The ID of the form to search for @param {object} singleFormQuery A mongo query to find all of the submissions to search for @param {function} statusUpdaterFunction A function to update the status of an async submission export @param {function} cb
[ "buildCompositeForm", "-", "Building", "a", "merged", "list", "of", "fields", "based", "on", "the" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportSubmissions.js#L62-L116
30,754
feedhenry/fh-forms
lib/impl/exportSubmissions.js
buildCSVsForSingleMergedForm
function buildCSVsForSingleMergedForm(formSubmissionModel, params, cb) { var formId = params.formId; var formName = params.formName; var date = params.date; var mergedFields = params.mergedFields; var fieldHeader = params.fieldHeader; var singleFormQuery = params.singleFormQuery; var downloadUrl = params.downloadUrl; var fullSubmissionCSVString = ""; //Form Name might not be unique but the ID will always be. var fileName = date + "-" + formId + "-" + (formName.split(' ').join('_')); //Query the submissions for the formId //LEAN //Select only the metadata and formFields in the submission. // Stream response // Build CSV string for each entry. // Add to the zip file. cb = _.once(cb); params.statusUpdaterFunction({ message: "Beginning export of submissions for form ID: " + formId }); var exportProgressInterval = setInterval(function() { params.statusUpdaterFunction({ message: "Exporting submission " + params.exportCounter.numSubsExported + " of " + params.exportCounter.numSubmissionsToExport }); }, 1000); //First, generate headers. fullSubmissionCSVString = csvHeaders.generateCSVHeaders(_.keys(mergedFields[formId]), mergedFields[formId], fieldHeader); var submissionQueryStream = formSubmissionModel.find(singleFormQuery).select({ "formSubmittedAgainst.pages": 0, "formSubmittedAgainst.pageRules": 0, "formSubmittedAgainst.fieldRules": 0 }).lean().stream(); submissionQueryStream.on('data', function addSubmissionToCSV(submissionJSON) { //Merge the form fields fullSubmissionCSVString += processSingleSubmission({ mergedFields: mergedFields, submission: submissionJSON, date: date, fieldHeader: fieldHeader, downloadUrl: downloadUrl }); params.exportCounter.numSubsExported ++; }).on('error', function(err) { logger.error("Error streaming submissions ", err); clearInterval(exportProgressInterval); return cb(err); }).on('close', function() { clearInterval(exportProgressInterval); return cb(undefined, { formId: formId, fileName: fileName, csvString: fullSubmissionCSVString }); }); }
javascript
function buildCSVsForSingleMergedForm(formSubmissionModel, params, cb) { var formId = params.formId; var formName = params.formName; var date = params.date; var mergedFields = params.mergedFields; var fieldHeader = params.fieldHeader; var singleFormQuery = params.singleFormQuery; var downloadUrl = params.downloadUrl; var fullSubmissionCSVString = ""; //Form Name might not be unique but the ID will always be. var fileName = date + "-" + formId + "-" + (formName.split(' ').join('_')); //Query the submissions for the formId //LEAN //Select only the metadata and formFields in the submission. // Stream response // Build CSV string for each entry. // Add to the zip file. cb = _.once(cb); params.statusUpdaterFunction({ message: "Beginning export of submissions for form ID: " + formId }); var exportProgressInterval = setInterval(function() { params.statusUpdaterFunction({ message: "Exporting submission " + params.exportCounter.numSubsExported + " of " + params.exportCounter.numSubmissionsToExport }); }, 1000); //First, generate headers. fullSubmissionCSVString = csvHeaders.generateCSVHeaders(_.keys(mergedFields[formId]), mergedFields[formId], fieldHeader); var submissionQueryStream = formSubmissionModel.find(singleFormQuery).select({ "formSubmittedAgainst.pages": 0, "formSubmittedAgainst.pageRules": 0, "formSubmittedAgainst.fieldRules": 0 }).lean().stream(); submissionQueryStream.on('data', function addSubmissionToCSV(submissionJSON) { //Merge the form fields fullSubmissionCSVString += processSingleSubmission({ mergedFields: mergedFields, submission: submissionJSON, date: date, fieldHeader: fieldHeader, downloadUrl: downloadUrl }); params.exportCounter.numSubsExported ++; }).on('error', function(err) { logger.error("Error streaming submissions ", err); clearInterval(exportProgressInterval); return cb(err); }).on('close', function() { clearInterval(exportProgressInterval); return cb(undefined, { formId: formId, fileName: fileName, csvString: fullSubmissionCSVString }); }); }
[ "function", "buildCSVsForSingleMergedForm", "(", "formSubmissionModel", ",", "params", ",", "cb", ")", "{", "var", "formId", "=", "params", ".", "formId", ";", "var", "formName", "=", "params", ".", "formName", ";", "var", "date", "=", "params", ".", "date",...
buildCSVsForSingleMergedForm - Building a CSV representation of a submission based on the merged definiton of all of the versions of the form it was submitted against. @param {Model} formSubmissionModel The Submission mongoose Model @param {type} params @param {string} params.formId @param {function} params.statusUpdaterFunction Function to update the status of a submission export. @param {string} params.date Formatted date of export @param {string} params.formName Form Name @param {object} params.mergedFields Set of merged field definitions @param {string} params.fieldHeader Field header to use for export @param {object} params.singleFormQuery Query to search for submissions based in a form ID @param {number} params.exportCounter.numSubmissionsToExport The total number of submissions to export @param {number} params.exportCounter.numSubsExported The total number of submissions exported to date @param {string} params.downloadUrl The downloadUrl template to use when generating submission file URLs. @param {function} cb
[ "buildCSVsForSingleMergedForm", "-", "Building", "a", "CSV", "representation", "of", "a", "submission", "based", "on", "the", "merged", "definiton", "of", "all", "of", "the", "versions", "of", "the", "form", "it", "was", "submitted", "against", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportSubmissions.js#L136-L198
30,755
feedhenry/fh-forms
lib/impl/exportSubmissions.js
buildCSVsForSingleForm
function buildCSVsForSingleForm(formSubmissionModel, params, formId, callback) { logger.debug("buildCSVsForSingleForm", params, formId); var date = params.date; var searchParams = params.searchParams || {}; var fieldHeader = searchParams.fieldHeader; var downloadUrl = searchParams.downloadUrl || ""; formId = formId.toString(); params.statusUpdaterFunction({ message: "Starting export of submissions for form with ID:" + formId }); generateQuery(_.defaults({ formId: formId }, searchParams), function(err, singleFormQuery) { if (err) { return callback(err); } async.waterfall([ async.apply(buildCompositeForm, formSubmissionModel, formId, singleFormQuery, params.statusUpdaterFunction), function buildSubmissionCSVForSingleForm(mergedFields, formName, cb) { buildCSVsForSingleMergedForm(formSubmissionModel, { date: date, fieldHeader: fieldHeader, downloadUrl: downloadUrl, mergedFields: mergedFields, formName: formName, formId: formId, exportCounter: params.exportCounter, singleFormQuery: singleFormQuery, statusUpdaterFunction: params.statusUpdaterFunction }, cb); } ], callback); }); }
javascript
function buildCSVsForSingleForm(formSubmissionModel, params, formId, callback) { logger.debug("buildCSVsForSingleForm", params, formId); var date = params.date; var searchParams = params.searchParams || {}; var fieldHeader = searchParams.fieldHeader; var downloadUrl = searchParams.downloadUrl || ""; formId = formId.toString(); params.statusUpdaterFunction({ message: "Starting export of submissions for form with ID:" + formId }); generateQuery(_.defaults({ formId: formId }, searchParams), function(err, singleFormQuery) { if (err) { return callback(err); } async.waterfall([ async.apply(buildCompositeForm, formSubmissionModel, formId, singleFormQuery, params.statusUpdaterFunction), function buildSubmissionCSVForSingleForm(mergedFields, formName, cb) { buildCSVsForSingleMergedForm(formSubmissionModel, { date: date, fieldHeader: fieldHeader, downloadUrl: downloadUrl, mergedFields: mergedFields, formName: formName, formId: formId, exportCounter: params.exportCounter, singleFormQuery: singleFormQuery, statusUpdaterFunction: params.statusUpdaterFunction }, cb); } ], callback); }); }
[ "function", "buildCSVsForSingleForm", "(", "formSubmissionModel", ",", "params", ",", "formId", ",", "callback", ")", "{", "logger", ".", "debug", "(", "\"buildCSVsForSingleForm\"", ",", "params", ",", "formId", ")", ";", "var", "date", "=", "params", ".", "da...
buildCSVsForSingleForm - Generating the full CSV file for a single form. @param {Model} formSubmissionModel description @param {object} params @param {function} params.statusUpdaterFunction Function to update the status of the export. @param {string} params.formId @param {string} params.date Formatted date of export @param {object} params.searchParams Submission Parameters To Search By @param {array} params.searchParams.formId Array of form IDs to search for @param {array} params.searchParams.subid Array of submission IDs to search for @param {string} params.searchParams.filter A string value to filter the submissions by metadata @param {array} params.searchParams.appId Array of Project IDs to search for @param {string} params.searchParams.fieldHeader Field header to use (fieldName or fieldCode) @param {string} params.searchParams.downloadUrl URL to use for file downloads @param {number} params.exportCounter.numSubmissionsToExport The total number of submissions to export @param {number} params.exportCounter.numSubsExported The total number of submissions exported to date @param {string} formId The ID of the form to export @param {function} callback @return {type}
[ "buildCSVsForSingleForm", "-", "Generating", "the", "full", "CSV", "file", "for", "a", "single", "form", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/exportSubmissions.js#L221-L259
30,756
crispy1989/node-zstreams
lib/writable.js
ZWritable
function ZWritable(options) { if(options) { if(options.writableObjectMode) { options.objectMode = true; } //Add support for iojs simplified stream constructor if(typeof options.write === 'function') { this._write = options.write; } if(typeof options.flush === 'function') { this._flush = options.flush; } } Transform.call(this, options); streamMixins.call(this, Transform.prototype, options); writableMixins.call(this, options); }
javascript
function ZWritable(options) { if(options) { if(options.writableObjectMode) { options.objectMode = true; } //Add support for iojs simplified stream constructor if(typeof options.write === 'function') { this._write = options.write; } if(typeof options.flush === 'function') { this._flush = options.flush; } } Transform.call(this, options); streamMixins.call(this, Transform.prototype, options); writableMixins.call(this, options); }
[ "function", "ZWritable", "(", "options", ")", "{", "if", "(", "options", ")", "{", "if", "(", "options", ".", "writableObjectMode", ")", "{", "options", ".", "objectMode", "=", "true", ";", "}", "//Add support for iojs simplified stream constructor", "if", "(", ...
ZWritable implements the Writable stream interface with the _write function. ZWritable also accepts a `_flush` function to facilitate cleanup. @class ZWritable @constructor @extends Transform @uses _Stream @uses _Writable @param {Object} [options] - Stream options
[ "ZWritable", "implements", "the", "Writable", "stream", "interface", "with", "the", "_write", "function", ".", "ZWritable", "also", "accepts", "a", "_flush", "function", "to", "facilitate", "cleanup", "." ]
4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd
https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/writable.js#L18-L35
30,757
feedhenry/fh-forms
lib/impl/dataSources/checkUpdateInterval.js
needsAnUpdate
function needsAnUpdate(dataSource, currentTime) { //The last time the Data Source was refreshed var lastRefreshedMs = new Date(dataSource.cache[0].lastRefreshed).valueOf(); currentTime = new Date(currentTime); var conf = config.get(); var defaults = config.defaults(); //The number of minutes between backoffs var minsPerBackOffIndex = conf.minsPerBackOffIndex || defaults.minsPerBackOffIndex; //The number of milliseconds to wait until the Data Source needs to be refreshed. var refreshIntervalMs = dataSource.refreshInterval * MIN_MS; var backOffIndex = dataSource.cache[0].backOffIndex || 0; //The number of milliseconds to wait because of backing off from errors. var backOffMs = backOffIndex * (minsPerBackOffIndex * MIN_MS); //Will only wait a max of a week between failed updates. backOffMs = Math.min(backOffMs, conf.dsMaxIntervalMs || defaults.dsMaxIntervalMs); //The next time the Data Source will refresh will either be normal interval or the backOff interval, whichever is the largest. var nextRefreshMs = Math.max(refreshIntervalMs, backOffMs); //Checking if the total of the three times is <= currentTime. If it is, then the data source should try to update. return new Date(lastRefreshedMs + nextRefreshMs) <= currentTime; }
javascript
function needsAnUpdate(dataSource, currentTime) { //The last time the Data Source was refreshed var lastRefreshedMs = new Date(dataSource.cache[0].lastRefreshed).valueOf(); currentTime = new Date(currentTime); var conf = config.get(); var defaults = config.defaults(); //The number of minutes between backoffs var minsPerBackOffIndex = conf.minsPerBackOffIndex || defaults.minsPerBackOffIndex; //The number of milliseconds to wait until the Data Source needs to be refreshed. var refreshIntervalMs = dataSource.refreshInterval * MIN_MS; var backOffIndex = dataSource.cache[0].backOffIndex || 0; //The number of milliseconds to wait because of backing off from errors. var backOffMs = backOffIndex * (minsPerBackOffIndex * MIN_MS); //Will only wait a max of a week between failed updates. backOffMs = Math.min(backOffMs, conf.dsMaxIntervalMs || defaults.dsMaxIntervalMs); //The next time the Data Source will refresh will either be normal interval or the backOff interval, whichever is the largest. var nextRefreshMs = Math.max(refreshIntervalMs, backOffMs); //Checking if the total of the three times is <= currentTime. If it is, then the data source should try to update. return new Date(lastRefreshedMs + nextRefreshMs) <= currentTime; }
[ "function", "needsAnUpdate", "(", "dataSource", ",", "currentTime", ")", "{", "//The last time the Data Source was refreshed", "var", "lastRefreshedMs", "=", "new", "Date", "(", "dataSource", ".", "cache", "[", "0", "]", ".", "lastRefreshed", ")", ".", "valueOf", ...
needsAnUpdate - Comparing the current time to when the data source needs to be updated. The backoff calculation is based on the assumption that - update fails: wait 1 interval - update fails again: wait 2 intervals - update fails again: wait 3 interval ... ... ... - update fails again: wait a max of a week between refreshes @param {object} dataSource A data source to check @param {date} currentTime The time to scan for @param {number} minsPerBackOffIndex The number of minutes to back-off per backOff interval @return {boolean} true/false
[ "needsAnUpdate", "-", "Comparing", "the", "current", "time", "to", "when", "the", "data", "source", "needs", "to", "be", "updated", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/dataSources/checkUpdateInterval.js#L23-L48
30,758
feedhenry/fh-forms
lib/impl/deleteTheme.js
validateThemeNotInUseByApps
function validateThemeNotInUseByApps(cb) { var appThemeModel = models.get(connections.mongooseConnection, models.MODELNAMES.APP_THEMES); appThemeModel.count({"theme" : options._id}, function(err, countAppsUsingTheme) { if (err) { return cb(err); } if (countAppsUsingTheme > 0) { return cb(new Error("Cannot delete theme in use by apps. Apps Using this theme" + countAppsUsingTheme)); } return cb(); }); }
javascript
function validateThemeNotInUseByApps(cb) { var appThemeModel = models.get(connections.mongooseConnection, models.MODELNAMES.APP_THEMES); appThemeModel.count({"theme" : options._id}, function(err, countAppsUsingTheme) { if (err) { return cb(err); } if (countAppsUsingTheme > 0) { return cb(new Error("Cannot delete theme in use by apps. Apps Using this theme" + countAppsUsingTheme)); } return cb(); }); }
[ "function", "validateThemeNotInUseByApps", "(", "cb", ")", "{", "var", "appThemeModel", "=", "models", ".", "get", "(", "connections", ".", "mongooseConnection", ",", "models", ".", "MODELNAMES", ".", "APP_THEMES", ")", ";", "appThemeModel", ".", "count", "(", ...
Themes associated with app should not be deleted.
[ "Themes", "associated", "with", "app", "should", "not", "be", "deleted", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/deleteTheme.js#L26-L40
30,759
cloudfour/drizzle-builder
src/helpers/pattern.js
registerPatternHelpers
function registerPatternHelpers(options) { const Handlebars = options.handlebars; if (Handlebars.helpers.pattern) { DrizzleError.error( new DrizzleError( '`pattern` helper already registered', DrizzleError.LEVELS.WARN ), options.debug ); } /** * The `pattern` helper allows the embedding of patterns anywhere * and they can get their correct local context. */ Handlebars.registerHelper('pattern', (id, rootContext, opts) => { const renderedTemplate = renderPatternPartial( id, rootContext.drizzle, Handlebars ); return renderedTemplate; }); if (Handlebars.helpers.patternSource) { DrizzleError.error( new DrizzleError( '`patternSource` helper already registered', DrizzleError.LEVELS.WARN ), options.debug ); } /** * Similar to `pattern` but the returned string is HTML-escaped. * Can be used for rendering source in `<pre>` tags. */ Handlebars.registerHelper('patternSource', (id, rootContext, opts) => { const renderedTemplate = renderPatternPartial( id, rootContext.drizzle, Handlebars ); const sourceMarkup = beautify(renderedTemplate, options.beautifier); return Handlebars.Utils.escapeExpression(sourceMarkup); }); return Handlebars; }
javascript
function registerPatternHelpers(options) { const Handlebars = options.handlebars; if (Handlebars.helpers.pattern) { DrizzleError.error( new DrizzleError( '`pattern` helper already registered', DrizzleError.LEVELS.WARN ), options.debug ); } /** * The `pattern` helper allows the embedding of patterns anywhere * and they can get their correct local context. */ Handlebars.registerHelper('pattern', (id, rootContext, opts) => { const renderedTemplate = renderPatternPartial( id, rootContext.drizzle, Handlebars ); return renderedTemplate; }); if (Handlebars.helpers.patternSource) { DrizzleError.error( new DrizzleError( '`patternSource` helper already registered', DrizzleError.LEVELS.WARN ), options.debug ); } /** * Similar to `pattern` but the returned string is HTML-escaped. * Can be used for rendering source in `<pre>` tags. */ Handlebars.registerHelper('patternSource', (id, rootContext, opts) => { const renderedTemplate = renderPatternPartial( id, rootContext.drizzle, Handlebars ); const sourceMarkup = beautify(renderedTemplate, options.beautifier); return Handlebars.Utils.escapeExpression(sourceMarkup); }); return Handlebars; }
[ "function", "registerPatternHelpers", "(", "options", ")", "{", "const", "Handlebars", "=", "options", ".", "handlebars", ";", "if", "(", "Handlebars", ".", "helpers", ".", "pattern", ")", "{", "DrizzleError", ".", "error", "(", "new", "DrizzleError", "(", "...
Register some drizzle-specific pattern helpers
[ "Register", "some", "drizzle", "-", "specific", "pattern", "helpers" ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/helpers/pattern.js#L34-L81
30,760
feedhenry/fh-forms
lib/middleware/dataSources.js
deploy
function deploy(req, res, next) { var dataSource = req.body; dataSource._id = req.params.id; forms.dataSources.deploy(req.connectionOptions, dataSource, dataSourcesHandler(constants.resultTypes.dataSources, req, next)); }
javascript
function deploy(req, res, next) { var dataSource = req.body; dataSource._id = req.params.id; forms.dataSources.deploy(req.connectionOptions, dataSource, dataSourcesHandler(constants.resultTypes.dataSources, req, next)); }
[ "function", "deploy", "(", "req", ",", "res", ",", "next", ")", "{", "var", "dataSource", "=", "req", ".", "body", ";", "dataSource", ".", "_id", "=", "req", ".", "params", ".", "id", ";", "forms", ".", "dataSources", ".", "deploy", "(", "req", "."...
Deploying A Data Source. This will update if already exists or create one if not. @param req @param res @param next
[ "Deploying", "A", "Data", "Source", ".", "This", "will", "update", "if", "already", "exists", "or", "create", "one", "if", "not", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/dataSources.js#L53-L59
30,761
stackgl/gl-shader-core
lib/reflect.js
makeReflectTypes
function makeReflectTypes(uniforms, useIndex) { var obj = {} for(var i=0; i<uniforms.length; ++i) { var n = uniforms[i].name var parts = n.split(".") var o = obj for(var j=0; j<parts.length; ++j) { var x = parts[j].split("[") if(x.length > 1) { if(!(x[0] in o)) { o[x[0]] = [] } o = o[x[0]] for(var k=1; k<x.length; ++k) { var y = parseInt(x[k]) if(k<x.length-1 || j<parts.length-1) { if(!(y in o)) { if(k < x.length-1) { o[y] = [] } else { o[y] = {} } } o = o[y] } else { if(useIndex) { o[y] = i } else { o[y] = uniforms[i].type } } } } else if(j < parts.length-1) { if(!(x[0] in o)) { o[x[0]] = {} } o = o[x[0]] } else { if(useIndex) { o[x[0]] = i } else { o[x[0]] = uniforms[i].type } } } } return obj }
javascript
function makeReflectTypes(uniforms, useIndex) { var obj = {} for(var i=0; i<uniforms.length; ++i) { var n = uniforms[i].name var parts = n.split(".") var o = obj for(var j=0; j<parts.length; ++j) { var x = parts[j].split("[") if(x.length > 1) { if(!(x[0] in o)) { o[x[0]] = [] } o = o[x[0]] for(var k=1; k<x.length; ++k) { var y = parseInt(x[k]) if(k<x.length-1 || j<parts.length-1) { if(!(y in o)) { if(k < x.length-1) { o[y] = [] } else { o[y] = {} } } o = o[y] } else { if(useIndex) { o[y] = i } else { o[y] = uniforms[i].type } } } } else if(j < parts.length-1) { if(!(x[0] in o)) { o[x[0]] = {} } o = o[x[0]] } else { if(useIndex) { o[x[0]] = i } else { o[x[0]] = uniforms[i].type } } } } return obj }
[ "function", "makeReflectTypes", "(", "uniforms", ",", "useIndex", ")", "{", "var", "obj", "=", "{", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "uniforms", ".", "length", ";", "++", "i", ")", "{", "var", "n", "=", "uniforms", "[", "i", ...
Construct type info for reflection. This iterates over the flattened list of uniform type values and smashes them into a JSON object. The leaves of the resulting object are either indices or type strings representing primitive glslify types
[ "Construct", "type", "info", "for", "reflection", ".", "This", "iterates", "over", "the", "flattened", "list", "of", "uniform", "type", "values", "and", "smashes", "them", "into", "a", "JSON", "object", ".", "The", "leaves", "of", "the", "resulting", "object...
25e021e9239ad7b73ce08ff0fdc97e2e68e1d075
https://github.com/stackgl/gl-shader-core/blob/25e021e9239ad7b73ce08ff0fdc97e2e68e1d075/lib/reflect.js#L10-L57
30,762
feedhenry/fh-forms
lib/middleware/submissions.js
getRequestFileParameters
function getRequestFileParameters(req, res, next) { //A valid getForms request must have an appId parameter set var submitFileParams = {}; submitFileParams.fileDetails = {}; //Get the content body for normal parameter var filesInRequest = req.files; if (_.size(filesInRequest) === 0) { logger.error("Middleware: getRequestFileParameters, Expected A File To Have Been Sent ", {params: req.params}); return next(new Error("Expected A File To Have Been Submitted")); } var fileDetails = _.map(filesInRequest, function(fileValue) { return fileValue; }); fileDetails = _.first(fileDetails); logger.debug("Middleware: getRequestFileParameters ", {fileDetails: fileDetails, body: req.body}); submitFileParams.fileDetails = { fileStream: fileDetails.path, fileName: fileDetails.originalname || fileDetails.name, fileType: fileDetails.mimetype, fileSize: fileDetails.size }; req.appformsResultPayload = { data: submitFileParams, type: constants.resultTypes.submissions }; logger.debug("Middleware: getRequestFileParameters ", {params: req.appformsResultPayload}); return next(); }
javascript
function getRequestFileParameters(req, res, next) { //A valid getForms request must have an appId parameter set var submitFileParams = {}; submitFileParams.fileDetails = {}; //Get the content body for normal parameter var filesInRequest = req.files; if (_.size(filesInRequest) === 0) { logger.error("Middleware: getRequestFileParameters, Expected A File To Have Been Sent ", {params: req.params}); return next(new Error("Expected A File To Have Been Submitted")); } var fileDetails = _.map(filesInRequest, function(fileValue) { return fileValue; }); fileDetails = _.first(fileDetails); logger.debug("Middleware: getRequestFileParameters ", {fileDetails: fileDetails, body: req.body}); submitFileParams.fileDetails = { fileStream: fileDetails.path, fileName: fileDetails.originalname || fileDetails.name, fileType: fileDetails.mimetype, fileSize: fileDetails.size }; req.appformsResultPayload = { data: submitFileParams, type: constants.resultTypes.submissions }; logger.debug("Middleware: getRequestFileParameters ", {params: req.appformsResultPayload}); return next(); }
[ "function", "getRequestFileParameters", "(", "req", ",", "res", ",", "next", ")", "{", "//A valid getForms request must have an appId parameter set", "var", "submitFileParams", "=", "{", "}", ";", "submitFileParams", ".", "fileDetails", "=", "{", "}", ";", "//Get the ...
Middleware For Populating File Parameters From A Multipart Request Used For Updating Submission Files @param req @param res @returns next
[ "Middleware", "For", "Populating", "File", "Parameters", "From", "A", "Multipart", "Request" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L30-L66
30,763
feedhenry/fh-forms
lib/middleware/submissions.js
list
function list(req, res, next) { logger.debug("Middleware Submissions List ", {connectionOptions: req.connectionOptions}); forms.getSubmissions(req.connectionOptions, {}, _getSubmissionsResultHandler(req, next)); }
javascript
function list(req, res, next) { logger.debug("Middleware Submissions List ", {connectionOptions: req.connectionOptions}); forms.getSubmissions(req.connectionOptions, {}, _getSubmissionsResultHandler(req, next)); }
[ "function", "list", "(", "req", ",", "res", ",", "next", ")", "{", "logger", ".", "debug", "(", "\"Middleware Submissions List \"", ",", "{", "connectionOptions", ":", "req", ".", "connectionOptions", "}", ")", ";", "forms", ".", "getSubmissions", "(", "req"...
List All Submissions @param req @param res @param next
[ "List", "All", "Submissions" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L75-L78
30,764
feedhenry/fh-forms
lib/middleware/submissions.js
listProjectSubmissions
function listProjectSubmissions(req, res, next) { var formId = req.body.formId; var subIds = req.body.subid; var params = { wantRestrictions: false, appId: req.params.projectid }; //Assigning Form Search If Set if (_.isString(formId)) { params.formId = formId; } //Assigning Submission Search Params If Set if (_.isArray(subIds)) { params.subid = subIds; } else if (_.isString(subIds)) { params.subid = [subIds]; } logger.debug("Middleware listProjectSubmissions ", {params: params}); forms.getSubmissions(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next)); }
javascript
function listProjectSubmissions(req, res, next) { var formId = req.body.formId; var subIds = req.body.subid; var params = { wantRestrictions: false, appId: req.params.projectid }; //Assigning Form Search If Set if (_.isString(formId)) { params.formId = formId; } //Assigning Submission Search Params If Set if (_.isArray(subIds)) { params.subid = subIds; } else if (_.isString(subIds)) { params.subid = [subIds]; } logger.debug("Middleware listProjectSubmissions ", {params: params}); forms.getSubmissions(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next)); }
[ "function", "listProjectSubmissions", "(", "req", ",", "res", ",", "next", ")", "{", "var", "formId", "=", "req", ".", "body", ".", "formId", ";", "var", "subIds", "=", "req", ".", "body", ".", "subid", ";", "var", "params", "=", "{", "wantRestrictions...
Search Submissions That Belong To The Project. @param req @param res @param next
[ "Search", "Submissions", "That", "Belong", "To", "The", "Project", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L86-L110
30,765
feedhenry/fh-forms
lib/middleware/submissions.js
remove
function remove(req, res, next) { var params = {"_id": req.params.id}; logger.debug("Middleware Submissions Remove ", {params: params}); forms.deleteSubmission(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next)); }
javascript
function remove(req, res, next) { var params = {"_id": req.params.id}; logger.debug("Middleware Submissions Remove ", {params: params}); forms.deleteSubmission(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next)); }
[ "function", "remove", "(", "req", ",", "res", ",", "next", ")", "{", "var", "params", "=", "{", "\"_id\"", ":", "req", ".", "params", ".", "id", "}", ";", "logger", ".", "debug", "(", "\"Middleware Submissions Remove \"", ",", "{", "params", ":", "para...
Remove A Single Submission @param req @param res @param next
[ "Remove", "A", "Single", "Submission" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L158-L163
30,766
feedhenry/fh-forms
lib/middleware/submissions.js
getSubmissionFile
function getSubmissionFile(req, res, next) { var params = {"_id": req.params.fileId}; logger.debug("Middleware getSubmissionFile ", {params: params}); forms.getSubmissionFile(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next)); }
javascript
function getSubmissionFile(req, res, next) { var params = {"_id": req.params.fileId}; logger.debug("Middleware getSubmissionFile ", {params: params}); forms.getSubmissionFile(req.connectionOptions, params, submissionsHandler(constants.resultTypes.submissions, req, next)); }
[ "function", "getSubmissionFile", "(", "req", ",", "res", ",", "next", ")", "{", "var", "params", "=", "{", "\"_id\"", ":", "req", ".", "params", ".", "fileId", "}", ";", "logger", ".", "debug", "(", "\"Middleware getSubmissionFile \"", ",", "{", "params", ...
Get A Single Submission File @param req @param res @param next
[ "Get", "A", "Single", "Submission", "File" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L173-L177
30,767
feedhenry/fh-forms
lib/middleware/submissions.js
updateSubmissionFile
function updateSubmissionFile(req, res, next) { var fileUpdateOptions = req.appformsResultPayload.data; fileUpdateOptions.submission = { submissionId: req.params.id, fieldId: req.params.fieldId }; //Remove the cached file when finished fileUpdateOptions.keepFile = false; //Adding A New File If Required fileUpdateOptions.addingNewSubmissionFile = req.addingNewSubmissionFile; //If not adding a new file, the fileId param is expected to be the file group id if (!fileUpdateOptions.addingNewSubmissionFile) { fileUpdateOptions.fileDetails.groupId = req.params.fileId; } else { fileUpdateOptions.fileDetails.hashName = req.params.fileId; } logger.debug("Middleware updateSubmissionFile ", {fileUpdateOptions: fileUpdateOptions}); forms.updateSubmissionFile(_.extend(fileUpdateOptions, req.connectionOptions), submissionsHandler(constants.resultTypes.submissions, req, next)); }
javascript
function updateSubmissionFile(req, res, next) { var fileUpdateOptions = req.appformsResultPayload.data; fileUpdateOptions.submission = { submissionId: req.params.id, fieldId: req.params.fieldId }; //Remove the cached file when finished fileUpdateOptions.keepFile = false; //Adding A New File If Required fileUpdateOptions.addingNewSubmissionFile = req.addingNewSubmissionFile; //If not adding a new file, the fileId param is expected to be the file group id if (!fileUpdateOptions.addingNewSubmissionFile) { fileUpdateOptions.fileDetails.groupId = req.params.fileId; } else { fileUpdateOptions.fileDetails.hashName = req.params.fileId; } logger.debug("Middleware updateSubmissionFile ", {fileUpdateOptions: fileUpdateOptions}); forms.updateSubmissionFile(_.extend(fileUpdateOptions, req.connectionOptions), submissionsHandler(constants.resultTypes.submissions, req, next)); }
[ "function", "updateSubmissionFile", "(", "req", ",", "res", ",", "next", ")", "{", "var", "fileUpdateOptions", "=", "req", ".", "appformsResultPayload", ".", "data", ";", "fileUpdateOptions", ".", "submission", "=", "{", "submissionId", ":", "req", ".", "param...
Update A Single Submission File @param req @param res @param next
[ "Update", "A", "Single", "Submission", "File" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L186-L210
30,768
feedhenry/fh-forms
lib/middleware/submissions.js
addSubmissionFile
function addSubmissionFile(req, res, next) { req.addingNewSubmissionFile = true; updateSubmissionFile(req, res, next); }
javascript
function addSubmissionFile(req, res, next) { req.addingNewSubmissionFile = true; updateSubmissionFile(req, res, next); }
[ "function", "addSubmissionFile", "(", "req", ",", "res", ",", "next", ")", "{", "req", ".", "addingNewSubmissionFile", "=", "true", ";", "updateSubmissionFile", "(", "req", ",", "res", ",", "next", ")", ";", "}" ]
Adding A New File To A Submission @param req @param res @param next
[ "Adding", "A", "New", "File", "To", "A", "Submission" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L218-L222
30,769
feedhenry/fh-forms
lib/middleware/submissions.js
status
function status(req, res, next) { var params = { submission: { submissionId: req.params.id } }; logger.debug("Middleware Submission status ", {params: params}); forms.getSubmissionStatus(_.extend(params, req.connectionOptions), submissionsHandler(constants.resultTypes.submissions, req, next)); }
javascript
function status(req, res, next) { var params = { submission: { submissionId: req.params.id } }; logger.debug("Middleware Submission status ", {params: params}); forms.getSubmissionStatus(_.extend(params, req.connectionOptions), submissionsHandler(constants.resultTypes.submissions, req, next)); }
[ "function", "status", "(", "req", ",", "res", ",", "next", ")", "{", "var", "params", "=", "{", "submission", ":", "{", "submissionId", ":", "req", ".", "params", ".", "id", "}", "}", ";", "logger", ".", "debug", "(", "\"Middleware Submission status \"",...
Middleware For Getting The Current Status Of A Submission @param req @param res @param next
[ "Middleware", "For", "Getting", "The", "Current", "Status", "Of", "A", "Submission" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L279-L289
30,770
feedhenry/fh-forms
lib/middleware/submissions.js
search
function search(req, res, next) { var queryParams = req.body; logger.debug("Middleware Submission Search ", {params: queryParams}); forms.submissionSearch(req.connectionOptions, queryParams, _getSubmissionsResultHandler(req, next)); }
javascript
function search(req, res, next) { var queryParams = req.body; logger.debug("Middleware Submission Search ", {params: queryParams}); forms.submissionSearch(req.connectionOptions, queryParams, _getSubmissionsResultHandler(req, next)); }
[ "function", "search", "(", "req", ",", "res", ",", "next", ")", "{", "var", "queryParams", "=", "req", ".", "body", ";", "logger", ".", "debug", "(", "\"Middleware Submission Search \"", ",", "{", "params", ":", "queryParams", "}", ")", ";", "forms", "."...
Search For Submissions. Used For Advanced Search @param req @param res @param next
[ "Search", "For", "Submissions", ".", "Used", "For", "Advanced", "Search" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L317-L323
30,771
feedhenry/fh-forms
lib/middleware/submissions.js
exportSubmissions
function exportSubmissions(req, res, next) { var params = { "appId" : req.body.projectId, "subid": req.body.subid, "formId": req.body.formId, "fieldHeader": req.body.fieldHeader, "downloadUrl": req.body.fileUrl, "filter": req.body.filter, "query": req.body.query, "wantRestrictions": false }; logger.debug("Middleware exportSubmissions ", {req: req, body: req.body, params: params}); forms.exportSubmissions(req.connectionOptions, params, function(err, submissionCsvValues) { if (err) { logger.error("Middleware Export Submissions ", {error: err}); return next(err); } logger.debug("Middleware exportSubmissions submissionCsvValues", {submissionCsvValues: submissionCsvValues.length}); _processExportResponse(submissionCsvValues, res, next); }); }
javascript
function exportSubmissions(req, res, next) { var params = { "appId" : req.body.projectId, "subid": req.body.subid, "formId": req.body.formId, "fieldHeader": req.body.fieldHeader, "downloadUrl": req.body.fileUrl, "filter": req.body.filter, "query": req.body.query, "wantRestrictions": false }; logger.debug("Middleware exportSubmissions ", {req: req, body: req.body, params: params}); forms.exportSubmissions(req.connectionOptions, params, function(err, submissionCsvValues) { if (err) { logger.error("Middleware Export Submissions ", {error: err}); return next(err); } logger.debug("Middleware exportSubmissions submissionCsvValues", {submissionCsvValues: submissionCsvValues.length}); _processExportResponse(submissionCsvValues, res, next); }); }
[ "function", "exportSubmissions", "(", "req", ",", "res", ",", "next", ")", "{", "var", "params", "=", "{", "\"appId\"", ":", "req", ".", "body", ".", "projectId", ",", "\"subid\"", ":", "req", ".", "body", ".", "subid", ",", "\"formId\"", ":", "req", ...
Export Submissions As CSV Files Contained In A Single Zip @param req @param res @param next
[ "Export", "Submissions", "As", "CSV", "Files", "Contained", "In", "A", "Single", "Zip" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L349-L373
30,772
feedhenry/fh-forms
lib/middleware/submissions.js
generatePDF
function generatePDF(req, res, next) { req.appformsResultPayload = req.appformsResultPayload || {}; //If there is already a submission result, render this. This is useful for cases where the submission is fetched from another database and rendered elsewhere. var existingSubmission = req.appformsResultPayload.data; var params = { _id: req.params.id, pdfExportDir: req.pdfExportDir, downloadUrl: '' + req.protocol + '://' + req.hostname, existingSubmission: existingSubmission, environment: req.environment, mbaasConf: req.mbaasConf, domain: req.user.domain, filesAreRemote: req.filesAreRemote, fileUriPath: req.fileUriPath, location: req.coreLocation, pdfTemplateLoc: req.pdfTemplateLoc, maxConcurrentPhantomPerWorker: req.maxConcurrentPhantomPerWorker }; logger.debug("Middleware generatePDF ", {params: params}); forms.generateSubmissionPdf(_.extend(params, req.connectionOptions), function(err, submissionPdfLocation) { if (err) { logger.error("Middleware generatePDF", {error: err}); return next(err); } logger.debug("Middleware generatePDF ", {submissionPdfLocation: submissionPdfLocation}); //Streaming the file as an attachment res.download(submissionPdfLocation, '' + req.params.id + ".pdf", function(fileDownloadError) { //Download Complete, remove the cached file fs.unlink(submissionPdfLocation, function() { if (fileDownloadError) { logger.error("Middleware generatePDF ", {error: fileDownloadError}); //If the headers have not been sent to the client, can use the error handler if (!res.headersSent) { return next(fileDownloadError); } } }); }); }); }
javascript
function generatePDF(req, res, next) { req.appformsResultPayload = req.appformsResultPayload || {}; //If there is already a submission result, render this. This is useful for cases where the submission is fetched from another database and rendered elsewhere. var existingSubmission = req.appformsResultPayload.data; var params = { _id: req.params.id, pdfExportDir: req.pdfExportDir, downloadUrl: '' + req.protocol + '://' + req.hostname, existingSubmission: existingSubmission, environment: req.environment, mbaasConf: req.mbaasConf, domain: req.user.domain, filesAreRemote: req.filesAreRemote, fileUriPath: req.fileUriPath, location: req.coreLocation, pdfTemplateLoc: req.pdfTemplateLoc, maxConcurrentPhantomPerWorker: req.maxConcurrentPhantomPerWorker }; logger.debug("Middleware generatePDF ", {params: params}); forms.generateSubmissionPdf(_.extend(params, req.connectionOptions), function(err, submissionPdfLocation) { if (err) { logger.error("Middleware generatePDF", {error: err}); return next(err); } logger.debug("Middleware generatePDF ", {submissionPdfLocation: submissionPdfLocation}); //Streaming the file as an attachment res.download(submissionPdfLocation, '' + req.params.id + ".pdf", function(fileDownloadError) { //Download Complete, remove the cached file fs.unlink(submissionPdfLocation, function() { if (fileDownloadError) { logger.error("Middleware generatePDF ", {error: fileDownloadError}); //If the headers have not been sent to the client, can use the error handler if (!res.headersSent) { return next(fileDownloadError); } } }); }); }); }
[ "function", "generatePDF", "(", "req", ",", "res", ",", "next", ")", "{", "req", ".", "appformsResultPayload", "=", "req", ".", "appformsResultPayload", "||", "{", "}", ";", "//If there is already a submission result, render this. This is useful for cases where the submissi...
Middleware For Generating A PDF Representation Of A Submission This is the last step in a request. It will be terminated here unless there is an error. @param req @param res @param next
[ "Middleware", "For", "Generating", "A", "PDF", "Representation", "Of", "A", "Submission" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L383-L429
30,773
feedhenry/fh-forms
lib/middleware/submissions.js
_processExportResponse
function _processExportResponse(csvs, res, next) { var zip = archiver('zip'); // convert csv entries to in-memory zip file and stream response res.setHeader('Content-type', 'application/zip'); res.setHeader('Content-disposition', 'attachment; filename=submissions.zip'); zip.pipe(res); for (var form in csvs) { // eslint-disable-line guard-for-in var csv = csvs[form]; zip.append(csv, {name: form + '.csv'}); } var respSent = false; zip.on('error', function(err) { logger.error("_processExportResponse ", {error: err}); if (err) { if (!respSent) { respSent = true; return next(err); } } }); zip.finalize(function(err) { if (err) { logger.error("_processExportResponse finalize", {error: err}); if (!respSent) { respSent = true; return next(err); } logger.debug("_processExportResponse finalize headers sent"); } logger.debug("_processExportResponse finalize finished"); }); }
javascript
function _processExportResponse(csvs, res, next) { var zip = archiver('zip'); // convert csv entries to in-memory zip file and stream response res.setHeader('Content-type', 'application/zip'); res.setHeader('Content-disposition', 'attachment; filename=submissions.zip'); zip.pipe(res); for (var form in csvs) { // eslint-disable-line guard-for-in var csv = csvs[form]; zip.append(csv, {name: form + '.csv'}); } var respSent = false; zip.on('error', function(err) { logger.error("_processExportResponse ", {error: err}); if (err) { if (!respSent) { respSent = true; return next(err); } } }); zip.finalize(function(err) { if (err) { logger.error("_processExportResponse finalize", {error: err}); if (!respSent) { respSent = true; return next(err); } logger.debug("_processExportResponse finalize headers sent"); } logger.debug("_processExportResponse finalize finished"); }); }
[ "function", "_processExportResponse", "(", "csvs", ",", "res", ",", "next", ")", "{", "var", "zip", "=", "archiver", "(", "'zip'", ")", ";", "// convert csv entries to in-memory zip file and stream response", "res", ".", "setHeader", "(", "'Content-type'", ",", "'ap...
Function for processing submissions into a zip file containing csv files.
[ "Function", "for", "processing", "submissions", "into", "a", "zip", "file", "containing", "csv", "files", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L435-L472
30,774
feedhenry/fh-forms
lib/middleware/submissions.js
processFileResponse
function processFileResponse(req, res, next) { var fileDetails = req.appformsResultPayload.data; if (fileDetails.stream) { var headers = {}; headers["Content-Type"] = fileDetails.type;//Setting the file content type. Mime types are set by the file handler. headers["Content-Disposition"] = "attachment; filename=" + fileDetails.name; res.writeHead(200, headers); fileDetails.stream.pipe(res); fileDetails.stream.resume(); //Unpausing the stream as it was paused by the file handler } else { return next('Error getting submitted file - result: ' + JSON.stringify(fileDetails)); } }
javascript
function processFileResponse(req, res, next) { var fileDetails = req.appformsResultPayload.data; if (fileDetails.stream) { var headers = {}; headers["Content-Type"] = fileDetails.type;//Setting the file content type. Mime types are set by the file handler. headers["Content-Disposition"] = "attachment; filename=" + fileDetails.name; res.writeHead(200, headers); fileDetails.stream.pipe(res); fileDetails.stream.resume(); //Unpausing the stream as it was paused by the file handler } else { return next('Error getting submitted file - result: ' + JSON.stringify(fileDetails)); } }
[ "function", "processFileResponse", "(", "req", ",", "res", ",", "next", ")", "{", "var", "fileDetails", "=", "req", ".", "appformsResultPayload", ".", "data", ";", "if", "(", "fileDetails", ".", "stream", ")", "{", "var", "headers", "=", "{", "}", ";", ...
Function for handling a file response. Used when loading files from a submission @param req @param res @param next
[ "Function", "for", "handling", "a", "file", "response", ".", "Used", "when", "loading", "files", "from", "a", "submission" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/middleware/submissions.js#L481-L493
30,775
feedhenry/fh-forms
lib/impl/getSubmissions/processListResult.js
reformatFormIdAndName
function reformatFormIdAndName(submission) { var formName = "Unknown"; if (submission && submission.formId && submission.formId.name) { formName = submission.formId.name; } if (submission && submission.formSubmittedAgainst) { formName = submission.formSubmittedAgainst.name; } submission.formName = formName; submission.formId = submission.formId.toString(); return submission; }
javascript
function reformatFormIdAndName(submission) { var formName = "Unknown"; if (submission && submission.formId && submission.formId.name) { formName = submission.formId.name; } if (submission && submission.formSubmittedAgainst) { formName = submission.formSubmittedAgainst.name; } submission.formName = formName; submission.formId = submission.formId.toString(); return submission; }
[ "function", "reformatFormIdAndName", "(", "submission", ")", "{", "var", "formName", "=", "\"Unknown\"", ";", "if", "(", "submission", "&&", "submission", ".", "formId", "&&", "submission", ".", "formId", ".", "name", ")", "{", "formName", "=", "submission", ...
reformatFormIdAndName - Reformatting the form ID associated with the submission. @param {object} submission Submission to process. @return {object} Updated submission
[ "reformatFormIdAndName", "-", "Reformatting", "the", "form", "ID", "associated", "with", "the", "submission", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getSubmissions/processListResult.js#L11-L24
30,776
feedhenry/fh-forms
lib/impl/getSubmissions/processListResult.js
restrictSubmissionForSummary
function restrictSubmissionForSummary(submission) { submission.formFields = _.filter(submission.formFields, function(formField) { return CONSTANTS.FIELD_TYPES_INCLUDED_IN_SUMMARY.indexOf(formField.fieldId.type) >= 0; }); submission.formFields = _.first(submission.formFields, CONSTANTS.NUM_FIELDS_INCLUDED_IN_SUMMARY); return submission; }
javascript
function restrictSubmissionForSummary(submission) { submission.formFields = _.filter(submission.formFields, function(formField) { return CONSTANTS.FIELD_TYPES_INCLUDED_IN_SUMMARY.indexOf(formField.fieldId.type) >= 0; }); submission.formFields = _.first(submission.formFields, CONSTANTS.NUM_FIELDS_INCLUDED_IN_SUMMARY); return submission; }
[ "function", "restrictSubmissionForSummary", "(", "submission", ")", "{", "submission", ".", "formFields", "=", "_", ".", "filter", "(", "submission", ".", "formFields", ",", "function", "(", "formField", ")", "{", "return", "CONSTANTS", ".", "FIELD_TYPES_INCLUDED_...
Only Includes Fields In The Summary @param submission @returns {Object}
[ "Only", "Includes", "Fields", "In", "The", "Summary" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/getSubmissions/processListResult.js#L31-L39
30,777
feedhenry/fh-forms
lib/impl/deleteSubmission.js
function(submission) { return _.flatten(submission.formFields.map(function(field) { return field.fieldValues.filter(hasGroupId); }).map(function(fieldValue) { return fieldValue.map(extractGroupId); })); }
javascript
function(submission) { return _.flatten(submission.formFields.map(function(field) { return field.fieldValues.filter(hasGroupId); }).map(function(fieldValue) { return fieldValue.map(extractGroupId); })); }
[ "function", "(", "submission", ")", "{", "return", "_", ".", "flatten", "(", "submission", ".", "formFields", ".", "map", "(", "function", "(", "field", ")", "{", "return", "field", ".", "fieldValues", ".", "filter", "(", "hasGroupId", ")", ";", "}", "...
Returns all the `groupId` values for the passed-in submission. A submission can have multiple fields, and each field can have multiple fieldValues.
[ "Returns", "all", "the", "groupId", "values", "for", "the", "passed", "-", "in", "submission", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/deleteSubmission.js#L21-L27
30,778
techcoop/react-material-site
scripts/prebuild.js
spawnWatcher
function spawnWatcher() { var subprocess = spawn(process.argv[0], ['prebuild.js', '--watcher'], {detached: true, stdio: 'ignore'}) subprocess.unref() }
javascript
function spawnWatcher() { var subprocess = spawn(process.argv[0], ['prebuild.js', '--watcher'], {detached: true, stdio: 'ignore'}) subprocess.unref() }
[ "function", "spawnWatcher", "(", ")", "{", "var", "subprocess", "=", "spawn", "(", "process", ".", "argv", "[", "0", "]", ",", "[", "'prebuild.js'", ",", "'--watcher'", "]", ",", "{", "detached", ":", "true", ",", "stdio", ":", "'ignore'", "}", ")", ...
Spawn watcher process
[ "Spawn", "watcher", "process" ]
cb2973dbccfa17426abc8cd6f342910203c7f007
https://github.com/techcoop/react-material-site/blob/cb2973dbccfa17426abc8cd6f342910203c7f007/scripts/prebuild.js#L65-L68
30,779
techcoop/react-material-site
scripts/prebuild.js
createIndex
function createIndex() { var directory = 'src/views' var directories = fs.readdirSync(directory) try { var lines = ['// This is a generated file, do not edit, or disable "prebuild" command in package.json if you want to take control'] for (var i = 0; i < directories.length; i++) { var path = directory + '/' + directories[i]; if (fs.existsSync(path) && fs.lstatSync(path).isDirectory()) { var file = directories[i] + '.js' if (fs.existsSync(directory + '/' + directories[i] + '/' + file)) { lines.push('export { default as ' + directories[i] + ' } from \'./' + directories[i] + '/' + directories[i] + '\'') } } } fs.writeFileSync(directory + '/index.js', lines.join('\n') + '\n'); } catch (err) { console.log(err) } }
javascript
function createIndex() { var directory = 'src/views' var directories = fs.readdirSync(directory) try { var lines = ['// This is a generated file, do not edit, or disable "prebuild" command in package.json if you want to take control'] for (var i = 0; i < directories.length; i++) { var path = directory + '/' + directories[i]; if (fs.existsSync(path) && fs.lstatSync(path).isDirectory()) { var file = directories[i] + '.js' if (fs.existsSync(directory + '/' + directories[i] + '/' + file)) { lines.push('export { default as ' + directories[i] + ' } from \'./' + directories[i] + '/' + directories[i] + '\'') } } } fs.writeFileSync(directory + '/index.js', lines.join('\n') + '\n'); } catch (err) { console.log(err) } }
[ "function", "createIndex", "(", ")", "{", "var", "directory", "=", "'src/views'", "var", "directories", "=", "fs", ".", "readdirSync", "(", "directory", ")", "try", "{", "var", "lines", "=", "[", "'// This is a generated file, do not edit, or disable \"prebuild\" comm...
Creates index file for views
[ "Creates", "index", "file", "for", "views" ]
cb2973dbccfa17426abc8cd6f342910203c7f007
https://github.com/techcoop/react-material-site/blob/cb2973dbccfa17426abc8cd6f342910203c7f007/scripts/prebuild.js#L71-L91
30,780
feedhenry/fh-forms
lib/impl/submissionExportHelper/csvHeaders.js
generateFieldHeader
function generateFieldHeader(field, headerName, fieldRepeatIndex) { var csv = ''; //If the field is repeating, the structure of the header is different if (_.isNumber(fieldRepeatIndex)) { //If it is a file type field, need to add two fields for the file name and url if (fieldTypeUtils.isFileType(field.type)) { csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-name") + ","; csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-url"); } else if (fieldTypeUtils.isBarcodeType(field.type)) { //If it is a barcode type field, need to add two fields for the format name and text csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-format") + ","; csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-text"); } else { //Otherwise, just append the index. csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1)); } } else { //If it is a file type field, need to add two fields for the file name and url if (fieldTypeUtils.isFileType(field.type)) { csv += csvStr(headerName + "-name") + ","; csv += csvStr(headerName + "-url"); } else if (fieldTypeUtils.isBarcodeType(field.type)) { //If it is a barcode type field, need to add two fields for the format name and text csv += csvStr(headerName + "-format") + ","; csv += csvStr(headerName + "-text"); } else { csv += csvStr(headerName); } } return csv; }
javascript
function generateFieldHeader(field, headerName, fieldRepeatIndex) { var csv = ''; //If the field is repeating, the structure of the header is different if (_.isNumber(fieldRepeatIndex)) { //If it is a file type field, need to add two fields for the file name and url if (fieldTypeUtils.isFileType(field.type)) { csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-name") + ","; csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-url"); } else if (fieldTypeUtils.isBarcodeType(field.type)) { //If it is a barcode type field, need to add two fields for the format name and text csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-format") + ","; csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1) + "-text"); } else { //Otherwise, just append the index. csv += csvStr(headerName + '-' + (fieldRepeatIndex + 1)); } } else { //If it is a file type field, need to add two fields for the file name and url if (fieldTypeUtils.isFileType(field.type)) { csv += csvStr(headerName + "-name") + ","; csv += csvStr(headerName + "-url"); } else if (fieldTypeUtils.isBarcodeType(field.type)) { //If it is a barcode type field, need to add two fields for the format name and text csv += csvStr(headerName + "-format") + ","; csv += csvStr(headerName + "-text"); } else { csv += csvStr(headerName); } } return csv; }
[ "function", "generateFieldHeader", "(", "field", ",", "headerName", ",", "fieldRepeatIndex", ")", "{", "var", "csv", "=", "''", ";", "//If the field is repeating, the structure of the header is different", "if", "(", "_", ".", "isNumber", "(", "fieldRepeatIndex", ")", ...
generateFieldHeader - Generating A single field header. @param {object} field Field definition @param {string} headerName Header Name to add @param {number} fieldRepeatIndex The index of a repeating field (null if it is not repeating) @return {string} Generated CSV
[ "generateFieldHeader", "-", "Generating", "A", "single", "field", "header", "." ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/submissionExportHelper/csvHeaders.js#L20-L52
30,781
feedhenry/fh-forms
lib/impl/submissionExportHelper/csvHeaders.js
generateCSVHeader
function generateCSVHeader(csv, field, headerName, fieldRepeatIndex) { //If the previous csv value is set, then a ',' is needed to separate. if (csv) { csv += ','; } // Sanity check after the headers to ensure we don't have a double ,, appearing // The above if is necessary and cannot be removed if (endsWith(csv, ',,')) { csv = csv.slice(0, -1); } csv += generateFieldHeader(field, headerName, fieldRepeatIndex); return csv; }
javascript
function generateCSVHeader(csv, field, headerName, fieldRepeatIndex) { //If the previous csv value is set, then a ',' is needed to separate. if (csv) { csv += ','; } // Sanity check after the headers to ensure we don't have a double ,, appearing // The above if is necessary and cannot be removed if (endsWith(csv, ',,')) { csv = csv.slice(0, -1); } csv += generateFieldHeader(field, headerName, fieldRepeatIndex); return csv; }
[ "function", "generateCSVHeader", "(", "csv", ",", "field", ",", "headerName", ",", "fieldRepeatIndex", ")", "{", "//If the previous csv value is set, then a ',' is needed to separate.", "if", "(", "csv", ")", "{", "csv", "+=", "','", ";", "}", "// Sanity check after the...
generateCSVHeader - Generating the Headers For All Of The Fields In The CSV @param {string} csv Existing CSV String. @param {object} field Field definition @param {string} headerName Header Name to add @param {number} fieldRepeatIndex The index of a repeating field (null if it is not repeating) @return {string} Generated CSV
[ "generateCSVHeader", "-", "Generating", "the", "Headers", "For", "All", "Of", "The", "Fields", "In", "The", "CSV" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/submissionExportHelper/csvHeaders.js#L63-L79
30,782
feedhenry/fh-forms
lib/impl/submissionExportHelper/csvHeaders.js
generateCSVHeaders
function generateCSVHeaders(fieldKeys, mergedFieldEntries, fieldHeader) { var csv = ''; var fieldRepeatIndex = 0; // Here we need to add the metaDataHeaders _.each(metaDataHeaders, function(headerName) { csv += headerName + ','; }); var fieldKeysProcessed = []; var fieldsProcessed = {}; fieldKeys.forEach(function(fieldKey) { // check if its a repeating form (and extra headers required) var field = mergedFieldEntries[fieldKey]; if (field.type === 'sectionBreak' && field.repeating) { var fieldsInThisSection = sectionUtils.getFieldsInSection(field._id, _.values(mergedFieldEntries)); _.each(fieldsInThisSection, function(field) { fieldsProcessed[field._id] = true; }); for (var i = 0; i < field.fieldOptions.definition.maxRepeat; i++) { _.each(fieldsInThisSection, function(fieldInThisSection) { fieldKeysProcessed.push({key: fieldInThisSection._id, sectionIndex: i + 1, inRepeatingForm: true}); }); } } else if (!fieldsProcessed[fieldKey]) { fieldKeysProcessed.push({key: fieldKey}); } }); //for each form get each of the unique fields and add a header fieldKeysProcessed.forEach(function(processedField) { // check if its a repeating form (and extra headers required) var field = mergedFieldEntries[processedField.key]; //Fields may not have a field code, if not just use the field name. var headerName = typeof (field[fieldHeader]) === "string" ? field[fieldHeader] : field.name; if (processedField.inRepeatingForm) { headerName = '(section repeat: ' + processedField.sectionIndex + ') ' + headerName; } if (field.repeating === true) { for (fieldRepeatIndex = 0; fieldRepeatIndex < field.fieldOptions.definition.maxRepeat; fieldRepeatIndex++) { csv = generateCSVHeader(csv, field, headerName, fieldRepeatIndex); } } else { csv = generateCSVHeader(csv, field, headerName, null); } }); csv += '\r\n'; return csv; }
javascript
function generateCSVHeaders(fieldKeys, mergedFieldEntries, fieldHeader) { var csv = ''; var fieldRepeatIndex = 0; // Here we need to add the metaDataHeaders _.each(metaDataHeaders, function(headerName) { csv += headerName + ','; }); var fieldKeysProcessed = []; var fieldsProcessed = {}; fieldKeys.forEach(function(fieldKey) { // check if its a repeating form (and extra headers required) var field = mergedFieldEntries[fieldKey]; if (field.type === 'sectionBreak' && field.repeating) { var fieldsInThisSection = sectionUtils.getFieldsInSection(field._id, _.values(mergedFieldEntries)); _.each(fieldsInThisSection, function(field) { fieldsProcessed[field._id] = true; }); for (var i = 0; i < field.fieldOptions.definition.maxRepeat; i++) { _.each(fieldsInThisSection, function(fieldInThisSection) { fieldKeysProcessed.push({key: fieldInThisSection._id, sectionIndex: i + 1, inRepeatingForm: true}); }); } } else if (!fieldsProcessed[fieldKey]) { fieldKeysProcessed.push({key: fieldKey}); } }); //for each form get each of the unique fields and add a header fieldKeysProcessed.forEach(function(processedField) { // check if its a repeating form (and extra headers required) var field = mergedFieldEntries[processedField.key]; //Fields may not have a field code, if not just use the field name. var headerName = typeof (field[fieldHeader]) === "string" ? field[fieldHeader] : field.name; if (processedField.inRepeatingForm) { headerName = '(section repeat: ' + processedField.sectionIndex + ') ' + headerName; } if (field.repeating === true) { for (fieldRepeatIndex = 0; fieldRepeatIndex < field.fieldOptions.definition.maxRepeat; fieldRepeatIndex++) { csv = generateCSVHeader(csv, field, headerName, fieldRepeatIndex); } } else { csv = generateCSVHeader(csv, field, headerName, null); } }); csv += '\r\n'; return csv; }
[ "function", "generateCSVHeaders", "(", "fieldKeys", ",", "mergedFieldEntries", ",", "fieldHeader", ")", "{", "var", "csv", "=", "''", ";", "var", "fieldRepeatIndex", "=", "0", ";", "// Here we need to add the metaDataHeaders", "_", ".", "each", "(", "metaDataHeaders...
generateCSVHeaders - Generating CSV Headers from a merged form definition @param {array} fieldKeys Field IDs @param {object} mergedFieldEntries Merged field definitions @param {string} fieldHeader Header type to use (fieldName, fieldCode) @return {string}
[ "generateCSVHeaders", "-", "Generating", "CSV", "Headers", "from", "a", "merged", "form", "definition" ]
87df586b9589e3c636e1e607163862cfb64872dd
https://github.com/feedhenry/fh-forms/blob/87df586b9589e3c636e1e607163862cfb64872dd/lib/impl/submissionExportHelper/csvHeaders.js#L106-L157
30,783
stackgl/gl-shader-core
lib/create-attributes.js
ShaderAttribute
function ShaderAttribute(gl, program, location, dimension, name, constFunc, relink) { this._gl = gl this._program = program this._location = location this._dimension = dimension this._name = name this._constFunc = constFunc this._relink = relink }
javascript
function ShaderAttribute(gl, program, location, dimension, name, constFunc, relink) { this._gl = gl this._program = program this._location = location this._dimension = dimension this._name = name this._constFunc = constFunc this._relink = relink }
[ "function", "ShaderAttribute", "(", "gl", ",", "program", ",", "location", ",", "dimension", ",", "name", ",", "constFunc", ",", "relink", ")", "{", "this", ".", "_gl", "=", "gl", "this", ".", "_program", "=", "program", "this", ".", "_location", "=", ...
Shader attribute class
[ "Shader", "attribute", "class" ]
25e021e9239ad7b73ce08ff0fdc97e2e68e1d075
https://github.com/stackgl/gl-shader-core/blob/25e021e9239ad7b73ce08ff0fdc97e2e68e1d075/lib/create-attributes.js#L6-L14
30,784
stackgl/gl-shader-core
lib/create-attributes.js
addVectorAttribute
function addVectorAttribute(gl, program, location, dimension, obj, name, doLink) { var constFuncArgs = [ 'gl', 'v' ] var varNames = [] for(var i=0; i<dimension; ++i) { constFuncArgs.push('x'+i) varNames.push('x'+i) } constFuncArgs.push([ 'if(x0.length===void 0){return gl.vertexAttrib', dimension, 'f(v,', varNames.join(), ')}else{return gl.vertexAttrib', dimension, 'fv(v,x0)}' ].join('')) var constFunc = Function.apply(undefined, constFuncArgs) var attr = new ShaderAttribute(gl, program, location, dimension, name, constFunc, doLink) Object.defineProperty(obj, name, { set: function(x) { gl.disableVertexAttribArray(attr._location) constFunc(gl, attr._location, x) return x } , get: function() { return attr } , enumerable: true }) }
javascript
function addVectorAttribute(gl, program, location, dimension, obj, name, doLink) { var constFuncArgs = [ 'gl', 'v' ] var varNames = [] for(var i=0; i<dimension; ++i) { constFuncArgs.push('x'+i) varNames.push('x'+i) } constFuncArgs.push([ 'if(x0.length===void 0){return gl.vertexAttrib', dimension, 'f(v,', varNames.join(), ')}else{return gl.vertexAttrib', dimension, 'fv(v,x0)}' ].join('')) var constFunc = Function.apply(undefined, constFuncArgs) var attr = new ShaderAttribute(gl, program, location, dimension, name, constFunc, doLink) Object.defineProperty(obj, name, { set: function(x) { gl.disableVertexAttribArray(attr._location) constFunc(gl, attr._location, x) return x } , get: function() { return attr } , enumerable: true }) }
[ "function", "addVectorAttribute", "(", "gl", ",", "program", ",", "location", ",", "dimension", ",", "obj", ",", "name", ",", "doLink", ")", "{", "var", "constFuncArgs", "=", "[", "'gl'", ",", "'v'", "]", "var", "varNames", "=", "[", "]", "for", "(", ...
Adds a vector attribute to obj
[ "Adds", "a", "vector", "attribute", "to", "obj" ]
25e021e9239ad7b73ce08ff0fdc97e2e68e1d075
https://github.com/stackgl/gl-shader-core/blob/25e021e9239ad7b73ce08ff0fdc97e2e68e1d075/lib/create-attributes.js#L40-L63
30,785
stackgl/gl-shader-core
lib/create-attributes.js
createAttributeWrapper
function createAttributeWrapper(gl, program, attributes, doLink) { var obj = {} for(var i=0, n=attributes.length; i<n; ++i) { var a = attributes[i] var name = a.name var type = a.type var location = gl.getAttribLocation(program, name) switch(type) { case 'bool': case 'int': case 'float': addVectorAttribute(gl, program, location, 1, obj, name, doLink) break default: if(type.indexOf('vec') >= 0) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { throw new Error('gl-shader: Invalid data type for attribute ' + name + ': ' + type) } addVectorAttribute(gl, program, location, d, obj, name, doLink) } else { throw new Error('gl-shader: Unknown data type for attribute ' + name + ': ' + type) } break } } return obj }
javascript
function createAttributeWrapper(gl, program, attributes, doLink) { var obj = {} for(var i=0, n=attributes.length; i<n; ++i) { var a = attributes[i] var name = a.name var type = a.type var location = gl.getAttribLocation(program, name) switch(type) { case 'bool': case 'int': case 'float': addVectorAttribute(gl, program, location, 1, obj, name, doLink) break default: if(type.indexOf('vec') >= 0) { var d = type.charCodeAt(type.length-1) - 48 if(d < 2 || d > 4) { throw new Error('gl-shader: Invalid data type for attribute ' + name + ': ' + type) } addVectorAttribute(gl, program, location, d, obj, name, doLink) } else { throw new Error('gl-shader: Unknown data type for attribute ' + name + ': ' + type) } break } } return obj }
[ "function", "createAttributeWrapper", "(", "gl", ",", "program", ",", "attributes", ",", "doLink", ")", "{", "var", "obj", "=", "{", "}", "for", "(", "var", "i", "=", "0", ",", "n", "=", "attributes", ".", "length", ";", "i", "<", "n", ";", "++", ...
Create shims for attributes
[ "Create", "shims", "for", "attributes" ]
25e021e9239ad7b73ce08ff0fdc97e2e68e1d075
https://github.com/stackgl/gl-shader-core/blob/25e021e9239ad7b73ce08ff0fdc97e2e68e1d075/lib/create-attributes.js#L66-L95
30,786
cloudfour/drizzle-builder
src/render/index.js
render
function render(drizzleData) { return Promise.all([ renderPages(drizzleData), renderCollections(drizzleData) ]).then( allData => { return { data: drizzleData.data, pages: allData[0], patterns: allData[1], templates: drizzleData.templates, options: drizzleData.options, tree: drizzleData.tree }; }, error => DrizzleError.error(error, drizzleData.options.debug) ); }
javascript
function render(drizzleData) { return Promise.all([ renderPages(drizzleData), renderCollections(drizzleData) ]).then( allData => { return { data: drizzleData.data, pages: allData[0], patterns: allData[1], templates: drizzleData.templates, options: drizzleData.options, tree: drizzleData.tree }; }, error => DrizzleError.error(error, drizzleData.options.debug) ); }
[ "function", "render", "(", "drizzleData", ")", "{", "return", "Promise", ".", "all", "(", "[", "renderPages", "(", "drizzleData", ")", ",", "renderCollections", "(", "drizzleData", ")", "]", ")", ".", "then", "(", "allData", "=>", "{", "return", "{", "da...
Render pages and pattern-collection pages. @param {Object} drizzleData All data built so far @return {Promise} resolving to drizzleData
[ "Render", "pages", "and", "pattern", "-", "collection", "pages", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/render/index.js#L12-L29
30,787
crispy1989/node-zstreams
lib/conversion.js
convertToZStream
function convertToZStream(stream, options) { if(stream._isZStream) return stream; if(isRequestStream(stream)) { // Request Stream return new RequestStream(stream, options); } if(isClassicStream(stream)) { if(stream.readable && stream.writable) { // Duplex return new ClassicDuplex(stream, options); } else if(stream.readable) { // Readable return new ClassicReadable(stream, options); } else { // Writable return new ClassicWritable(stream, options); } } var origFuncs = {}; for(var key in stream) { origFuncs[key] = stream[key]; } // Use duck typing in case of multiple stream implementations extend(stream, streamMixins.prototype); streamMixins.call(stream, origFuncs); if(stream.read) { extend(stream, readableMixins.prototype); readableMixins.call(stream); } if(stream.write) { extend(stream, writableMixins.prototype); writableMixins.call(stream); } if(typeof process === 'object' && (stream === process.stdout || stream === process.stderr)) { // Don't abort stdio streams on error stream._zNoAbort = true; } return stream; }
javascript
function convertToZStream(stream, options) { if(stream._isZStream) return stream; if(isRequestStream(stream)) { // Request Stream return new RequestStream(stream, options); } if(isClassicStream(stream)) { if(stream.readable && stream.writable) { // Duplex return new ClassicDuplex(stream, options); } else if(stream.readable) { // Readable return new ClassicReadable(stream, options); } else { // Writable return new ClassicWritable(stream, options); } } var origFuncs = {}; for(var key in stream) { origFuncs[key] = stream[key]; } // Use duck typing in case of multiple stream implementations extend(stream, streamMixins.prototype); streamMixins.call(stream, origFuncs); if(stream.read) { extend(stream, readableMixins.prototype); readableMixins.call(stream); } if(stream.write) { extend(stream, writableMixins.prototype); writableMixins.call(stream); } if(typeof process === 'object' && (stream === process.stdout || stream === process.stderr)) { // Don't abort stdio streams on error stream._zNoAbort = true; } return stream; }
[ "function", "convertToZStream", "(", "stream", ",", "options", ")", "{", "if", "(", "stream", ".", "_isZStream", ")", "return", "stream", ";", "if", "(", "isRequestStream", "(", "stream", ")", ")", "{", "// Request Stream", "return", "new", "RequestStream", ...
Convert a Stream into a ZStream. Either by wrapping it, or adding ZStream mixins @class zstreams @static @method convertToZStream @param {Stream} stream - The stream to try converting into a ZStream @param {Object} [options] - If expecting to convert, this will be passed as options into the stream being instanciated.
[ "Convert", "a", "Stream", "into", "a", "ZStream", ".", "Either", "by", "wrapping", "it", "or", "adding", "ZStream", "mixins" ]
4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd
https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/conversion.js#L39-L80
30,788
back4app/back4app-entity
src/back/models/Entity.js
isDirty
function isDirty(attribute) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when checking if an Entity attribute is ' + 'dirty (it has to be passed less than 2 arguments)' ); var attributes = this.Entity.attributes; if (attribute) { expect(attribute).to.be.a( 'string', 'Invalid argument "attribute" when checking if an Entity attribute ' + 'is dirty (it has to be a string)' ); expect(attributes).to.have.ownProperty( attribute, 'Invalid argument "attribute" when checking an Entity attribute ' + 'is dirty (this attribute does not exist in the Entity)' ); var newAttributes = {}; newAttributes[attribute] = attributes[attribute]; attributes = newAttributes; } if (this.isNew) { return true; } for (var attributeName in attributes) { if (_cleanSet) { if (_attributeIsSet[attributeName]) { if ( !_attributeStorageValues.hasOwnProperty(attributeName) || _attributeStorageValues[attributeName] !== this[attributeName] ) { return true; } } } else { if ( !_attributeStorageValues.hasOwnProperty(attributeName) || _attributeStorageValues[attributeName] !== this[attributeName] ) { return true; } } } return false; }
javascript
function isDirty(attribute) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when checking if an Entity attribute is ' + 'dirty (it has to be passed less than 2 arguments)' ); var attributes = this.Entity.attributes; if (attribute) { expect(attribute).to.be.a( 'string', 'Invalid argument "attribute" when checking if an Entity attribute ' + 'is dirty (it has to be a string)' ); expect(attributes).to.have.ownProperty( attribute, 'Invalid argument "attribute" when checking an Entity attribute ' + 'is dirty (this attribute does not exist in the Entity)' ); var newAttributes = {}; newAttributes[attribute] = attributes[attribute]; attributes = newAttributes; } if (this.isNew) { return true; } for (var attributeName in attributes) { if (_cleanSet) { if (_attributeIsSet[attributeName]) { if ( !_attributeStorageValues.hasOwnProperty(attributeName) || _attributeStorageValues[attributeName] !== this[attributeName] ) { return true; } } } else { if ( !_attributeStorageValues.hasOwnProperty(attributeName) || _attributeStorageValues[attributeName] !== this[attributeName] ) { return true; } } } return false; }
[ "function", "isDirty", "(", "attribute", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "below", "(", "2", ",", "'Invalid arguments length when checking if an Entity attribute is '", "+", "'dirty (it has to be passed less than 2 a...
Checks if an Entity attribute is dirty. @name module:back4app-entity/models.Entity#isDirty @function @param {?string} [attribute] The name of the attribute to be checked. If no attribute is passed, all attributes will be checked. @returns {boolean} True if is dirty and false otherwise. @example console.log(myEntity.isDirty('myAttribute')); // Validates attribute // "myAttribute" of // Entity "myEntity" @example console.log(myEntity.isDirty()); // Checks all attributes of "myEntity"
[ "Checks", "if", "an", "Entity", "attribute", "is", "dirty", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L373-L425
30,789
back4app/back4app-entity
src/back/models/Entity.js
clean
function clean(attribute) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when cleaning an Entity attribute (it has ' + 'to be passed less than 2 arguments)' ); var attributes = this.Entity.attributes; if (attribute) { expect(attribute).to.be.a( 'string', 'Invalid argument "attribute" when cleaning an Entity attribute (it ' + 'has to be a string)' ); expect(attributes).to.have.ownProperty( attribute, 'Invalid argument "attribute" when cleaning an Entity attribute ' + '(this attribute does not exist in the Entity)' ); var newAttributes = {}; newAttributes[attribute] = attributes[attribute]; attributes = newAttributes; } for (var attributeName in attributes) { _attributeStorageValues[attributeName] = this[attributeName]; _attributeIsSet[attributeName] = false; } }
javascript
function clean(attribute) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when cleaning an Entity attribute (it has ' + 'to be passed less than 2 arguments)' ); var attributes = this.Entity.attributes; if (attribute) { expect(attribute).to.be.a( 'string', 'Invalid argument "attribute" when cleaning an Entity attribute (it ' + 'has to be a string)' ); expect(attributes).to.have.ownProperty( attribute, 'Invalid argument "attribute" when cleaning an Entity attribute ' + '(this attribute does not exist in the Entity)' ); var newAttributes = {}; newAttributes[attribute] = attributes[attribute]; attributes = newAttributes; } for (var attributeName in attributes) { _attributeStorageValues[attributeName] = this[attributeName]; _attributeIsSet[attributeName] = false; } }
[ "function", "clean", "(", "attribute", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "below", "(", "2", ",", "'Invalid arguments length when cleaning an Entity attribute (it has '", "+", "'to be passed less than 2 arguments)'", ...
Cleans an Entity attribute. @name module:back4app-entity/models.Entity#clean @function @param {?string} [attribute] The name of the attribute to be cleaned. If no attribute is passed, all attributes will be cleaned. @example myEntity.clean('myAttribute'); // Cleans attribute "myAttribute" of // Entity "myEntity" @example myEntity.clean(); // Cleans all attributes of "myEntity"
[ "Cleans", "an", "Entity", "attribute", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L439-L470
30,790
back4app/back4app-entity
src/back/models/Entity.js
_visitSpecializations
function _visitSpecializations(entities, visitedEntities) { for (var entityName in entities) { if (!visitedEntities.hasOwnProperty(entityName)) { visitedEntities[entityName] = entities[entityName]; _visitSpecializations( entities[entityName].directSpecializations, visitedEntities ); } } }
javascript
function _visitSpecializations(entities, visitedEntities) { for (var entityName in entities) { if (!visitedEntities.hasOwnProperty(entityName)) { visitedEntities[entityName] = entities[entityName]; _visitSpecializations( entities[entityName].directSpecializations, visitedEntities ); } } }
[ "function", "_visitSpecializations", "(", "entities", ",", "visitedEntities", ")", "{", "for", "(", "var", "entityName", "in", "entities", ")", "{", "if", "(", "!", "visitedEntities", ".", "hasOwnProperty", "(", "entityName", ")", ")", "{", "visitedEntities", ...
Visits all specializations of a list of entities. @name module:back4app-entity/models.Entity~_visitSpecializations @function @param entities The entities whose specializations shall be visited. @param visitedEntities The list of visited entities. @private @example var specializations = []; _visitSpecializations(MyEntity.directSpecializations, specializations); console.log(specializations); // Logs all specializations of MyEntity
[ "Visits", "all", "specializations", "of", "a", "list", "of", "entities", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L743-L754
30,791
back4app/back4app-entity
src/back/models/Entity.js
function (CurrentEntity) { return function (entity) { expect(arguments).to.have.length( 1, 'Invalid arguments length when getting an Entity specialization (it ' + 'has to be passed 1 argument)' ); expect(entity).to.be.a( 'string', 'Invalid argument when creating a new Entity function (it has to be ' + 'a string' ); var entities = CurrentEntity.specializations; try { expect(entities).to.have.ownProperty(entity); } catch (e) { throw new errors.EntityNotFoundError( entity, e ); } return entities[entity]; }; }
javascript
function (CurrentEntity) { return function (entity) { expect(arguments).to.have.length( 1, 'Invalid arguments length when getting an Entity specialization (it ' + 'has to be passed 1 argument)' ); expect(entity).to.be.a( 'string', 'Invalid argument when creating a new Entity function (it has to be ' + 'a string' ); var entities = CurrentEntity.specializations; try { expect(entities).to.have.ownProperty(entity); } catch (e) { throw new errors.EntityNotFoundError( entity, e ); } return entities[entity]; }; }
[ "function", "(", "CurrentEntity", ")", "{", "return", "function", "(", "entity", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", "(", "1", ",", "'Invalid arguments length when getting an Entity specialization (it '", "+", "'has to...
Private function used to get the getSpecialization function specific for the current Entity class. @name module:back4app-entity/models.Entity~_getGetSpecializationFunction @function @param {!Class} CurrentEntity The current entity class for which the new function will be created. @returns {Function} The new function. @private @example Entity.getSpecialization = _getGetSpecializationFunction(Entity);
[ "Private", "function", "used", "to", "get", "the", "getSpecialization", "function", "specific", "for", "the", "current", "Entity", "class", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L1236-L1263
30,792
back4app/back4app-entity
src/back/models/Entity.js
function (CurrentEntity) { return function (entity) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when creating a new Entity function (it has ' + 'to be passed less than 2 arguments)' ); return function (attributeValues) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when creating a new Entity (it has ' + 'not to be passed less than 2 arguments)' ); var EntityClass = CurrentEntity; if (entity) { EntityClass = Entity.getSpecialization(entity); } return new EntityClass(attributeValues); }; }; }
javascript
function (CurrentEntity) { return function (entity) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when creating a new Entity function (it has ' + 'to be passed less than 2 arguments)' ); return function (attributeValues) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when creating a new Entity (it has ' + 'not to be passed less than 2 arguments)' ); var EntityClass = CurrentEntity; if (entity) { EntityClass = Entity.getSpecialization(entity); } return new EntityClass(attributeValues); }; }; }
[ "function", "(", "CurrentEntity", ")", "{", "return", "function", "(", "entity", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "below", "(", "2", ",", "'Invalid arguments length when creating a new Entity function (it has '...
Private function used to get the new function specific for the current Entity class. @name module:back4app-entity/models.Entity~_getNewFunction @function @param {!Class} CurrentEntity The current entity class for which the new function will be created. @returns {function} The new function. @private @example Entity.new = _getNewFunction(Entity);
[ "Private", "function", "used", "to", "get", "the", "new", "function", "specific", "for", "the", "current", "Entity", "class", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L1290-L1314
30,793
back4app/back4app-entity
src/back/models/Entity.js
function (CurrentEntity) { return function (attributeValues) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when creating a new "' + CurrentEntity.specification.name + '" instance (it has to be passed less than 2 arguments)'); return new Promise(function (resolve, reject) { var newEntity = new CurrentEntity(attributeValues); newEntity .save({ forceCreate: true }) .then(function () { resolve(newEntity); }) .catch(reject); }); }; }
javascript
function (CurrentEntity) { return function (attributeValues) { expect(arguments).to.have.length.below( 2, 'Invalid arguments length when creating a new "' + CurrentEntity.specification.name + '" instance (it has to be passed less than 2 arguments)'); return new Promise(function (resolve, reject) { var newEntity = new CurrentEntity(attributeValues); newEntity .save({ forceCreate: true }) .then(function () { resolve(newEntity); }) .catch(reject); }); }; }
[ "function", "(", "CurrentEntity", ")", "{", "return", "function", "(", "attributeValues", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "below", "(", "2", ",", "'Invalid arguments length when creating a new \"'", "+", "...
Private function used to get the create function specific for the current Entity class. @name module:back4app-entity/models.Entity~_getCreateFunction @function @param {!Class} CurrentEntity The current entity class for which the new function will be created. @returns {function} The new function. @private @example Entity.create = _getCreateFunction(Entity);
[ "Private", "function", "used", "to", "get", "the", "create", "function", "specific", "for", "the", "current", "Entity", "class", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L1343-L1364
30,794
back4app/back4app-entity
src/back/models/Entity.js
_getFindFunction
function _getFindFunction(CurrentEntity) { return function (query, params) { expect(arguments).to.have.length.within( 1, 2, 'Invalid arguments length when finding an Entity ' + '(it has to be passed 1 or 2 arguments)' ); expect(query).to.be.an( 'object', 'Invalid argument when finding an Entity (it has to be an object)' ); return Promise.try(function () { var adapter = CurrentEntity.adapter; return adapter.findObjects(CurrentEntity, query, params); }); }; }
javascript
function _getFindFunction(CurrentEntity) { return function (query, params) { expect(arguments).to.have.length.within( 1, 2, 'Invalid arguments length when finding an Entity ' + '(it has to be passed 1 or 2 arguments)' ); expect(query).to.be.an( 'object', 'Invalid argument when finding an Entity (it has to be an object)' ); return Promise.try(function () { var adapter = CurrentEntity.adapter; return adapter.findObjects(CurrentEntity, query, params); }); }; }
[ "function", "_getFindFunction", "(", "CurrentEntity", ")", "{", "return", "function", "(", "query", ",", "params", ")", "{", "expect", "(", "arguments", ")", ".", "to", ".", "have", ".", "length", ".", "within", "(", "1", ",", "2", ",", "'Invalid argumen...
Private function used to get the `find` function specific for the current Entity class. @name module:back4app-entity/models.Entity~_getFindFunction @function @param {!Class} CurrentEntity The current entity class for which the new function will be created. @returns {function} The find function. @private @example Entity.find = _getFindFunction(Entity);
[ "Private", "function", "used", "to", "get", "the", "find", "function", "specific", "for", "the", "current", "Entity", "class", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L1449-L1468
30,795
back4app/back4app-entity
src/back/models/Entity.js
isValid
function isValid(attribute) { try { this.validate(attribute); } catch (e) { if (e instanceof errors.ValidationError) { return false; } else { throw e; } } return true; }
javascript
function isValid(attribute) { try { this.validate(attribute); } catch (e) { if (e instanceof errors.ValidationError) { return false; } else { throw e; } } return true; }
[ "function", "isValid", "(", "attribute", ")", "{", "try", "{", "this", ".", "validate", "(", "attribute", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "e", "instanceof", "errors", ".", "ValidationError", ")", "{", "return", "false", ";", "}...
Validates an entity and returns a boolean indicating if it is valid. @name module:back4app-entity/models.Entity#isValid @function @param {?string} [attribute] The name of the attribute to be validated. If no attribute is passed, all attributes will be validated. @returns {boolean} The validation result. @example myEntity.isValid('myAttribute'); // Validates attribute "myAttribute" of // Entity "myEntity" and returns true/false @example myEntity.isValid(); // Validates all attributes of "myEntity" and returns // true/false
[ "Validates", "an", "entity", "and", "returns", "a", "boolean", "indicating", "if", "it", "is", "valid", "." ]
16a15284d2e119508fcb4e0c88f647ffb285d2e9
https://github.com/back4app/back4app-entity/blob/16a15284d2e119508fcb4e0c88f647ffb285d2e9/src/back/models/Entity.js#L1550-L1561
30,796
cloudfour/drizzle-builder
src/utils/shared.js
relativePathArray
function relativePathArray(filePath, fromPath) { filePath = path.normalize(filePath); fromPath = path.normalize(fromPath); if (filePath.indexOf(fromPath) === -1 || filePath === fromPath) { // TODO Error handling: this should cause a warn return []; } const keys = path.relative(fromPath, path.dirname(filePath)); if (keys && keys.length !== 0) { return keys.split(path.sep); } return []; }
javascript
function relativePathArray(filePath, fromPath) { filePath = path.normalize(filePath); fromPath = path.normalize(fromPath); if (filePath.indexOf(fromPath) === -1 || filePath === fromPath) { // TODO Error handling: this should cause a warn return []; } const keys = path.relative(fromPath, path.dirname(filePath)); if (keys && keys.length !== 0) { return keys.split(path.sep); } return []; }
[ "function", "relativePathArray", "(", "filePath", ",", "fromPath", ")", "{", "filePath", "=", "path", ".", "normalize", "(", "filePath", ")", ";", "fromPath", "=", "path", ".", "normalize", "(", "fromPath", ")", ";", "if", "(", "filePath", ".", "indexOf", ...
Given a file's path and a string representing a directory name, return an Array that only contains directories at or beneath that directory. @example relativePathArray('/foo/bar/baz/ding/dong/tink.txt', 'baz') // -> ['baz', 'ding', 'dong'] @param {String} filePath @param {String} fromPath @return {Array}
[ "Given", "a", "file", "s", "path", "and", "a", "string", "representing", "a", "directory", "name", "return", "an", "Array", "that", "only", "contains", "directories", "at", "or", "beneath", "that", "directory", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/shared.js#L33-L45
30,797
cloudfour/drizzle-builder
src/utils/shared.js
resourcePath
function resourcePath(resourceId, dest = '') { const subPath = idKeys(resourceId); // Remove first item because it is the "resource type" // If there _is_ only one item in the ID, it will be left alone // To serve as the filename. if (subPath.length !== 0 && subPath.length > 1) { subPath.shift(); } const filename = subPath.pop() + '.html'; const outputPath = path.normalize( path.join(dest, subPath.join(path.sep), filename) ); return outputPath; }
javascript
function resourcePath(resourceId, dest = '') { const subPath = idKeys(resourceId); // Remove first item because it is the "resource type" // If there _is_ only one item in the ID, it will be left alone // To serve as the filename. if (subPath.length !== 0 && subPath.length > 1) { subPath.shift(); } const filename = subPath.pop() + '.html'; const outputPath = path.normalize( path.join(dest, subPath.join(path.sep), filename) ); return outputPath; }
[ "function", "resourcePath", "(", "resourceId", ",", "dest", "=", "''", ")", "{", "const", "subPath", "=", "idKeys", "(", "resourceId", ")", ";", "// Remove first item because it is the \"resource type\"", "// If there _is_ only one item in the ID, it will be left alone", "// ...
Generate a path for a resource based on its ID. @param {String} resourceId '.'-separated ID for this resource @param {String} dest This path will be prepended @return {String} path
[ "Generate", "a", "path", "for", "a", "resource", "based", "on", "its", "ID", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/utils/shared.js#L53-L66
30,798
crispy1989/node-zstreams
lib/passthrough.js
ZPassThrough
function ZPassThrough(options) { if(options) { if(options.objectMode) { options.readableObjectMode = true; options.writableObjectMode = true; } if(options.readableObjectMode && options.writableObjectMode) { options.objectMode = true; } } PassThrough.call(this, options); // note: exclamation marks are used to convert to booleans if(options && !options.objectMode && (!options.readableObjectMode) !== (!options.writableObjectMode)) { this._writableState.objectMode = !!options.writableObjectMode; this._readableState.objectMode = !!options.readableObjectMode; } if(options && options.readableObjectMode) { this._readableState.highWaterMark = 16; } if(options && options.writableObjectMode) { this._writableState.highWaterMark = 16; } streamMixins.call(this, PassThrough.prototype, options); readableMixins.call(this, options); writableMixins.call(this, options); }
javascript
function ZPassThrough(options) { if(options) { if(options.objectMode) { options.readableObjectMode = true; options.writableObjectMode = true; } if(options.readableObjectMode && options.writableObjectMode) { options.objectMode = true; } } PassThrough.call(this, options); // note: exclamation marks are used to convert to booleans if(options && !options.objectMode && (!options.readableObjectMode) !== (!options.writableObjectMode)) { this._writableState.objectMode = !!options.writableObjectMode; this._readableState.objectMode = !!options.readableObjectMode; } if(options && options.readableObjectMode) { this._readableState.highWaterMark = 16; } if(options && options.writableObjectMode) { this._writableState.highWaterMark = 16; } streamMixins.call(this, PassThrough.prototype, options); readableMixins.call(this, options); writableMixins.call(this, options); }
[ "function", "ZPassThrough", "(", "options", ")", "{", "if", "(", "options", ")", "{", "if", "(", "options", ".", "objectMode", ")", "{", "options", ".", "readableObjectMode", "=", "true", ";", "options", ".", "writableObjectMode", "=", "true", ";", "}", ...
ZPassThrough writes everything written to it into the other side @class ZPassThrough @constructor @extends PassThrough @uses _Stream @uses _Readable @uses _Writable @param {Object} [options] - Stream options
[ "ZPassThrough", "writes", "everything", "written", "to", "it", "into", "the", "other", "side" ]
4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd
https://github.com/crispy1989/node-zstreams/blob/4ec01a49d1d00c542ee1dfa4b3bedcf1324e9ffd/lib/passthrough.js#L19-L44
30,799
cloudfour/drizzle-builder
src/helpers/page.js
destRoot
function destRoot(type, drizzle) { const options = drizzle.options; // TODO: this is unfortunate, and due to difficulty using defaults.keys const keys = new Map([ ['page', 'pages'], ['collection', 'collections'], ['pattern', 'patterns'] ]); return relativePath(options.dest.root, options.dest[keys.get(type)]); }
javascript
function destRoot(type, drizzle) { const options = drizzle.options; // TODO: this is unfortunate, and due to difficulty using defaults.keys const keys = new Map([ ['page', 'pages'], ['collection', 'collections'], ['pattern', 'patterns'] ]); return relativePath(options.dest.root, options.dest[keys.get(type)]); }
[ "function", "destRoot", "(", "type", ",", "drizzle", ")", "{", "const", "options", "=", "drizzle", ".", "options", ";", "// TODO: this is unfortunate, and due to difficulty using defaults.keys", "const", "keys", "=", "new", "Map", "(", "[", "[", "'page'", ",", "'p...
Return a relative base path for .html destinations. @param {String} type The resource type identifier (e.g. "page", "pattern", "collection") @param {Object} drizzle The Drizzle root context. @return {String} The relative base path for the supplied resource type.
[ "Return", "a", "relative", "base", "path", "for", ".", "html", "destinations", "." ]
1c320cb059c749c28339a661d1768d3a643e5f1c
https://github.com/cloudfour/drizzle-builder/blob/1c320cb059c749c28339a661d1768d3a643e5f1c/src/helpers/page.js#L39-L50