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
47,900
mikesamuel/module-keys
index.js
unboxStrict
function unboxStrict(box, ifFrom) { // eslint-disable-line no-shadow const result = unbox(box, ifFrom, neverBoxed); if (result === neverBoxed) { throw new Error('Could not unbox'); } return result; }
javascript
function unboxStrict(box, ifFrom) { // eslint-disable-line no-shadow const result = unbox(box, ifFrom, neverBoxed); if (result === neverBoxed) { throw new Error('Could not unbox'); } return result; }
[ "function", "unboxStrict", "(", "box", ",", "ifFrom", ")", "{", "// eslint-disable-line no-shadow", "const", "result", "=", "unbox", "(", "box", ",", "ifFrom", ",", "neverBoxed", ")", ";", "if", "(", "result", "===", "neverBoxed", ")", "{", "throw", "new", "Error", "(", "'Could not unbox'", ")", ";", "}", "return", "result", ";", "}" ]
Like unbox but raises an exception if unboxing fails. @param {*} box the box to unbox. @param {?function(function():boolean):boolean} ifFrom if the box may be opened by this unboxer's owner, then ifFrom receives the publicKey of the box creator. It should return true to allow unboxing to proceed. @return {*} the value if unboxing is allowed or fallback otherwise.
[ "Like", "unbox", "but", "raises", "an", "exception", "if", "unboxing", "fails", "." ]
39100b07d143af3f77a0bec519a92634d5173dd6
https://github.com/mikesamuel/module-keys/blob/39100b07d143af3f77a0bec519a92634d5173dd6/index.js#L243-L249
47,901
niallo/gumshoe
index.js
result
function result(rule) { var r = {} var reserved = ['filename', 'exists', 'grep', 'jsonKeyExists'] Object.keys(rule).forEach(function(key) { if (reserved.indexOf(key) !== -1) return r[key] = rule[key] }) return r }
javascript
function result(rule) { var r = {} var reserved = ['filename', 'exists', 'grep', 'jsonKeyExists'] Object.keys(rule).forEach(function(key) { if (reserved.indexOf(key) !== -1) return r[key] = rule[key] }) return r }
[ "function", "result", "(", "rule", ")", "{", "var", "r", "=", "{", "}", "var", "reserved", "=", "[", "'filename'", ",", "'exists'", ",", "'grep'", ",", "'jsonKeyExists'", "]", "Object", ".", "keys", "(", "rule", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "if", "(", "reserved", ".", "indexOf", "(", "key", ")", "!==", "-", "1", ")", "return", "r", "[", "key", "]", "=", "rule", "[", "key", "]", "}", ")", "return", "r", "}" ]
Return an object created by removing all special properties from a rules object.
[ "Return", "an", "object", "created", "by", "removing", "all", "special", "properties", "from", "a", "rules", "object", "." ]
eff4a8a59bd580536889c4771bb70ca4db2ed96d
https://github.com/niallo/gumshoe/blob/eff4a8a59bd580536889c4771bb70ca4db2ed96d/index.js#L10-L21
47,902
nicktindall/cyclon.p2p-rtc-client
lib/RedundantSignallingSocket.js
scheduleServerConnectivityChecks
function scheduleServerConnectivityChecks() { if (connectivityIntervalId === null) { connectivityIntervalId = asyncExecService.setInterval(function () { updateRegistrations(); connectToServers(); }, INTERVAL_BETWEEN_SERVER_CONNECTIVITY_CHECKS); } else { throw new Error("BUG ::: Attempt was made to start connectivity checks twice"); } }
javascript
function scheduleServerConnectivityChecks() { if (connectivityIntervalId === null) { connectivityIntervalId = asyncExecService.setInterval(function () { updateRegistrations(); connectToServers(); }, INTERVAL_BETWEEN_SERVER_CONNECTIVITY_CHECKS); } else { throw new Error("BUG ::: Attempt was made to start connectivity checks twice"); } }
[ "function", "scheduleServerConnectivityChecks", "(", ")", "{", "if", "(", "connectivityIntervalId", "===", "null", ")", "{", "connectivityIntervalId", "=", "asyncExecService", ".", "setInterval", "(", "function", "(", ")", "{", "updateRegistrations", "(", ")", ";", "connectToServers", "(", ")", ";", "}", ",", "INTERVAL_BETWEEN_SERVER_CONNECTIVITY_CHECKS", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"BUG ::: Attempt was made to start connectivity checks twice\"", ")", ";", "}", "}" ]
Schedule periodic server connectivity checks
[ "Schedule", "periodic", "server", "connectivity", "checks" ]
eb586ce288a6ad7e1b221280825037e855b03904
https://github.com/nicktindall/cyclon.p2p-rtc-client/blob/eb586ce288a6ad7e1b221280825037e855b03904/lib/RedundantSignallingSocket.js#L54-L64
47,903
nicktindall/cyclon.p2p-rtc-client
lib/RedundantSignallingSocket.js
connectToServers
function connectToServers() { var knownServers = signallingServerSelector.getServerSpecsInPriorityOrder(); for (var i = 0; i < knownServers.length; i++) { var connectionsRemaining = signallingServerService.getPreferredNumberOfSockets() - Object.keys(connectedSockets).length; // // We have enough connections // if (connectionsRemaining === 0) { break; } // // Try to connect to a new server // var serverSpec = knownServers[i]; if (!currentlyConnectedToServer(serverSpec)) { var socket; try { socket = socketFactory.createSocket(serverSpec); storeSocket(serverSpec, socket); addListeners(socket, serverSpec); loggingService.info("Attempting to connect to signalling server (" + serverSpec.signallingApiBase + ")"); } catch (error) { loggingService.error("Error connecting to socket " + serverSpec.signallingApiBase, error); } } } // // Store the new set of connected servers in session storage so we // can prefer them in the event of a reload // signallingServerSelector.setLastConnectedServers(getListOfCurrentSignallingApiBases()); }
javascript
function connectToServers() { var knownServers = signallingServerSelector.getServerSpecsInPriorityOrder(); for (var i = 0; i < knownServers.length; i++) { var connectionsRemaining = signallingServerService.getPreferredNumberOfSockets() - Object.keys(connectedSockets).length; // // We have enough connections // if (connectionsRemaining === 0) { break; } // // Try to connect to a new server // var serverSpec = knownServers[i]; if (!currentlyConnectedToServer(serverSpec)) { var socket; try { socket = socketFactory.createSocket(serverSpec); storeSocket(serverSpec, socket); addListeners(socket, serverSpec); loggingService.info("Attempting to connect to signalling server (" + serverSpec.signallingApiBase + ")"); } catch (error) { loggingService.error("Error connecting to socket " + serverSpec.signallingApiBase, error); } } } // // Store the new set of connected servers in session storage so we // can prefer them in the event of a reload // signallingServerSelector.setLastConnectedServers(getListOfCurrentSignallingApiBases()); }
[ "function", "connectToServers", "(", ")", "{", "var", "knownServers", "=", "signallingServerSelector", ".", "getServerSpecsInPriorityOrder", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "knownServers", ".", "length", ";", "i", "++", ")", "{", "var", "connectionsRemaining", "=", "signallingServerService", ".", "getPreferredNumberOfSockets", "(", ")", "-", "Object", ".", "keys", "(", "connectedSockets", ")", ".", "length", ";", "//", "// We have enough connections", "//", "if", "(", "connectionsRemaining", "===", "0", ")", "{", "break", ";", "}", "//", "// Try to connect to a new server", "//", "var", "serverSpec", "=", "knownServers", "[", "i", "]", ";", "if", "(", "!", "currentlyConnectedToServer", "(", "serverSpec", ")", ")", "{", "var", "socket", ";", "try", "{", "socket", "=", "socketFactory", ".", "createSocket", "(", "serverSpec", ")", ";", "storeSocket", "(", "serverSpec", ",", "socket", ")", ";", "addListeners", "(", "socket", ",", "serverSpec", ")", ";", "loggingService", ".", "info", "(", "\"Attempting to connect to signalling server (\"", "+", "serverSpec", ".", "signallingApiBase", "+", "\")\"", ")", ";", "}", "catch", "(", "error", ")", "{", "loggingService", ".", "error", "(", "\"Error connecting to socket \"", "+", "serverSpec", ".", "signallingApiBase", ",", "error", ")", ";", "}", "}", "}", "//", "// Store the new set of connected servers in session storage so we", "// can prefer them in the event of a reload", "//", "signallingServerSelector", ".", "setLastConnectedServers", "(", "getListOfCurrentSignallingApiBases", "(", ")", ")", ";", "}" ]
Connect to servers if we're not connected to enough
[ "Connect", "to", "servers", "if", "we", "re", "not", "connected", "to", "enough" ]
eb586ce288a6ad7e1b221280825037e855b03904
https://github.com/nicktindall/cyclon.p2p-rtc-client/blob/eb586ce288a6ad7e1b221280825037e855b03904/lib/RedundantSignallingSocket.js#L105-L141
47,904
nicktindall/cyclon.p2p-rtc-client
lib/RedundantSignallingSocket.js
storeSocket
function storeSocket(spec, socket) { connectedSpecs[spec.signallingApiBase] = spec; connectedSockets[spec.signallingApiBase] = socket; }
javascript
function storeSocket(spec, socket) { connectedSpecs[spec.signallingApiBase] = spec; connectedSockets[spec.signallingApiBase] = socket; }
[ "function", "storeSocket", "(", "spec", ",", "socket", ")", "{", "connectedSpecs", "[", "spec", ".", "signallingApiBase", "]", "=", "spec", ";", "connectedSockets", "[", "spec", ".", "signallingApiBase", "]", "=", "socket", ";", "}" ]
Delete a socket from the local store @param spec @param socket
[ "Delete", "a", "socket", "from", "the", "local", "store" ]
eb586ce288a6ad7e1b221280825037e855b03904
https://github.com/nicktindall/cyclon.p2p-rtc-client/blob/eb586ce288a6ad7e1b221280825037e855b03904/lib/RedundantSignallingSocket.js#L169-L172
47,905
nicktindall/cyclon.p2p-rtc-client
lib/RedundantSignallingSocket.js
addListeners
function addListeners(socket, serverSpec) { var apiBase = serverSpec.signallingApiBase; var disposeFunction = disposeOfSocket(apiBase); var registerFunction = register(socket); // Register if we connect socket.on("connect", registerFunction); // Dispose if we disconnect/fail to connect/error socket.io.on("connect_error", disposeFunction); socket.on("error", disposeFunction); socket.on("disconnect", disposeFunction); /** * Emit offers/answers when they're received */ socket.on("answer", emitAnswer); socket.on("offer", emitOffer); socket.on("candidates", emitCandidates); }
javascript
function addListeners(socket, serverSpec) { var apiBase = serverSpec.signallingApiBase; var disposeFunction = disposeOfSocket(apiBase); var registerFunction = register(socket); // Register if we connect socket.on("connect", registerFunction); // Dispose if we disconnect/fail to connect/error socket.io.on("connect_error", disposeFunction); socket.on("error", disposeFunction); socket.on("disconnect", disposeFunction); /** * Emit offers/answers when they're received */ socket.on("answer", emitAnswer); socket.on("offer", emitOffer); socket.on("candidates", emitCandidates); }
[ "function", "addListeners", "(", "socket", ",", "serverSpec", ")", "{", "var", "apiBase", "=", "serverSpec", ".", "signallingApiBase", ";", "var", "disposeFunction", "=", "disposeOfSocket", "(", "apiBase", ")", ";", "var", "registerFunction", "=", "register", "(", "socket", ")", ";", "// Register if we connect", "socket", ".", "on", "(", "\"connect\"", ",", "registerFunction", ")", ";", "// Dispose if we disconnect/fail to connect/error", "socket", ".", "io", ".", "on", "(", "\"connect_error\"", ",", "disposeFunction", ")", ";", "socket", ".", "on", "(", "\"error\"", ",", "disposeFunction", ")", ";", "socket", ".", "on", "(", "\"disconnect\"", ",", "disposeFunction", ")", ";", "/**\n * Emit offers/answers when they're received\n */", "socket", ".", "on", "(", "\"answer\"", ",", "emitAnswer", ")", ";", "socket", ".", "on", "(", "\"offer\"", ",", "emitOffer", ")", ";", "socket", ".", "on", "(", "\"candidates\"", ",", "emitCandidates", ")", ";", "}" ]
Add listeners for a socket @param socket @param serverSpec
[ "Add", "listeners", "for", "a", "socket" ]
eb586ce288a6ad7e1b221280825037e855b03904
https://github.com/nicktindall/cyclon.p2p-rtc-client/blob/eb586ce288a6ad7e1b221280825037e855b03904/lib/RedundantSignallingSocket.js#L191-L210
47,906
nicktindall/cyclon.p2p-rtc-client
lib/RedundantSignallingSocket.js
disposeOfSocket
function disposeOfSocket(apiBase) { return function (error) { loggingService.warn("Got disconnected from signalling server (" + apiBase + ")", error); var socket = connectedSockets[apiBase]; if (socket) { stopConnectivityChecks(); socket.removeAllListeners(); socket.io.removeAllListeners(); try { socket.disconnect(); } catch (ignore) { } deleteSocket(apiBase); if (!unloadInProgress) { connectAndMonitor(); } } else { throw new Error("BUG ::: Disconnected from a socket we're not connected to?!"); } }; }
javascript
function disposeOfSocket(apiBase) { return function (error) { loggingService.warn("Got disconnected from signalling server (" + apiBase + ")", error); var socket = connectedSockets[apiBase]; if (socket) { stopConnectivityChecks(); socket.removeAllListeners(); socket.io.removeAllListeners(); try { socket.disconnect(); } catch (ignore) { } deleteSocket(apiBase); if (!unloadInProgress) { connectAndMonitor(); } } else { throw new Error("BUG ::: Disconnected from a socket we're not connected to?!"); } }; }
[ "function", "disposeOfSocket", "(", "apiBase", ")", "{", "return", "function", "(", "error", ")", "{", "loggingService", ".", "warn", "(", "\"Got disconnected from signalling server (\"", "+", "apiBase", "+", "\")\"", ",", "error", ")", ";", "var", "socket", "=", "connectedSockets", "[", "apiBase", "]", ";", "if", "(", "socket", ")", "{", "stopConnectivityChecks", "(", ")", ";", "socket", ".", "removeAllListeners", "(", ")", ";", "socket", ".", "io", ".", "removeAllListeners", "(", ")", ";", "try", "{", "socket", ".", "disconnect", "(", ")", ";", "}", "catch", "(", "ignore", ")", "{", "}", "deleteSocket", "(", "apiBase", ")", ";", "if", "(", "!", "unloadInProgress", ")", "{", "connectAndMonitor", "(", ")", ";", "}", "}", "else", "{", "throw", "new", "Error", "(", "\"BUG ::: Disconnected from a socket we're not connected to?!\"", ")", ";", "}", "}", ";", "}" ]
Return a closure that will dispose of a socket @param apiBase @returns {Function}
[ "Return", "a", "closure", "that", "will", "dispose", "of", "a", "socket" ]
eb586ce288a6ad7e1b221280825037e855b03904
https://github.com/nicktindall/cyclon.p2p-rtc-client/blob/eb586ce288a6ad7e1b221280825037e855b03904/lib/RedundantSignallingSocket.js#L218-L242
47,907
YuhangGe/node-freetype
lib/parse/glyf.js
parseGlyphCoordinate
function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { var v; if ((flag & shortVectorBitMask) > 0) { // The coordinate is 1 byte long. v = p.parseByte(); // The `same` bit is re-used for short values to signify the sign of the value. if ((flag & sameBitMask) === 0) { v = -v; } v = previousValue + v; } else { // The coordinate is 2 bytes long. // If the `same` bit is set, the coordinate is the same as the previous coordinate. if ((flag & sameBitMask) > 0) { v = previousValue; } else { // Parse the coordinate as a signed 16-bit delta value. v = previousValue + p.parseShort(); } } return v; }
javascript
function parseGlyphCoordinate(p, flag, previousValue, shortVectorBitMask, sameBitMask) { var v; if ((flag & shortVectorBitMask) > 0) { // The coordinate is 1 byte long. v = p.parseByte(); // The `same` bit is re-used for short values to signify the sign of the value. if ((flag & sameBitMask) === 0) { v = -v; } v = previousValue + v; } else { // The coordinate is 2 bytes long. // If the `same` bit is set, the coordinate is the same as the previous coordinate. if ((flag & sameBitMask) > 0) { v = previousValue; } else { // Parse the coordinate as a signed 16-bit delta value. v = previousValue + p.parseShort(); } } return v; }
[ "function", "parseGlyphCoordinate", "(", "p", ",", "flag", ",", "previousValue", ",", "shortVectorBitMask", ",", "sameBitMask", ")", "{", "var", "v", ";", "if", "(", "(", "flag", "&", "shortVectorBitMask", ")", ">", "0", ")", "{", "// The coordinate is 1 byte long.", "v", "=", "p", ".", "parseByte", "(", ")", ";", "// The `same` bit is re-used for short values to signify the sign of the value.", "if", "(", "(", "flag", "&", "sameBitMask", ")", "===", "0", ")", "{", "v", "=", "-", "v", ";", "}", "v", "=", "previousValue", "+", "v", ";", "}", "else", "{", "// The coordinate is 2 bytes long.", "// If the `same` bit is set, the coordinate is the same as the previous coordinate.", "if", "(", "(", "flag", "&", "sameBitMask", ")", ">", "0", ")", "{", "v", "=", "previousValue", ";", "}", "else", "{", "// Parse the coordinate as a signed 16-bit delta value.", "v", "=", "previousValue", "+", "p", ".", "parseShort", "(", ")", ";", "}", "}", "return", "v", ";", "}" ]
Parse the coordinate data for a glyph.
[ "Parse", "the", "coordinate", "data", "for", "a", "glyph", "." ]
4c8d2e2503f088ffbd61e613a23b9ff2e64d3489
https://github.com/YuhangGe/node-freetype/blob/4c8d2e2503f088ffbd61e613a23b9ff2e64d3489/lib/parse/glyf.js#L10-L31
47,908
YuhangGe/node-freetype
lib/parse/glyf.js
transformPoints
function transformPoints(points, transform) { var newPoints, i, pt, newPt; newPoints = []; for (i = 0; i < points.length; i += 1) { pt = points[i]; newPt = { x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx, y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy, onCurve: pt.onCurve, lastPointOfContour: pt.lastPointOfContour }; newPoints.push(newPt); } return newPoints; }
javascript
function transformPoints(points, transform) { var newPoints, i, pt, newPt; newPoints = []; for (i = 0; i < points.length; i += 1) { pt = points[i]; newPt = { x: transform.xScale * pt.x + transform.scale01 * pt.y + transform.dx, y: transform.scale10 * pt.x + transform.yScale * pt.y + transform.dy, onCurve: pt.onCurve, lastPointOfContour: pt.lastPointOfContour }; newPoints.push(newPt); } return newPoints; }
[ "function", "transformPoints", "(", "points", ",", "transform", ")", "{", "var", "newPoints", ",", "i", ",", "pt", ",", "newPt", ";", "newPoints", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "points", ".", "length", ";", "i", "+=", "1", ")", "{", "pt", "=", "points", "[", "i", "]", ";", "newPt", "=", "{", "x", ":", "transform", ".", "xScale", "*", "pt", ".", "x", "+", "transform", ".", "scale01", "*", "pt", ".", "y", "+", "transform", ".", "dx", ",", "y", ":", "transform", ".", "scale10", "*", "pt", ".", "x", "+", "transform", ".", "yScale", "*", "pt", ".", "y", "+", "transform", ".", "dy", ",", "onCurve", ":", "pt", ".", "onCurve", ",", "lastPointOfContour", ":", "pt", ".", "lastPointOfContour", "}", ";", "newPoints", ".", "push", "(", "newPt", ")", ";", "}", "return", "newPoints", ";", "}" ]
Transform an array of points and return a new array.
[ "Transform", "an", "array", "of", "points", "and", "return", "a", "new", "array", "." ]
4c8d2e2503f088ffbd61e613a23b9ff2e64d3489
https://github.com/YuhangGe/node-freetype/blob/4c8d2e2503f088ffbd61e613a23b9ff2e64d3489/lib/parse/glyf.js#L160-L174
47,909
YuhangGe/node-freetype
lib/parse/glyf.js
getPath
function getPath(points) { var p, contours, i, realFirstPoint, j, contour, pt, firstPt, prevPt, midPt, curvePt, lastPt; p = new path.Path(); if (!points) { return p; } contours = getContours(points); for (i = 0; i < contours.length; i += 1) { contour = contours[i]; firstPt = contour[0]; lastPt = contour[contour.length - 1]; if (firstPt.onCurve) { curvePt = null; // The first point will be consumed by the moveTo command, // so skip it in the loop. realFirstPoint = true; } else { if (lastPt.onCurve) { // If the first point is off-curve and the last point is on-curve, // start at the last point. firstPt = lastPt; } else { // If both first and last points are off-curve, start at their middle. firstPt = { x: (firstPt.x + lastPt.x) / 2, y: (firstPt.y + lastPt.y) / 2 }; } curvePt = firstPt; // The first point is synthesized, so don't skip the real first point. realFirstPoint = false; } p.moveTo(firstPt.x, firstPt.y); for (j = realFirstPoint ? 1 : 0; j < contour.length; j += 1) { pt = contour[j]; prevPt = j === 0 ? firstPt : contour[j - 1]; if (prevPt.onCurve && pt.onCurve) { // This is a straight line. p.lineTo(pt.x, pt.y); } else if (prevPt.onCurve && !pt.onCurve) { curvePt = pt; } else if (!prevPt.onCurve && !pt.onCurve) { midPt = { x: (prevPt.x + pt.x) / 2, y: (prevPt.y + pt.y) / 2 }; p.quadraticCurveTo(prevPt.x, prevPt.y, midPt.x, midPt.y); curvePt = pt; } else if (!prevPt.onCurve && pt.onCurve) { // Previous point off-curve, this point on-curve. p.quadraticCurveTo(curvePt.x, curvePt.y, pt.x, pt.y); curvePt = null; } else { throw new Error('Invalid state.'); } } if (firstPt !== lastPt) { // Connect the last and first points if (curvePt) { p.quadraticCurveTo(curvePt.x, curvePt.y, firstPt.x, firstPt.y); } else { p.lineTo(firstPt.x, firstPt.y); } } } p.closePath(); return p; }
javascript
function getPath(points) { var p, contours, i, realFirstPoint, j, contour, pt, firstPt, prevPt, midPt, curvePt, lastPt; p = new path.Path(); if (!points) { return p; } contours = getContours(points); for (i = 0; i < contours.length; i += 1) { contour = contours[i]; firstPt = contour[0]; lastPt = contour[contour.length - 1]; if (firstPt.onCurve) { curvePt = null; // The first point will be consumed by the moveTo command, // so skip it in the loop. realFirstPoint = true; } else { if (lastPt.onCurve) { // If the first point is off-curve and the last point is on-curve, // start at the last point. firstPt = lastPt; } else { // If both first and last points are off-curve, start at their middle. firstPt = { x: (firstPt.x + lastPt.x) / 2, y: (firstPt.y + lastPt.y) / 2 }; } curvePt = firstPt; // The first point is synthesized, so don't skip the real first point. realFirstPoint = false; } p.moveTo(firstPt.x, firstPt.y); for (j = realFirstPoint ? 1 : 0; j < contour.length; j += 1) { pt = contour[j]; prevPt = j === 0 ? firstPt : contour[j - 1]; if (prevPt.onCurve && pt.onCurve) { // This is a straight line. p.lineTo(pt.x, pt.y); } else if (prevPt.onCurve && !pt.onCurve) { curvePt = pt; } else if (!prevPt.onCurve && !pt.onCurve) { midPt = { x: (prevPt.x + pt.x) / 2, y: (prevPt.y + pt.y) / 2 }; p.quadraticCurveTo(prevPt.x, prevPt.y, midPt.x, midPt.y); curvePt = pt; } else if (!prevPt.onCurve && pt.onCurve) { // Previous point off-curve, this point on-curve. p.quadraticCurveTo(curvePt.x, curvePt.y, pt.x, pt.y); curvePt = null; } else { throw new Error('Invalid state.'); } } if (firstPt !== lastPt) { // Connect the last and first points if (curvePt) { p.quadraticCurveTo(curvePt.x, curvePt.y, firstPt.x, firstPt.y); } else { p.lineTo(firstPt.x, firstPt.y); } } } p.closePath(); return p; }
[ "function", "getPath", "(", "points", ")", "{", "var", "p", ",", "contours", ",", "i", ",", "realFirstPoint", ",", "j", ",", "contour", ",", "pt", ",", "firstPt", ",", "prevPt", ",", "midPt", ",", "curvePt", ",", "lastPt", ";", "p", "=", "new", "path", ".", "Path", "(", ")", ";", "if", "(", "!", "points", ")", "{", "return", "p", ";", "}", "contours", "=", "getContours", "(", "points", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "contours", ".", "length", ";", "i", "+=", "1", ")", "{", "contour", "=", "contours", "[", "i", "]", ";", "firstPt", "=", "contour", "[", "0", "]", ";", "lastPt", "=", "contour", "[", "contour", ".", "length", "-", "1", "]", ";", "if", "(", "firstPt", ".", "onCurve", ")", "{", "curvePt", "=", "null", ";", "// The first point will be consumed by the moveTo command,", "// so skip it in the loop.", "realFirstPoint", "=", "true", ";", "}", "else", "{", "if", "(", "lastPt", ".", "onCurve", ")", "{", "// If the first point is off-curve and the last point is on-curve,", "// start at the last point.", "firstPt", "=", "lastPt", ";", "}", "else", "{", "// If both first and last points are off-curve, start at their middle.", "firstPt", "=", "{", "x", ":", "(", "firstPt", ".", "x", "+", "lastPt", ".", "x", ")", "/", "2", ",", "y", ":", "(", "firstPt", ".", "y", "+", "lastPt", ".", "y", ")", "/", "2", "}", ";", "}", "curvePt", "=", "firstPt", ";", "// The first point is synthesized, so don't skip the real first point.", "realFirstPoint", "=", "false", ";", "}", "p", ".", "moveTo", "(", "firstPt", ".", "x", ",", "firstPt", ".", "y", ")", ";", "for", "(", "j", "=", "realFirstPoint", "?", "1", ":", "0", ";", "j", "<", "contour", ".", "length", ";", "j", "+=", "1", ")", "{", "pt", "=", "contour", "[", "j", "]", ";", "prevPt", "=", "j", "===", "0", "?", "firstPt", ":", "contour", "[", "j", "-", "1", "]", ";", "if", "(", "prevPt", ".", "onCurve", "&&", "pt", ".", "onCurve", ")", "{", "// This is a straight line.", "p", ".", "lineTo", "(", "pt", ".", "x", ",", "pt", ".", "y", ")", ";", "}", "else", "if", "(", "prevPt", ".", "onCurve", "&&", "!", "pt", ".", "onCurve", ")", "{", "curvePt", "=", "pt", ";", "}", "else", "if", "(", "!", "prevPt", ".", "onCurve", "&&", "!", "pt", ".", "onCurve", ")", "{", "midPt", "=", "{", "x", ":", "(", "prevPt", ".", "x", "+", "pt", ".", "x", ")", "/", "2", ",", "y", ":", "(", "prevPt", ".", "y", "+", "pt", ".", "y", ")", "/", "2", "}", ";", "p", ".", "quadraticCurveTo", "(", "prevPt", ".", "x", ",", "prevPt", ".", "y", ",", "midPt", ".", "x", ",", "midPt", ".", "y", ")", ";", "curvePt", "=", "pt", ";", "}", "else", "if", "(", "!", "prevPt", ".", "onCurve", "&&", "pt", ".", "onCurve", ")", "{", "// Previous point off-curve, this point on-curve.", "p", ".", "quadraticCurveTo", "(", "curvePt", ".", "x", ",", "curvePt", ".", "y", ",", "pt", ".", "x", ",", "pt", ".", "y", ")", ";", "curvePt", "=", "null", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Invalid state.'", ")", ";", "}", "}", "if", "(", "firstPt", "!==", "lastPt", ")", "{", "// Connect the last and first points", "if", "(", "curvePt", ")", "{", "p", ".", "quadraticCurveTo", "(", "curvePt", ".", "x", ",", "curvePt", ".", "y", ",", "firstPt", ".", "x", ",", "firstPt", ".", "y", ")", ";", "}", "else", "{", "p", ".", "lineTo", "(", "firstPt", ".", "x", ",", "firstPt", ".", "y", ")", ";", "}", "}", "}", "p", ".", "closePath", "(", ")", ";", "return", "p", ";", "}" ]
Convert the TrueType glyph outline to a Path.
[ "Convert", "the", "TrueType", "glyph", "outline", "to", "a", "Path", "." ]
4c8d2e2503f088ffbd61e613a23b9ff2e64d3489
https://github.com/YuhangGe/node-freetype/blob/4c8d2e2503f088ffbd61e613a23b9ff2e64d3489/lib/parse/glyf.js#L194-L257
47,910
YuhangGe/node-freetype
lib/parse/glyf.js
parseGlyfTable
function parseGlyfTable(data, start, loca) { var glyphs, i, j, offset, nextOffset, glyph, component, componentGlyph, transformedPoints; glyphs = []; // The last element of the loca table is invalid. for (i = 0; i < loca.length - 1; i += 1) { offset = loca[i]; nextOffset = loca[i + 1]; // console.log('pg: ', offset, nextOffset); if (offset !== nextOffset) { glyphs.push(parseGlyph(data, i, start + offset)); } else { glyphs.push(new Glyph(i)); } } // console.log(start); // Go over the glyphs again, resolving the composite glyphs. for (i = 0; i < glyphs.length; i += 1) { glyph = glyphs[i]; if (glyph.isComposite) { for (j = 0; j < glyph.components.length; j += 1) { component = glyph.components[j]; componentGlyph = glyphs[component.glyphIndex]; if (componentGlyph.points) { transformedPoints = transformPoints(componentGlyph.points, component); glyph.points = glyph.points.concat(transformedPoints); } } } glyph.path = getPath(glyph.points); } return glyphs; }
javascript
function parseGlyfTable(data, start, loca) { var glyphs, i, j, offset, nextOffset, glyph, component, componentGlyph, transformedPoints; glyphs = []; // The last element of the loca table is invalid. for (i = 0; i < loca.length - 1; i += 1) { offset = loca[i]; nextOffset = loca[i + 1]; // console.log('pg: ', offset, nextOffset); if (offset !== nextOffset) { glyphs.push(parseGlyph(data, i, start + offset)); } else { glyphs.push(new Glyph(i)); } } // console.log(start); // Go over the glyphs again, resolving the composite glyphs. for (i = 0; i < glyphs.length; i += 1) { glyph = glyphs[i]; if (glyph.isComposite) { for (j = 0; j < glyph.components.length; j += 1) { component = glyph.components[j]; componentGlyph = glyphs[component.glyphIndex]; if (componentGlyph.points) { transformedPoints = transformPoints(componentGlyph.points, component); glyph.points = glyph.points.concat(transformedPoints); } } } glyph.path = getPath(glyph.points); } return glyphs; }
[ "function", "parseGlyfTable", "(", "data", ",", "start", ",", "loca", ")", "{", "var", "glyphs", ",", "i", ",", "j", ",", "offset", ",", "nextOffset", ",", "glyph", ",", "component", ",", "componentGlyph", ",", "transformedPoints", ";", "glyphs", "=", "[", "]", ";", "// The last element of the loca table is invalid.", "for", "(", "i", "=", "0", ";", "i", "<", "loca", ".", "length", "-", "1", ";", "i", "+=", "1", ")", "{", "offset", "=", "loca", "[", "i", "]", ";", "nextOffset", "=", "loca", "[", "i", "+", "1", "]", ";", "// console.log('pg: ', offset, nextOffset);", "if", "(", "offset", "!==", "nextOffset", ")", "{", "glyphs", ".", "push", "(", "parseGlyph", "(", "data", ",", "i", ",", "start", "+", "offset", ")", ")", ";", "}", "else", "{", "glyphs", ".", "push", "(", "new", "Glyph", "(", "i", ")", ")", ";", "}", "}", "// console.log(start);", "// Go over the glyphs again, resolving the composite glyphs.", "for", "(", "i", "=", "0", ";", "i", "<", "glyphs", ".", "length", ";", "i", "+=", "1", ")", "{", "glyph", "=", "glyphs", "[", "i", "]", ";", "if", "(", "glyph", ".", "isComposite", ")", "{", "for", "(", "j", "=", "0", ";", "j", "<", "glyph", ".", "components", ".", "length", ";", "j", "+=", "1", ")", "{", "component", "=", "glyph", ".", "components", "[", "j", "]", ";", "componentGlyph", "=", "glyphs", "[", "component", ".", "glyphIndex", "]", ";", "if", "(", "componentGlyph", ".", "points", ")", "{", "transformedPoints", "=", "transformPoints", "(", "componentGlyph", ".", "points", ",", "component", ")", ";", "glyph", ".", "points", "=", "glyph", ".", "points", ".", "concat", "(", "transformedPoints", ")", ";", "}", "}", "}", "glyph", ".", "path", "=", "getPath", "(", "glyph", ".", "points", ")", ";", "}", "return", "glyphs", ";", "}" ]
Parse all the glyphs according to the offsets from the `loca` table.
[ "Parse", "all", "the", "glyphs", "according", "to", "the", "offsets", "from", "the", "loca", "table", "." ]
4c8d2e2503f088ffbd61e613a23b9ff2e64d3489
https://github.com/YuhangGe/node-freetype/blob/4c8d2e2503f088ffbd61e613a23b9ff2e64d3489/lib/parse/glyf.js#L273-L305
47,911
oegea/soap_salesforce
salesforce.js
Salesforce
function Salesforce(username, password, token, wsdl) { //Required NodeJS libraries this.q = require("q"); this.soap = require("soap"); //Salesforce access data this.username = username; this.password = password; this.token = token; this.wsdl = wsdl || "./node_modules/soap_salesforce/wsdl/enterprise.xml"; //Other properties this.promise; //A promise will be used for returning soapClient after finishing Salesforce login this.soapClient; //Salesforce SOAP client instance will be stored here }
javascript
function Salesforce(username, password, token, wsdl) { //Required NodeJS libraries this.q = require("q"); this.soap = require("soap"); //Salesforce access data this.username = username; this.password = password; this.token = token; this.wsdl = wsdl || "./node_modules/soap_salesforce/wsdl/enterprise.xml"; //Other properties this.promise; //A promise will be used for returning soapClient after finishing Salesforce login this.soapClient; //Salesforce SOAP client instance will be stored here }
[ "function", "Salesforce", "(", "username", ",", "password", ",", "token", ",", "wsdl", ")", "{", "//Required NodeJS libraries", "this", ".", "q", "=", "require", "(", "\"q\"", ")", ";", "this", ".", "soap", "=", "require", "(", "\"soap\"", ")", ";", "//Salesforce access data", "this", ".", "username", "=", "username", ";", "this", ".", "password", "=", "password", ";", "this", ".", "token", "=", "token", ";", "this", ".", "wsdl", "=", "wsdl", "||", "\"./node_modules/soap_salesforce/wsdl/enterprise.xml\"", ";", "//Other properties", "this", ".", "promise", ";", "//A promise will be used for returning soapClient after finishing Salesforce login", "this", ".", "soapClient", ";", "//Salesforce SOAP client instance will be stored here", "}" ]
Salesforce connection library constructor.
[ "Salesforce", "connection", "library", "constructor", "." ]
2cfe10234f6d86c404faf61b730e6ec03d79bce5
https://github.com/oegea/soap_salesforce/blob/2cfe10234f6d86c404faf61b730e6ec03d79bce5/salesforce.js#L4-L19
47,912
digitalwm/cloudjs
modules/callbacks.js
AddCallback
function AddCallback(mesgId, callbackFunction, callbackTimeout) { var callbackElement, now; now = new Date().getTime(); callbackElement = { id : mesgId, func : callbackFunction, timeout : now + callbackTimeout }; callbackList.push(callbackElement); }
javascript
function AddCallback(mesgId, callbackFunction, callbackTimeout) { var callbackElement, now; now = new Date().getTime(); callbackElement = { id : mesgId, func : callbackFunction, timeout : now + callbackTimeout }; callbackList.push(callbackElement); }
[ "function", "AddCallback", "(", "mesgId", ",", "callbackFunction", ",", "callbackTimeout", ")", "{", "var", "callbackElement", ",", "now", ";", "now", "=", "new", "Date", "(", ")", ".", "getTime", "(", ")", ";", "callbackElement", "=", "{", "id", ":", "mesgId", ",", "func", ":", "callbackFunction", ",", "timeout", ":", "now", "+", "callbackTimeout", "}", ";", "callbackList", ".", "push", "(", "callbackElement", ")", ";", "}" ]
Add a callback for a specific message ID @param string mesgId @param function callbackFunction @param number callbackTimeout
[ "Add", "a", "callback", "for", "a", "specific", "message", "ID" ]
96f9394d939f8369c7a1acc03815f43e882adba2
https://github.com/digitalwm/cloudjs/blob/96f9394d939f8369c7a1acc03815f43e882adba2/modules/callbacks.js#L47-L59
47,913
digitalwm/cloudjs
modules/callbacks.js
ParseReply
function ParseReply(mesgId, data, sid) { var i; for(i = 0 ; i < callbackList.length ; i++) { if(callbackList[i].id.toString() === mesgId.toString() ) { callbackList[i].func(data, sid); } } }
javascript
function ParseReply(mesgId, data, sid) { var i; for(i = 0 ; i < callbackList.length ; i++) { if(callbackList[i].id.toString() === mesgId.toString() ) { callbackList[i].func(data, sid); } } }
[ "function", "ParseReply", "(", "mesgId", ",", "data", ",", "sid", ")", "{", "var", "i", ";", "for", "(", "i", "=", "0", ";", "i", "<", "callbackList", ".", "length", ";", "i", "++", ")", "{", "if", "(", "callbackList", "[", "i", "]", ".", "id", ".", "toString", "(", ")", "===", "mesgId", ".", "toString", "(", ")", ")", "{", "callbackList", "[", "i", "]", ".", "func", "(", "data", ",", "sid", ")", ";", "}", "}", "}" ]
Calls all the saved callbacks for a specific message ID @param string mesgId @param object data
[ "Calls", "all", "the", "saved", "callbacks", "for", "a", "specific", "message", "ID" ]
96f9394d939f8369c7a1acc03815f43e882adba2
https://github.com/digitalwm/cloudjs/blob/96f9394d939f8369c7a1acc03815f43e882adba2/modules/callbacks.js#L66-L74
47,914
digitalwm/cloudjs
modules/callbacks.js
GetOnEvent
function GetOnEvent(title) { var retList, i; retList = []; for(i = 0 ; i < onList.length ; i++) { if(onList[i].event.toString() === title.toString()) { retList.push(onList[i].callback); } } return retList; }
javascript
function GetOnEvent(title) { var retList, i; retList = []; for(i = 0 ; i < onList.length ; i++) { if(onList[i].event.toString() === title.toString()) { retList.push(onList[i].callback); } } return retList; }
[ "function", "GetOnEvent", "(", "title", ")", "{", "var", "retList", ",", "i", ";", "retList", "=", "[", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "onList", ".", "length", ";", "i", "++", ")", "{", "if", "(", "onList", "[", "i", "]", ".", "event", ".", "toString", "(", ")", "===", "title", ".", "toString", "(", ")", ")", "{", "retList", ".", "push", "(", "onList", "[", "i", "]", ".", "callback", ")", ";", "}", "}", "return", "retList", ";", "}" ]
Gets a list of callbacks for a requested event @param string title @return array
[ "Gets", "a", "list", "of", "callbacks", "for", "a", "requested", "event" ]
96f9394d939f8369c7a1acc03815f43e882adba2
https://github.com/digitalwm/cloudjs/blob/96f9394d939f8369c7a1acc03815f43e882adba2/modules/callbacks.js#L93-L103
47,915
BladeRunnerJS/topiarist
src/msg.js
msg
function msg(str) { if (str == null) { return null; } for (var i = 1, len = arguments.length; i < len; ++i) { str = str.replace('{' + (i - 1) + '}', String(arguments[i])); } return str; }
javascript
function msg(str) { if (str == null) { return null; } for (var i = 1, len = arguments.length; i < len; ++i) { str = str.replace('{' + (i - 1) + '}', String(arguments[i])); } return str; }
[ "function", "msg", "(", "str", ")", "{", "if", "(", "str", "==", "null", ")", "{", "return", "null", ";", "}", "for", "(", "var", "i", "=", "1", ",", "len", "=", "arguments", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "str", "=", "str", ".", "replace", "(", "'{'", "+", "(", "i", "-", "1", ")", "+", "'}'", ",", "String", "(", "arguments", "[", "i", "]", ")", ")", ";", "}", "return", "str", ";", "}" ]
Interpolates a string with the arguments, used for error messages. @private
[ "Interpolates", "a", "string", "with", "the", "arguments", "used", "for", "error", "messages", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/msg.js#L7-L17
47,916
i5ting/tpl_apply
index.js
tpl_apply_with_register_helper
function tpl_apply_with_register_helper(Handlebars, template_path, data_obj, dest_file_path) { var rs = fs.createReadStream(template_path, {bufferSize: 11}); var bufferHelper = new BufferHelper(); rs.on("data", function (trunk){ bufferHelper.concat(trunk); }); rs.on("end", function () { var source = bufferHelper.toBuffer().toString('utf8'); var template = Handlebars.compile(source); // log(template); var content = template(data_obj); fs.writeFile(dest_file_path, content , function (err) { if (err) throw err; log('It\'s saved!'); }); }); }
javascript
function tpl_apply_with_register_helper(Handlebars, template_path, data_obj, dest_file_path) { var rs = fs.createReadStream(template_path, {bufferSize: 11}); var bufferHelper = new BufferHelper(); rs.on("data", function (trunk){ bufferHelper.concat(trunk); }); rs.on("end", function () { var source = bufferHelper.toBuffer().toString('utf8'); var template = Handlebars.compile(source); // log(template); var content = template(data_obj); fs.writeFile(dest_file_path, content , function (err) { if (err) throw err; log('It\'s saved!'); }); }); }
[ "function", "tpl_apply_with_register_helper", "(", "Handlebars", ",", "template_path", ",", "data_obj", ",", "dest_file_path", ")", "{", "var", "rs", "=", "fs", ".", "createReadStream", "(", "template_path", ",", "{", "bufferSize", ":", "11", "}", ")", ";", "var", "bufferHelper", "=", "new", "BufferHelper", "(", ")", ";", "rs", ".", "on", "(", "\"data\"", ",", "function", "(", "trunk", ")", "{", "bufferHelper", ".", "concat", "(", "trunk", ")", ";", "}", ")", ";", "rs", ".", "on", "(", "\"end\"", ",", "function", "(", ")", "{", "var", "source", "=", "bufferHelper", ".", "toBuffer", "(", ")", ".", "toString", "(", "'utf8'", ")", ";", "var", "template", "=", "Handlebars", ".", "compile", "(", "source", ")", ";", "// log(template);", "var", "content", "=", "template", "(", "data_obj", ")", ";", "fs", ".", "writeFile", "(", "dest_file_path", ",", "content", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "log", "(", "'It\\'s saved!'", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Custom with helpers
[ "Custom", "with", "helpers" ]
eb2e0f91035f68a94e5fe049058f13d94b35710e
https://github.com/i5ting/tpl_apply/blob/eb2e0f91035f68a94e5fe049058f13d94b35710e/index.js#L22-L44
47,917
reelyactive/chickadee
lib/associationmanager.js
AssociationManager
function AssociationManager(options) { var self = this; self.associationsRootUrl = options.associationsRootUrl || SNIFFYPEDIA_ROOT_URL; var datafolder = options.persistentDataFolder || DEFAULT_DATA_FOLDER; var filename = ASSOCIATION_DB; if(options.persistentDataFolder !== '') { filename = datafolder.concat('/' + filename); } self.db = new nedb({ filename: filename, autoload: true }); self.db.insert(TEST_TRANSMITTER); self.db.insert(TEST_RECEIVER_0); self.db.insert(TEST_RECEIVER_1); self.db.insert(TEST_RECEIVER_2); self.db.insert(TEST_RECEIVER_3); }
javascript
function AssociationManager(options) { var self = this; self.associationsRootUrl = options.associationsRootUrl || SNIFFYPEDIA_ROOT_URL; var datafolder = options.persistentDataFolder || DEFAULT_DATA_FOLDER; var filename = ASSOCIATION_DB; if(options.persistentDataFolder !== '') { filename = datafolder.concat('/' + filename); } self.db = new nedb({ filename: filename, autoload: true }); self.db.insert(TEST_TRANSMITTER); self.db.insert(TEST_RECEIVER_0); self.db.insert(TEST_RECEIVER_1); self.db.insert(TEST_RECEIVER_2); self.db.insert(TEST_RECEIVER_3); }
[ "function", "AssociationManager", "(", "options", ")", "{", "var", "self", "=", "this", ";", "self", ".", "associationsRootUrl", "=", "options", ".", "associationsRootUrl", "||", "SNIFFYPEDIA_ROOT_URL", ";", "var", "datafolder", "=", "options", ".", "persistentDataFolder", "||", "DEFAULT_DATA_FOLDER", ";", "var", "filename", "=", "ASSOCIATION_DB", ";", "if", "(", "options", ".", "persistentDataFolder", "!==", "''", ")", "{", "filename", "=", "datafolder", ".", "concat", "(", "'/'", "+", "filename", ")", ";", "}", "self", ".", "db", "=", "new", "nedb", "(", "{", "filename", ":", "filename", ",", "autoload", ":", "true", "}", ")", ";", "self", ".", "db", ".", "insert", "(", "TEST_TRANSMITTER", ")", ";", "self", ".", "db", ".", "insert", "(", "TEST_RECEIVER_0", ")", ";", "self", ".", "db", ".", "insert", "(", "TEST_RECEIVER_1", ")", ";", "self", ".", "db", ".", "insert", "(", "TEST_RECEIVER_2", ")", ";", "self", ".", "db", ".", "insert", "(", "TEST_RECEIVER_3", ")", ";", "}" ]
AssociationManager Class Manages the association of identifiers with URLs @param {Object} options The options as a JSON object. @constructor
[ "AssociationManager", "Class", "Manages", "the", "association", "of", "identifiers", "with", "URLs" ]
1f65c2d369694d93796aae63318fa76326275120
https://github.com/reelyactive/chickadee/blob/1f65c2d369694d93796aae63318fa76326275120/lib/associationmanager.js#L36-L53
47,918
reelyactive/chickadee
lib/associationmanager.js
getAssociations
function getAssociations(instance, ids, callback) { instance.db.find({ _id: { $in: ids } }, function(err, associations) { for(var cAssociation = 0; cAssociation < associations.length; cAssociation++) { associations[cAssociation].deviceId = associations[cAssociation]._id; } callback(err, associations); }); }
javascript
function getAssociations(instance, ids, callback) { instance.db.find({ _id: { $in: ids } }, function(err, associations) { for(var cAssociation = 0; cAssociation < associations.length; cAssociation++) { associations[cAssociation].deviceId = associations[cAssociation]._id; } callback(err, associations); }); }
[ "function", "getAssociations", "(", "instance", ",", "ids", ",", "callback", ")", "{", "instance", ".", "db", ".", "find", "(", "{", "_id", ":", "{", "$in", ":", "ids", "}", "}", ",", "function", "(", "err", ",", "associations", ")", "{", "for", "(", "var", "cAssociation", "=", "0", ";", "cAssociation", "<", "associations", ".", "length", ";", "cAssociation", "++", ")", "{", "associations", "[", "cAssociation", "]", ".", "deviceId", "=", "associations", "[", "cAssociation", "]", ".", "_id", ";", "}", "callback", "(", "err", ",", "associations", ")", ";", "}", ")", ";", "}" ]
Retrieve from the database the associations of the given ids @param {Object} instance The given Chickadee instance. @param {Array} ids The given ids. @param {function} callback Function to call on completion.
[ "Retrieve", "from", "the", "database", "the", "associations", "of", "the", "given", "ids" ]
1f65c2d369694d93796aae63318fa76326275120
https://github.com/reelyactive/chickadee/blob/1f65c2d369694d93796aae63318fa76326275120/lib/associationmanager.js#L91-L99
47,919
reelyactive/chickadee
lib/associationmanager.js
extractRadioDecoders
function extractRadioDecoders(devices) { var radioDecoders = {}; for(var deviceId in devices) { var radioDecodings = devices[deviceId].radioDecodings || []; for(var cDecoding = 0; cDecoding < radioDecodings.length; cDecoding++) { var radioDecoder = radioDecodings[cDecoding].identifier; var radioDecoderId = radioDecoder.value; radioDecoders[radioDecoderId] = { identifier: radioDecoder }; } } return radioDecoders; }
javascript
function extractRadioDecoders(devices) { var radioDecoders = {}; for(var deviceId in devices) { var radioDecodings = devices[deviceId].radioDecodings || []; for(var cDecoding = 0; cDecoding < radioDecodings.length; cDecoding++) { var radioDecoder = radioDecodings[cDecoding].identifier; var radioDecoderId = radioDecoder.value; radioDecoders[radioDecoderId] = { identifier: radioDecoder }; } } return radioDecoders; }
[ "function", "extractRadioDecoders", "(", "devices", ")", "{", "var", "radioDecoders", "=", "{", "}", ";", "for", "(", "var", "deviceId", "in", "devices", ")", "{", "var", "radioDecodings", "=", "devices", "[", "deviceId", "]", ".", "radioDecodings", "||", "[", "]", ";", "for", "(", "var", "cDecoding", "=", "0", ";", "cDecoding", "<", "radioDecodings", ".", "length", ";", "cDecoding", "++", ")", "{", "var", "radioDecoder", "=", "radioDecodings", "[", "cDecoding", "]", ".", "identifier", ";", "var", "radioDecoderId", "=", "radioDecoder", ".", "value", ";", "radioDecoders", "[", "radioDecoderId", "]", "=", "{", "identifier", ":", "radioDecoder", "}", ";", "}", "}", "return", "radioDecoders", ";", "}" ]
Extract the radio decoders from the given list of devices. @param {Object} devices The given devices.
[ "Extract", "the", "radio", "decoders", "from", "the", "given", "list", "of", "devices", "." ]
1f65c2d369694d93796aae63318fa76326275120
https://github.com/reelyactive/chickadee/blob/1f65c2d369694d93796aae63318fa76326275120/lib/associationmanager.js#L502-L515
47,920
reelyactive/chickadee
lib/associationmanager.js
extractAssociationIds
function extractAssociationIds(devices) { var associationIds = []; for(var deviceId in devices) { var device = devices[deviceId]; var hasAssociationIds = device.hasOwnProperty("associationIds"); if(!hasAssociationIds) { device.associationIds = reelib.tiraid.getAssociationIds(device); } for(var cId = 0; cId < device.associationIds.length; cId++) { if(associationIds.indexOf(device.associationIds[cId]) < 0) { associationIds.push(device.associationIds[cId]); } } } return associationIds; }
javascript
function extractAssociationIds(devices) { var associationIds = []; for(var deviceId in devices) { var device = devices[deviceId]; var hasAssociationIds = device.hasOwnProperty("associationIds"); if(!hasAssociationIds) { device.associationIds = reelib.tiraid.getAssociationIds(device); } for(var cId = 0; cId < device.associationIds.length; cId++) { if(associationIds.indexOf(device.associationIds[cId]) < 0) { associationIds.push(device.associationIds[cId]); } } } return associationIds; }
[ "function", "extractAssociationIds", "(", "devices", ")", "{", "var", "associationIds", "=", "[", "]", ";", "for", "(", "var", "deviceId", "in", "devices", ")", "{", "var", "device", "=", "devices", "[", "deviceId", "]", ";", "var", "hasAssociationIds", "=", "device", ".", "hasOwnProperty", "(", "\"associationIds\"", ")", ";", "if", "(", "!", "hasAssociationIds", ")", "{", "device", ".", "associationIds", "=", "reelib", ".", "tiraid", ".", "getAssociationIds", "(", "device", ")", ";", "}", "for", "(", "var", "cId", "=", "0", ";", "cId", "<", "device", ".", "associationIds", ".", "length", ";", "cId", "++", ")", "{", "if", "(", "associationIds", ".", "indexOf", "(", "device", ".", "associationIds", "[", "cId", "]", ")", "<", "0", ")", "{", "associationIds", ".", "push", "(", "device", ".", "associationIds", "[", "cId", "]", ")", ";", "}", "}", "}", "return", "associationIds", ";", "}" ]
Extract all non-duplicate association ids from the given list of devices, adding an assocationIds field to each device when absent. @param {Object} devices The given devices. @return {Array} Non-duplicate association identifiers.
[ "Extract", "all", "non", "-", "duplicate", "association", "ids", "from", "the", "given", "list", "of", "devices", "adding", "an", "assocationIds", "field", "to", "each", "device", "when", "absent", "." ]
1f65c2d369694d93796aae63318fa76326275120
https://github.com/reelyactive/chickadee/blob/1f65c2d369694d93796aae63318fa76326275120/lib/associationmanager.js#L524-L541
47,921
fibo/laplace-determinant
laplace-determinant.js
subMatrix
function subMatrix (data, numRows, numCols, row, col) { var sub = [] for (var i = 0; i < numRows; i++) { for (var j = 0; j < numCols; j++) { if ((i !== row) && (j !== col)) { sub.push(data[matrixToArrayIndex(i, j, numCols)]) } } } return sub }
javascript
function subMatrix (data, numRows, numCols, row, col) { var sub = [] for (var i = 0; i < numRows; i++) { for (var j = 0; j < numCols; j++) { if ((i !== row) && (j !== col)) { sub.push(data[matrixToArrayIndex(i, j, numCols)]) } } } return sub }
[ "function", "subMatrix", "(", "data", ",", "numRows", ",", "numCols", ",", "row", ",", "col", ")", "{", "var", "sub", "=", "[", "]", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numRows", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "numCols", ";", "j", "++", ")", "{", "if", "(", "(", "i", "!==", "row", ")", "&&", "(", "j", "!==", "col", ")", ")", "{", "sub", ".", "push", "(", "data", "[", "matrixToArrayIndex", "(", "i", ",", "j", ",", "numCols", ")", "]", ")", "}", "}", "}", "return", "sub", "}" ]
Compute the sub-matrix formed by deleting the i-th row and j-th column @function @param {Array} data set @param {Number} numRows @param {Number} numCols @param {Number} row index deleted @param {Number} col index deleted @returns {Array} sub data-set
[ "Compute", "the", "sub", "-", "matrix", "formed", "by", "deleting", "the", "i", "-", "th", "row", "and", "j", "-", "th", "column" ]
b66ff70e932a7131639f8d6a57eaeb8c7eaf1d6f
https://github.com/fibo/laplace-determinant/blob/b66ff70e932a7131639f8d6a57eaeb8c7eaf1d6f/laplace-determinant.js#L32-L44
47,922
fibo/laplace-determinant
laplace-determinant.js
determinant
function determinant (data, scalar, order) { // Recursion will stop here: // the determinant of a 1x1 matrix is its only element. if (data.length === 1) return data[0] if (no(order)) order = Math.sqrt(data.length) if (order % 1 !== 0) { throw new TypeError('data.lenght must be a square') } // Default to common real number field. if (no(scalar)) { scalar = { addition: function (a, b) { return a + b }, multiplication: function (a, b) { return a * b }, negation: function (a) { return -a } } } var det // TODO choose best row or column to start from, i.e. the one with more zeros // by now we start from first row, and walk by column // needs scalar.isZero // // is scalar.isZero is a function will be used, but should remain optional var startingRow = 0 for (var col = 0; col < order; col++) { var subData = subMatrix(data, order, order, startingRow, col) // +-- Recursion here. // ↓ var cofactor = determinant(subData, scalar, order - 1) if ((startingRow + col) % 2 === 1) { cofactor = scalar.negation(cofactor) } var index = matrixToArrayIndex(startingRow, col, order) if (no(det)) { det = scalar.multiplication(data[index], cofactor) // first iteration } else { det = scalar.addition(det, scalar.multiplication(data[index], cofactor)) } } return det }
javascript
function determinant (data, scalar, order) { // Recursion will stop here: // the determinant of a 1x1 matrix is its only element. if (data.length === 1) return data[0] if (no(order)) order = Math.sqrt(data.length) if (order % 1 !== 0) { throw new TypeError('data.lenght must be a square') } // Default to common real number field. if (no(scalar)) { scalar = { addition: function (a, b) { return a + b }, multiplication: function (a, b) { return a * b }, negation: function (a) { return -a } } } var det // TODO choose best row or column to start from, i.e. the one with more zeros // by now we start from first row, and walk by column // needs scalar.isZero // // is scalar.isZero is a function will be used, but should remain optional var startingRow = 0 for (var col = 0; col < order; col++) { var subData = subMatrix(data, order, order, startingRow, col) // +-- Recursion here. // ↓ var cofactor = determinant(subData, scalar, order - 1) if ((startingRow + col) % 2 === 1) { cofactor = scalar.negation(cofactor) } var index = matrixToArrayIndex(startingRow, col, order) if (no(det)) { det = scalar.multiplication(data[index], cofactor) // first iteration } else { det = scalar.addition(det, scalar.multiplication(data[index], cofactor)) } } return det }
[ "function", "determinant", "(", "data", ",", "scalar", ",", "order", ")", "{", "// Recursion will stop here:", "// the determinant of a 1x1 matrix is its only element.", "if", "(", "data", ".", "length", "===", "1", ")", "return", "data", "[", "0", "]", "if", "(", "no", "(", "order", ")", ")", "order", "=", "Math", ".", "sqrt", "(", "data", ".", "length", ")", "if", "(", "order", "%", "1", "!==", "0", ")", "{", "throw", "new", "TypeError", "(", "'data.lenght must be a square'", ")", "}", "// Default to common real number field.", "if", "(", "no", "(", "scalar", ")", ")", "{", "scalar", "=", "{", "addition", ":", "function", "(", "a", ",", "b", ")", "{", "return", "a", "+", "b", "}", ",", "multiplication", ":", "function", "(", "a", ",", "b", ")", "{", "return", "a", "*", "b", "}", ",", "negation", ":", "function", "(", "a", ")", "{", "return", "-", "a", "}", "}", "}", "var", "det", "// TODO choose best row or column to start from, i.e. the one with more zeros", "// by now we start from first row, and walk by column", "// needs scalar.isZero", "//", "// is scalar.isZero is a function will be used, but should remain optional", "var", "startingRow", "=", "0", "for", "(", "var", "col", "=", "0", ";", "col", "<", "order", ";", "col", "++", ")", "{", "var", "subData", "=", "subMatrix", "(", "data", ",", "order", ",", "order", ",", "startingRow", ",", "col", ")", "// +-- Recursion here.", "// ↓", "var", "cofactor", "=", "determinant", "(", "subData", ",", "scalar", ",", "order", "-", "1", ")", "if", "(", "(", "startingRow", "+", "col", ")", "%", "2", "===", "1", ")", "{", "cofactor", "=", "scalar", ".", "negation", "(", "cofactor", ")", "}", "var", "index", "=", "matrixToArrayIndex", "(", "startingRow", ",", "col", ",", "order", ")", "if", "(", "no", "(", "det", ")", ")", "{", "det", "=", "scalar", ".", "multiplication", "(", "data", "[", "index", "]", ",", "cofactor", ")", "// first iteration", "}", "else", "{", "det", "=", "scalar", ".", "addition", "(", "det", ",", "scalar", ".", "multiplication", "(", "data", "[", "index", "]", ",", "cofactor", ")", ")", "}", "}", "return", "det", "}" ]
Computes the determinant of a matrix using Laplace's formula See https://en.wikipedia.org/wiki/Laplace_expansion @function @param {Array} data, lenght must be a square. @param {Object} [scalar] @param {Function} [scalar.addition = (a, b) -> a + b ] @param {Function} [scalar.multiplication = (a, b) -> a * b ] @param {Function} [scalar.negation = (a) -> -a ] @param {Number} [order], defaults to Math.sqrt(data.length) @returns {*} det
[ "Computes", "the", "determinant", "of", "a", "matrix", "using", "Laplace", "s", "formula" ]
b66ff70e932a7131639f8d6a57eaeb8c7eaf1d6f
https://github.com/fibo/laplace-determinant/blob/b66ff70e932a7131639f8d6a57eaeb8c7eaf1d6f/laplace-determinant.js#L63-L113
47,923
rtm/upward
src/Acc.js
notifyAccess
function notifyAccess({object, name}) { // Create an observer for changes in properties accessed during execution of this function. function makeAccessedObserver() { return Observer(object, function(changes) { changes.forEach(({type, name}) => { var {names} = accessEntry; if (!names || type === 'update' && names.indexOf(name) !== -1) rerun(); }); }); } // Make a new entry in the access table, containing initial property name if any // and observer for properties accessed on the object. function makeAccessEntry() { accesses.set(object, { names: name ? [name] : null, observer: makeAccessedObserver() }); } // If properties on this object are already being watched, there is already an entry // in the access table for it. Add a new property name to the existing entry. function setAccessEntry() { if (name && accessEntry.names) accessEntry.names.push(name); else accessEntry.names = null; } var accessEntry = accesses.get(object); if (accessEntry) setAccessEntry(); else makeAccessEntry(); }
javascript
function notifyAccess({object, name}) { // Create an observer for changes in properties accessed during execution of this function. function makeAccessedObserver() { return Observer(object, function(changes) { changes.forEach(({type, name}) => { var {names} = accessEntry; if (!names || type === 'update' && names.indexOf(name) !== -1) rerun(); }); }); } // Make a new entry in the access table, containing initial property name if any // and observer for properties accessed on the object. function makeAccessEntry() { accesses.set(object, { names: name ? [name] : null, observer: makeAccessedObserver() }); } // If properties on this object are already being watched, there is already an entry // in the access table for it. Add a new property name to the existing entry. function setAccessEntry() { if (name && accessEntry.names) accessEntry.names.push(name); else accessEntry.names = null; } var accessEntry = accesses.get(object); if (accessEntry) setAccessEntry(); else makeAccessEntry(); }
[ "function", "notifyAccess", "(", "{", "object", ",", "name", "}", ")", "{", "// Create an observer for changes in properties accessed during execution of this function.", "function", "makeAccessedObserver", "(", ")", "{", "return", "Observer", "(", "object", ",", "function", "(", "changes", ")", "{", "changes", ".", "forEach", "(", "(", "{", "type", ",", "name", "}", ")", "=>", "{", "var", "{", "names", "}", "=", "accessEntry", ";", "if", "(", "!", "names", "||", "type", "===", "'update'", "&&", "names", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ")", "rerun", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", "// Make a new entry in the access table, containing initial property name if any", "// and observer for properties accessed on the object.", "function", "makeAccessEntry", "(", ")", "{", "accesses", ".", "set", "(", "object", ",", "{", "names", ":", "name", "?", "[", "name", "]", ":", "null", ",", "observer", ":", "makeAccessedObserver", "(", ")", "}", ")", ";", "}", "// If properties on this object are already being watched, there is already an entry", "// in the access table for it. Add a new property name to the existing entry.", "function", "setAccessEntry", "(", ")", "{", "if", "(", "name", "&&", "accessEntry", ".", "names", ")", "accessEntry", ".", "names", ".", "push", "(", "name", ")", ";", "else", "accessEntry", ".", "names", "=", "null", ";", "}", "var", "accessEntry", "=", "accesses", ".", "get", "(", "object", ")", ";", "if", "(", "accessEntry", ")", "setAccessEntry", "(", ")", ";", "else", "makeAccessEntry", "(", ")", ";", "}" ]
`notifyAccess` is the callback invoked by upwardables when a property is accessed. It records the access in the `accesses` map.
[ "notifyAccess", "is", "the", "callback", "invoked", "by", "upwardables", "when", "a", "property", "is", "accessed", ".", "It", "records", "the", "access", "in", "the", "accesses", "map", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Acc.js#L68-L100
47,924
rtm/upward
src/Acc.js
makeAccessedObserver
function makeAccessedObserver() { return Observer(object, function(changes) { changes.forEach(({type, name}) => { var {names} = accessEntry; if (!names || type === 'update' && names.indexOf(name) !== -1) rerun(); }); }); }
javascript
function makeAccessedObserver() { return Observer(object, function(changes) { changes.forEach(({type, name}) => { var {names} = accessEntry; if (!names || type === 'update' && names.indexOf(name) !== -1) rerun(); }); }); }
[ "function", "makeAccessedObserver", "(", ")", "{", "return", "Observer", "(", "object", ",", "function", "(", "changes", ")", "{", "changes", ".", "forEach", "(", "(", "{", "type", ",", "name", "}", ")", "=>", "{", "var", "{", "names", "}", "=", "accessEntry", ";", "if", "(", "!", "names", "||", "type", "===", "'update'", "&&", "names", ".", "indexOf", "(", "name", ")", "!==", "-", "1", ")", "rerun", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Create an observer for changes in properties accessed during execution of this function.
[ "Create", "an", "observer", "for", "changes", "in", "properties", "accessed", "during", "execution", "of", "this", "function", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Acc.js#L71-L79
47,925
rtm/upward
src/Acc.js
makeAccessEntry
function makeAccessEntry() { accesses.set(object, { names: name ? [name] : null, observer: makeAccessedObserver() }); }
javascript
function makeAccessEntry() { accesses.set(object, { names: name ? [name] : null, observer: makeAccessedObserver() }); }
[ "function", "makeAccessEntry", "(", ")", "{", "accesses", ".", "set", "(", "object", ",", "{", "names", ":", "name", "?", "[", "name", "]", ":", "null", ",", "observer", ":", "makeAccessedObserver", "(", ")", "}", ")", ";", "}" ]
Make a new entry in the access table, containing initial property name if any and observer for properties accessed on the object.
[ "Make", "a", "new", "entry", "in", "the", "access", "table", "containing", "initial", "property", "name", "if", "any", "and", "observer", "for", "properties", "accessed", "on", "the", "object", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Acc.js#L83-L88
47,926
rtm/upward
src/Acc.js
setAccessEntry
function setAccessEntry() { if (name && accessEntry.names) accessEntry.names.push(name); else accessEntry.names = null; }
javascript
function setAccessEntry() { if (name && accessEntry.names) accessEntry.names.push(name); else accessEntry.names = null; }
[ "function", "setAccessEntry", "(", ")", "{", "if", "(", "name", "&&", "accessEntry", ".", "names", ")", "accessEntry", ".", "names", ".", "push", "(", "name", ")", ";", "else", "accessEntry", ".", "names", "=", "null", ";", "}" ]
If properties on this object are already being watched, there is already an entry in the access table for it. Add a new property name to the existing entry.
[ "If", "properties", "on", "this", "object", "are", "already", "being", "watched", "there", "is", "already", "an", "entry", "in", "the", "access", "table", "for", "it", ".", "Add", "a", "new", "property", "name", "to", "the", "existing", "entry", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Acc.js#L92-L95
47,927
smartface/sf-component-calendar
scripts/services/StyleContext.js
fromSFComponent
function fromSFComponent(component, name, initialClassNameMap) { var hooksList = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var flatted = {}; function collect(component, name, initialClassNameMap) { var newComp = makeStylable(component, initialClassNameMap(name), name, hooks(hooksList)); flat(name, newComp); component.children && Object.keys(component.children).forEach(function (child) { collect(component.children[child], name + "_" + child, initialClassNameMap); }); } function flat(name, comp) { flatted[name] = comp; } collect(component, name, initialClassNameMap); return createStyleContext(flatted, hooks(hooksList)); }
javascript
function fromSFComponent(component, name, initialClassNameMap) { var hooksList = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var flatted = {}; function collect(component, name, initialClassNameMap) { var newComp = makeStylable(component, initialClassNameMap(name), name, hooks(hooksList)); flat(name, newComp); component.children && Object.keys(component.children).forEach(function (child) { collect(component.children[child], name + "_" + child, initialClassNameMap); }); } function flat(name, comp) { flatted[name] = comp; } collect(component, name, initialClassNameMap); return createStyleContext(flatted, hooks(hooksList)); }
[ "function", "fromSFComponent", "(", "component", ",", "name", ",", "initialClassNameMap", ")", "{", "var", "hooksList", "=", "arguments", ".", "length", ">", "3", "&&", "arguments", "[", "3", "]", "!==", "undefined", "?", "arguments", "[", "3", "]", ":", "null", ";", "var", "flatted", "=", "{", "}", ";", "function", "collect", "(", "component", ",", "name", ",", "initialClassNameMap", ")", "{", "var", "newComp", "=", "makeStylable", "(", "component", ",", "initialClassNameMap", "(", "name", ")", ",", "name", ",", "hooks", "(", "hooksList", ")", ")", ";", "flat", "(", "name", ",", "newComp", ")", ";", "component", ".", "children", "&&", "Object", ".", "keys", "(", "component", ".", "children", ")", ".", "forEach", "(", "function", "(", "child", ")", "{", "collect", "(", "component", ".", "children", "[", "child", "]", ",", "name", "+", "\"_\"", "+", "child", ",", "initialClassNameMap", ")", ";", "}", ")", ";", "}", "function", "flat", "(", "name", ",", "comp", ")", "{", "flatted", "[", "name", "]", "=", "comp", ";", "}", "collect", "(", "component", ",", "name", ",", "initialClassNameMap", ")", ";", "return", "createStyleContext", "(", "flatted", ",", "hooks", "(", "hooksList", ")", ")", ";", "}" ]
Create styleContext tree from a SF Component and flat component tree to create actors @param {Object} component - A sf-core component @param {string} name - component name @param {function} initialClassNameMap - classNames mapping with specified component and children @param {?function} hookList - callback function to capture context's hooks @return {function} - context helper
[ "Create", "styleContext", "tree", "from", "a", "SF", "Component", "and", "flat", "component", "tree", "to", "create", "actors" ]
d6c8310564ff551b9424ac6955efa5e8cf5f8dff
https://github.com/smartface/sf-component-calendar/blob/d6c8310564ff551b9424ac6955efa5e8cf5f8dff/scripts/services/StyleContext.js#L43-L61
47,928
lpinca/sauce-browsers
index.js
filterByVersion
function filterByVersion(browsers, version) { version = String(version); if (version === 'latest' || version === 'oldest') { const filtered = numericVersions(browsers); const i = version === 'latest' ? filtered.length - 1 : 0; const value = filtered[i].short_version; return filtered.filter((el) => el.short_version === value); } const splits = version.split('..'); if (splits.length === 2) { const versions = browsers.map((el) => el.short_version); const start = splits[0]; const end = splits[1]; let startIndex = 0; let endIndex = browsers.length - 1; if (end === 'latest') endIndex = numericVersions(browsers).length - 1; else endIndex = versions.lastIndexOf(end); if (start < 0) startIndex = endIndex + Number(start); else if (start !== 'oldest') startIndex = versions.indexOf(start); if (startIndex < 0) { throw new Error(`Unable to find start version: ${start}`); } if (endIndex < 0) throw new Error(`Unable to find end version: ${end}`); return browsers.slice(startIndex, endIndex + 1); } return browsers.filter((el) => { return el.short_version === version || el.short_version === `${version}.0`; }); }
javascript
function filterByVersion(browsers, version) { version = String(version); if (version === 'latest' || version === 'oldest') { const filtered = numericVersions(browsers); const i = version === 'latest' ? filtered.length - 1 : 0; const value = filtered[i].short_version; return filtered.filter((el) => el.short_version === value); } const splits = version.split('..'); if (splits.length === 2) { const versions = browsers.map((el) => el.short_version); const start = splits[0]; const end = splits[1]; let startIndex = 0; let endIndex = browsers.length - 1; if (end === 'latest') endIndex = numericVersions(browsers).length - 1; else endIndex = versions.lastIndexOf(end); if (start < 0) startIndex = endIndex + Number(start); else if (start !== 'oldest') startIndex = versions.indexOf(start); if (startIndex < 0) { throw new Error(`Unable to find start version: ${start}`); } if (endIndex < 0) throw new Error(`Unable to find end version: ${end}`); return browsers.slice(startIndex, endIndex + 1); } return browsers.filter((el) => { return el.short_version === version || el.short_version === `${version}.0`; }); }
[ "function", "filterByVersion", "(", "browsers", ",", "version", ")", "{", "version", "=", "String", "(", "version", ")", ";", "if", "(", "version", "===", "'latest'", "||", "version", "===", "'oldest'", ")", "{", "const", "filtered", "=", "numericVersions", "(", "browsers", ")", ";", "const", "i", "=", "version", "===", "'latest'", "?", "filtered", ".", "length", "-", "1", ":", "0", ";", "const", "value", "=", "filtered", "[", "i", "]", ".", "short_version", ";", "return", "filtered", ".", "filter", "(", "(", "el", ")", "=>", "el", ".", "short_version", "===", "value", ")", ";", "}", "const", "splits", "=", "version", ".", "split", "(", "'..'", ")", ";", "if", "(", "splits", ".", "length", "===", "2", ")", "{", "const", "versions", "=", "browsers", ".", "map", "(", "(", "el", ")", "=>", "el", ".", "short_version", ")", ";", "const", "start", "=", "splits", "[", "0", "]", ";", "const", "end", "=", "splits", "[", "1", "]", ";", "let", "startIndex", "=", "0", ";", "let", "endIndex", "=", "browsers", ".", "length", "-", "1", ";", "if", "(", "end", "===", "'latest'", ")", "endIndex", "=", "numericVersions", "(", "browsers", ")", ".", "length", "-", "1", ";", "else", "endIndex", "=", "versions", ".", "lastIndexOf", "(", "end", ")", ";", "if", "(", "start", "<", "0", ")", "startIndex", "=", "endIndex", "+", "Number", "(", "start", ")", ";", "else", "if", "(", "start", "!==", "'oldest'", ")", "startIndex", "=", "versions", ".", "indexOf", "(", "start", ")", ";", "if", "(", "startIndex", "<", "0", ")", "{", "throw", "new", "Error", "(", "`", "${", "start", "}", "`", ")", ";", "}", "if", "(", "endIndex", "<", "0", ")", "throw", "new", "Error", "(", "`", "${", "end", "}", "`", ")", ";", "return", "browsers", ".", "slice", "(", "startIndex", ",", "endIndex", "+", "1", ")", ";", "}", "return", "browsers", ".", "filter", "(", "(", "el", ")", "=>", "{", "return", "el", ".", "short_version", "===", "version", "||", "el", ".", "short_version", "===", "`", "${", "version", "}", "`", ";", "}", ")", ";", "}" ]
Filter out entries whose version does not match a given version from a list of objects describing the OS and browser platforms on Sauce Labs. @param {Array} browsers The array to filter @param {(Number|String)} version The version to test against @return {Array} The filtered array @private
[ "Filter", "out", "entries", "whose", "version", "does", "not", "match", "a", "given", "version", "from", "a", "list", "of", "objects", "describing", "the", "OS", "and", "browser", "platforms", "on", "Sauce", "Labs", "." ]
3fe31c326971dd6cf025030664bbfb83ff9c9a3a
https://github.com/lpinca/sauce-browsers/blob/3fe31c326971dd6cf025030664bbfb83ff9c9a3a/index.js#L41-L78
47,929
lpinca/sauce-browsers
index.js
transform
function transform(wanted, available) { const browsers = new Set(); wanted.forEach((browser) => { const name = browser.name.toLowerCase(); if (!available.has(name)) { throw new Error(`Browser ${name} is not available`); } let list = available.get(name).slice().sort(compare); let platforms = browser.platform; if (platforms === undefined) { // // Remove all duplicate versions. // const filtered = [list[0]]; for (let i = 1; i < list.length; i++) { if (list[i].short_version !== list[i - 1].short_version) { filtered.push(list[i]); } } list = filtered; } else { if (!Array.isArray(platforms)) platforms = [platforms]; // // Filter out unwanted platforms. // platforms = platforms.map((el) => String(el).toLowerCase()); list = list.filter((el) => ~platforms.indexOf(el.os.toLowerCase())); } if (list.length === 0) return; let versions = browser.version; if (versions === undefined) { list.forEach((el) => browsers.add(el)); } else { if (!Array.isArray(versions)) versions = [versions]; versions.forEach((version) => { filterByVersion(list, version).forEach((el) => browsers.add(el)); }); } }); return Array.from(browsers); }
javascript
function transform(wanted, available) { const browsers = new Set(); wanted.forEach((browser) => { const name = browser.name.toLowerCase(); if (!available.has(name)) { throw new Error(`Browser ${name} is not available`); } let list = available.get(name).slice().sort(compare); let platforms = browser.platform; if (platforms === undefined) { // // Remove all duplicate versions. // const filtered = [list[0]]; for (let i = 1; i < list.length; i++) { if (list[i].short_version !== list[i - 1].short_version) { filtered.push(list[i]); } } list = filtered; } else { if (!Array.isArray(platforms)) platforms = [platforms]; // // Filter out unwanted platforms. // platforms = platforms.map((el) => String(el).toLowerCase()); list = list.filter((el) => ~platforms.indexOf(el.os.toLowerCase())); } if (list.length === 0) return; let versions = browser.version; if (versions === undefined) { list.forEach((el) => browsers.add(el)); } else { if (!Array.isArray(versions)) versions = [versions]; versions.forEach((version) => { filterByVersion(list, version).forEach((el) => browsers.add(el)); }); } }); return Array.from(browsers); }
[ "function", "transform", "(", "wanted", ",", "available", ")", "{", "const", "browsers", "=", "new", "Set", "(", ")", ";", "wanted", ".", "forEach", "(", "(", "browser", ")", "=>", "{", "const", "name", "=", "browser", ".", "name", ".", "toLowerCase", "(", ")", ";", "if", "(", "!", "available", ".", "has", "(", "name", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "name", "}", "`", ")", ";", "}", "let", "list", "=", "available", ".", "get", "(", "name", ")", ".", "slice", "(", ")", ".", "sort", "(", "compare", ")", ";", "let", "platforms", "=", "browser", ".", "platform", ";", "if", "(", "platforms", "===", "undefined", ")", "{", "//", "// Remove all duplicate versions.", "//", "const", "filtered", "=", "[", "list", "[", "0", "]", "]", ";", "for", "(", "let", "i", "=", "1", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "if", "(", "list", "[", "i", "]", ".", "short_version", "!==", "list", "[", "i", "-", "1", "]", ".", "short_version", ")", "{", "filtered", ".", "push", "(", "list", "[", "i", "]", ")", ";", "}", "}", "list", "=", "filtered", ";", "}", "else", "{", "if", "(", "!", "Array", ".", "isArray", "(", "platforms", ")", ")", "platforms", "=", "[", "platforms", "]", ";", "//", "// Filter out unwanted platforms.", "//", "platforms", "=", "platforms", ".", "map", "(", "(", "el", ")", "=>", "String", "(", "el", ")", ".", "toLowerCase", "(", ")", ")", ";", "list", "=", "list", ".", "filter", "(", "(", "el", ")", "=>", "~", "platforms", ".", "indexOf", "(", "el", ".", "os", ".", "toLowerCase", "(", ")", ")", ")", ";", "}", "if", "(", "list", ".", "length", "===", "0", ")", "return", ";", "let", "versions", "=", "browser", ".", "version", ";", "if", "(", "versions", "===", "undefined", ")", "{", "list", ".", "forEach", "(", "(", "el", ")", "=>", "browsers", ".", "add", "(", "el", ")", ")", ";", "}", "else", "{", "if", "(", "!", "Array", ".", "isArray", "(", "versions", ")", ")", "versions", "=", "[", "versions", "]", ";", "versions", ".", "forEach", "(", "(", "version", ")", "=>", "{", "filterByVersion", "(", "list", ",", "version", ")", ".", "forEach", "(", "(", "el", ")", "=>", "browsers", ".", "add", "(", "el", ")", ")", ";", "}", ")", ";", "}", "}", ")", ";", "return", "Array", ".", "from", "(", "browsers", ")", ";", "}" ]
Convert a list of platforms in "zuul" format to a list of platforms in the same format returned by Sauce Labs REST API. @param {Array} available The list of all supported platforms on Sauce Labs @param {Array} wanted The list of platforms in "zuul" format @return {Array} The transformed list @private
[ "Convert", "a", "list", "of", "platforms", "in", "zuul", "format", "to", "a", "list", "of", "platforms", "in", "the", "same", "format", "returned", "by", "Sauce", "Labs", "REST", "API", "." ]
3fe31c326971dd6cf025030664bbfb83ff9c9a3a
https://github.com/lpinca/sauce-browsers/blob/3fe31c326971dd6cf025030664bbfb83ff9c9a3a/index.js#L89-L137
47,930
lpinca/sauce-browsers
index.js
aggregate
function aggregate(browsers) { const map = new Map(); browsers.forEach((browser) => { const name = browser.api_name.toLowerCase(); let value = map.get(name); if (value === undefined) { value = []; map.set(name, value); } value.push(browser); }); const ie = map.get('internet explorer'); map.set('iexplore', ie).set('ie', ie); map.set('googlechrome', map.get('chrome')); return map; }
javascript
function aggregate(browsers) { const map = new Map(); browsers.forEach((browser) => { const name = browser.api_name.toLowerCase(); let value = map.get(name); if (value === undefined) { value = []; map.set(name, value); } value.push(browser); }); const ie = map.get('internet explorer'); map.set('iexplore', ie).set('ie', ie); map.set('googlechrome', map.get('chrome')); return map; }
[ "function", "aggregate", "(", "browsers", ")", "{", "const", "map", "=", "new", "Map", "(", ")", ";", "browsers", ".", "forEach", "(", "(", "browser", ")", "=>", "{", "const", "name", "=", "browser", ".", "api_name", ".", "toLowerCase", "(", ")", ";", "let", "value", "=", "map", ".", "get", "(", "name", ")", ";", "if", "(", "value", "===", "undefined", ")", "{", "value", "=", "[", "]", ";", "map", ".", "set", "(", "name", ",", "value", ")", ";", "}", "value", ".", "push", "(", "browser", ")", ";", "}", ")", ";", "const", "ie", "=", "map", ".", "get", "(", "'internet explorer'", ")", ";", "map", ".", "set", "(", "'iexplore'", ",", "ie", ")", ".", "set", "(", "'ie'", ",", "ie", ")", ";", "map", ".", "set", "(", "'googlechrome'", ",", "map", ".", "get", "(", "'chrome'", ")", ")", ";", "return", "map", ";", "}" ]
Aggregate a list of platforms by `api_name`. @param {Array} browsers The list of platforms supported on Sauce Labs @return {Map} Aggregated list @private
[ "Aggregate", "a", "list", "of", "platforms", "by", "api_name", "." ]
3fe31c326971dd6cf025030664bbfb83ff9c9a3a
https://github.com/lpinca/sauce-browsers/blob/3fe31c326971dd6cf025030664bbfb83ff9c9a3a/index.js#L146-L167
47,931
lpinca/sauce-browsers
index.js
sauceBrowsers
function sauceBrowsers(wanted) { return got({ path: '/rest/v1/info/platforms/webdriver', hostname: 'saucelabs.com', protocol: 'https:', json: true }).then((res) => { if (wanted === undefined) return res.body; return transform(wanted, aggregate(res.body)); }); }
javascript
function sauceBrowsers(wanted) { return got({ path: '/rest/v1/info/platforms/webdriver', hostname: 'saucelabs.com', protocol: 'https:', json: true }).then((res) => { if (wanted === undefined) return res.body; return transform(wanted, aggregate(res.body)); }); }
[ "function", "sauceBrowsers", "(", "wanted", ")", "{", "return", "got", "(", "{", "path", ":", "'/rest/v1/info/platforms/webdriver'", ",", "hostname", ":", "'saucelabs.com'", ",", "protocol", ":", "'https:'", ",", "json", ":", "true", "}", ")", ".", "then", "(", "(", "res", ")", "=>", "{", "if", "(", "wanted", "===", "undefined", ")", "return", "res", ".", "body", ";", "return", "transform", "(", "wanted", ",", "aggregate", "(", "res", ".", "body", ")", ")", ";", "}", ")", ";", "}" ]
Get a list of objects describing the OS and browser platforms on Sauce Labs using the "zuul" format. @param {Array} wanted The list of wanted platforms in "zuul" format @return {Promise} Promise which is fulfilled with the list @public
[ "Get", "a", "list", "of", "objects", "describing", "the", "OS", "and", "browser", "platforms", "on", "Sauce", "Labs", "using", "the", "zuul", "format", "." ]
3fe31c326971dd6cf025030664bbfb83ff9c9a3a
https://github.com/lpinca/sauce-browsers/blob/3fe31c326971dd6cf025030664bbfb83ff9c9a3a/index.js#L177-L188
47,932
oliversalzburg/absync
dist/development/absync.concat.js
AbsyncProvider
function AbsyncProvider( $provide, absyncCache ) { var self = this; // Store a reference to the provide provider. self.__provide = $provide; // Store a reference to the cache service constructor. self.__absyncCache = absyncCache; // A reference to the socket.io instance we're using to receive updates from the server. self.__ioSocket = null; // We usually register event listeners on the socket.io instance right away. // If socket.io was not connected when a service was constructed, we put the registration request // into this array and register it as soon as socket.io is configured. self.__registerLater = []; // References to all registered event listeners. self.__listeners = []; // The collections that absync provides. // The keys are the names of the collections, the value contains the constructor of // the respective cache service. self.__collections = {}; // The entities that absync provides. // The keys are the names of the entities, the value contains the constructor of // the respective cache service. self.__entities = {}; // Debug should either be set through a configure() call, or on instantiated services. self.debug = undefined; }
javascript
function AbsyncProvider( $provide, absyncCache ) { var self = this; // Store a reference to the provide provider. self.__provide = $provide; // Store a reference to the cache service constructor. self.__absyncCache = absyncCache; // A reference to the socket.io instance we're using to receive updates from the server. self.__ioSocket = null; // We usually register event listeners on the socket.io instance right away. // If socket.io was not connected when a service was constructed, we put the registration request // into this array and register it as soon as socket.io is configured. self.__registerLater = []; // References to all registered event listeners. self.__listeners = []; // The collections that absync provides. // The keys are the names of the collections, the value contains the constructor of // the respective cache service. self.__collections = {}; // The entities that absync provides. // The keys are the names of the entities, the value contains the constructor of // the respective cache service. self.__entities = {}; // Debug should either be set through a configure() call, or on instantiated services. self.debug = undefined; }
[ "function", "AbsyncProvider", "(", "$provide", ",", "absyncCache", ")", "{", "var", "self", "=", "this", ";", "// Store a reference to the provide provider.", "self", ".", "__provide", "=", "$provide", ";", "// Store a reference to the cache service constructor.", "self", ".", "__absyncCache", "=", "absyncCache", ";", "// A reference to the socket.io instance we're using to receive updates from the server.", "self", ".", "__ioSocket", "=", "null", ";", "// We usually register event listeners on the socket.io instance right away.", "// If socket.io was not connected when a service was constructed, we put the registration request", "// into this array and register it as soon as socket.io is configured.", "self", ".", "__registerLater", "=", "[", "]", ";", "// References to all registered event listeners.", "self", ".", "__listeners", "=", "[", "]", ";", "// The collections that absync provides.", "// The keys are the names of the collections, the value contains the constructor of", "// the respective cache service.", "self", ".", "__collections", "=", "{", "}", ";", "// The entities that absync provides.", "// The keys are the names of the entities, the value contains the constructor of", "// the respective cache service.", "self", ".", "__entities", "=", "{", "}", ";", "// Debug should either be set through a configure() call, or on instantiated services.", "self", ".", "debug", "=", "undefined", ";", "}" ]
Retrieves the absync provider. @param {angular.auto.IProvideService|Object} $provide The $provide provider. @param {Function} absyncCache The AbsyncCache service constructor. @constructor
[ "Retrieves", "the", "absync", "provider", "." ]
13807648d513c77008951446cfa1b334a2ab2ccf
https://github.com/oliversalzburg/absync/blob/13807648d513c77008951446cfa1b334a2ab2ccf/dist/development/absync.concat.js#L42-L71
47,933
oliversalzburg/absync
dist/development/absync.concat.js
onCollectionReceived
function onCollectionReceived( serverResponse ) { if( !serverResponse.data[ configuration.collectionName ] ) { throw new Error( "The response from the server was not in the expected format. It should have a member named '" + configuration.collectionName + "'." ); } self.__entityCacheRaw = serverResponse.data; self.entityCache.splice( 0, self.entityCache.length ); return self.__onDataAvailable( serverResponse.data ); }
javascript
function onCollectionReceived( serverResponse ) { if( !serverResponse.data[ configuration.collectionName ] ) { throw new Error( "The response from the server was not in the expected format. It should have a member named '" + configuration.collectionName + "'." ); } self.__entityCacheRaw = serverResponse.data; self.entityCache.splice( 0, self.entityCache.length ); return self.__onDataAvailable( serverResponse.data ); }
[ "function", "onCollectionReceived", "(", "serverResponse", ")", "{", "if", "(", "!", "serverResponse", ".", "data", "[", "configuration", ".", "collectionName", "]", ")", "{", "throw", "new", "Error", "(", "\"The response from the server was not in the expected format. It should have a member named '\"", "+", "configuration", ".", "collectionName", "+", "\"'.\"", ")", ";", "}", "self", ".", "__entityCacheRaw", "=", "serverResponse", ".", "data", ";", "self", ".", "entityCache", ".", "splice", "(", "0", ",", "self", ".", "entityCache", ".", "length", ")", ";", "return", "self", ".", "__onDataAvailable", "(", "serverResponse", ".", "data", ")", ";", "}" ]
Invoked when the collection was received from the server. @param {angular.IHttpPromiseCallbackArg|Object} serverResponse The reply sent from the server.
[ "Invoked", "when", "the", "collection", "was", "received", "from", "the", "server", "." ]
13807648d513c77008951446cfa1b334a2ab2ccf
https://github.com/oliversalzburg/absync/blob/13807648d513c77008951446cfa1b334a2ab2ccf/dist/development/absync.concat.js#L699-L707
47,934
oliversalzburg/absync
dist/development/absync.concat.js
onCollectionRetrievalFailure
function onCollectionRetrievalFailure( serverResponse ) { self.logInterface.error( self.logPrefix + "Unable to retrieve the collection from the server.", serverResponse ); self.__entityCacheRaw = null; self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
javascript
function onCollectionRetrievalFailure( serverResponse ) { self.logInterface.error( self.logPrefix + "Unable to retrieve the collection from the server.", serverResponse ); self.__entityCacheRaw = null; self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
[ "function", "onCollectionRetrievalFailure", "(", "serverResponse", ")", "{", "self", ".", "logInterface", ".", "error", "(", "self", ".", "logPrefix", "+", "\"Unable to retrieve the collection from the server.\"", ",", "serverResponse", ")", ";", "self", ".", "__entityCacheRaw", "=", "null", ";", "self", ".", "scope", ".", "$emit", "(", "\"absyncError\"", ",", "serverResponse", ")", ";", "if", "(", "self", ".", "throwFailures", ")", "{", "throw", "serverResponse", ";", "}", "}" ]
Invoked when there was an error while trying to retrieve the collection from the server. @param {angular.IHttpPromiseCallbackArg|Object} serverResponse The reply sent from the server.
[ "Invoked", "when", "there", "was", "an", "error", "while", "trying", "to", "retrieve", "the", "collection", "from", "the", "server", "." ]
13807648d513c77008951446cfa1b334a2ab2ccf
https://github.com/oliversalzburg/absync/blob/13807648d513c77008951446cfa1b334a2ab2ccf/dist/development/absync.concat.js#L713-L723
47,935
oliversalzburg/absync
dist/development/absync.concat.js
onSingleEntityReceived
function onSingleEntityReceived( serverResponse ) { if( !serverResponse.data[ configuration.entityName ] ) { throw new Error( "The response from the server was not in the expected format. It should have a member named '" + configuration.entityName + "'." ); } self.__entityCacheRaw = serverResponse.data; self.__onDataAvailable( serverResponse.data ); }
javascript
function onSingleEntityReceived( serverResponse ) { if( !serverResponse.data[ configuration.entityName ] ) { throw new Error( "The response from the server was not in the expected format. It should have a member named '" + configuration.entityName + "'." ); } self.__entityCacheRaw = serverResponse.data; self.__onDataAvailable( serverResponse.data ); }
[ "function", "onSingleEntityReceived", "(", "serverResponse", ")", "{", "if", "(", "!", "serverResponse", ".", "data", "[", "configuration", ".", "entityName", "]", ")", "{", "throw", "new", "Error", "(", "\"The response from the server was not in the expected format. It should have a member named '\"", "+", "configuration", ".", "entityName", "+", "\"'.\"", ")", ";", "}", "self", ".", "__entityCacheRaw", "=", "serverResponse", ".", "data", ";", "self", ".", "__onDataAvailable", "(", "serverResponse", ".", "data", ")", ";", "}" ]
Invoked when the entity was received from the server. @param {angular.IHttpPromiseCallbackArg|Object} serverResponse The reply sent from the server.
[ "Invoked", "when", "the", "entity", "was", "received", "from", "the", "server", "." ]
13807648d513c77008951446cfa1b334a2ab2ccf
https://github.com/oliversalzburg/absync/blob/13807648d513c77008951446cfa1b334a2ab2ccf/dist/development/absync.concat.js#L729-L736
47,936
oliversalzburg/absync
dist/development/absync.concat.js
onEntityRetrieved
function onEntityRetrieved( serverResponse ) { if( !serverResponse.data[ configuration.entityName ] ) { throw new Error( "The response from the server was not in the expected format. It should have a member named '" + configuration.entityName + "'." ); } var rawEntity = serverResponse.data[ configuration.entityName ]; // Put the raw entity into our raw entity cache. // We keep the raw copy to allow caching of the raw data. self.__cacheMaintain( self.__entityCacheRaw[ configuration.collectionName || configuration.entityName ], rawEntity, "update", false ); // Deserialize the object and place it into the cache. // We do not need to check here if the object already exists in the cache. // While it could be possible that the same entity is retrieved multiple times, __updateCacheWithEntity // will not insert duplicates into the cache. var deserialized = self.deserializer( rawEntity ); self.__updateCacheWithEntity( deserialized ); return deserialized; }
javascript
function onEntityRetrieved( serverResponse ) { if( !serverResponse.data[ configuration.entityName ] ) { throw new Error( "The response from the server was not in the expected format. It should have a member named '" + configuration.entityName + "'." ); } var rawEntity = serverResponse.data[ configuration.entityName ]; // Put the raw entity into our raw entity cache. // We keep the raw copy to allow caching of the raw data. self.__cacheMaintain( self.__entityCacheRaw[ configuration.collectionName || configuration.entityName ], rawEntity, "update", false ); // Deserialize the object and place it into the cache. // We do not need to check here if the object already exists in the cache. // While it could be possible that the same entity is retrieved multiple times, __updateCacheWithEntity // will not insert duplicates into the cache. var deserialized = self.deserializer( rawEntity ); self.__updateCacheWithEntity( deserialized ); return deserialized; }
[ "function", "onEntityRetrieved", "(", "serverResponse", ")", "{", "if", "(", "!", "serverResponse", ".", "data", "[", "configuration", ".", "entityName", "]", ")", "{", "throw", "new", "Error", "(", "\"The response from the server was not in the expected format. It should have a member named '\"", "+", "configuration", ".", "entityName", "+", "\"'.\"", ")", ";", "}", "var", "rawEntity", "=", "serverResponse", ".", "data", "[", "configuration", ".", "entityName", "]", ";", "// Put the raw entity into our raw entity cache.", "// We keep the raw copy to allow caching of the raw data.", "self", ".", "__cacheMaintain", "(", "self", ".", "__entityCacheRaw", "[", "configuration", ".", "collectionName", "||", "configuration", ".", "entityName", "]", ",", "rawEntity", ",", "\"update\"", ",", "false", ")", ";", "// Deserialize the object and place it into the cache.", "// We do not need to check here if the object already exists in the cache.", "// While it could be possible that the same entity is retrieved multiple times, __updateCacheWithEntity", "// will not insert duplicates into the cache.", "var", "deserialized", "=", "self", ".", "deserializer", "(", "rawEntity", ")", ";", "self", ".", "__updateCacheWithEntity", "(", "deserialized", ")", ";", "return", "deserialized", ";", "}" ]
Invoked when the entity was retrieved from the server. @param {angular.IHttpPromiseCallbackArg|Object} serverResponse The reply sent from the server.
[ "Invoked", "when", "the", "entity", "was", "retrieved", "from", "the", "server", "." ]
13807648d513c77008951446cfa1b334a2ab2ccf
https://github.com/oliversalzburg/absync/blob/13807648d513c77008951446cfa1b334a2ab2ccf/dist/development/absync.concat.js#L889-L910
47,937
oliversalzburg/absync
dist/development/absync.concat.js
onEntityRetrievalFailure
function onEntityRetrievalFailure( serverResponse ) { self.logInterface.error( self.logPrefix + "Unable to retrieve entity with ID '" + id + "' from the server.", serverResponse ); self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
javascript
function onEntityRetrievalFailure( serverResponse ) { self.logInterface.error( self.logPrefix + "Unable to retrieve entity with ID '" + id + "' from the server.", serverResponse ); self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
[ "function", "onEntityRetrievalFailure", "(", "serverResponse", ")", "{", "self", ".", "logInterface", ".", "error", "(", "self", ".", "logPrefix", "+", "\"Unable to retrieve entity with ID '\"", "+", "id", "+", "\"' from the server.\"", ",", "serverResponse", ")", ";", "self", ".", "scope", ".", "$emit", "(", "\"absyncError\"", ",", "serverResponse", ")", ";", "if", "(", "self", ".", "throwFailures", ")", "{", "throw", "serverResponse", ";", "}", "}" ]
Invoked when there was an error while trying to retrieve the entity from the server. @param {angular.IHttpPromiseCallbackArg|Object} serverResponse The reply sent from the server.
[ "Invoked", "when", "there", "was", "an", "error", "while", "trying", "to", "retrieve", "the", "entity", "from", "the", "server", "." ]
13807648d513c77008951446cfa1b334a2ab2ccf
https://github.com/oliversalzburg/absync/blob/13807648d513c77008951446cfa1b334a2ab2ccf/dist/development/absync.concat.js#L916-L924
47,938
oliversalzburg/absync
dist/development/absync.concat.js
afterEntityStored
function afterEntityStored( returnResult, serverResponse ) { var self = this; // Writing an entity to the backend will usually invoke an update event to be // broadcast over websockets, where we would also retrieve the updated record. // We still put the updated record we receive here into the cache to ensure early consistency, if that is requested. if( !returnResult && !self.forceEarlyCacheUpdate ) { return; } if( serverResponse.data[ configuration.entityName ] ) { var rawEntity = serverResponse.data[ configuration.entityName ]; // If early cache updates are forced, put the return entity into the cache. if( self.forceEarlyCacheUpdate ) { var newEntity = self.deserializer( rawEntity ); self.__updateCacheWithEntity( newEntity ); if( returnResult ) { return newEntity; } } if( returnResult ) { return rawEntity; } } }
javascript
function afterEntityStored( returnResult, serverResponse ) { var self = this; // Writing an entity to the backend will usually invoke an update event to be // broadcast over websockets, where we would also retrieve the updated record. // We still put the updated record we receive here into the cache to ensure early consistency, if that is requested. if( !returnResult && !self.forceEarlyCacheUpdate ) { return; } if( serverResponse.data[ configuration.entityName ] ) { var rawEntity = serverResponse.data[ configuration.entityName ]; // If early cache updates are forced, put the return entity into the cache. if( self.forceEarlyCacheUpdate ) { var newEntity = self.deserializer( rawEntity ); self.__updateCacheWithEntity( newEntity ); if( returnResult ) { return newEntity; } } if( returnResult ) { return rawEntity; } } }
[ "function", "afterEntityStored", "(", "returnResult", ",", "serverResponse", ")", "{", "var", "self", "=", "this", ";", "// Writing an entity to the backend will usually invoke an update event to be", "// broadcast over websockets, where we would also retrieve the updated record.", "// We still put the updated record we receive here into the cache to ensure early consistency, if that is requested.", "if", "(", "!", "returnResult", "&&", "!", "self", ".", "forceEarlyCacheUpdate", ")", "{", "return", ";", "}", "if", "(", "serverResponse", ".", "data", "[", "configuration", ".", "entityName", "]", ")", "{", "var", "rawEntity", "=", "serverResponse", ".", "data", "[", "configuration", ".", "entityName", "]", ";", "// If early cache updates are forced, put the return entity into the cache.", "if", "(", "self", ".", "forceEarlyCacheUpdate", ")", "{", "var", "newEntity", "=", "self", ".", "deserializer", "(", "rawEntity", ")", ";", "self", ".", "__updateCacheWithEntity", "(", "newEntity", ")", ";", "if", "(", "returnResult", ")", "{", "return", "newEntity", ";", "}", "}", "if", "(", "returnResult", ")", "{", "return", "rawEntity", ";", "}", "}", "}" ]
Invoked when the entity was stored on the server. @param {Boolean} returnResult Should we return the parsed entity that is contained in the response? @param {angular.IHttpPromiseCallbackArg|Object} serverResponse The reply sent from the server.
[ "Invoked", "when", "the", "entity", "was", "stored", "on", "the", "server", "." ]
13807648d513c77008951446cfa1b334a2ab2ccf
https://github.com/oliversalzburg/absync/blob/13807648d513c77008951446cfa1b334a2ab2ccf/dist/development/absync.concat.js#L1033-L1058
47,939
oliversalzburg/absync
dist/development/absync.concat.js
onEntityStorageFailure
function onEntityStorageFailure( serverResponse ) { var self = this; self.logInterface.error( self.logPrefix + "Unable to store entity on the server.", serverResponse ); self.logInterface.error( serverResponse ); self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
javascript
function onEntityStorageFailure( serverResponse ) { var self = this; self.logInterface.error( self.logPrefix + "Unable to store entity on the server.", serverResponse ); self.logInterface.error( serverResponse ); self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
[ "function", "onEntityStorageFailure", "(", "serverResponse", ")", "{", "var", "self", "=", "this", ";", "self", ".", "logInterface", ".", "error", "(", "self", ".", "logPrefix", "+", "\"Unable to store entity on the server.\"", ",", "serverResponse", ")", ";", "self", ".", "logInterface", ".", "error", "(", "serverResponse", ")", ";", "self", ".", "scope", ".", "$emit", "(", "\"absyncError\"", ",", "serverResponse", ")", ";", "if", "(", "self", ".", "throwFailures", ")", "{", "throw", "serverResponse", ";", "}", "}" ]
Invoked when there was an error while trying to store the entity on the server. @param {angular.IHttpPromiseCallbackArg|Object} serverResponse The reply sent from the server.
[ "Invoked", "when", "there", "was", "an", "error", "while", "trying", "to", "store", "the", "entity", "on", "the", "server", "." ]
13807648d513c77008951446cfa1b334a2ab2ccf
https://github.com/oliversalzburg/absync/blob/13807648d513c77008951446cfa1b334a2ab2ccf/dist/development/absync.concat.js#L1064-L1075
47,940
oliversalzburg/absync
dist/development/absync.concat.js
onEntityDeleted
function onEntityDeleted( serverResponse ) { self.__cacheMaintain( self.__entityCacheRaw[ configuration.collectionName || configuration.entityName ], entity, "delete", false ); return self.__removeEntityFromCache( entityId ); }
javascript
function onEntityDeleted( serverResponse ) { self.__cacheMaintain( self.__entityCacheRaw[ configuration.collectionName || configuration.entityName ], entity, "delete", false ); return self.__removeEntityFromCache( entityId ); }
[ "function", "onEntityDeleted", "(", "serverResponse", ")", "{", "self", ".", "__cacheMaintain", "(", "self", ".", "__entityCacheRaw", "[", "configuration", ".", "collectionName", "||", "configuration", ".", "entityName", "]", ",", "entity", ",", "\"delete\"", ",", "false", ")", ";", "return", "self", ".", "__removeEntityFromCache", "(", "entityId", ")", ";", "}" ]
Invoked when the entity was successfully deleted from the server. @param {angular.IHttpPromiseCallbackArg|Object} serverResponse The reply sent from the server.
[ "Invoked", "when", "the", "entity", "was", "successfully", "deleted", "from", "the", "server", "." ]
13807648d513c77008951446cfa1b334a2ab2ccf
https://github.com/oliversalzburg/absync/blob/13807648d513c77008951446cfa1b334a2ab2ccf/dist/development/absync.concat.js#L1094-L1101
47,941
oliversalzburg/absync
dist/development/absync.concat.js
onEntityDeletionFailed
function onEntityDeletionFailed( serverResponse ) { self.logInterface.error( serverResponse.data ); self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
javascript
function onEntityDeletionFailed( serverResponse ) { self.logInterface.error( serverResponse.data ); self.scope.$emit( "absyncError", serverResponse ); if( self.throwFailures ) { throw serverResponse; } }
[ "function", "onEntityDeletionFailed", "(", "serverResponse", ")", "{", "self", ".", "logInterface", ".", "error", "(", "serverResponse", ".", "data", ")", ";", "self", ".", "scope", ".", "$emit", "(", "\"absyncError\"", ",", "serverResponse", ")", ";", "if", "(", "self", ".", "throwFailures", ")", "{", "throw", "serverResponse", ";", "}", "}" ]
Invoked when there was an error while trying to delete the entity from the server. @param {angular.IHttpPromiseCallbackArg|Object} serverResponse The reply sent from the server.
[ "Invoked", "when", "there", "was", "an", "error", "while", "trying", "to", "delete", "the", "entity", "from", "the", "server", "." ]
13807648d513c77008951446cfa1b334a2ab2ccf
https://github.com/oliversalzburg/absync/blob/13807648d513c77008951446cfa1b334a2ab2ccf/dist/development/absync.concat.js#L1107-L1114
47,942
jhermsmeier/node-apple-data-compression
lib/decompress.js
decompress
function decompress( buffer ) { var chunks = [] var chunkType = ADC.CHUNK_UNKNOWN var position = 0 var length = 0 windowOffset = 0 while( position < buffer.length ) { chunkType = ADC.getChunkType( buffer[ position ] ) length = ADC.getSequenceLength( buffer[ position ] ) switch( chunkType ) { case ADC.CHUNK_DATA: chunks.push( decodeData( window, buffer, position ) ) break case ADC.CHUNK_THREE: chunks.push( decodeRunlength( window, buffer, position ) ) break case ADC.CHUNK_TWO: chunks.push( decodeRunlength( window, buffer, position ) ) break default: throw new Error( 'Unknown chunk type 0x' + buffer[ position ].toString(16) + ' at ' + position ) } position += length } return Buffer.concat( chunks ) }
javascript
function decompress( buffer ) { var chunks = [] var chunkType = ADC.CHUNK_UNKNOWN var position = 0 var length = 0 windowOffset = 0 while( position < buffer.length ) { chunkType = ADC.getChunkType( buffer[ position ] ) length = ADC.getSequenceLength( buffer[ position ] ) switch( chunkType ) { case ADC.CHUNK_DATA: chunks.push( decodeData( window, buffer, position ) ) break case ADC.CHUNK_THREE: chunks.push( decodeRunlength( window, buffer, position ) ) break case ADC.CHUNK_TWO: chunks.push( decodeRunlength( window, buffer, position ) ) break default: throw new Error( 'Unknown chunk type 0x' + buffer[ position ].toString(16) + ' at ' + position ) } position += length } return Buffer.concat( chunks ) }
[ "function", "decompress", "(", "buffer", ")", "{", "var", "chunks", "=", "[", "]", "var", "chunkType", "=", "ADC", ".", "CHUNK_UNKNOWN", "var", "position", "=", "0", "var", "length", "=", "0", "windowOffset", "=", "0", "while", "(", "position", "<", "buffer", ".", "length", ")", "{", "chunkType", "=", "ADC", ".", "getChunkType", "(", "buffer", "[", "position", "]", ")", "length", "=", "ADC", ".", "getSequenceLength", "(", "buffer", "[", "position", "]", ")", "switch", "(", "chunkType", ")", "{", "case", "ADC", ".", "CHUNK_DATA", ":", "chunks", ".", "push", "(", "decodeData", "(", "window", ",", "buffer", ",", "position", ")", ")", "break", "case", "ADC", ".", "CHUNK_THREE", ":", "chunks", ".", "push", "(", "decodeRunlength", "(", "window", ",", "buffer", ",", "position", ")", ")", "break", "case", "ADC", ".", "CHUNK_TWO", ":", "chunks", ".", "push", "(", "decodeRunlength", "(", "window", ",", "buffer", ",", "position", ")", ")", "break", "default", ":", "throw", "new", "Error", "(", "'Unknown chunk type 0x'", "+", "buffer", "[", "position", "]", ".", "toString", "(", "16", ")", "+", "' at '", "+", "position", ")", "}", "position", "+=", "length", "}", "return", "Buffer", ".", "concat", "(", "chunks", ")", "}" ]
Decompress an ADC compressed buffer @param {Buffer} buffer @returns {Buffer}
[ "Decompress", "an", "ADC", "compressed", "buffer" ]
914ad4625754d1c77b76345845b24227c8a55181
https://github.com/jhermsmeier/node-apple-data-compression/blob/914ad4625754d1c77b76345845b24227c8a55181/lib/decompress.js#L65-L95
47,943
scttnlsn/mongoose-denormalize
lib/index.js
function(schema, from) { return function(next) { var self = this; var funcs = []; for (var key in from) { var items = from[key]; var model = mongoose.model(schema.path(key).options.ref); funcs.push(function(callback) { model.findOne({ _id: self[key] }, function(err, instance) { if (err) return callback(err); items.forEach(function(item) { self[item.key] = instance[item.field]; }); callback(); }); }); } async.parallel(funcs, function(err) { if (err) return next(err); next(); }); }; }
javascript
function(schema, from) { return function(next) { var self = this; var funcs = []; for (var key in from) { var items = from[key]; var model = mongoose.model(schema.path(key).options.ref); funcs.push(function(callback) { model.findOne({ _id: self[key] }, function(err, instance) { if (err) return callback(err); items.forEach(function(item) { self[item.key] = instance[item.field]; }); callback(); }); }); } async.parallel(funcs, function(err) { if (err) return next(err); next(); }); }; }
[ "function", "(", "schema", ",", "from", ")", "{", "return", "function", "(", "next", ")", "{", "var", "self", "=", "this", ";", "var", "funcs", "=", "[", "]", ";", "for", "(", "var", "key", "in", "from", ")", "{", "var", "items", "=", "from", "[", "key", "]", ";", "var", "model", "=", "mongoose", ".", "model", "(", "schema", ".", "path", "(", "key", ")", ".", "options", ".", "ref", ")", ";", "funcs", ".", "push", "(", "function", "(", "callback", ")", "{", "model", ".", "findOne", "(", "{", "_id", ":", "self", "[", "key", "]", "}", ",", "function", "(", "err", ",", "instance", ")", "{", "if", "(", "err", ")", "return", "callback", "(", "err", ")", ";", "items", ".", "forEach", "(", "function", "(", "item", ")", "{", "self", "[", "item", ".", "key", "]", "=", "instance", "[", "item", ".", "field", "]", ";", "}", ")", ";", "callback", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", "async", ".", "parallel", "(", "funcs", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "return", "next", "(", "err", ")", ";", "next", "(", ")", ";", "}", ")", ";", "}", ";", "}" ]
Denormalize values from foreign refs into local model
[ "Denormalize", "values", "from", "foreign", "refs", "into", "local", "model" ]
81b7bf73412aff119bfc49020cf63be9933df547
https://github.com/scttnlsn/mongoose-denormalize/blob/81b7bf73412aff119bfc49020cf63be9933df547/lib/index.js#L5-L32
47,944
archilogic-com/instant-api
lib/json-rpc2-server.js
function (result) { // don't send a second response if (responseHasBeenSent) { console.warn('JSON-RPC2 response has already been sent.') return } // notifications should not send error responses (JSON-RPC2 specs) if (!isMethodCall) { logNotificationResponseWarning(result, requestMessage) callback() return } // result should not be undefined if (result === undefined) { console.warn('JSON-RPC2 response from method ' + methodName + ' should return a result. (JSON-RPC2 spec)') result = '' } var rpcMessage = { jsonrpc: '2.0', result: result, id: id } callback(rpcMessage) responseHasBeenSent = true }
javascript
function (result) { // don't send a second response if (responseHasBeenSent) { console.warn('JSON-RPC2 response has already been sent.') return } // notifications should not send error responses (JSON-RPC2 specs) if (!isMethodCall) { logNotificationResponseWarning(result, requestMessage) callback() return } // result should not be undefined if (result === undefined) { console.warn('JSON-RPC2 response from method ' + methodName + ' should return a result. (JSON-RPC2 spec)') result = '' } var rpcMessage = { jsonrpc: '2.0', result: result, id: id } callback(rpcMessage) responseHasBeenSent = true }
[ "function", "(", "result", ")", "{", "// don't send a second response", "if", "(", "responseHasBeenSent", ")", "{", "console", ".", "warn", "(", "'JSON-RPC2 response has already been sent.'", ")", "return", "}", "// notifications should not send error responses (JSON-RPC2 specs)", "if", "(", "!", "isMethodCall", ")", "{", "logNotificationResponseWarning", "(", "result", ",", "requestMessage", ")", "callback", "(", ")", "return", "}", "// result should not be undefined", "if", "(", "result", "===", "undefined", ")", "{", "console", ".", "warn", "(", "'JSON-RPC2 response from method '", "+", "methodName", "+", "' should return a result. (JSON-RPC2 spec)'", ")", "result", "=", "''", "}", "var", "rpcMessage", "=", "{", "jsonrpc", ":", "'2.0'", ",", "result", ":", "result", ",", "id", ":", "id", "}", "callback", "(", "rpcMessage", ")", "responseHasBeenSent", "=", "true", "}" ]
create send result handler
[ "create", "send", "result", "handler" ]
a47728312e283136a24933f250aabb0be867cb2f
https://github.com/archilogic-com/instant-api/blob/a47728312e283136a24933f250aabb0be867cb2f/lib/json-rpc2-server.js#L198-L227
47,945
archilogic-com/instant-api
lib/json-rpc2-server.js
function (method, result) { // result should not be undefined if (result === undefined) { console.warn('JSON-RPC2 response from method ' + methodName + ' should return a result. (JSON-RPC2 spec)') result = '' } var rpcMessage = { jsonrpc: '2.0', result: result, id: id } callback(rpcMessage) responseHasBeenSent = true }
javascript
function (method, result) { // result should not be undefined if (result === undefined) { console.warn('JSON-RPC2 response from method ' + methodName + ' should return a result. (JSON-RPC2 spec)') result = '' } var rpcMessage = { jsonrpc: '2.0', result: result, id: id } callback(rpcMessage) responseHasBeenSent = true }
[ "function", "(", "method", ",", "result", ")", "{", "// result should not be undefined", "if", "(", "result", "===", "undefined", ")", "{", "console", ".", "warn", "(", "'JSON-RPC2 response from method '", "+", "methodName", "+", "' should return a result. (JSON-RPC2 spec)'", ")", "result", "=", "''", "}", "var", "rpcMessage", "=", "{", "jsonrpc", ":", "'2.0'", ",", "result", ":", "result", ",", "id", ":", "id", "}", "callback", "(", "rpcMessage", ")", "responseHasBeenSent", "=", "true", "}" ]
create send message method
[ "create", "send", "message", "method" ]
a47728312e283136a24933f250aabb0be867cb2f
https://github.com/archilogic-com/instant-api/blob/a47728312e283136a24933f250aabb0be867cb2f/lib/json-rpc2-server.js#L230-L247
47,946
archilogic-com/instant-api
lib/json-rpc2-server.js
function (error, type) { // don't send a second response if (responseHasBeenSent) { console.warn('JSON-RPC2 response has already been sent.') return } // notifications should not send error responses (JSON-RPC2 specs) if (!isMethodCall) { var message = (error && error.toString) ? error.toString() : undefined logNotificationResponseWarning(message, requestMessage) callback() return } // internals var errorObject if (error instanceof Error) { // serious application error console.warn( 'Error in JSON-RPC2 method ' + methodName + ': ' + error.toString() + '\n' + error.stack ) // not sending detailed error info to not expose details about server code errorObject = { code: errorCodes['APPLICATION_ERROR'], message: errorMessages['APPLICATION_ERROR'] + ' (Check server logs for details)' } } else if (typeof error === 'string') { // error message errorObject = { code: errorCodes[type] || errorCodes['INVALID_REQUEST'], message: error } } else if (typeof error === 'object') { if (error.message) { // error object errorObject = error if (error.code === undefined) { error.code = errorCodes['INVALID_REQUEST'] } } else { // error data errorObject = { code: errorCodes[type] || errorCodes['INVALID_REQUEST'], message: errorMessages[type] || errorMessages['INVALID_REQUEST'], data: error } } } else { if (error !== undefined) { console.warn('Error parameter must be a string (error message) or object (error data)') } // fallback errorObject = errorObjects['INVALID_REQUEST'] } var rpcMessage = { jsonrpc: '2.0', error: errorObject, id: id } callback(rpcMessage) responseHasBeenSent = true }
javascript
function (error, type) { // don't send a second response if (responseHasBeenSent) { console.warn('JSON-RPC2 response has already been sent.') return } // notifications should not send error responses (JSON-RPC2 specs) if (!isMethodCall) { var message = (error && error.toString) ? error.toString() : undefined logNotificationResponseWarning(message, requestMessage) callback() return } // internals var errorObject if (error instanceof Error) { // serious application error console.warn( 'Error in JSON-RPC2 method ' + methodName + ': ' + error.toString() + '\n' + error.stack ) // not sending detailed error info to not expose details about server code errorObject = { code: errorCodes['APPLICATION_ERROR'], message: errorMessages['APPLICATION_ERROR'] + ' (Check server logs for details)' } } else if (typeof error === 'string') { // error message errorObject = { code: errorCodes[type] || errorCodes['INVALID_REQUEST'], message: error } } else if (typeof error === 'object') { if (error.message) { // error object errorObject = error if (error.code === undefined) { error.code = errorCodes['INVALID_REQUEST'] } } else { // error data errorObject = { code: errorCodes[type] || errorCodes['INVALID_REQUEST'], message: errorMessages[type] || errorMessages['INVALID_REQUEST'], data: error } } } else { if (error !== undefined) { console.warn('Error parameter must be a string (error message) or object (error data)') } // fallback errorObject = errorObjects['INVALID_REQUEST'] } var rpcMessage = { jsonrpc: '2.0', error: errorObject, id: id } callback(rpcMessage) responseHasBeenSent = true }
[ "function", "(", "error", ",", "type", ")", "{", "// don't send a second response", "if", "(", "responseHasBeenSent", ")", "{", "console", ".", "warn", "(", "'JSON-RPC2 response has already been sent.'", ")", "return", "}", "// notifications should not send error responses (JSON-RPC2 specs)", "if", "(", "!", "isMethodCall", ")", "{", "var", "message", "=", "(", "error", "&&", "error", ".", "toString", ")", "?", "error", ".", "toString", "(", ")", ":", "undefined", "logNotificationResponseWarning", "(", "message", ",", "requestMessage", ")", "callback", "(", ")", "return", "}", "// internals", "var", "errorObject", "if", "(", "error", "instanceof", "Error", ")", "{", "// serious application error", "console", ".", "warn", "(", "'Error in JSON-RPC2 method '", "+", "methodName", "+", "': '", "+", "error", ".", "toString", "(", ")", "+", "'\\n'", "+", "error", ".", "stack", ")", "// not sending detailed error info to not expose details about server code", "errorObject", "=", "{", "code", ":", "errorCodes", "[", "'APPLICATION_ERROR'", "]", ",", "message", ":", "errorMessages", "[", "'APPLICATION_ERROR'", "]", "+", "' (Check server logs for details)'", "}", "}", "else", "if", "(", "typeof", "error", "===", "'string'", ")", "{", "// error message", "errorObject", "=", "{", "code", ":", "errorCodes", "[", "type", "]", "||", "errorCodes", "[", "'INVALID_REQUEST'", "]", ",", "message", ":", "error", "}", "}", "else", "if", "(", "typeof", "error", "===", "'object'", ")", "{", "if", "(", "error", ".", "message", ")", "{", "// error object", "errorObject", "=", "error", "if", "(", "error", ".", "code", "===", "undefined", ")", "{", "error", ".", "code", "=", "errorCodes", "[", "'INVALID_REQUEST'", "]", "}", "}", "else", "{", "// error data", "errorObject", "=", "{", "code", ":", "errorCodes", "[", "type", "]", "||", "errorCodes", "[", "'INVALID_REQUEST'", "]", ",", "message", ":", "errorMessages", "[", "type", "]", "||", "errorMessages", "[", "'INVALID_REQUEST'", "]", ",", "data", ":", "error", "}", "}", "}", "else", "{", "if", "(", "error", "!==", "undefined", ")", "{", "console", ".", "warn", "(", "'Error parameter must be a string (error message) or object (error data)'", ")", "}", "// fallback", "errorObject", "=", "errorObjects", "[", "'INVALID_REQUEST'", "]", "}", "var", "rpcMessage", "=", "{", "jsonrpc", ":", "'2.0'", ",", "error", ":", "errorObject", ",", "id", ":", "id", "}", "callback", "(", "rpcMessage", ")", "responseHasBeenSent", "=", "true", "}" ]
create send error handler
[ "create", "send", "error", "handler" ]
a47728312e283136a24933f250aabb0be867cb2f
https://github.com/archilogic-com/instant-api/blob/a47728312e283136a24933f250aabb0be867cb2f/lib/json-rpc2-server.js#L250-L322
47,947
e-picas/grunt-nunjucks-render
lib/lib.js
merge
function merge(obj1, obj2) { var obj3 = {}, index; for (index in obj1) { obj3[index] = obj1[index]; } for (index in obj2) { obj3[index] = obj2[index]; } return obj3; }
javascript
function merge(obj1, obj2) { var obj3 = {}, index; for (index in obj1) { obj3[index] = obj1[index]; } for (index in obj2) { obj3[index] = obj2[index]; } return obj3; }
[ "function", "merge", "(", "obj1", ",", "obj2", ")", "{", "var", "obj3", "=", "{", "}", ",", "index", ";", "for", "(", "index", "in", "obj1", ")", "{", "obj3", "[", "index", "]", "=", "obj1", "[", "index", "]", ";", "}", "for", "(", "index", "in", "obj2", ")", "{", "obj3", "[", "index", "]", "=", "obj2", "[", "index", "]", ";", "}", "return", "obj3", ";", "}" ]
merge two objects with priority on second
[ "merge", "two", "objects", "with", "priority", "on", "second" ]
eab88e5ef943755853c2250f4df68398401ed0ab
https://github.com/e-picas/grunt-nunjucks-render/blob/eab88e5ef943755853c2250f4df68398401ed0ab/lib/lib.js#L27-L37
47,948
e-picas/grunt-nunjucks-render
lib/lib.js
parseData
function parseData(data) { var tmp_data = {}; if (nlib.isString(data)) { if (data.match(/\.json/i) && grunt.file.exists(data)) { tmp_data = grunt.file.readJSON(data); } else if (data.match(/\.ya?ml/i) && grunt.file.exists(data)) { tmp_data = grunt.file.readYAML(data); } else { tmp_data = data; } } else if (nlib.isObject(data) || nlib.isArray(data)) { for (var i in data) { if (nlib.isString(data[i])) { var parsed = parseData(data[i]); if (nlib.isString(parsed)) { tmp_data[i] = parsed; } else { tmp_data = merge(tmp_data, parsed); } } else { tmp_data = merge(tmp_data, data[i]); } } } return tmp_data; }
javascript
function parseData(data) { var tmp_data = {}; if (nlib.isString(data)) { if (data.match(/\.json/i) && grunt.file.exists(data)) { tmp_data = grunt.file.readJSON(data); } else if (data.match(/\.ya?ml/i) && grunt.file.exists(data)) { tmp_data = grunt.file.readYAML(data); } else { tmp_data = data; } } else if (nlib.isObject(data) || nlib.isArray(data)) { for (var i in data) { if (nlib.isString(data[i])) { var parsed = parseData(data[i]); if (nlib.isString(parsed)) { tmp_data[i] = parsed; } else { tmp_data = merge(tmp_data, parsed); } } else { tmp_data = merge(tmp_data, data[i]); } } } return tmp_data; }
[ "function", "parseData", "(", "data", ")", "{", "var", "tmp_data", "=", "{", "}", ";", "if", "(", "nlib", ".", "isString", "(", "data", ")", ")", "{", "if", "(", "data", ".", "match", "(", "/", "\\.json", "/", "i", ")", "&&", "grunt", ".", "file", ".", "exists", "(", "data", ")", ")", "{", "tmp_data", "=", "grunt", ".", "file", ".", "readJSON", "(", "data", ")", ";", "}", "else", "if", "(", "data", ".", "match", "(", "/", "\\.ya?ml", "/", "i", ")", "&&", "grunt", ".", "file", ".", "exists", "(", "data", ")", ")", "{", "tmp_data", "=", "grunt", ".", "file", ".", "readYAML", "(", "data", ")", ";", "}", "else", "{", "tmp_data", "=", "data", ";", "}", "}", "else", "if", "(", "nlib", ".", "isObject", "(", "data", ")", "||", "nlib", ".", "isArray", "(", "data", ")", ")", "{", "for", "(", "var", "i", "in", "data", ")", "{", "if", "(", "nlib", ".", "isString", "(", "data", "[", "i", "]", ")", ")", "{", "var", "parsed", "=", "parseData", "(", "data", "[", "i", "]", ")", ";", "if", "(", "nlib", ".", "isString", "(", "parsed", ")", ")", "{", "tmp_data", "[", "i", "]", "=", "parsed", ";", "}", "else", "{", "tmp_data", "=", "merge", "(", "tmp_data", ",", "parsed", ")", ";", "}", "}", "else", "{", "tmp_data", "=", "merge", "(", "tmp_data", ",", "data", "[", "i", "]", ")", ";", "}", "}", "}", "return", "tmp_data", ";", "}" ]
prepare data parsing JSON or YAML file if so
[ "prepare", "data", "parsing", "JSON", "or", "YAML", "file", "if", "so" ]
eab88e5ef943755853c2250f4df68398401ed0ab
https://github.com/e-picas/grunt-nunjucks-render/blob/eab88e5ef943755853c2250f4df68398401ed0ab/lib/lib.js#L41-L67
47,949
joneit/filter-tree
js/Conditionals.js
inOp
function inOp(a, b) { return b .trim() // remove leading and trailing space chars .replace(/\s*,\s*/g, ',') // remove any white-space chars from around commas .split(',') // put in an array .indexOf((a + '')); // search array whole matches }
javascript
function inOp(a, b) { return b .trim() // remove leading and trailing space chars .replace(/\s*,\s*/g, ',') // remove any white-space chars from around commas .split(',') // put in an array .indexOf((a + '')); // search array whole matches }
[ "function", "inOp", "(", "a", ",", "b", ")", "{", "return", "b", ".", "trim", "(", ")", "// remove leading and trailing space chars", ".", "replace", "(", "/", "\\s*,\\s*", "/", "g", ",", "','", ")", "// remove any white-space chars from around commas", ".", "split", "(", "','", ")", "// put in an array", ".", "indexOf", "(", "(", "a", "+", "''", ")", ")", ";", "// search array whole matches", "}" ]
UNICODE 'NOT EQUAL TO'
[ "UNICODE", "NOT", "EQUAL", "TO" ]
c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e
https://github.com/joneit/filter-tree/blob/c070a4045fced3e4ab20ed2e0c706c9a5fd07d1e/js/Conditionals.js#L238-L244
47,950
adplabs/PigeonKeeper
lib/genericService.js
GenericService
function GenericService(serviceId) { var self = this; var id = serviceId; var data = {}; /** * Method called by PK * * @param {Object} sharedData - Data object that gets passed-around by PK */ this.doStuff = function (sharedData) { console.log("In service #" + id + ", a = " + sharedData.a + " and b = " + sharedData.b); if(SERVICE_ALWAYS_FAILS) { var err = new Error("Service failed", "Service failed - it always does!"); onServiceError(err, sharedData); } else { if(id != BAD_SERVICE_ID) { data = {"id": id}; onServiceSuccess(data, sharedData); } else { var err = new Error("Service " + BAD_SERVICE_ID + " failed", "Service " + BAD_SERVICE_ID + " failed - it always does!"); onServiceError(err, sharedData); } } }; /** * @private * @param {Object} data * @param {Object} sharedData */ function onServiceSuccess(data, sharedData) { console.log("In GenericService" + id + ".onServiceSuccess: " + JSON.stringify(data)); sharedData[id] = {value: "This is the result from successful service #" + id}; self.emit("success", data); } /** * @private * @param err * @param {Object} sharedData */ function onServiceError(err, sharedData) { console.log("In GenericService" + id + ".onServiceError: " + JSON.stringify(err)); sharedData[id] = {value: "This is the result from failed service #" + id}; self.emit("error", err); } }
javascript
function GenericService(serviceId) { var self = this; var id = serviceId; var data = {}; /** * Method called by PK * * @param {Object} sharedData - Data object that gets passed-around by PK */ this.doStuff = function (sharedData) { console.log("In service #" + id + ", a = " + sharedData.a + " and b = " + sharedData.b); if(SERVICE_ALWAYS_FAILS) { var err = new Error("Service failed", "Service failed - it always does!"); onServiceError(err, sharedData); } else { if(id != BAD_SERVICE_ID) { data = {"id": id}; onServiceSuccess(data, sharedData); } else { var err = new Error("Service " + BAD_SERVICE_ID + " failed", "Service " + BAD_SERVICE_ID + " failed - it always does!"); onServiceError(err, sharedData); } } }; /** * @private * @param {Object} data * @param {Object} sharedData */ function onServiceSuccess(data, sharedData) { console.log("In GenericService" + id + ".onServiceSuccess: " + JSON.stringify(data)); sharedData[id] = {value: "This is the result from successful service #" + id}; self.emit("success", data); } /** * @private * @param err * @param {Object} sharedData */ function onServiceError(err, sharedData) { console.log("In GenericService" + id + ".onServiceError: " + JSON.stringify(err)); sharedData[id] = {value: "This is the result from failed service #" + id}; self.emit("error", err); } }
[ "function", "GenericService", "(", "serviceId", ")", "{", "var", "self", "=", "this", ";", "var", "id", "=", "serviceId", ";", "var", "data", "=", "{", "}", ";", "/**\n * Method called by PK\n *\n * @param {Object} sharedData - Data object that gets passed-around by PK\n */", "this", ".", "doStuff", "=", "function", "(", "sharedData", ")", "{", "console", ".", "log", "(", "\"In service #\"", "+", "id", "+", "\", a = \"", "+", "sharedData", ".", "a", "+", "\" and b = \"", "+", "sharedData", ".", "b", ")", ";", "if", "(", "SERVICE_ALWAYS_FAILS", ")", "{", "var", "err", "=", "new", "Error", "(", "\"Service failed\"", ",", "\"Service failed - it always does!\"", ")", ";", "onServiceError", "(", "err", ",", "sharedData", ")", ";", "}", "else", "{", "if", "(", "id", "!=", "BAD_SERVICE_ID", ")", "{", "data", "=", "{", "\"id\"", ":", "id", "}", ";", "onServiceSuccess", "(", "data", ",", "sharedData", ")", ";", "}", "else", "{", "var", "err", "=", "new", "Error", "(", "\"Service \"", "+", "BAD_SERVICE_ID", "+", "\" failed\"", ",", "\"Service \"", "+", "BAD_SERVICE_ID", "+", "\" failed - it always does!\"", ")", ";", "onServiceError", "(", "err", ",", "sharedData", ")", ";", "}", "}", "}", ";", "/**\n * @private\n * @param {Object} data\n * @param {Object} sharedData\n */", "function", "onServiceSuccess", "(", "data", ",", "sharedData", ")", "{", "console", ".", "log", "(", "\"In GenericService\"", "+", "id", "+", "\".onServiceSuccess: \"", "+", "JSON", ".", "stringify", "(", "data", ")", ")", ";", "sharedData", "[", "id", "]", "=", "{", "value", ":", "\"This is the result from successful service #\"", "+", "id", "}", ";", "self", ".", "emit", "(", "\"success\"", ",", "data", ")", ";", "}", "/**\n * @private\n * @param err\n * @param {Object} sharedData\n */", "function", "onServiceError", "(", "err", ",", "sharedData", ")", "{", "console", ".", "log", "(", "\"In GenericService\"", "+", "id", "+", "\".onServiceError: \"", "+", "JSON", ".", "stringify", "(", "err", ")", ")", ";", "sharedData", "[", "id", "]", "=", "{", "value", ":", "\"This is the result from failed service #\"", "+", "id", "}", ";", "self", ".", "emit", "(", "\"error\"", ",", "err", ")", ";", "}", "}" ]
"3" Event emitter; this code is to be used as a sample of how to implement an event emitter for use with PigeonKeeper @constructor @param {string} serviceId - ID of the service @fires "success" @fires "error"
[ "3", "Event", "emitter", ";", "this", "code", "is", "to", "be", "used", "as", "a", "sample", "of", "how", "to", "implement", "an", "event", "emitter", "for", "use", "with", "PigeonKeeper" ]
c0a92d2032415617c2b6f6bd49d00a2c59bfaa41
https://github.com/adplabs/PigeonKeeper/blob/c0a92d2032415617c2b6f6bd49d00a2c59bfaa41/lib/genericService.js#L13-L73
47,951
Kurento/kurento-module-crowddetector-js
lib/complexTypes/RegionOfInterestConfig.js
RegionOfInterestConfig
function RegionOfInterestConfig(regionOfInterestConfigDict){ if(!(this instanceof RegionOfInterestConfig)) return new RegionOfInterestConfig(regionOfInterestConfigDict) regionOfInterestConfigDict = regionOfInterestConfigDict || {} // Check regionOfInterestConfigDict has the required fields // // checkType('int', 'regionOfInterestConfigDict.occupancyLevelMin', regionOfInterestConfigDict.occupancyLevelMin); // // checkType('int', 'regionOfInterestConfigDict.occupancyLevelMed', regionOfInterestConfigDict.occupancyLevelMed); // // checkType('int', 'regionOfInterestConfigDict.occupancyLevelMax', regionOfInterestConfigDict.occupancyLevelMax); // // checkType('int', 'regionOfInterestConfigDict.occupancyNumFramesToEvent', regionOfInterestConfigDict.occupancyNumFramesToEvent); // // checkType('int', 'regionOfInterestConfigDict.fluidityLevelMin', regionOfInterestConfigDict.fluidityLevelMin); // // checkType('int', 'regionOfInterestConfigDict.fluidityLevelMed', regionOfInterestConfigDict.fluidityLevelMed); // // checkType('int', 'regionOfInterestConfigDict.fluidityLevelMax', regionOfInterestConfigDict.fluidityLevelMax); // // checkType('int', 'regionOfInterestConfigDict.fluidityNumFramesToEvent', regionOfInterestConfigDict.fluidityNumFramesToEvent); // // checkType('boolean', 'regionOfInterestConfigDict.sendOpticalFlowEvent', regionOfInterestConfigDict.sendOpticalFlowEvent); // // checkType('int', 'regionOfInterestConfigDict.opticalFlowNumFramesToEvent', regionOfInterestConfigDict.opticalFlowNumFramesToEvent); // // checkType('int', 'regionOfInterestConfigDict.opticalFlowNumFramesToReset', regionOfInterestConfigDict.opticalFlowNumFramesToReset); // // checkType('int', 'regionOfInterestConfigDict.opticalFlowAngleOffset', regionOfInterestConfigDict.opticalFlowAngleOffset); // // Init parent class RegionOfInterestConfig.super_.call(this, regionOfInterestConfigDict) // Set object properties Object.defineProperties(this, { occupancyLevelMin: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyLevelMin }, occupancyLevelMed: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyLevelMed }, occupancyLevelMax: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyLevelMax }, occupancyNumFramesToEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyNumFramesToEvent }, fluidityLevelMin: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityLevelMin }, fluidityLevelMed: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityLevelMed }, fluidityLevelMax: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityLevelMax }, fluidityNumFramesToEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityNumFramesToEvent }, sendOpticalFlowEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.sendOpticalFlowEvent }, opticalFlowNumFramesToEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.opticalFlowNumFramesToEvent }, opticalFlowNumFramesToReset: { writable: true, enumerable: true, value: regionOfInterestConfigDict.opticalFlowNumFramesToReset }, opticalFlowAngleOffset: { writable: true, enumerable: true, value: regionOfInterestConfigDict.opticalFlowAngleOffset } }) }
javascript
function RegionOfInterestConfig(regionOfInterestConfigDict){ if(!(this instanceof RegionOfInterestConfig)) return new RegionOfInterestConfig(regionOfInterestConfigDict) regionOfInterestConfigDict = regionOfInterestConfigDict || {} // Check regionOfInterestConfigDict has the required fields // // checkType('int', 'regionOfInterestConfigDict.occupancyLevelMin', regionOfInterestConfigDict.occupancyLevelMin); // // checkType('int', 'regionOfInterestConfigDict.occupancyLevelMed', regionOfInterestConfigDict.occupancyLevelMed); // // checkType('int', 'regionOfInterestConfigDict.occupancyLevelMax', regionOfInterestConfigDict.occupancyLevelMax); // // checkType('int', 'regionOfInterestConfigDict.occupancyNumFramesToEvent', regionOfInterestConfigDict.occupancyNumFramesToEvent); // // checkType('int', 'regionOfInterestConfigDict.fluidityLevelMin', regionOfInterestConfigDict.fluidityLevelMin); // // checkType('int', 'regionOfInterestConfigDict.fluidityLevelMed', regionOfInterestConfigDict.fluidityLevelMed); // // checkType('int', 'regionOfInterestConfigDict.fluidityLevelMax', regionOfInterestConfigDict.fluidityLevelMax); // // checkType('int', 'regionOfInterestConfigDict.fluidityNumFramesToEvent', regionOfInterestConfigDict.fluidityNumFramesToEvent); // // checkType('boolean', 'regionOfInterestConfigDict.sendOpticalFlowEvent', regionOfInterestConfigDict.sendOpticalFlowEvent); // // checkType('int', 'regionOfInterestConfigDict.opticalFlowNumFramesToEvent', regionOfInterestConfigDict.opticalFlowNumFramesToEvent); // // checkType('int', 'regionOfInterestConfigDict.opticalFlowNumFramesToReset', regionOfInterestConfigDict.opticalFlowNumFramesToReset); // // checkType('int', 'regionOfInterestConfigDict.opticalFlowAngleOffset', regionOfInterestConfigDict.opticalFlowAngleOffset); // // Init parent class RegionOfInterestConfig.super_.call(this, regionOfInterestConfigDict) // Set object properties Object.defineProperties(this, { occupancyLevelMin: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyLevelMin }, occupancyLevelMed: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyLevelMed }, occupancyLevelMax: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyLevelMax }, occupancyNumFramesToEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.occupancyNumFramesToEvent }, fluidityLevelMin: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityLevelMin }, fluidityLevelMed: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityLevelMed }, fluidityLevelMax: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityLevelMax }, fluidityNumFramesToEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.fluidityNumFramesToEvent }, sendOpticalFlowEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.sendOpticalFlowEvent }, opticalFlowNumFramesToEvent: { writable: true, enumerable: true, value: regionOfInterestConfigDict.opticalFlowNumFramesToEvent }, opticalFlowNumFramesToReset: { writable: true, enumerable: true, value: regionOfInterestConfigDict.opticalFlowNumFramesToReset }, opticalFlowAngleOffset: { writable: true, enumerable: true, value: regionOfInterestConfigDict.opticalFlowAngleOffset } }) }
[ "function", "RegionOfInterestConfig", "(", "regionOfInterestConfigDict", ")", "{", "if", "(", "!", "(", "this", "instanceof", "RegionOfInterestConfig", ")", ")", "return", "new", "RegionOfInterestConfig", "(", "regionOfInterestConfigDict", ")", "regionOfInterestConfigDict", "=", "regionOfInterestConfigDict", "||", "{", "}", "// Check regionOfInterestConfigDict has the required fields", "// ", "// checkType('int', 'regionOfInterestConfigDict.occupancyLevelMin', regionOfInterestConfigDict.occupancyLevelMin);", "// ", "// checkType('int', 'regionOfInterestConfigDict.occupancyLevelMed', regionOfInterestConfigDict.occupancyLevelMed);", "// ", "// checkType('int', 'regionOfInterestConfigDict.occupancyLevelMax', regionOfInterestConfigDict.occupancyLevelMax);", "// ", "// checkType('int', 'regionOfInterestConfigDict.occupancyNumFramesToEvent', regionOfInterestConfigDict.occupancyNumFramesToEvent);", "// ", "// checkType('int', 'regionOfInterestConfigDict.fluidityLevelMin', regionOfInterestConfigDict.fluidityLevelMin);", "// ", "// checkType('int', 'regionOfInterestConfigDict.fluidityLevelMed', regionOfInterestConfigDict.fluidityLevelMed);", "// ", "// checkType('int', 'regionOfInterestConfigDict.fluidityLevelMax', regionOfInterestConfigDict.fluidityLevelMax);", "// ", "// checkType('int', 'regionOfInterestConfigDict.fluidityNumFramesToEvent', regionOfInterestConfigDict.fluidityNumFramesToEvent);", "// ", "// checkType('boolean', 'regionOfInterestConfigDict.sendOpticalFlowEvent', regionOfInterestConfigDict.sendOpticalFlowEvent);", "// ", "// checkType('int', 'regionOfInterestConfigDict.opticalFlowNumFramesToEvent', regionOfInterestConfigDict.opticalFlowNumFramesToEvent);", "// ", "// checkType('int', 'regionOfInterestConfigDict.opticalFlowNumFramesToReset', regionOfInterestConfigDict.opticalFlowNumFramesToReset);", "// ", "// checkType('int', 'regionOfInterestConfigDict.opticalFlowAngleOffset', regionOfInterestConfigDict.opticalFlowAngleOffset);", "// ", "// Init parent class", "RegionOfInterestConfig", ".", "super_", ".", "call", "(", "this", ",", "regionOfInterestConfigDict", ")", "// Set object properties", "Object", ".", "defineProperties", "(", "this", ",", "{", "occupancyLevelMin", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "occupancyLevelMin", "}", ",", "occupancyLevelMed", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "occupancyLevelMed", "}", ",", "occupancyLevelMax", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "occupancyLevelMax", "}", ",", "occupancyNumFramesToEvent", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "occupancyNumFramesToEvent", "}", ",", "fluidityLevelMin", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "fluidityLevelMin", "}", ",", "fluidityLevelMed", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "fluidityLevelMed", "}", ",", "fluidityLevelMax", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "fluidityLevelMax", "}", ",", "fluidityNumFramesToEvent", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "fluidityNumFramesToEvent", "}", ",", "sendOpticalFlowEvent", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "sendOpticalFlowEvent", "}", ",", "opticalFlowNumFramesToEvent", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "opticalFlowNumFramesToEvent", "}", ",", "opticalFlowNumFramesToReset", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "opticalFlowNumFramesToReset", "}", ",", "opticalFlowAngleOffset", ":", "{", "writable", ":", "true", ",", "enumerable", ":", "true", ",", "value", ":", "regionOfInterestConfigDict", ".", "opticalFlowAngleOffset", "}", "}", ")", "}" ]
data structure for configuration of CrowdDetector regions of interest @constructor module:crowddetector/complexTypes.RegionOfInterestConfig @property {external:Integer} occupancyLevelMin minimun occupancy percentage in the ROI to send occupancy events @property {external:Integer} occupancyLevelMed send occupancy level = 1 if the occupancy percentage is between occupancy_level_min and this level @property {external:Integer} occupancyLevelMax send occupancy level = 2 if the occupancy percentage is between occupancy_level_med and this level, and send occupancy level = 3 if the occupancy percentage is between this level and 100 @property {external:Integer} occupancyNumFramesToEvent number of consecutive frames that a new occupancy level has to be detected to recognize it as a occupancy level change. A new occupancy event will be send @property {external:Integer} fluidityLevelMin minimun fluidity percentage in the ROI to send fluidity events @property {external:Integer} fluidityLevelMed send fluidity level = 1 if the fluidity percentage is between fluidity_level_min and this level @property {external:Integer} fluidityLevelMax send fluidity level = 2 if the fluidity percentage is between fluidity_level_med and this level, and send fluidity level = 3 if the fluidity percentage is between this level and 100 @property {external:Integer} fluidityNumFramesToEvent number of consecutive frames that a new fluidity level has to be detected to A new fluidity event will be send @property {external:Boolean} sendOpticalFlowEvent Enable/disable the movement direction detection into the ROI @property {external:Integer} opticalFlowNumFramesToEvent number of consecutive frames that a new direction of movement has to be detected to recognize a new movement direction. A new direction event will be send @property {external:Integer} opticalFlowNumFramesToReset number of consecutive frames in order to reset the counter of repeated directions @property {external:Integer} opticalFlowAngleOffset Direction of the movement. The angle could have four different values: left (0), up (90), right (180) and down (270). This cartesian axis could be
[ "data", "structure", "for", "configuration", "of", "CrowdDetector", "regions", "of", "interest" ]
ae0a03c5d6bbc07a23d083fe8916017cb4a63855
https://github.com/Kurento/kurento-module-crowddetector-js/blob/ae0a03c5d6bbc07a23d083fe8916017cb4a63855/lib/complexTypes/RegionOfInterestConfig.js#L74-L173
47,952
smartface/sf-component-calendar
scripts/components/CalendarCore.js
getInitialState
function getInitialState() { return { month: {}, day: {}, rangeSelection: null, rangeSelectionMode: RangeSelection.IDLE, selectedDays: [], selectedDaysByIndex: [], weekIndex: 0 }; }
javascript
function getInitialState() { return { month: {}, day: {}, rangeSelection: null, rangeSelectionMode: RangeSelection.IDLE, selectedDays: [], selectedDaysByIndex: [], weekIndex: 0 }; }
[ "function", "getInitialState", "(", ")", "{", "return", "{", "month", ":", "{", "}", ",", "day", ":", "{", "}", ",", "rangeSelection", ":", "null", ",", "rangeSelectionMode", ":", "RangeSelection", ".", "IDLE", ",", "selectedDays", ":", "[", "]", ",", "selectedDaysByIndex", ":", "[", "]", ",", "weekIndex", ":", "0", "}", ";", "}" ]
Returns initial state @returns {object}
[ "Returns", "initial", "state" ]
d6c8310564ff551b9424ac6955efa5e8cf5f8dff
https://github.com/smartface/sf-component-calendar/blob/d6c8310564ff551b9424ac6955efa5e8cf5f8dff/scripts/components/CalendarCore.js#L16-L26
47,953
smartface/sf-component-calendar
scripts/components/CalendarCore.js
calculateDatePos
function calculateDatePos(startDayOfMonth, day) { const start = startDayOfMonth - 1; day = day - 1; const weekDayIndex = (start + day) % WEEKDAYS; const weekIndex = Math.ceil((start + day + 1) / WEEKDAYS) - 1; return { weekIndex, weekDayIndex }; }
javascript
function calculateDatePos(startDayOfMonth, day) { const start = startDayOfMonth - 1; day = day - 1; const weekDayIndex = (start + day) % WEEKDAYS; const weekIndex = Math.ceil((start + day + 1) / WEEKDAYS) - 1; return { weekIndex, weekDayIndex }; }
[ "function", "calculateDatePos", "(", "startDayOfMonth", ",", "day", ")", "{", "const", "start", "=", "startDayOfMonth", "-", "1", ";", "day", "=", "day", "-", "1", ";", "const", "weekDayIndex", "=", "(", "start", "+", "day", ")", "%", "WEEKDAYS", ";", "const", "weekIndex", "=", "Math", ".", "ceil", "(", "(", "start", "+", "day", "+", "1", ")", "/", "WEEKDAYS", ")", "-", "1", ";", "return", "{", "weekIndex", ",", "weekDayIndex", "}", ";", "}" ]
Calcucalte given day's week and weekday index @param {number} startDayOfMonth @param {number} day
[ "Calcucalte", "given", "day", "s", "week", "and", "weekday", "index" ]
d6c8310564ff551b9424ac6955efa5e8cf5f8dff
https://github.com/smartface/sf-component-calendar/blob/d6c8310564ff551b9424ac6955efa5e8cf5f8dff/scripts/components/CalendarCore.js#L59-L68
47,954
smartface/sf-component-calendar
scripts/components/CalendarCore.js
getDateData
function getDateData(date, month) { const pos = getDatePos(date, month); if (pos === null) { throw new TypeError(JSON.stringify(date) + " is invalid format."); } return getDayData(pos.weekIndex, pos.weekDayIndex, month); }
javascript
function getDateData(date, month) { const pos = getDatePos(date, month); if (pos === null) { throw new TypeError(JSON.stringify(date) + " is invalid format."); } return getDayData(pos.weekIndex, pos.weekDayIndex, month); }
[ "function", "getDateData", "(", "date", ",", "month", ")", "{", "const", "pos", "=", "getDatePos", "(", "date", ",", "month", ")", ";", "if", "(", "pos", "===", "null", ")", "{", "throw", "new", "TypeError", "(", "JSON", ".", "stringify", "(", "date", ")", "+", "\" is invalid format.\"", ")", ";", "}", "return", "getDayData", "(", "pos", ".", "weekIndex", ",", "pos", ".", "weekDayIndex", ",", "month", ")", ";", "}" ]
Gets specified date's info data in specified month. @param {object} date @param {object} month @throw {TypeError} @returns {Calendar~DateInfo}
[ "Gets", "specified", "date", "s", "info", "data", "in", "specified", "month", "." ]
d6c8310564ff551b9424ac6955efa5e8cf5f8dff
https://github.com/smartface/sf-component-calendar/blob/d6c8310564ff551b9424ac6955efa5e8cf5f8dff/scripts/components/CalendarCore.js#L107-L115
47,955
smartface/sf-component-calendar
scripts/components/CalendarCore.js
getDayData
function getDayData(weekIndex, weekDayIndex, currentMonth) { const dayData = {}; if (!currentMonth || !currentMonth.days || currentMonth.days[weekIndex] === undefined) { throw new TypeError("WeekIndex : " + weekIndex + ", weekDayIndex " + weekDayIndex + " selected day cannot be undefined"); } const selectedDay = currentMonth.days[weekIndex][weekDayIndex]; dayData.dayInfo = { weekDay: weekDayIndex, longName: currentMonth.daysLong[weekDayIndex], shortName: currentMonth.daysShort[weekDayIndex], specialDay: selectedDay.specialDay, }; dayData.date = { day: selectedDay.day }; dayData.localeDate = { day: currentMonth.days[weekIndex][weekDayIndex].localeDay, month: currentMonth.localeDate.month, year: currentMonth.localeDate.year, }; switch (selectedDay.month) { // if selected day is in the current month. case 'current': dayData.monthInfo = { longName: currentMonth.longName, shortName: currentMonth.shortName, }; dayData.date.month = currentMonth.date.month; dayData.date.year = currentMonth.date.year; break; // if selected day is in the next month. case 'next': dayData.monthInfo = { longName: currentMonth.nextMonth.longName, shortName: currentMonth.nextMonth.shortName, }; dayData.localeDate.month = currentMonth.nextMonth.localeDate.month; dayData.localeDate.year = currentMonth.nextMonth.localeDate.year; dayData.date.month = currentMonth.nextMonth.date.month; dayData.date.year = currentMonth.nextMonth.date.year; break; // if selected day is in the previous month. case 'previous': dayData.monthInfo = { longName: currentMonth.previousMonth.longName, shortName: currentMonth.previousMonth.shortName, }; dayData.localeDate.month = currentMonth.previousMonth.localeDate.month; dayData.localeDate.year = currentMonth.previousMonth.localeDate.year; dayData.date.month = currentMonth.previousMonth.date.month; dayData.date.year = currentMonth.previousMonth.date.year; break; default: throw new Error('Selected day has invalid data'); } Object.seal(dayData); return dayData; }
javascript
function getDayData(weekIndex, weekDayIndex, currentMonth) { const dayData = {}; if (!currentMonth || !currentMonth.days || currentMonth.days[weekIndex] === undefined) { throw new TypeError("WeekIndex : " + weekIndex + ", weekDayIndex " + weekDayIndex + " selected day cannot be undefined"); } const selectedDay = currentMonth.days[weekIndex][weekDayIndex]; dayData.dayInfo = { weekDay: weekDayIndex, longName: currentMonth.daysLong[weekDayIndex], shortName: currentMonth.daysShort[weekDayIndex], specialDay: selectedDay.specialDay, }; dayData.date = { day: selectedDay.day }; dayData.localeDate = { day: currentMonth.days[weekIndex][weekDayIndex].localeDay, month: currentMonth.localeDate.month, year: currentMonth.localeDate.year, }; switch (selectedDay.month) { // if selected day is in the current month. case 'current': dayData.monthInfo = { longName: currentMonth.longName, shortName: currentMonth.shortName, }; dayData.date.month = currentMonth.date.month; dayData.date.year = currentMonth.date.year; break; // if selected day is in the next month. case 'next': dayData.monthInfo = { longName: currentMonth.nextMonth.longName, shortName: currentMonth.nextMonth.shortName, }; dayData.localeDate.month = currentMonth.nextMonth.localeDate.month; dayData.localeDate.year = currentMonth.nextMonth.localeDate.year; dayData.date.month = currentMonth.nextMonth.date.month; dayData.date.year = currentMonth.nextMonth.date.year; break; // if selected day is in the previous month. case 'previous': dayData.monthInfo = { longName: currentMonth.previousMonth.longName, shortName: currentMonth.previousMonth.shortName, }; dayData.localeDate.month = currentMonth.previousMonth.localeDate.month; dayData.localeDate.year = currentMonth.previousMonth.localeDate.year; dayData.date.month = currentMonth.previousMonth.date.month; dayData.date.year = currentMonth.previousMonth.date.year; break; default: throw new Error('Selected day has invalid data'); } Object.seal(dayData); return dayData; }
[ "function", "getDayData", "(", "weekIndex", ",", "weekDayIndex", ",", "currentMonth", ")", "{", "const", "dayData", "=", "{", "}", ";", "if", "(", "!", "currentMonth", "||", "!", "currentMonth", ".", "days", "||", "currentMonth", ".", "days", "[", "weekIndex", "]", "===", "undefined", ")", "{", "throw", "new", "TypeError", "(", "\"WeekIndex : \"", "+", "weekIndex", "+", "\", weekDayIndex \"", "+", "weekDayIndex", "+", "\" selected day cannot be undefined\"", ")", ";", "}", "const", "selectedDay", "=", "currentMonth", ".", "days", "[", "weekIndex", "]", "[", "weekDayIndex", "]", ";", "dayData", ".", "dayInfo", "=", "{", "weekDay", ":", "weekDayIndex", ",", "longName", ":", "currentMonth", ".", "daysLong", "[", "weekDayIndex", "]", ",", "shortName", ":", "currentMonth", ".", "daysShort", "[", "weekDayIndex", "]", ",", "specialDay", ":", "selectedDay", ".", "specialDay", ",", "}", ";", "dayData", ".", "date", "=", "{", "day", ":", "selectedDay", ".", "day", "}", ";", "dayData", ".", "localeDate", "=", "{", "day", ":", "currentMonth", ".", "days", "[", "weekIndex", "]", "[", "weekDayIndex", "]", ".", "localeDay", ",", "month", ":", "currentMonth", ".", "localeDate", ".", "month", ",", "year", ":", "currentMonth", ".", "localeDate", ".", "year", ",", "}", ";", "switch", "(", "selectedDay", ".", "month", ")", "{", "// if selected day is in the current month.", "case", "'current'", ":", "dayData", ".", "monthInfo", "=", "{", "longName", ":", "currentMonth", ".", "longName", ",", "shortName", ":", "currentMonth", ".", "shortName", ",", "}", ";", "dayData", ".", "date", ".", "month", "=", "currentMonth", ".", "date", ".", "month", ";", "dayData", ".", "date", ".", "year", "=", "currentMonth", ".", "date", ".", "year", ";", "break", ";", "// if selected day is in the next month.", "case", "'next'", ":", "dayData", ".", "monthInfo", "=", "{", "longName", ":", "currentMonth", ".", "nextMonth", ".", "longName", ",", "shortName", ":", "currentMonth", ".", "nextMonth", ".", "shortName", ",", "}", ";", "dayData", ".", "localeDate", ".", "month", "=", "currentMonth", ".", "nextMonth", ".", "localeDate", ".", "month", ";", "dayData", ".", "localeDate", ".", "year", "=", "currentMonth", ".", "nextMonth", ".", "localeDate", ".", "year", ";", "dayData", ".", "date", ".", "month", "=", "currentMonth", ".", "nextMonth", ".", "date", ".", "month", ";", "dayData", ".", "date", ".", "year", "=", "currentMonth", ".", "nextMonth", ".", "date", ".", "year", ";", "break", ";", "// if selected day is in the previous month.", "case", "'previous'", ":", "dayData", ".", "monthInfo", "=", "{", "longName", ":", "currentMonth", ".", "previousMonth", ".", "longName", ",", "shortName", ":", "currentMonth", ".", "previousMonth", ".", "shortName", ",", "}", ";", "dayData", ".", "localeDate", ".", "month", "=", "currentMonth", ".", "previousMonth", ".", "localeDate", ".", "month", ";", "dayData", ".", "localeDate", ".", "year", "=", "currentMonth", ".", "previousMonth", ".", "localeDate", ".", "year", ";", "dayData", ".", "date", ".", "month", "=", "currentMonth", ".", "previousMonth", ".", "date", ".", "month", ";", "dayData", ".", "date", ".", "year", "=", "currentMonth", ".", "previousMonth", ".", "date", ".", "year", ";", "break", ";", "default", ":", "throw", "new", "Error", "(", "'Selected day has invalid data'", ")", ";", "}", "Object", ".", "seal", "(", "dayData", ")", ";", "return", "dayData", ";", "}" ]
Select specified day @private
[ "Select", "specified", "day" ]
d6c8310564ff551b9424ac6955efa5e8cf5f8dff
https://github.com/smartface/sf-component-calendar/blob/d6c8310564ff551b9424ac6955efa5e8cf5f8dff/scripts/components/CalendarCore.js#L123-L191
47,956
smartface/sf-component-calendar
scripts/components/CalendarCore.js
getDatePos
function getDatePos(date, month, notValue = null) { const monthPos = (date.month === month.date.month && 'current') || (date.month === month.nextMonth.date.month && 'next') || (date.month === month.previousMonth.date.month && 'prev'); switch (monthPos) { case 'current': return calculateDatePos(month.startDayOfMonth, date.day); case 'prev': return calculateDatePosinPrev( month.startDayOfMonth, month.previousMonth.daysCount, date.day ); case 'next': const posNext = calculateDatePosinNext( month.startDayOfMonth, month.daysCount, date.day ); return posNext; default: return notValue; } }
javascript
function getDatePos(date, month, notValue = null) { const monthPos = (date.month === month.date.month && 'current') || (date.month === month.nextMonth.date.month && 'next') || (date.month === month.previousMonth.date.month && 'prev'); switch (monthPos) { case 'current': return calculateDatePos(month.startDayOfMonth, date.day); case 'prev': return calculateDatePosinPrev( month.startDayOfMonth, month.previousMonth.daysCount, date.day ); case 'next': const posNext = calculateDatePosinNext( month.startDayOfMonth, month.daysCount, date.day ); return posNext; default: return notValue; } }
[ "function", "getDatePos", "(", "date", ",", "month", ",", "notValue", "=", "null", ")", "{", "const", "monthPos", "=", "(", "date", ".", "month", "===", "month", ".", "date", ".", "month", "&&", "'current'", ")", "||", "(", "date", ".", "month", "===", "month", ".", "nextMonth", ".", "date", ".", "month", "&&", "'next'", ")", "||", "(", "date", ".", "month", "===", "month", ".", "previousMonth", ".", "date", ".", "month", "&&", "'prev'", ")", ";", "switch", "(", "monthPos", ")", "{", "case", "'current'", ":", "return", "calculateDatePos", "(", "month", ".", "startDayOfMonth", ",", "date", ".", "day", ")", ";", "case", "'prev'", ":", "return", "calculateDatePosinPrev", "(", "month", ".", "startDayOfMonth", ",", "month", ".", "previousMonth", ".", "daysCount", ",", "date", ".", "day", ")", ";", "case", "'next'", ":", "const", "posNext", "=", "calculateDatePosinNext", "(", "month", ".", "startDayOfMonth", ",", "month", ".", "daysCount", ",", "date", ".", "day", ")", ";", "return", "posNext", ";", "default", ":", "return", "notValue", ";", "}", "}" ]
Calculates week and weekday indexes in the month @param {object} date @param {object} month @param {object} notValue @returns {({weekIndex:number, weekDayIndex:number}|*)}
[ "Calculates", "week", "and", "weekday", "indexes", "in", "the", "month" ]
d6c8310564ff551b9424ac6955efa5e8cf5f8dff
https://github.com/smartface/sf-component-calendar/blob/d6c8310564ff551b9424ac6955efa5e8cf5f8dff/scripts/components/CalendarCore.js#L201-L227
47,957
areslabs/babel-plugin-import-css
src/index.js
devHandler
function devHandler(curPath, importPath, jsFilename) { var absPath = resolve(importPath, jsFilename) var projectDir = path.resolve(require.resolve('./index.js'), '..', '..', '..', '..', '..') absPath = absPath.replace(projectDir, '@areslabs/babel-plugin-import-css/rncsscache') curPath.node.source.value = (absPath + '.js') }
javascript
function devHandler(curPath, importPath, jsFilename) { var absPath = resolve(importPath, jsFilename) var projectDir = path.resolve(require.resolve('./index.js'), '..', '..', '..', '..', '..') absPath = absPath.replace(projectDir, '@areslabs/babel-plugin-import-css/rncsscache') curPath.node.source.value = (absPath + '.js') }
[ "function", "devHandler", "(", "curPath", ",", "importPath", ",", "jsFilename", ")", "{", "var", "absPath", "=", "resolve", "(", "importPath", ",", "jsFilename", ")", "var", "projectDir", "=", "path", ".", "resolve", "(", "require", ".", "resolve", "(", "'./index.js'", ")", ",", "'..'", ",", "'..'", ",", "'..'", ",", "'..'", ",", "'..'", ")", "absPath", "=", "absPath", ".", "replace", "(", "projectDir", ",", "'@areslabs/babel-plugin-import-css/rncsscache'", ")", "curPath", ".", "node", ".", "source", ".", "value", "=", "(", "absPath", "+", "'.js'", ")", "}" ]
In development, we just modify the import path, target file will be generated by 'cssWatch' @param curPath @param importPath @param jsFilename
[ "In", "development", "we", "just", "modify", "the", "import", "path", "target", "file", "will", "be", "generated", "by", "cssWatch" ]
b90d3a4ec3a644edcaa1c803314e2c39de1d29c9
https://github.com/areslabs/babel-plugin-import-css/blob/b90d3a4ec3a644edcaa1c803314e2c39de1d29c9/src/index.js#L61-L68
47,958
areslabs/babel-plugin-import-css
src/index.js
prodHandler
function prodHandler(curPath, opts, importPath, jsFilename, template, t){ var absPath = resolve(importPath, jsFilename) const cssStr = fse.readFileSync(absPath).toString() const {styles: obj} = createStylefromCode(cssStr, absPath) const cssObj = convertStylesToRNCSS(obj) var defautIdenti = curPath.node.specifiers[0].local.name const buildNode = template('const STYLES = STYOBJ;', { sourceType: 'module' }) const styleExpre = buildNode({ STYLES: t.identifier(defautIdenti), STYOBJ: t.identifier(cssObj) }) curPath.replaceWith(styleExpre) }
javascript
function prodHandler(curPath, opts, importPath, jsFilename, template, t){ var absPath = resolve(importPath, jsFilename) const cssStr = fse.readFileSync(absPath).toString() const {styles: obj} = createStylefromCode(cssStr, absPath) const cssObj = convertStylesToRNCSS(obj) var defautIdenti = curPath.node.specifiers[0].local.name const buildNode = template('const STYLES = STYOBJ;', { sourceType: 'module' }) const styleExpre = buildNode({ STYLES: t.identifier(defautIdenti), STYOBJ: t.identifier(cssObj) }) curPath.replaceWith(styleExpre) }
[ "function", "prodHandler", "(", "curPath", ",", "opts", ",", "importPath", ",", "jsFilename", ",", "template", ",", "t", ")", "{", "var", "absPath", "=", "resolve", "(", "importPath", ",", "jsFilename", ")", "const", "cssStr", "=", "fse", ".", "readFileSync", "(", "absPath", ")", ".", "toString", "(", ")", "const", "{", "styles", ":", "obj", "}", "=", "createStylefromCode", "(", "cssStr", ",", "absPath", ")", "const", "cssObj", "=", "convertStylesToRNCSS", "(", "obj", ")", "var", "defautIdenti", "=", "curPath", ".", "node", ".", "specifiers", "[", "0", "]", ".", "local", ".", "name", "const", "buildNode", "=", "template", "(", "'const STYLES = STYOBJ;'", ",", "{", "sourceType", ":", "'module'", "}", ")", "const", "styleExpre", "=", "buildNode", "(", "{", "STYLES", ":", "t", ".", "identifier", "(", "defautIdenti", ")", ",", "STYOBJ", ":", "t", ".", "identifier", "(", "cssObj", ")", "}", ")", "curPath", ".", "replaceWith", "(", "styleExpre", ")", "}" ]
In prod, the js's object which is generated by the ralated css file will write directly in the js file. @param curPath @param opts @param importPath @param jsFilename @param template @param t
[ "In", "prod", "the", "js", "s", "object", "which", "is", "generated", "by", "the", "ralated", "css", "file", "will", "write", "directly", "in", "the", "js", "file", "." ]
b90d3a4ec3a644edcaa1c803314e2c39de1d29c9
https://github.com/areslabs/babel-plugin-import-css/blob/b90d3a4ec3a644edcaa1c803314e2c39de1d29c9/src/index.js#L79-L94
47,959
luminous-patterns/angular-environment-config
Gruntfile.js
gruntPrepareRelease
function gruntPrepareRelease () { var bower = grunt.file.readJSON('bower.json'); var version = bower.version; if (version !== grunt.config('pkg.version')) { throw new Error('Version mismatch in bower.json'); } function searchForExistingTag () { return exec('git tag -l \"' + version + '\"'); } function setGruntConfig (searchResult) { if ('' !== searchResult.stdout.trim()) { throw new Error('Tag \'' + version + '\' already exists'); } grunt.config('buildTag', ''); grunt.config('buildDir', releaseDirName); } var done = this.async(); ensureCleanMaster() .then(searchForExistingTag) .then(setGruntConfig) .then(function () { done(); }) .catch(handleAsyncError.bind(undefined, done)) .done(); }
javascript
function gruntPrepareRelease () { var bower = grunt.file.readJSON('bower.json'); var version = bower.version; if (version !== grunt.config('pkg.version')) { throw new Error('Version mismatch in bower.json'); } function searchForExistingTag () { return exec('git tag -l \"' + version + '\"'); } function setGruntConfig (searchResult) { if ('' !== searchResult.stdout.trim()) { throw new Error('Tag \'' + version + '\' already exists'); } grunt.config('buildTag', ''); grunt.config('buildDir', releaseDirName); } var done = this.async(); ensureCleanMaster() .then(searchForExistingTag) .then(setGruntConfig) .then(function () { done(); }) .catch(handleAsyncError.bind(undefined, done)) .done(); }
[ "function", "gruntPrepareRelease", "(", ")", "{", "var", "bower", "=", "grunt", ".", "file", ".", "readJSON", "(", "'bower.json'", ")", ";", "var", "version", "=", "bower", ".", "version", ";", "if", "(", "version", "!==", "grunt", ".", "config", "(", "'pkg.version'", ")", ")", "{", "throw", "new", "Error", "(", "'Version mismatch in bower.json'", ")", ";", "}", "function", "searchForExistingTag", "(", ")", "{", "return", "exec", "(", "'git tag -l \\\"'", "+", "version", "+", "'\\\"'", ")", ";", "}", "function", "setGruntConfig", "(", "searchResult", ")", "{", "if", "(", "''", "!==", "searchResult", ".", "stdout", ".", "trim", "(", ")", ")", "{", "throw", "new", "Error", "(", "'Tag \\''", "+", "version", "+", "'\\' already exists'", ")", ";", "}", "grunt", ".", "config", "(", "'buildTag'", ",", "''", ")", ";", "grunt", ".", "config", "(", "'buildDir'", ",", "releaseDirName", ")", ";", "}", "var", "done", "=", "this", ".", "async", "(", ")", ";", "ensureCleanMaster", "(", ")", ".", "then", "(", "searchForExistingTag", ")", ".", "then", "(", "setGruntConfig", ")", ".", "then", "(", "function", "(", ")", "{", "done", "(", ")", ";", "}", ")", ".", "catch", "(", "handleAsyncError", ".", "bind", "(", "undefined", ",", "done", ")", ")", ".", "done", "(", ")", ";", "}" ]
Grunt Task Functions
[ "Grunt", "Task", "Functions" ]
081bda487e16da8f0991699031cd9297c2464bc6
https://github.com/luminous-patterns/angular-environment-config/blob/081bda487e16da8f0991699031cd9297c2464bc6/Gruntfile.js#L213-L248
47,960
tether/request-body
index.js
add
function add (obj, name, value) { const previous = obj[name] if (previous) { const arr = [].concat(previous) arr.push(value) return arr } else return value }
javascript
function add (obj, name, value) { const previous = obj[name] if (previous) { const arr = [].concat(previous) arr.push(value) return arr } else return value }
[ "function", "add", "(", "obj", ",", "name", ",", "value", ")", "{", "const", "previous", "=", "obj", "[", "name", "]", "if", "(", "previous", ")", "{", "const", "arr", "=", "[", "]", ".", "concat", "(", "previous", ")", "arr", ".", "push", "(", "value", ")", "return", "arr", "}", "else", "return", "value", "}" ]
Return value of array of values. @param {Object} obj @param {String} name @param {Any} value @return {Any|Array} @api private
[ "Return", "value", "of", "array", "of", "values", "." ]
825dfc130b728847dd1836b76383c17b3811ce93
https://github.com/tether/request-body/blob/825dfc130b728847dd1836b76383c17b3811ce93/index.js#L89-L96
47,961
reelyactive/chickadee
lib/routes/contextat.js
retrieveContextAtReceiver
function retrieveContextAtReceiver(req, res) { if(redirect(req.params.id, '', '', res)) { return; } switch(req.accepts(['json', 'html'])) { case 'html': res.sendFile(path.resolve(__dirname + '/../../web/response.html')); break; default: var options = { query: 'receivedStrongestBy', id: req.params.id, omit: [ 'timestamp' ] }; var rootUrl = req.protocol + '://' + req.get('host'); var queryPath = req.originalUrl; req.chickadee.getDevicesContext(req, options, rootUrl, queryPath, function(response, status) { res.status(status).json(response); }); break; } }
javascript
function retrieveContextAtReceiver(req, res) { if(redirect(req.params.id, '', '', res)) { return; } switch(req.accepts(['json', 'html'])) { case 'html': res.sendFile(path.resolve(__dirname + '/../../web/response.html')); break; default: var options = { query: 'receivedStrongestBy', id: req.params.id, omit: [ 'timestamp' ] }; var rootUrl = req.protocol + '://' + req.get('host'); var queryPath = req.originalUrl; req.chickadee.getDevicesContext(req, options, rootUrl, queryPath, function(response, status) { res.status(status).json(response); }); break; } }
[ "function", "retrieveContextAtReceiver", "(", "req", ",", "res", ")", "{", "if", "(", "redirect", "(", "req", ".", "params", ".", "id", ",", "''", ",", "''", ",", "res", ")", ")", "{", "return", ";", "}", "switch", "(", "req", ".", "accepts", "(", "[", "'json'", ",", "'html'", "]", ")", ")", "{", "case", "'html'", ":", "res", ".", "sendFile", "(", "path", ".", "resolve", "(", "__dirname", "+", "'/../../web/response.html'", ")", ")", ";", "break", ";", "default", ":", "var", "options", "=", "{", "query", ":", "'receivedStrongestBy'", ",", "id", ":", "req", ".", "params", ".", "id", ",", "omit", ":", "[", "'timestamp'", "]", "}", ";", "var", "rootUrl", "=", "req", ".", "protocol", "+", "'://'", "+", "req", ".", "get", "(", "'host'", ")", ";", "var", "queryPath", "=", "req", ".", "originalUrl", ";", "req", ".", "chickadee", ".", "getDevicesContext", "(", "req", ",", "options", ",", "rootUrl", ",", "queryPath", ",", "function", "(", "response", ",", "status", ")", "{", "res", ".", "status", "(", "status", ")", ".", "json", "(", "response", ")", ";", "}", ")", ";", "break", ";", "}", "}" ]
Retrieve the context at a given receiver device id. @param {Object} req The HTTP request. @param {Object} res The HTTP result.
[ "Retrieve", "the", "context", "at", "a", "given", "receiver", "device", "id", "." ]
1f65c2d369694d93796aae63318fa76326275120
https://github.com/reelyactive/chickadee/blob/1f65c2d369694d93796aae63318fa76326275120/lib/routes/contextat.js#L37-L59
47,962
fulmicoton/potato
doc/assets/CodeMirror-2.22/mode/xmlpure/xmlpure.js
popContext
function popContext(state) { if (state.context) { var oldContext = state.context; state.context = oldContext.prev; return oldContext; } // we shouldn't be here - it means we didn't have a context to pop return null; }
javascript
function popContext(state) { if (state.context) { var oldContext = state.context; state.context = oldContext.prev; return oldContext; } // we shouldn't be here - it means we didn't have a context to pop return null; }
[ "function", "popContext", "(", "state", ")", "{", "if", "(", "state", ".", "context", ")", "{", "var", "oldContext", "=", "state", ".", "context", ";", "state", ".", "context", "=", "oldContext", ".", "prev", ";", "return", "oldContext", ";", "}", "// we shouldn't be here - it means we didn't have a context to pop", "return", "null", ";", "}" ]
go up a level in the document
[ "go", "up", "a", "level", "in", "the", "document" ]
50f9506224b65f9f171ac52e5a9c8311f9f41c67
https://github.com/fulmicoton/potato/blob/50f9506224b65f9f171ac52e5a9c8311f9f41c67/doc/assets/CodeMirror-2.22/mode/xmlpure/xmlpure.js#L75-L84
47,963
fulmicoton/potato
doc/assets/CodeMirror-2.22/mode/xmlpure/xmlpure.js
isTokenSeparated
function isTokenSeparated(stream) { return stream.sol() || stream.string.charAt(stream.start - 1) == " " || stream.string.charAt(stream.start - 1) == "\t"; }
javascript
function isTokenSeparated(stream) { return stream.sol() || stream.string.charAt(stream.start - 1) == " " || stream.string.charAt(stream.start - 1) == "\t"; }
[ "function", "isTokenSeparated", "(", "stream", ")", "{", "return", "stream", ".", "sol", "(", ")", "||", "stream", ".", "string", ".", "charAt", "(", "stream", ".", "start", "-", "1", ")", "==", "\" \"", "||", "stream", ".", "string", ".", "charAt", "(", "stream", ".", "start", "-", "1", ")", "==", "\"\\t\"", ";", "}" ]
return true if the current token is seperated from the tokens before it which means either this is the start of the line, or there is at least one space or tab character behind the token otherwise returns false
[ "return", "true", "if", "the", "current", "token", "is", "seperated", "from", "the", "tokens", "before", "it", "which", "means", "either", "this", "is", "the", "start", "of", "the", "line", "or", "there", "is", "at", "least", "one", "space", "or", "tab", "character", "behind", "the", "token", "otherwise", "returns", "false" ]
50f9506224b65f9f171ac52e5a9c8311f9f41c67
https://github.com/fulmicoton/potato/blob/50f9506224b65f9f171ac52e5a9c8311f9f41c67/doc/assets/CodeMirror-2.22/mode/xmlpure/xmlpure.js#L90-L94
47,964
CodeOtter/bulkhead
lib/Plugin.js
loadPackage
function loadPackage(target, location, section, options, done) { if(section == 'config') { options.dirname = path.resolve(location + '/' + section); } else { options.dirname = path.resolve(location + '/api/' + section); } buildDictionary.optional(options, function(err, modules) { if(err) return done(err); if(section == 'config') { for(var i in modules) { target.config = _.extend(target.config || {}, modules[i]); } } else { target[section] = _.extend(target[section] || {}, modules); } return done(); }); }
javascript
function loadPackage(target, location, section, options, done) { if(section == 'config') { options.dirname = path.resolve(location + '/' + section); } else { options.dirname = path.resolve(location + '/api/' + section); } buildDictionary.optional(options, function(err, modules) { if(err) return done(err); if(section == 'config') { for(var i in modules) { target.config = _.extend(target.config || {}, modules[i]); } } else { target[section] = _.extend(target[section] || {}, modules); } return done(); }); }
[ "function", "loadPackage", "(", "target", ",", "location", ",", "section", ",", "options", ",", "done", ")", "{", "if", "(", "section", "==", "'config'", ")", "{", "options", ".", "dirname", "=", "path", ".", "resolve", "(", "location", "+", "'/'", "+", "section", ")", ";", "}", "else", "{", "options", ".", "dirname", "=", "path", ".", "resolve", "(", "location", "+", "'/api/'", "+", "section", ")", ";", "}", "buildDictionary", ".", "optional", "(", "options", ",", "function", "(", "err", ",", "modules", ")", "{", "if", "(", "err", ")", "return", "done", "(", "err", ")", ";", "if", "(", "section", "==", "'config'", ")", "{", "for", "(", "var", "i", "in", "modules", ")", "{", "target", ".", "config", "=", "_", ".", "extend", "(", "target", ".", "config", "||", "{", "}", ",", "modules", "[", "i", "]", ")", ";", "}", "}", "else", "{", "target", "[", "section", "]", "=", "_", ".", "extend", "(", "target", "[", "section", "]", "||", "{", "}", ",", "modules", ")", ";", "}", "return", "done", "(", ")", ";", "}", ")", ";", "}" ]
This function will merge Sails-like components into an NPM package, forming a Bulkhead package. @private @param Object The NPM module instance @param String The location of the package @param String The category name of Sails-like components @param Object Sails-build-directory configuration override @param Function The callback to fire when the package is loaded
[ "This", "function", "will", "merge", "Sails", "-", "like", "components", "into", "an", "NPM", "package", "forming", "a", "Bulkhead", "package", "." ]
7a247ef30a600c83dce0dd3e8921e306e2895324
https://github.com/CodeOtter/bulkhead/blob/7a247ef30a600c83dce0dd3e8921e306e2895324/lib/Plugin.js#L23-L42
47,965
CodeOtter/bulkhead
lib/Plugin.js
function(sails, done) { sails.log.silly('Initializing Bulkhead packages...'); // Detach models from the Sails instance var bulkheads = Object.keys(Bulkhead), i = 0, detachedLoadModels = sails.modules.loadModels; /** * Reload event that loads each Bulkhead package's models */ var reloadedEvent = function() { _.each(Bulkhead, function(bulkhead, bulkheadName) { // A registered Bulkhead package needs to be initiated, bound to the Sails instance, detached, and merged back into the Bulkhead _.each(bulkhead.models, function(model, index) { bulkhead.models[model.originalIdentity] = sails.models[model.identity]; bulkhead[model.originalGlobalId] = bulkhead.models[model.originalIdentity]; delete model.originalIdentity; delete model.originalGlobalId; }); _.each(bulkhead.services, function(service, index) { service.plugin = bulkhead; bulkhead[service.originalIdentity] = bulkhead.services[index]; delete service.originalIdentity; }); sails.log.silly(Object.keys(bulkhead.models).length + ' loaded from the ' + path.basename(bulkheadName) + ' package...'); }); sails.removeListener('hook:orm:reloaded', reloadedEvent); sails.modules.loadModels = detachedLoadModels; loaded = true; sails.log.silly('Bulkhead packages are active.'); done(); }; // Attach a custom reload event sails.on('hook:orm:reloaded', reloadedEvent); // Attaches and reloads the ORM if(!loaded && Bulkhead[bulkheads[i]]) { // We detach the model path to make sure that the loadModels module never refreshes and overrides sails.modules.loadModels = function(cb) { // Load all models into the global scope with namespacing sails.log.silly('Loading Bulkhead models...'); async.series([ detachedLoadModels, function(next) { var models = {}; _.each(Bulkhead, function(bulkhead) { _.each(bulkhead.models, function(model) { models[model.identity] = model; }); }); next(null, models); } ], function(err, results) { cb(null, _.extend(results[0], results[1])); }); }; sails.hooks.orm.reload(); } else { // No Bulkheads were detected if(loaded) { sails.log.silly('Bulkhead already loaded.'); } else { sails.log.silly('No Bulkhead packages found!'); } done(); } }
javascript
function(sails, done) { sails.log.silly('Initializing Bulkhead packages...'); // Detach models from the Sails instance var bulkheads = Object.keys(Bulkhead), i = 0, detachedLoadModels = sails.modules.loadModels; /** * Reload event that loads each Bulkhead package's models */ var reloadedEvent = function() { _.each(Bulkhead, function(bulkhead, bulkheadName) { // A registered Bulkhead package needs to be initiated, bound to the Sails instance, detached, and merged back into the Bulkhead _.each(bulkhead.models, function(model, index) { bulkhead.models[model.originalIdentity] = sails.models[model.identity]; bulkhead[model.originalGlobalId] = bulkhead.models[model.originalIdentity]; delete model.originalIdentity; delete model.originalGlobalId; }); _.each(bulkhead.services, function(service, index) { service.plugin = bulkhead; bulkhead[service.originalIdentity] = bulkhead.services[index]; delete service.originalIdentity; }); sails.log.silly(Object.keys(bulkhead.models).length + ' loaded from the ' + path.basename(bulkheadName) + ' package...'); }); sails.removeListener('hook:orm:reloaded', reloadedEvent); sails.modules.loadModels = detachedLoadModels; loaded = true; sails.log.silly('Bulkhead packages are active.'); done(); }; // Attach a custom reload event sails.on('hook:orm:reloaded', reloadedEvent); // Attaches and reloads the ORM if(!loaded && Bulkhead[bulkheads[i]]) { // We detach the model path to make sure that the loadModels module never refreshes and overrides sails.modules.loadModels = function(cb) { // Load all models into the global scope with namespacing sails.log.silly('Loading Bulkhead models...'); async.series([ detachedLoadModels, function(next) { var models = {}; _.each(Bulkhead, function(bulkhead) { _.each(bulkhead.models, function(model) { models[model.identity] = model; }); }); next(null, models); } ], function(err, results) { cb(null, _.extend(results[0], results[1])); }); }; sails.hooks.orm.reload(); } else { // No Bulkheads were detected if(loaded) { sails.log.silly('Bulkhead already loaded.'); } else { sails.log.silly('No Bulkhead packages found!'); } done(); } }
[ "function", "(", "sails", ",", "done", ")", "{", "sails", ".", "log", ".", "silly", "(", "'Initializing Bulkhead packages...'", ")", ";", "// Detach models from the Sails instance", "var", "bulkheads", "=", "Object", ".", "keys", "(", "Bulkhead", ")", ",", "i", "=", "0", ",", "detachedLoadModels", "=", "sails", ".", "modules", ".", "loadModels", ";", "/**\n\t\t * Reload event that loads each Bulkhead package's models\n\t\t */", "var", "reloadedEvent", "=", "function", "(", ")", "{", "_", ".", "each", "(", "Bulkhead", ",", "function", "(", "bulkhead", ",", "bulkheadName", ")", "{", "// A registered Bulkhead package needs to be initiated, bound to the Sails instance, detached, and merged back into the Bulkhead", "_", ".", "each", "(", "bulkhead", ".", "models", ",", "function", "(", "model", ",", "index", ")", "{", "bulkhead", ".", "models", "[", "model", ".", "originalIdentity", "]", "=", "sails", ".", "models", "[", "model", ".", "identity", "]", ";", "bulkhead", "[", "model", ".", "originalGlobalId", "]", "=", "bulkhead", ".", "models", "[", "model", ".", "originalIdentity", "]", ";", "delete", "model", ".", "originalIdentity", ";", "delete", "model", ".", "originalGlobalId", ";", "}", ")", ";", "_", ".", "each", "(", "bulkhead", ".", "services", ",", "function", "(", "service", ",", "index", ")", "{", "service", ".", "plugin", "=", "bulkhead", ";", "bulkhead", "[", "service", ".", "originalIdentity", "]", "=", "bulkhead", ".", "services", "[", "index", "]", ";", "delete", "service", ".", "originalIdentity", ";", "}", ")", ";", "sails", ".", "log", ".", "silly", "(", "Object", ".", "keys", "(", "bulkhead", ".", "models", ")", ".", "length", "+", "' loaded from the '", "+", "path", ".", "basename", "(", "bulkheadName", ")", "+", "' package...'", ")", ";", "}", ")", ";", "sails", ".", "removeListener", "(", "'hook:orm:reloaded'", ",", "reloadedEvent", ")", ";", "sails", ".", "modules", ".", "loadModels", "=", "detachedLoadModels", ";", "loaded", "=", "true", ";", "sails", ".", "log", ".", "silly", "(", "'Bulkhead packages are active.'", ")", ";", "done", "(", ")", ";", "}", ";", "// Attach a custom reload event", "sails", ".", "on", "(", "'hook:orm:reloaded'", ",", "reloadedEvent", ")", ";", "// Attaches and reloads the ORM", "if", "(", "!", "loaded", "&&", "Bulkhead", "[", "bulkheads", "[", "i", "]", "]", ")", "{", "// We detach the model path to make sure that the loadModels module never refreshes and overrides", "sails", ".", "modules", ".", "loadModels", "=", "function", "(", "cb", ")", "{", "// Load all models into the global scope with namespacing", "sails", ".", "log", ".", "silly", "(", "'Loading Bulkhead models...'", ")", ";", "async", ".", "series", "(", "[", "detachedLoadModels", ",", "function", "(", "next", ")", "{", "var", "models", "=", "{", "}", ";", "_", ".", "each", "(", "Bulkhead", ",", "function", "(", "bulkhead", ")", "{", "_", ".", "each", "(", "bulkhead", ".", "models", ",", "function", "(", "model", ")", "{", "models", "[", "model", ".", "identity", "]", "=", "model", ";", "}", ")", ";", "}", ")", ";", "next", "(", "null", ",", "models", ")", ";", "}", "]", ",", "function", "(", "err", ",", "results", ")", "{", "cb", "(", "null", ",", "_", ".", "extend", "(", "results", "[", "0", "]", ",", "results", "[", "1", "]", ")", ")", ";", "}", ")", ";", "}", ";", "sails", ".", "hooks", ".", "orm", ".", "reload", "(", ")", ";", "}", "else", "{", "// No Bulkheads were detected", "if", "(", "loaded", ")", "{", "sails", ".", "log", ".", "silly", "(", "'Bulkhead already loaded.'", ")", ";", "}", "else", "{", "sails", ".", "log", ".", "silly", "(", "'No Bulkhead packages found!'", ")", ";", "}", "done", "(", ")", ";", "}", "}" ]
Initializes all registered Bulkhead packages, grafts them to the Sails object, then moves them to their individual packages. @param Object Sails instance @param Function Callback to fire when initialization is finished
[ "Initializes", "all", "registered", "Bulkhead", "packages", "grafts", "them", "to", "the", "Sails", "object", "then", "moves", "them", "to", "their", "individual", "packages", "." ]
7a247ef30a600c83dce0dd3e8921e306e2895324
https://github.com/CodeOtter/bulkhead/blob/7a247ef30a600c83dce0dd3e8921e306e2895324/lib/Plugin.js#L70-L142
47,966
CodeOtter/bulkhead
lib/Plugin.js
function() { _.each(Bulkhead, function(bulkhead, bulkheadName) { // A registered Bulkhead package needs to be initiated, bound to the Sails instance, detached, and merged back into the Bulkhead _.each(bulkhead.models, function(model, index) { bulkhead.models[model.originalIdentity] = sails.models[model.identity]; bulkhead[model.originalGlobalId] = bulkhead.models[model.originalIdentity]; delete model.originalIdentity; delete model.originalGlobalId; }); _.each(bulkhead.services, function(service, index) { service.plugin = bulkhead; bulkhead[service.originalIdentity] = bulkhead.services[index]; delete service.originalIdentity; }); sails.log.silly(Object.keys(bulkhead.models).length + ' loaded from the ' + path.basename(bulkheadName) + ' package...'); }); sails.removeListener('hook:orm:reloaded', reloadedEvent); sails.modules.loadModels = detachedLoadModels; loaded = true; sails.log.silly('Bulkhead packages are active.'); done(); }
javascript
function() { _.each(Bulkhead, function(bulkhead, bulkheadName) { // A registered Bulkhead package needs to be initiated, bound to the Sails instance, detached, and merged back into the Bulkhead _.each(bulkhead.models, function(model, index) { bulkhead.models[model.originalIdentity] = sails.models[model.identity]; bulkhead[model.originalGlobalId] = bulkhead.models[model.originalIdentity]; delete model.originalIdentity; delete model.originalGlobalId; }); _.each(bulkhead.services, function(service, index) { service.plugin = bulkhead; bulkhead[service.originalIdentity] = bulkhead.services[index]; delete service.originalIdentity; }); sails.log.silly(Object.keys(bulkhead.models).length + ' loaded from the ' + path.basename(bulkheadName) + ' package...'); }); sails.removeListener('hook:orm:reloaded', reloadedEvent); sails.modules.loadModels = detachedLoadModels; loaded = true; sails.log.silly('Bulkhead packages are active.'); done(); }
[ "function", "(", ")", "{", "_", ".", "each", "(", "Bulkhead", ",", "function", "(", "bulkhead", ",", "bulkheadName", ")", "{", "// A registered Bulkhead package needs to be initiated, bound to the Sails instance, detached, and merged back into the Bulkhead", "_", ".", "each", "(", "bulkhead", ".", "models", ",", "function", "(", "model", ",", "index", ")", "{", "bulkhead", ".", "models", "[", "model", ".", "originalIdentity", "]", "=", "sails", ".", "models", "[", "model", ".", "identity", "]", ";", "bulkhead", "[", "model", ".", "originalGlobalId", "]", "=", "bulkhead", ".", "models", "[", "model", ".", "originalIdentity", "]", ";", "delete", "model", ".", "originalIdentity", ";", "delete", "model", ".", "originalGlobalId", ";", "}", ")", ";", "_", ".", "each", "(", "bulkhead", ".", "services", ",", "function", "(", "service", ",", "index", ")", "{", "service", ".", "plugin", "=", "bulkhead", ";", "bulkhead", "[", "service", ".", "originalIdentity", "]", "=", "bulkhead", ".", "services", "[", "index", "]", ";", "delete", "service", ".", "originalIdentity", ";", "}", ")", ";", "sails", ".", "log", ".", "silly", "(", "Object", ".", "keys", "(", "bulkhead", ".", "models", ")", ".", "length", "+", "' loaded from the '", "+", "path", ".", "basename", "(", "bulkheadName", ")", "+", "' package...'", ")", ";", "}", ")", ";", "sails", ".", "removeListener", "(", "'hook:orm:reloaded'", ",", "reloadedEvent", ")", ";", "sails", ".", "modules", ".", "loadModels", "=", "detachedLoadModels", ";", "loaded", "=", "true", ";", "sails", ".", "log", ".", "silly", "(", "'Bulkhead packages are active.'", ")", ";", "done", "(", ")", ";", "}" ]
Reload event that loads each Bulkhead package's models
[ "Reload", "event", "that", "loads", "each", "Bulkhead", "package", "s", "models" ]
7a247ef30a600c83dce0dd3e8921e306e2895324
https://github.com/CodeOtter/bulkhead/blob/7a247ef30a600c83dce0dd3e8921e306e2895324/lib/Plugin.js#L80-L104
47,967
rtm/upward
src/Upw.js
make
function make(x, options = {}) { var {debug = DEBUG_ALL} = options; var u; debug = DEBUG && debug; if (x === undefined) u = makeUndefined(); else if (x === null) u = makeNull(); else { u = Object(x); if (!is(u)) { add(u, debug); defineProperty(u, 'change', { value: change }); } } if (debug) console.debug(...channel.debug("Created upwardable", u._upwardableId, "from", x)); return u; }
javascript
function make(x, options = {}) { var {debug = DEBUG_ALL} = options; var u; debug = DEBUG && debug; if (x === undefined) u = makeUndefined(); else if (x === null) u = makeNull(); else { u = Object(x); if (!is(u)) { add(u, debug); defineProperty(u, 'change', { value: change }); } } if (debug) console.debug(...channel.debug("Created upwardable", u._upwardableId, "from", x)); return u; }
[ "function", "make", "(", "x", ",", "options", "=", "{", "}", ")", "{", "var", "{", "debug", "=", "DEBUG_ALL", "}", "=", "options", ";", "var", "u", ";", "debug", "=", "DEBUG", "&&", "debug", ";", "if", "(", "x", "===", "undefined", ")", "u", "=", "makeUndefined", "(", ")", ";", "else", "if", "(", "x", "===", "null", ")", "u", "=", "makeNull", "(", ")", ";", "else", "{", "u", "=", "Object", "(", "x", ")", ";", "if", "(", "!", "is", "(", "u", ")", ")", "{", "add", "(", "u", ",", "debug", ")", ";", "defineProperty", "(", "u", ",", "'change'", ",", "{", "value", ":", "change", "}", ")", ";", "}", "}", "if", "(", "debug", ")", "console", ".", "debug", "(", "...", "channel", ".", "debug", "(", "\"Created upwardable\"", ",", "u", ".", "_upwardableId", ",", "\"from\"", ",", "x", ")", ")", ";", "return", "u", ";", "}" ]
Make a new upwardable. Register it, and add a `change` method which notifies when it is to be replaced.
[ "Make", "a", "new", "upwardable", ".", "Register", "it", "and", "add", "a", "change", "method", "which", "notifies", "when", "it", "is", "to", "be", "replaced", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Upw.js#L47-L64
47,968
rtm/upward
src/Upw.js
change
function change(x) { var u = this; var debug = u._upwardableDebug; if (x !== this.valueOf()) { u = make(x, { debug }); getNotifier(this).notify({object: this, newValue: u, type: 'upward'}); if (debug) { console.debug(...channel.debug("Replaced upwardable", this._upwardableId, "with", u._upwardableId)); } } return u; }
javascript
function change(x) { var u = this; var debug = u._upwardableDebug; if (x !== this.valueOf()) { u = make(x, { debug }); getNotifier(this).notify({object: this, newValue: u, type: 'upward'}); if (debug) { console.debug(...channel.debug("Replaced upwardable", this._upwardableId, "with", u._upwardableId)); } } return u; }
[ "function", "change", "(", "x", ")", "{", "var", "u", "=", "this", ";", "var", "debug", "=", "u", ".", "_upwardableDebug", ";", "if", "(", "x", "!==", "this", ".", "valueOf", "(", ")", ")", "{", "u", "=", "make", "(", "x", ",", "{", "debug", "}", ")", ";", "getNotifier", "(", "this", ")", ".", "notify", "(", "{", "object", ":", "this", ",", "newValue", ":", "u", ",", "type", ":", "'upward'", "}", ")", ";", "if", "(", "debug", ")", "{", "console", ".", "debug", "(", "...", "channel", ".", "debug", "(", "\"Replaced upwardable\"", ",", "this", ".", "_upwardableId", ",", "\"with\"", ",", "u", ".", "_upwardableId", ")", ")", ";", "}", "}", "return", "u", ";", "}" ]
Change an upwardable. Issue notification that it has changed.
[ "Change", "an", "upwardable", ".", "Issue", "notification", "that", "it", "has", "changed", "." ]
82495c34f70c9a4336a3b34cc6781e5662324c03
https://github.com/rtm/upward/blob/82495c34f70c9a4336a3b34cc6781e5662324c03/src/Upw.js#L67-L80
47,969
hexoul/metasdk-react
src/components/util.js
setQRstyle
function setQRstyle (dst, src, caller) { dst['qrpopup'] = src.qrpopup ? src.qrpopup : false dst['qrsize'] = src.qrsize > 0 ? src.qrsize : 128 dst['qrvoffset'] = src.qrvoffset >= 0 ? src.qrvoffset : 20 dst['qrpadding'] = src.qrpadding ? src.qrpadding : '1em' dst['qrposition'] = POSITIONS.includes(src.qrposition) ? src.qrposition : 'bottom right' dst['qrtext'] = src.qrtext ? src.qrtext : caller }
javascript
function setQRstyle (dst, src, caller) { dst['qrpopup'] = src.qrpopup ? src.qrpopup : false dst['qrsize'] = src.qrsize > 0 ? src.qrsize : 128 dst['qrvoffset'] = src.qrvoffset >= 0 ? src.qrvoffset : 20 dst['qrpadding'] = src.qrpadding ? src.qrpadding : '1em' dst['qrposition'] = POSITIONS.includes(src.qrposition) ? src.qrposition : 'bottom right' dst['qrtext'] = src.qrtext ? src.qrtext : caller }
[ "function", "setQRstyle", "(", "dst", ",", "src", ",", "caller", ")", "{", "dst", "[", "'qrpopup'", "]", "=", "src", ".", "qrpopup", "?", "src", ".", "qrpopup", ":", "false", "dst", "[", "'qrsize'", "]", "=", "src", ".", "qrsize", ">", "0", "?", "src", ".", "qrsize", ":", "128", "dst", "[", "'qrvoffset'", "]", "=", "src", ".", "qrvoffset", ">=", "0", "?", "src", ".", "qrvoffset", ":", "20", "dst", "[", "'qrpadding'", "]", "=", "src", ".", "qrpadding", "?", "src", ".", "qrpadding", ":", "'1em'", "dst", "[", "'qrposition'", "]", "=", "POSITIONS", ".", "includes", "(", "src", ".", "qrposition", ")", "?", "src", ".", "qrposition", ":", "'bottom right'", "dst", "[", "'qrtext'", "]", "=", "src", ".", "qrtext", "?", "src", ".", "qrtext", ":", "caller", "}" ]
Set QRCode style to dst from src @param {map} dst @param {map} src props @param {string} caller name
[ "Set", "QRCode", "style", "to", "dst", "from", "src" ]
5aa275bf2e19336edc1f5f0d3b43afc979cc2f42
https://github.com/hexoul/metasdk-react/blob/5aa275bf2e19336edc1f5f0d3b43afc979cc2f42/src/components/util.js#L25-L32
47,970
hexoul/metasdk-react
src/components/util.js
convertData2Hexd
function convertData2Hexd (data) { if (!isHexString(data)) { var hex = '' for (var i = 0; i < data.length; i++) { hex += data.charCodeAt(i).toString(16) } return '0x' + hex } return data }
javascript
function convertData2Hexd (data) { if (!isHexString(data)) { var hex = '' for (var i = 0; i < data.length; i++) { hex += data.charCodeAt(i).toString(16) } return '0x' + hex } return data }
[ "function", "convertData2Hexd", "(", "data", ")", "{", "if", "(", "!", "isHexString", "(", "data", ")", ")", "{", "var", "hex", "=", "''", "for", "(", "var", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "hex", "+=", "data", ".", "charCodeAt", "(", "i", ")", ".", "toString", "(", "16", ")", "}", "return", "'0x'", "+", "hex", "}", "return", "data", "}" ]
Convert to hexadecimal for data property of SendTransaction @param {*} data
[ "Convert", "to", "hexadecimal", "for", "data", "property", "of", "SendTransaction" ]
5aa275bf2e19336edc1f5f0d3b43afc979cc2f42
https://github.com/hexoul/metasdk-react/blob/5aa275bf2e19336edc1f5f0d3b43afc979cc2f42/src/components/util.js#L66-L75
47,971
alexindigo/batcher
lib/augmenter.js
augmenter
function augmenter(object, subject, hookCb) { var unaugment, originalCb = object[subject]; unaugment = function() { // return everything back to normal object[subject] = originalCb; }; object[subject] = function() { var args = Array.prototype.slice.call(arguments) , result = originalCb.apply(this, args) ; // revert callback augmentation unaugment(); // with everything out of the way // invoke custom hook return hookCb.call(this, [result].concat(args)); }; return unaugment; }
javascript
function augmenter(object, subject, hookCb) { var unaugment, originalCb = object[subject]; unaugment = function() { // return everything back to normal object[subject] = originalCb; }; object[subject] = function() { var args = Array.prototype.slice.call(arguments) , result = originalCb.apply(this, args) ; // revert callback augmentation unaugment(); // with everything out of the way // invoke custom hook return hookCb.call(this, [result].concat(args)); }; return unaugment; }
[ "function", "augmenter", "(", "object", ",", "subject", ",", "hookCb", ")", "{", "var", "unaugment", ",", "originalCb", "=", "object", "[", "subject", "]", ";", "unaugment", "=", "function", "(", ")", "{", "// return everything back to normal", "object", "[", "subject", "]", "=", "originalCb", ";", "}", ";", "object", "[", "subject", "]", "=", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ",", "result", "=", "originalCb", ".", "apply", "(", "this", ",", "args", ")", ";", "// revert callback augmentation", "unaugment", "(", ")", ";", "// with everything out of the way", "// invoke custom hook", "return", "hookCb", ".", "call", "(", "this", ",", "[", "result", "]", ".", "concat", "(", "args", ")", ")", ";", "}", ";", "return", "unaugment", ";", "}" ]
Augments provided callback to invoke custom hook after original callback invocation but before passing control @param {object} object - object to augment @param {string} subject - name of the callback property @param {function} hookCb - hook callback to add to the chain @returns {function} - provide un-augment function
[ "Augments", "provided", "callback", "to", "invoke", "custom", "hook", "after", "original", "callback", "invocation", "but", "before", "passing", "control" ]
73d9c8c994f915688db0627ea3b4854ead771138
https://github.com/alexindigo/batcher/blob/73d9c8c994f915688db0627ea3b4854ead771138/lib/augmenter.js#L13-L38
47,972
richardschneider/table-master-parser
lib/parser.js
step
function step() { var f = script.shift(); if(f) { f(stack, step); } else { return cb(null, stack.pop()); } }
javascript
function step() { var f = script.shift(); if(f) { f(stack, step); } else { return cb(null, stack.pop()); } }
[ "function", "step", "(", ")", "{", "var", "f", "=", "script", ".", "shift", "(", ")", ";", "if", "(", "f", ")", "{", "f", "(", "stack", ",", "step", ")", ";", "}", "else", "{", "return", "cb", "(", "null", ",", "stack", ".", "pop", "(", ")", ")", ";", "}", "}" ]
Execute the functions asynchronously
[ "Execute", "the", "functions", "asynchronously" ]
4236d465ba209f1f00b3c09631d75a9ec607c9e8
https://github.com/richardschneider/table-master-parser/blob/4236d465ba209f1f00b3c09631d75a9ec607c9e8/lib/parser.js#L23-L31
47,973
stayradiated/onepasswordjs
src/crypto_browser.js
function(ciphertext, key, iv, encoding) { var binary, bytes, hex; if (encoding == null) { encoding = "buffer"; } iv = this.toBuffer(iv); key = this.toBuffer(key); ciphertext = this.toBuffer(ciphertext); binary = Gibberish.rawDecrypt(ciphertext, key, iv, true); hex = this.bin2hex(binary); if (encoding === 'hex') { return hex; } bytes = Gibberish.h2a(hex); if (encoding === 'base64') { return Gibberish.Base64.encode(bytes); } if (encoding === "buffer") { return bytes; } else { throw new Error("Encoding now supported"); } }
javascript
function(ciphertext, key, iv, encoding) { var binary, bytes, hex; if (encoding == null) { encoding = "buffer"; } iv = this.toBuffer(iv); key = this.toBuffer(key); ciphertext = this.toBuffer(ciphertext); binary = Gibberish.rawDecrypt(ciphertext, key, iv, true); hex = this.bin2hex(binary); if (encoding === 'hex') { return hex; } bytes = Gibberish.h2a(hex); if (encoding === 'base64') { return Gibberish.Base64.encode(bytes); } if (encoding === "buffer") { return bytes; } else { throw new Error("Encoding now supported"); } }
[ "function", "(", "ciphertext", ",", "key", ",", "iv", ",", "encoding", ")", "{", "var", "binary", ",", "bytes", ",", "hex", ";", "if", "(", "encoding", "==", "null", ")", "{", "encoding", "=", "\"buffer\"", ";", "}", "iv", "=", "this", ".", "toBuffer", "(", "iv", ")", ";", "key", "=", "this", ".", "toBuffer", "(", "key", ")", ";", "ciphertext", "=", "this", ".", "toBuffer", "(", "ciphertext", ")", ";", "binary", "=", "Gibberish", ".", "rawDecrypt", "(", "ciphertext", ",", "key", ",", "iv", ",", "true", ")", ";", "hex", "=", "this", ".", "bin2hex", "(", "binary", ")", ";", "if", "(", "encoding", "===", "'hex'", ")", "{", "return", "hex", ";", "}", "bytes", "=", "Gibberish", ".", "h2a", "(", "hex", ")", ";", "if", "(", "encoding", "===", "'base64'", ")", "{", "return", "Gibberish", ".", "Base64", ".", "encode", "(", "bytes", ")", ";", "}", "if", "(", "encoding", "===", "\"buffer\"", ")", "{", "return", "bytes", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"Encoding now supported\"", ")", ";", "}", "}" ]
Decipher encrypted data. @param {String|Buffer} ciphertext The data to decipher. Must be a multiple of the blocksize. @param {String|Buffer} key The key to decipher the data with. @param {String|Buffer} iv The initialization vector to use. @param {String} [encoding=buffer] The format to return the decrypted contents as. @return {Buffer|String} The decrypted contents.
[ "Decipher", "encrypted", "data", "." ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L59-L81
47,974
stayradiated/onepasswordjs
src/crypto_browser.js
function(password, salt, iterations, keysize) { var bits, hmac, self; if (iterations == null) { iterations = 10000; } if (keysize == null) { keysize = 512; } self = this; hmac = (function() { function hmac(key) { this.key = sjcl.codec.bytes.fromBits(key); } hmac.prototype.encrypt = function(sjclArray) { var bits, byteArray, hex; byteArray = sjcl.codec.bytes.fromBits(sjclArray); hex = self.hmac(byteArray, this.key, keysize); bits = sjcl.codec.hex.toBits(hex); return bits; }; return hmac; })(); salt = sjcl.codec.hex.toBits(this.toHex(salt)); bits = sjcl.misc.pbkdf2(password, salt, iterations, keysize, hmac); return sjcl.codec.hex.fromBits(bits); }
javascript
function(password, salt, iterations, keysize) { var bits, hmac, self; if (iterations == null) { iterations = 10000; } if (keysize == null) { keysize = 512; } self = this; hmac = (function() { function hmac(key) { this.key = sjcl.codec.bytes.fromBits(key); } hmac.prototype.encrypt = function(sjclArray) { var bits, byteArray, hex; byteArray = sjcl.codec.bytes.fromBits(sjclArray); hex = self.hmac(byteArray, this.key, keysize); bits = sjcl.codec.hex.toBits(hex); return bits; }; return hmac; })(); salt = sjcl.codec.hex.toBits(this.toHex(salt)); bits = sjcl.misc.pbkdf2(password, salt, iterations, keysize, hmac); return sjcl.codec.hex.fromBits(bits); }
[ "function", "(", "password", ",", "salt", ",", "iterations", ",", "keysize", ")", "{", "var", "bits", ",", "hmac", ",", "self", ";", "if", "(", "iterations", "==", "null", ")", "{", "iterations", "=", "10000", ";", "}", "if", "(", "keysize", "==", "null", ")", "{", "keysize", "=", "512", ";", "}", "self", "=", "this", ";", "hmac", "=", "(", "function", "(", ")", "{", "function", "hmac", "(", "key", ")", "{", "this", ".", "key", "=", "sjcl", ".", "codec", ".", "bytes", ".", "fromBits", "(", "key", ")", ";", "}", "hmac", ".", "prototype", ".", "encrypt", "=", "function", "(", "sjclArray", ")", "{", "var", "bits", ",", "byteArray", ",", "hex", ";", "byteArray", "=", "sjcl", ".", "codec", ".", "bytes", ".", "fromBits", "(", "sjclArray", ")", ";", "hex", "=", "self", ".", "hmac", "(", "byteArray", ",", "this", ".", "key", ",", "keysize", ")", ";", "bits", "=", "sjcl", ".", "codec", ".", "hex", ".", "toBits", "(", "hex", ")", ";", "return", "bits", ";", "}", ";", "return", "hmac", ";", "}", ")", "(", ")", ";", "salt", "=", "sjcl", ".", "codec", ".", "hex", ".", "toBits", "(", "this", ".", "toHex", "(", "salt", ")", ")", ";", "bits", "=", "sjcl", ".", "misc", ".", "pbkdf2", "(", "password", ",", "salt", ",", "iterations", ",", "keysize", ",", "hmac", ")", ";", "return", "sjcl", ".", "codec", ".", "hex", ".", "fromBits", "(", "bits", ")", ";", "}" ]
Generate keys from password using PKDF2-HMAC-SHA512. @param {String} password The password. @param {String|Buffer} salt The salt. @param {Number} [iterations=10000] The numbers of iterations. @param {Numbers} [keysize=512] The length of the derived key in bits. @return {String} Returns the derived key encoded as hex.
[ "Generate", "keys", "from", "password", "using", "PKDF2", "-", "HMAC", "-", "SHA512", "." ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L91-L119
47,975
stayradiated/onepasswordjs
src/crypto_browser.js
function(data, key, keysize) { var input, mode; if (keysize == null) { keysize = 512; } data = this.toHex(data); key = this.toHex(key); mode = "SHA-" + keysize; input = new jsSHA(data, "HEX"); return input.getHMAC(key, "HEX", mode, "HEX"); }
javascript
function(data, key, keysize) { var input, mode; if (keysize == null) { keysize = 512; } data = this.toHex(data); key = this.toHex(key); mode = "SHA-" + keysize; input = new jsSHA(data, "HEX"); return input.getHMAC(key, "HEX", mode, "HEX"); }
[ "function", "(", "data", ",", "key", ",", "keysize", ")", "{", "var", "input", ",", "mode", ";", "if", "(", "keysize", "==", "null", ")", "{", "keysize", "=", "512", ";", "}", "data", "=", "this", ".", "toHex", "(", "data", ")", ";", "key", "=", "this", ".", "toHex", "(", "key", ")", ";", "mode", "=", "\"SHA-\"", "+", "keysize", ";", "input", "=", "new", "jsSHA", "(", "data", ",", "\"HEX\"", ")", ";", "return", "input", ".", "getHMAC", "(", "key", ",", "\"HEX\"", ",", "mode", ",", "\"HEX\"", ")", ";", "}" ]
Cryptographically hash data using HMAC. @param {String|Buffer} data The data to be hashed. @param {String|Buffer} key The key to use with HMAC. @param {Number} [keysize=512] The keysize for the hash function. @return {String} The hmac digest encoded as hex.
[ "Cryptographically", "hash", "data", "using", "HMAC", "." ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L128-L138
47,976
stayradiated/onepasswordjs
src/crypto_browser.js
function(data, keysize) { var input, mode; if (keysize == null) { keysize = 512; } data = this.toHex(data); mode = "SHA-" + keysize; input = new jsSHA(data, "HEX"); return input.getHash(mode, "HEX"); }
javascript
function(data, keysize) { var input, mode; if (keysize == null) { keysize = 512; } data = this.toHex(data); mode = "SHA-" + keysize; input = new jsSHA(data, "HEX"); return input.getHash(mode, "HEX"); }
[ "function", "(", "data", ",", "keysize", ")", "{", "var", "input", ",", "mode", ";", "if", "(", "keysize", "==", "null", ")", "{", "keysize", "=", "512", ";", "}", "data", "=", "this", ".", "toHex", "(", "data", ")", ";", "mode", "=", "\"SHA-\"", "+", "keysize", ";", "input", "=", "new", "jsSHA", "(", "data", ",", "\"HEX\"", ")", ";", "return", "input", ".", "getHash", "(", "mode", ",", "\"HEX\"", ")", ";", "}" ]
Create a hash digest of data. @param {String|Buffer} data The data to hash. @param {Number} [keysize=512] The keysize for the hash function. @return {String} The hash digest encoded as hex.
[ "Create", "a", "hash", "digest", "of", "data", "." ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L146-L155
47,977
stayradiated/onepasswordjs
src/crypto_browser.js
function(data) { var bytesToPad, padding; bytesToPad = BLOCKSIZE - (data.length % BLOCKSIZE); padding = this.randomBytes(bytesToPad); return this.concat([padding, data]); }
javascript
function(data) { var bytesToPad, padding; bytesToPad = BLOCKSIZE - (data.length % BLOCKSIZE); padding = this.randomBytes(bytesToPad); return this.concat([padding, data]); }
[ "function", "(", "data", ")", "{", "var", "bytesToPad", ",", "padding", ";", "bytesToPad", "=", "BLOCKSIZE", "-", "(", "data", ".", "length", "%", "BLOCKSIZE", ")", ";", "padding", "=", "this", ".", "randomBytes", "(", "bytesToPad", ")", ";", "return", "this", ".", "concat", "(", "[", "padding", ",", "data", "]", ")", ";", "}" ]
Prepend padding to data to make it fill the blocksize. @param {Buffer} data The data to pad. @return {Buffer} The data with padding added.
[ "Prepend", "padding", "to", "data", "to", "make", "it", "fill", "the", "blocksize", "." ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L162-L167
47,978
stayradiated/onepasswordjs
src/crypto_browser.js
function(length) { var array, byte, _i, _len, _results; array = new Uint8Array(length); window.crypto.getRandomValues(array); _results = []; for (_i = 0, _len = array.length; _i < _len; _i++) { byte = array[_i]; _results.push(byte); } return _results; }
javascript
function(length) { var array, byte, _i, _len, _results; array = new Uint8Array(length); window.crypto.getRandomValues(array); _results = []; for (_i = 0, _len = array.length; _i < _len; _i++) { byte = array[_i]; _results.push(byte); } return _results; }
[ "function", "(", "length", ")", "{", "var", "array", ",", "byte", ",", "_i", ",", "_len", ",", "_results", ";", "array", "=", "new", "Uint8Array", "(", "length", ")", ";", "window", ".", "crypto", ".", "getRandomValues", "(", "array", ")", ";", "_results", "=", "[", "]", ";", "for", "(", "_i", "=", "0", ",", "_len", "=", "array", ".", "length", ";", "_i", "<", "_len", ";", "_i", "++", ")", "{", "byte", "=", "array", "[", "_i", "]", ";", "_results", ".", "push", "(", "byte", ")", ";", "}", "return", "_results", ";", "}" ]
Generates cryptographically strong pseudo-random data. @param {Numbers} length How many bytes of data you want. @return {Buffer} The random data as a Buffer.
[ "Generates", "cryptographically", "strong", "pseudo", "-", "random", "data", "." ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L186-L196
47,979
stayradiated/onepasswordjs
src/crypto_browser.js
function(data, encoding) { if (encoding == null) { encoding = 'hex'; } if (Array.isArray(data)) { return data; } switch (encoding) { case 'base64': return Gibberish.base64.decode(data); case 'hex': return Gibberish.h2a(data); case 'utf8': return Gibberish.s2a(data); default: throw new Error("Encoding not supported"); } }
javascript
function(data, encoding) { if (encoding == null) { encoding = 'hex'; } if (Array.isArray(data)) { return data; } switch (encoding) { case 'base64': return Gibberish.base64.decode(data); case 'hex': return Gibberish.h2a(data); case 'utf8': return Gibberish.s2a(data); default: throw new Error("Encoding not supported"); } }
[ "function", "(", "data", ",", "encoding", ")", "{", "if", "(", "encoding", "==", "null", ")", "{", "encoding", "=", "'hex'", ";", "}", "if", "(", "Array", ".", "isArray", "(", "data", ")", ")", "{", "return", "data", ";", "}", "switch", "(", "encoding", ")", "{", "case", "'base64'", ":", "return", "Gibberish", ".", "base64", ".", "decode", "(", "data", ")", ";", "case", "'hex'", ":", "return", "Gibberish", ".", "h2a", "(", "data", ")", ";", "case", "'utf8'", ":", "return", "Gibberish", ".", "s2a", "(", "data", ")", ";", "default", ":", "throw", "new", "Error", "(", "\"Encoding not supported\"", ")", ";", "}", "}" ]
Convert data to a Buffer @param {String|Buffer} data The data to be converted. If a string, must be encoded as hex. @param {String} [encoding=hex] The format of the data to convert. @return {Buffer} The data as a Buffer
[ "Convert", "data", "to", "a", "Buffer" ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L204-L221
47,980
stayradiated/onepasswordjs
src/crypto_browser.js
function(hex) { var pow, result; result = 0; pow = 0; while (hex.length > 0) { result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow); hex = hex.substring(2, hex.length); pow += 8; } return result; }
javascript
function(hex) { var pow, result; result = 0; pow = 0; while (hex.length > 0) { result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow); hex = hex.substring(2, hex.length); pow += 8; } return result; }
[ "function", "(", "hex", ")", "{", "var", "pow", ",", "result", ";", "result", "=", "0", ";", "pow", "=", "0", ";", "while", "(", "hex", ".", "length", ">", "0", ")", "{", "result", "+=", "parseInt", "(", "hex", ".", "substring", "(", "0", ",", "2", ")", ",", "16", ")", "*", "Math", ".", "pow", "(", "2", ",", "pow", ")", ";", "hex", "=", "hex", ".", "substring", "(", "2", ",", "hex", ".", "length", ")", ";", "pow", "+=", "8", ";", "}", "return", "result", ";", "}" ]
Parse a litte endian number. @author Jim Rogers {@link http://www.jimandkatrin.com/CodeBlog/post/Parse-a-little-endian.aspx} @param {String} hex The little endian number. @return {Number} The little endian converted to a number.
[ "Parse", "a", "litte", "endian", "number", "." ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L259-L269
47,981
stayradiated/onepasswordjs
src/crypto_browser.js
function(number, pad) { var endian, i, multiplier, padding, power, remainder, value, _i; if (pad == null) { pad = true; } power = Math.floor((Math.log(number) / Math.LN2) / 8) * 8; multiplier = Math.pow(2, power); value = Math.floor(number / multiplier); remainder = number % multiplier; endian = ""; if (remainder > 255) { endian += this.stringifyLittleEndian(remainder, false); } else if (power !== 0) { endian += this.dec2hex(remainder); } endian += this.dec2hex(value); if (pad) { padding = 16 - endian.length; for (i = _i = 0; _i < padding; i = _i += 1) { endian += "0"; } } return endian; }
javascript
function(number, pad) { var endian, i, multiplier, padding, power, remainder, value, _i; if (pad == null) { pad = true; } power = Math.floor((Math.log(number) / Math.LN2) / 8) * 8; multiplier = Math.pow(2, power); value = Math.floor(number / multiplier); remainder = number % multiplier; endian = ""; if (remainder > 255) { endian += this.stringifyLittleEndian(remainder, false); } else if (power !== 0) { endian += this.dec2hex(remainder); } endian += this.dec2hex(value); if (pad) { padding = 16 - endian.length; for (i = _i = 0; _i < padding; i = _i += 1) { endian += "0"; } } return endian; }
[ "function", "(", "number", ",", "pad", ")", "{", "var", "endian", ",", "i", ",", "multiplier", ",", "padding", ",", "power", ",", "remainder", ",", "value", ",", "_i", ";", "if", "(", "pad", "==", "null", ")", "{", "pad", "=", "true", ";", "}", "power", "=", "Math", ".", "floor", "(", "(", "Math", ".", "log", "(", "number", ")", "/", "Math", ".", "LN2", ")", "/", "8", ")", "*", "8", ";", "multiplier", "=", "Math", ".", "pow", "(", "2", ",", "power", ")", ";", "value", "=", "Math", ".", "floor", "(", "number", "/", "multiplier", ")", ";", "remainder", "=", "number", "%", "multiplier", ";", "endian", "=", "\"\"", ";", "if", "(", "remainder", ">", "255", ")", "{", "endian", "+=", "this", ".", "stringifyLittleEndian", "(", "remainder", ",", "false", ")", ";", "}", "else", "if", "(", "power", "!==", "0", ")", "{", "endian", "+=", "this", ".", "dec2hex", "(", "remainder", ")", ";", "}", "endian", "+=", "this", ".", "dec2hex", "(", "value", ")", ";", "if", "(", "pad", ")", "{", "padding", "=", "16", "-", "endian", ".", "length", ";", "for", "(", "i", "=", "_i", "=", "0", ";", "_i", "<", "padding", ";", "i", "=", "_i", "+=", "1", ")", "{", "endian", "+=", "\"0\"", ";", "}", "}", "return", "endian", ";", "}" ]
Convert an integer into a little endian. @param {Number} number The integer you want to convert. @param {Boolean} [pad=true] Pad the little endian with zeroes. @return {String} The little endian.
[ "Convert", "an", "integer", "into", "a", "little", "endian", "." ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L277-L300
47,982
stayradiated/onepasswordjs
src/crypto_browser.js
function(dec) { var hex; hex = dec.toString(16); if (hex.length < 2) { hex = "0" + hex; } return hex; }
javascript
function(dec) { var hex; hex = dec.toString(16); if (hex.length < 2) { hex = "0" + hex; } return hex; }
[ "function", "(", "dec", ")", "{", "var", "hex", ";", "hex", "=", "dec", ".", "toString", "(", "16", ")", ";", "if", "(", "hex", ".", "length", "<", "2", ")", "{", "hex", "=", "\"0\"", "+", "hex", ";", "}", "return", "hex", ";", "}" ]
Turn a decimal into a hexadecimal. @param {Number} dec The decimal. @return {String} The hexadecimal.
[ "Turn", "a", "decimal", "into", "a", "hexadecimal", "." ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L307-L314
47,983
stayradiated/onepasswordjs
src/crypto_browser.js
function(binary) { var char, hex, _i, _len; hex = ""; for (_i = 0, _len = binary.length; _i < _len; _i++) { char = binary[_i]; hex += char.charCodeAt(0).toString(16).replace(/^([\dA-F])$/i, "0$1"); } return hex; }
javascript
function(binary) { var char, hex, _i, _len; hex = ""; for (_i = 0, _len = binary.length; _i < _len; _i++) { char = binary[_i]; hex += char.charCodeAt(0).toString(16).replace(/^([\dA-F])$/i, "0$1"); } return hex; }
[ "function", "(", "binary", ")", "{", "var", "char", ",", "hex", ",", "_i", ",", "_len", ";", "hex", "=", "\"\"", ";", "for", "(", "_i", "=", "0", ",", "_len", "=", "binary", ".", "length", ";", "_i", "<", "_len", ";", "_i", "++", ")", "{", "char", "=", "binary", "[", "_i", "]", ";", "hex", "+=", "char", ".", "charCodeAt", "(", "0", ")", ".", "toString", "(", "16", ")", ".", "replace", "(", "/", "^([\\dA-F])$", "/", "i", ",", "\"0$1\"", ")", ";", "}", "return", "hex", ";", "}" ]
Convert a binary string into a hex string. @param {String} binary The binary encoded string. @return {String} The hex encoded string.
[ "Convert", "a", "binary", "string", "into", "a", "hex", "string", "." ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L321-L329
47,984
stayradiated/onepasswordjs
src/crypto_browser.js
function(length) { var bytes, hex; if (length == null) { length = 32; } length /= 2; bytes = this.randomBytes(length); return hex = this.toHex(bytes).toUpperCase(); }
javascript
function(length) { var bytes, hex; if (length == null) { length = 32; } length /= 2; bytes = this.randomBytes(length); return hex = this.toHex(bytes).toUpperCase(); }
[ "function", "(", "length", ")", "{", "var", "bytes", ",", "hex", ";", "if", "(", "length", "==", "null", ")", "{", "length", "=", "32", ";", "}", "length", "/=", "2", ";", "bytes", "=", "this", ".", "randomBytes", "(", "length", ")", ";", "return", "hex", "=", "this", ".", "toHex", "(", "bytes", ")", ".", "toUpperCase", "(", ")", ";", "}" ]
Generate a uuid. @param {Number} [length=32] The length of the UUID. @return {String} The UUID.
[ "Generate", "a", "uuid", "." ]
6f37d31bd5e7e57489885e89ef9df88e8197a2c3
https://github.com/stayradiated/onepasswordjs/blob/6f37d31bd5e7e57489885e89ef9df88e8197a2c3/src/crypto_browser.js#L336-L344
47,985
ghinda/durruti
src/durruti.js
decorate
function decorate (Comp) { var component // instantiate classes if (typeof Comp === 'function') { component = new Comp() } else { // make sure we don't change the id on a cached component component = Object.create(Comp) } // components get a new id on render, // so we can clear the previous component cache. component._durrutiId = String(componentIndex++) // cache component componentCache.push({ id: component._durrutiId, component: component }) return component }
javascript
function decorate (Comp) { var component // instantiate classes if (typeof Comp === 'function') { component = new Comp() } else { // make sure we don't change the id on a cached component component = Object.create(Comp) } // components get a new id on render, // so we can clear the previous component cache. component._durrutiId = String(componentIndex++) // cache component componentCache.push({ id: component._durrutiId, component: component }) return component }
[ "function", "decorate", "(", "Comp", ")", "{", "var", "component", "// instantiate classes", "if", "(", "typeof", "Comp", "===", "'function'", ")", "{", "component", "=", "new", "Comp", "(", ")", "}", "else", "{", "// make sure we don't change the id on a cached component", "component", "=", "Object", ".", "create", "(", "Comp", ")", "}", "// components get a new id on render,", "// so we can clear the previous component cache.", "component", ".", "_durrutiId", "=", "String", "(", "componentIndex", "++", ")", "// cache component", "componentCache", ".", "push", "(", "{", "id", ":", "component", ".", "_durrutiId", ",", "component", ":", "component", "}", ")", "return", "component", "}" ]
decorate a basic class with durruti specific properties
[ "decorate", "a", "basic", "class", "with", "durruti", "specific", "properties" ]
a67a95e9a636367b43afffdbede1ba083be00ebe
https://github.com/ghinda/durruti/blob/a67a95e9a636367b43afffdbede1ba083be00ebe/src/durruti.js#L14-L36
47,986
ghinda/durruti
src/durruti.js
cleanAttrNodes
function cleanAttrNodes ($container, includeParent) { var nodes = [].slice.call($container.querySelectorAll(durrutiElemSelector)) if (includeParent) { nodes.push($container) } nodes.forEach(($node) => { // cache component in node $node._durruti = getCachedComponent($node) // clean-up data attributes $node.removeAttribute(durrutiAttr) }) return nodes }
javascript
function cleanAttrNodes ($container, includeParent) { var nodes = [].slice.call($container.querySelectorAll(durrutiElemSelector)) if (includeParent) { nodes.push($container) } nodes.forEach(($node) => { // cache component in node $node._durruti = getCachedComponent($node) // clean-up data attributes $node.removeAttribute(durrutiAttr) }) return nodes }
[ "function", "cleanAttrNodes", "(", "$container", ",", "includeParent", ")", "{", "var", "nodes", "=", "[", "]", ".", "slice", ".", "call", "(", "$container", ".", "querySelectorAll", "(", "durrutiElemSelector", ")", ")", "if", "(", "includeParent", ")", "{", "nodes", ".", "push", "(", "$container", ")", "}", "nodes", ".", "forEach", "(", "(", "$node", ")", "=>", "{", "// cache component in node", "$node", ".", "_durruti", "=", "getCachedComponent", "(", "$node", ")", "// clean-up data attributes", "$node", ".", "removeAttribute", "(", "durrutiAttr", ")", "}", ")", "return", "nodes", "}" ]
remove custom data attributes, and cache the component on the DOM node.
[ "remove", "custom", "data", "attributes", "and", "cache", "the", "component", "on", "the", "DOM", "node", "." ]
a67a95e9a636367b43afffdbede1ba083be00ebe
https://github.com/ghinda/durruti/blob/a67a95e9a636367b43afffdbede1ba083be00ebe/src/durruti.js#L55-L71
47,987
ghinda/durruti
src/durruti.js
getComponentNodes
function getComponentNodes ($container, traverse = true, arr = []) { if ($container._durruti) { arr.push($container) } if (traverse && $container.children) { for (let i = 0; i < $container.children.length; i++) { getComponentNodes($container.children[i], traverse, arr) } } return arr }
javascript
function getComponentNodes ($container, traverse = true, arr = []) { if ($container._durruti) { arr.push($container) } if (traverse && $container.children) { for (let i = 0; i < $container.children.length; i++) { getComponentNodes($container.children[i], traverse, arr) } } return arr }
[ "function", "getComponentNodes", "(", "$container", ",", "traverse", "=", "true", ",", "arr", "=", "[", "]", ")", "{", "if", "(", "$container", ".", "_durruti", ")", "{", "arr", ".", "push", "(", "$container", ")", "}", "if", "(", "traverse", "&&", "$container", ".", "children", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "$container", ".", "children", ".", "length", ";", "i", "++", ")", "{", "getComponentNodes", "(", "$container", ".", "children", "[", "i", "]", ",", "traverse", ",", "arr", ")", "}", "}", "return", "arr", "}" ]
traverse and find durruti nodes
[ "traverse", "and", "find", "durruti", "nodes" ]
a67a95e9a636367b43afffdbede1ba083be00ebe
https://github.com/ghinda/durruti/blob/a67a95e9a636367b43afffdbede1ba083be00ebe/src/durruti.js#L149-L161
47,988
BladeRunnerJS/topiarist
src/topiarist.js
extend
function extend(classDefinition, superclass, extraProperties) { var subclassName = className(classDefinition, 'Subclass'); // Find the right classDefinition - either the one provided, a new one or the one from extraProperties. var extraPropertiesHasConstructor = typeof extraProperties !== 'undefined' && extraProperties.hasOwnProperty('constructor') && typeof extraProperties.constructor === 'function'; if (classDefinition != null) { if (extraPropertiesHasConstructor && classDefinition !== extraProperties.constructor) { throw new Error(msg(ERROR_MESSAGES.TWO_CONSTRUCTORS, subclassName)); } } else if (extraPropertiesHasConstructor) { classDefinition = extraProperties.constructor; } else { classDefinition = function() { superclass.apply(this, arguments); }; } // check arguments assertArgumentOfType('function', classDefinition, ERROR_MESSAGES.SUBCLASS_NOT_CONSTRUCTOR); assertArgumentOfType('function', superclass, ERROR_MESSAGES.SUPERCLASS_NOT_CONSTRUCTOR, subclassName); assertNothingInObject(classDefinition.prototype, ERROR_MESSAGES.PROTOTYPE_NOT_CLEAN, subclassName); // copy class properties for (var staticPropertyName in superclass) { if (superclass.hasOwnProperty(staticPropertyName)) { // this is because we shouldn't copy nonenumerables, but removing enumerability isn't shimmable in ie8. // We need to make sure we don't inadvertently copy across any of the 'internal' fields we are using to // keep track of things. if (internalUseNames.indexOf(staticPropertyName) >= 0) { continue; } classDefinition[staticPropertyName] = superclass[staticPropertyName]; } } // create the superclass property on the subclass constructor Object.defineProperty(classDefinition, 'superclass', { enumerable: false, value: superclass }); // create the prototype with a constructor function. classDefinition.prototype = Object.create(superclass.prototype, { 'constructor': { enumerable: false, value: classDefinition } }); // copy everything from extra properties. if (extraProperties != null) { for (var property in extraProperties) { if (extraProperties.hasOwnProperty(property) && property !== 'constructor') { classDefinition.prototype[property] = extraProperties[property]; } } } // this is purely to work around a bad ie8 shim, when ie8 is no longer needed it can be deleted. if (classDefinition.prototype.hasOwnProperty('__proto__')) { delete classDefinition.prototype['__proto__']; } clearAssignableCache(classDefinition, superclass); return classDefinition; }
javascript
function extend(classDefinition, superclass, extraProperties) { var subclassName = className(classDefinition, 'Subclass'); // Find the right classDefinition - either the one provided, a new one or the one from extraProperties. var extraPropertiesHasConstructor = typeof extraProperties !== 'undefined' && extraProperties.hasOwnProperty('constructor') && typeof extraProperties.constructor === 'function'; if (classDefinition != null) { if (extraPropertiesHasConstructor && classDefinition !== extraProperties.constructor) { throw new Error(msg(ERROR_MESSAGES.TWO_CONSTRUCTORS, subclassName)); } } else if (extraPropertiesHasConstructor) { classDefinition = extraProperties.constructor; } else { classDefinition = function() { superclass.apply(this, arguments); }; } // check arguments assertArgumentOfType('function', classDefinition, ERROR_MESSAGES.SUBCLASS_NOT_CONSTRUCTOR); assertArgumentOfType('function', superclass, ERROR_MESSAGES.SUPERCLASS_NOT_CONSTRUCTOR, subclassName); assertNothingInObject(classDefinition.prototype, ERROR_MESSAGES.PROTOTYPE_NOT_CLEAN, subclassName); // copy class properties for (var staticPropertyName in superclass) { if (superclass.hasOwnProperty(staticPropertyName)) { // this is because we shouldn't copy nonenumerables, but removing enumerability isn't shimmable in ie8. // We need to make sure we don't inadvertently copy across any of the 'internal' fields we are using to // keep track of things. if (internalUseNames.indexOf(staticPropertyName) >= 0) { continue; } classDefinition[staticPropertyName] = superclass[staticPropertyName]; } } // create the superclass property on the subclass constructor Object.defineProperty(classDefinition, 'superclass', { enumerable: false, value: superclass }); // create the prototype with a constructor function. classDefinition.prototype = Object.create(superclass.prototype, { 'constructor': { enumerable: false, value: classDefinition } }); // copy everything from extra properties. if (extraProperties != null) { for (var property in extraProperties) { if (extraProperties.hasOwnProperty(property) && property !== 'constructor') { classDefinition.prototype[property] = extraProperties[property]; } } } // this is purely to work around a bad ie8 shim, when ie8 is no longer needed it can be deleted. if (classDefinition.prototype.hasOwnProperty('__proto__')) { delete classDefinition.prototype['__proto__']; } clearAssignableCache(classDefinition, superclass); return classDefinition; }
[ "function", "extend", "(", "classDefinition", ",", "superclass", ",", "extraProperties", ")", "{", "var", "subclassName", "=", "className", "(", "classDefinition", ",", "'Subclass'", ")", ";", "// Find the right classDefinition - either the one provided, a new one or the one from extraProperties.", "var", "extraPropertiesHasConstructor", "=", "typeof", "extraProperties", "!==", "'undefined'", "&&", "extraProperties", ".", "hasOwnProperty", "(", "'constructor'", ")", "&&", "typeof", "extraProperties", ".", "constructor", "===", "'function'", ";", "if", "(", "classDefinition", "!=", "null", ")", "{", "if", "(", "extraPropertiesHasConstructor", "&&", "classDefinition", "!==", "extraProperties", ".", "constructor", ")", "{", "throw", "new", "Error", "(", "msg", "(", "ERROR_MESSAGES", ".", "TWO_CONSTRUCTORS", ",", "subclassName", ")", ")", ";", "}", "}", "else", "if", "(", "extraPropertiesHasConstructor", ")", "{", "classDefinition", "=", "extraProperties", ".", "constructor", ";", "}", "else", "{", "classDefinition", "=", "function", "(", ")", "{", "superclass", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ";", "}", "// check arguments", "assertArgumentOfType", "(", "'function'", ",", "classDefinition", ",", "ERROR_MESSAGES", ".", "SUBCLASS_NOT_CONSTRUCTOR", ")", ";", "assertArgumentOfType", "(", "'function'", ",", "superclass", ",", "ERROR_MESSAGES", ".", "SUPERCLASS_NOT_CONSTRUCTOR", ",", "subclassName", ")", ";", "assertNothingInObject", "(", "classDefinition", ".", "prototype", ",", "ERROR_MESSAGES", ".", "PROTOTYPE_NOT_CLEAN", ",", "subclassName", ")", ";", "// copy class properties", "for", "(", "var", "staticPropertyName", "in", "superclass", ")", "{", "if", "(", "superclass", ".", "hasOwnProperty", "(", "staticPropertyName", ")", ")", "{", "// this is because we shouldn't copy nonenumerables, but removing enumerability isn't shimmable in ie8.", "// We need to make sure we don't inadvertently copy across any of the 'internal' fields we are using to", "// keep track of things.", "if", "(", "internalUseNames", ".", "indexOf", "(", "staticPropertyName", ")", ">=", "0", ")", "{", "continue", ";", "}", "classDefinition", "[", "staticPropertyName", "]", "=", "superclass", "[", "staticPropertyName", "]", ";", "}", "}", "// create the superclass property on the subclass constructor", "Object", ".", "defineProperty", "(", "classDefinition", ",", "'superclass'", ",", "{", "enumerable", ":", "false", ",", "value", ":", "superclass", "}", ")", ";", "// create the prototype with a constructor function.", "classDefinition", ".", "prototype", "=", "Object", ".", "create", "(", "superclass", ".", "prototype", ",", "{", "'constructor'", ":", "{", "enumerable", ":", "false", ",", "value", ":", "classDefinition", "}", "}", ")", ";", "// copy everything from extra properties.", "if", "(", "extraProperties", "!=", "null", ")", "{", "for", "(", "var", "property", "in", "extraProperties", ")", "{", "if", "(", "extraProperties", ".", "hasOwnProperty", "(", "property", ")", "&&", "property", "!==", "'constructor'", ")", "{", "classDefinition", ".", "prototype", "[", "property", "]", "=", "extraProperties", "[", "property", "]", ";", "}", "}", "}", "// this is purely to work around a bad ie8 shim, when ie8 is no longer needed it can be deleted.", "if", "(", "classDefinition", ".", "prototype", ".", "hasOwnProperty", "(", "'__proto__'", ")", ")", "{", "delete", "classDefinition", ".", "prototype", "[", "'__proto__'", "]", ";", "}", "clearAssignableCache", "(", "classDefinition", ",", "superclass", ")", ";", "return", "classDefinition", ";", "}" ]
Sets up the prototype chain for inheritance. <p>As well as setting up the prototype chain, this also copies so called 'class' definitions from the superclass to the subclass and makes sure that constructor will return the correct thing.</p> @throws Error if the prototype has been modified before extend is called. @memberOf topiarist @param {?function} classDefinition The constructor of the subclass. @param {!function} superclass The constructor of the superclass. @param {?object} [extraProperties] An object of extra properties to add to the subclasses prototype.
[ "Sets", "up", "the", "prototype", "chain", "for", "inheritance", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L25-L89
47,989
BladeRunnerJS/topiarist
src/topiarist.js
mixin
function mixin(target, Mix) { assertArgumentOfType('function', target, ERROR_MESSAGES.NOT_CONSTRUCTOR, 'Target', 'mixin'); Mix = toFunction( Mix, new TypeError( msg( ERROR_MESSAGES.WRONG_TYPE, 'Mix', 'mixin', 'non-null object or function', Mix === null ? 'null' : typeof Mix ) ) ); var targetPrototype = target.prototype, mixinProperties = Mix.prototype, resultingProperties = {}; var mixins = nonenum(target, '__multiparents__', []); var myMixId = mixins.length; for (var property in mixinProperties) { // property might spuriously be 'constructor' if you are in ie8 and using a shim. if (typeof mixinProperties[property] === 'function' && property !== 'constructor') { if (property in targetPrototype === false) { resultingProperties[property] = getSandboxedFunction(myMixId, Mix, mixinProperties[property]); } else if (targetPrototype[property]['__original__'] !== mixinProperties[property]) { throw new Error( msg( ERROR_MESSAGES.PROPERTY_ALREADY_PRESENT, property, className(Mix, 'mixin'), className(target, 'target') ) ); } } // we only mixin functions } copy(resultingProperties, targetPrototype); mixins.push(Mix); clearAssignableCache(target, Mix); return target; }
javascript
function mixin(target, Mix) { assertArgumentOfType('function', target, ERROR_MESSAGES.NOT_CONSTRUCTOR, 'Target', 'mixin'); Mix = toFunction( Mix, new TypeError( msg( ERROR_MESSAGES.WRONG_TYPE, 'Mix', 'mixin', 'non-null object or function', Mix === null ? 'null' : typeof Mix ) ) ); var targetPrototype = target.prototype, mixinProperties = Mix.prototype, resultingProperties = {}; var mixins = nonenum(target, '__multiparents__', []); var myMixId = mixins.length; for (var property in mixinProperties) { // property might spuriously be 'constructor' if you are in ie8 and using a shim. if (typeof mixinProperties[property] === 'function' && property !== 'constructor') { if (property in targetPrototype === false) { resultingProperties[property] = getSandboxedFunction(myMixId, Mix, mixinProperties[property]); } else if (targetPrototype[property]['__original__'] !== mixinProperties[property]) { throw new Error( msg( ERROR_MESSAGES.PROPERTY_ALREADY_PRESENT, property, className(Mix, 'mixin'), className(target, 'target') ) ); } } // we only mixin functions } copy(resultingProperties, targetPrototype); mixins.push(Mix); clearAssignableCache(target, Mix); return target; }
[ "function", "mixin", "(", "target", ",", "Mix", ")", "{", "assertArgumentOfType", "(", "'function'", ",", "target", ",", "ERROR_MESSAGES", ".", "NOT_CONSTRUCTOR", ",", "'Target'", ",", "'mixin'", ")", ";", "Mix", "=", "toFunction", "(", "Mix", ",", "new", "TypeError", "(", "msg", "(", "ERROR_MESSAGES", ".", "WRONG_TYPE", ",", "'Mix'", ",", "'mixin'", ",", "'non-null object or function'", ",", "Mix", "===", "null", "?", "'null'", ":", "typeof", "Mix", ")", ")", ")", ";", "var", "targetPrototype", "=", "target", ".", "prototype", ",", "mixinProperties", "=", "Mix", ".", "prototype", ",", "resultingProperties", "=", "{", "}", ";", "var", "mixins", "=", "nonenum", "(", "target", ",", "'__multiparents__'", ",", "[", "]", ")", ";", "var", "myMixId", "=", "mixins", ".", "length", ";", "for", "(", "var", "property", "in", "mixinProperties", ")", "{", "// property might spuriously be 'constructor' if you are in ie8 and using a shim.", "if", "(", "typeof", "mixinProperties", "[", "property", "]", "===", "'function'", "&&", "property", "!==", "'constructor'", ")", "{", "if", "(", "property", "in", "targetPrototype", "===", "false", ")", "{", "resultingProperties", "[", "property", "]", "=", "getSandboxedFunction", "(", "myMixId", ",", "Mix", ",", "mixinProperties", "[", "property", "]", ")", ";", "}", "else", "if", "(", "targetPrototype", "[", "property", "]", "[", "'__original__'", "]", "!==", "mixinProperties", "[", "property", "]", ")", "{", "throw", "new", "Error", "(", "msg", "(", "ERROR_MESSAGES", ".", "PROPERTY_ALREADY_PRESENT", ",", "property", ",", "className", "(", "Mix", ",", "'mixin'", ")", ",", "className", "(", "target", ",", "'target'", ")", ")", ")", ";", "}", "}", "// we only mixin functions", "}", "copy", "(", "resultingProperties", ",", "targetPrototype", ")", ";", "mixins", ".", "push", "(", "Mix", ")", ";", "clearAssignableCache", "(", "target", ",", "Mix", ")", ";", "return", "target", ";", "}" ]
Mixes functionality in to a class. <p>Only functions are mixed in.</p> <p>Code in the mixin is sandboxed and only has access to a 'mixin instance' rather than the real instance.</p> @memberOf topiarist @param {function} target @param {function|Object} Mix
[ "Mixes", "functionality", "in", "to", "a", "class", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L102-L146
47,990
BladeRunnerJS/topiarist
src/topiarist.js
inherit
function inherit(target, parent) { assertArgumentOfType('function', target, ERROR_MESSAGES.NOT_CONSTRUCTOR, 'Target', 'inherit'); parent = toFunction( parent, new TypeError( msg( ERROR_MESSAGES.WRONG_TYPE, 'Parent', 'inherit', 'non-null object or function', parent === null ? 'null' : typeof parent ) ) ); if (classIsA(target, parent)) { return target; } var resultingProperties = {}; var targetPrototype = target.prototype; for (var propertyName in parent.prototype) { // These properties should be nonenumerable in modern browsers, but shims might create them in ie8. if (propertyName === 'constructor' || propertyName === '__proto__' || propertyName === 'toString' || propertyName.match(/^Symbol\(__proto__\)/)) { continue; } var notInTarget = targetPrototype[propertyName] === undefined; var parentHasNewerImplementation = notInTarget || isOverriderOf(propertyName, parent, target); if (parentHasNewerImplementation) { resultingProperties[propertyName] = parent.prototype[propertyName]; } else { var areTheSame = targetPrototype[propertyName] === parent.prototype[propertyName]; var targetIsUpToDate = areTheSame || isOverriderOf(propertyName, target, parent); if (targetIsUpToDate === false) { // target is not up to date, but we can't bring it up to date. throw new Error( msg( ERROR_MESSAGES.ALREADY_PRESENT, propertyName, className(parent, 'parent'), className(target, 'target') ) ); } // otherwise we don't need to do anything. } } copy(resultingProperties, targetPrototype); var multiparents = nonenum(target, '__multiparents__', []); multiparents.push(parent); clearAssignableCache(target, parent); return target; }
javascript
function inherit(target, parent) { assertArgumentOfType('function', target, ERROR_MESSAGES.NOT_CONSTRUCTOR, 'Target', 'inherit'); parent = toFunction( parent, new TypeError( msg( ERROR_MESSAGES.WRONG_TYPE, 'Parent', 'inherit', 'non-null object or function', parent === null ? 'null' : typeof parent ) ) ); if (classIsA(target, parent)) { return target; } var resultingProperties = {}; var targetPrototype = target.prototype; for (var propertyName in parent.prototype) { // These properties should be nonenumerable in modern browsers, but shims might create them in ie8. if (propertyName === 'constructor' || propertyName === '__proto__' || propertyName === 'toString' || propertyName.match(/^Symbol\(__proto__\)/)) { continue; } var notInTarget = targetPrototype[propertyName] === undefined; var parentHasNewerImplementation = notInTarget || isOverriderOf(propertyName, parent, target); if (parentHasNewerImplementation) { resultingProperties[propertyName] = parent.prototype[propertyName]; } else { var areTheSame = targetPrototype[propertyName] === parent.prototype[propertyName]; var targetIsUpToDate = areTheSame || isOverriderOf(propertyName, target, parent); if (targetIsUpToDate === false) { // target is not up to date, but we can't bring it up to date. throw new Error( msg( ERROR_MESSAGES.ALREADY_PRESENT, propertyName, className(parent, 'parent'), className(target, 'target') ) ); } // otherwise we don't need to do anything. } } copy(resultingProperties, targetPrototype); var multiparents = nonenum(target, '__multiparents__', []); multiparents.push(parent); clearAssignableCache(target, parent); return target; }
[ "function", "inherit", "(", "target", ",", "parent", ")", "{", "assertArgumentOfType", "(", "'function'", ",", "target", ",", "ERROR_MESSAGES", ".", "NOT_CONSTRUCTOR", ",", "'Target'", ",", "'inherit'", ")", ";", "parent", "=", "toFunction", "(", "parent", ",", "new", "TypeError", "(", "msg", "(", "ERROR_MESSAGES", ".", "WRONG_TYPE", ",", "'Parent'", ",", "'inherit'", ",", "'non-null object or function'", ",", "parent", "===", "null", "?", "'null'", ":", "typeof", "parent", ")", ")", ")", ";", "if", "(", "classIsA", "(", "target", ",", "parent", ")", ")", "{", "return", "target", ";", "}", "var", "resultingProperties", "=", "{", "}", ";", "var", "targetPrototype", "=", "target", ".", "prototype", ";", "for", "(", "var", "propertyName", "in", "parent", ".", "prototype", ")", "{", "// These properties should be nonenumerable in modern browsers, but shims might create them in ie8.", "if", "(", "propertyName", "===", "'constructor'", "||", "propertyName", "===", "'__proto__'", "||", "propertyName", "===", "'toString'", "||", "propertyName", ".", "match", "(", "/", "^Symbol\\(__proto__\\)", "/", ")", ")", "{", "continue", ";", "}", "var", "notInTarget", "=", "targetPrototype", "[", "propertyName", "]", "===", "undefined", ";", "var", "parentHasNewerImplementation", "=", "notInTarget", "||", "isOverriderOf", "(", "propertyName", ",", "parent", ",", "target", ")", ";", "if", "(", "parentHasNewerImplementation", ")", "{", "resultingProperties", "[", "propertyName", "]", "=", "parent", ".", "prototype", "[", "propertyName", "]", ";", "}", "else", "{", "var", "areTheSame", "=", "targetPrototype", "[", "propertyName", "]", "===", "parent", ".", "prototype", "[", "propertyName", "]", ";", "var", "targetIsUpToDate", "=", "areTheSame", "||", "isOverriderOf", "(", "propertyName", ",", "target", ",", "parent", ")", ";", "if", "(", "targetIsUpToDate", "===", "false", ")", "{", "// target is not up to date, but we can't bring it up to date.", "throw", "new", "Error", "(", "msg", "(", "ERROR_MESSAGES", ".", "ALREADY_PRESENT", ",", "propertyName", ",", "className", "(", "parent", ",", "'parent'", ")", ",", "className", "(", "target", ",", "'target'", ")", ")", ")", ";", "}", "// otherwise we don't need to do anything.", "}", "}", "copy", "(", "resultingProperties", ",", "targetPrototype", ")", ";", "var", "multiparents", "=", "nonenum", "(", "target", ",", "'__multiparents__'", ",", "[", "]", ")", ";", "multiparents", ".", "push", "(", "parent", ")", ";", "clearAssignableCache", "(", "target", ",", "parent", ")", ";", "return", "target", ";", "}" ]
Provides multiple inheritance through copying. <p>This is discouraged; you should prefer to use aggregation first, single inheritance (extends) second, mixins third and this as a last resort.</p> @memberOf topiarist @param {function} target the class that should receive the functionality. @param {function|Object} parent the parent that provides the functionality.
[ "Provides", "multiple", "inheritance", "through", "copying", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L158-L214
47,991
BladeRunnerJS/topiarist
src/topiarist.js
implement
function implement(classDefinition, protocol) { doImplement(classDefinition, protocol); setTimeout(function() { assertHasImplemented(classDefinition, protocol); }, 0); return classDefinition; }
javascript
function implement(classDefinition, protocol) { doImplement(classDefinition, protocol); setTimeout(function() { assertHasImplemented(classDefinition, protocol); }, 0); return classDefinition; }
[ "function", "implement", "(", "classDefinition", ",", "protocol", ")", "{", "doImplement", "(", "classDefinition", ",", "protocol", ")", ";", "setTimeout", "(", "function", "(", ")", "{", "assertHasImplemented", "(", "classDefinition", ",", "protocol", ")", ";", "}", ",", "0", ")", ";", "return", "classDefinition", ";", "}" ]
Declares that the provided class will implement the provided protocol. <p>This involves immediately updating an internal list of interfaces attached to the class definition, and after a <code>setTimeout(0)</code> verifying that it does in fact implement the protocol.</p> <p>It can be called before the implementations are provided, i.e. immediately after the constructor.</p> @throws Error if there are any attributes on the protocol that are not matched on the class definition. @memberOf topiarist @param {function} classDefinition A constructor that should create objects matching the protocol. @param {function} protocol A constructor representing an interface that the class should implement.
[ "Declares", "that", "the", "provided", "class", "will", "implement", "the", "provided", "protocol", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L230-L238
47,992
BladeRunnerJS/topiarist
src/topiarist.js
hasImplemented
function hasImplemented(classDefinition, protocol) { doImplement(classDefinition, protocol); assertHasImplemented(classDefinition, protocol); return classDefinition; }
javascript
function hasImplemented(classDefinition, protocol) { doImplement(classDefinition, protocol); assertHasImplemented(classDefinition, protocol); return classDefinition; }
[ "function", "hasImplemented", "(", "classDefinition", ",", "protocol", ")", "{", "doImplement", "(", "classDefinition", ",", "protocol", ")", ";", "assertHasImplemented", "(", "classDefinition", ",", "protocol", ")", ";", "return", "classDefinition", ";", "}" ]
Declares that the provided class implements the provided protocol. <p>This involves checking that it does in fact implement the protocol and updating an internal list of interfaces attached to the class definition.</p> <p>It should be called after implementations are provided, i.e. at the end of the class definition.</p> @throws Error if there are any attributes on the protocol that are not matched on the class definition. @memberOf topiarist @param {function} classDefinition A constructor that should create objects matching the protocol. @param {function} protocol A constructor representing an interface that the class should implement.
[ "Declares", "that", "the", "provided", "class", "implements", "the", "provided", "protocol", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L254-L259
47,993
BladeRunnerJS/topiarist
src/topiarist.js
isA
function isA(instance, parent) { if(instance == null) { assertArgumentNotNullOrUndefined(instance, ERROR_MESSAGES.NULL, 'Object', 'isA'); } // sneaky edge case where we're checking against an object literal we've mixed in or against a prototype of // something. if (typeof parent === 'object' && parent.hasOwnProperty('constructor')) { parent = parent.constructor; } if((instance.constructor === parent) || (instance instanceof parent)) { return true; } return classIsA(instance.constructor, parent); }
javascript
function isA(instance, parent) { if(instance == null) { assertArgumentNotNullOrUndefined(instance, ERROR_MESSAGES.NULL, 'Object', 'isA'); } // sneaky edge case where we're checking against an object literal we've mixed in or against a prototype of // something. if (typeof parent === 'object' && parent.hasOwnProperty('constructor')) { parent = parent.constructor; } if((instance.constructor === parent) || (instance instanceof parent)) { return true; } return classIsA(instance.constructor, parent); }
[ "function", "isA", "(", "instance", ",", "parent", ")", "{", "if", "(", "instance", "==", "null", ")", "{", "assertArgumentNotNullOrUndefined", "(", "instance", ",", "ERROR_MESSAGES", ".", "NULL", ",", "'Object'", ",", "'isA'", ")", ";", "}", "// sneaky edge case where we're checking against an object literal we've mixed in or against a prototype of", "// something.", "if", "(", "typeof", "parent", "===", "'object'", "&&", "parent", ".", "hasOwnProperty", "(", "'constructor'", ")", ")", "{", "parent", "=", "parent", ".", "constructor", ";", "}", "if", "(", "(", "instance", ".", "constructor", "===", "parent", ")", "||", "(", "instance", "instanceof", "parent", ")", ")", "{", "return", "true", ";", "}", "return", "classIsA", "(", "instance", ".", "constructor", ",", "parent", ")", ";", "}" ]
Checks to see if an instance is defined to be a child of a parent. @memberOf topiarist @param {Object} instance An instance object to check. @param {function} parent A potential parent (see classIsA). @returns {boolean} true if this instance has been constructed from something that is assignable from the parent or is null, false otherwise.
[ "Checks", "to", "see", "if", "an", "instance", "is", "defined", "to", "be", "a", "child", "of", "a", "parent", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L367-L383
47,994
BladeRunnerJS/topiarist
src/topiarist.js
classFulfills
function classFulfills(classDefinition, protocol) { assertArgumentNotNullOrUndefined(classDefinition, ERROR_MESSAGES.NULL, 'Class', 'classFulfills'); assertArgumentNotNullOrUndefined(protocol, ERROR_MESSAGES.NULL, 'Protocol', 'classFulfills'); return fulfills(classDefinition.prototype, protocol); }
javascript
function classFulfills(classDefinition, protocol) { assertArgumentNotNullOrUndefined(classDefinition, ERROR_MESSAGES.NULL, 'Class', 'classFulfills'); assertArgumentNotNullOrUndefined(protocol, ERROR_MESSAGES.NULL, 'Protocol', 'classFulfills'); return fulfills(classDefinition.prototype, protocol); }
[ "function", "classFulfills", "(", "classDefinition", ",", "protocol", ")", "{", "assertArgumentNotNullOrUndefined", "(", "classDefinition", ",", "ERROR_MESSAGES", ".", "NULL", ",", "'Class'", ",", "'classFulfills'", ")", ";", "assertArgumentNotNullOrUndefined", "(", "protocol", ",", "ERROR_MESSAGES", ".", "NULL", ",", "'Protocol'", ",", "'classFulfills'", ")", ";", "return", "fulfills", "(", "classDefinition", ".", "prototype", ",", "protocol", ")", ";", "}" ]
Checks that a class provides a prototype that will fulfil a protocol. @memberOf topiarist @param {function} classDefinition @param {function|Object} protocol @returns {boolean}
[ "Checks", "that", "a", "class", "provides", "a", "prototype", "that", "will", "fulfil", "a", "protocol", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L446-L451
47,995
BladeRunnerJS/topiarist
src/topiarist.js
nonenum
function nonenum(object, propertyName, defaultValue) { var value = object[propertyName]; if (typeof value === 'undefined') { value = defaultValue; Object.defineProperty(object, propertyName, { enumerable: false, value: value }); } return value; }
javascript
function nonenum(object, propertyName, defaultValue) { var value = object[propertyName]; if (typeof value === 'undefined') { value = defaultValue; Object.defineProperty(object, propertyName, { enumerable: false, value: value }); } return value; }
[ "function", "nonenum", "(", "object", ",", "propertyName", ",", "defaultValue", ")", "{", "var", "value", "=", "object", "[", "propertyName", "]", ";", "if", "(", "typeof", "value", "===", "'undefined'", ")", "{", "value", "=", "defaultValue", ";", "Object", ".", "defineProperty", "(", "object", ",", "propertyName", ",", "{", "enumerable", ":", "false", ",", "value", ":", "value", "}", ")", ";", "}", "return", "value", ";", "}" ]
Returns a nonenumerable property if it exists, or creates one and returns that if it does not. @private
[ "Returns", "a", "nonenumerable", "property", "if", "it", "exists", "or", "creates", "one", "and", "returns", "that", "if", "it", "does", "not", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L513-L525
47,996
BladeRunnerJS/topiarist
src/topiarist.js
toFunction
function toFunction(obj, couldNotCastError) { if (obj == null) { throw couldNotCastError; } var result; if (typeof obj === 'object') { if (obj.hasOwnProperty('constructor')) { if (obj.constructor.prototype !== obj) { throw couldNotCastError; } result = obj.constructor; } else { var EmptyInitialiser = function() {}; EmptyInitialiser.prototype = obj; Object.defineProperty(obj, 'constructor', { enumerable: false, value: EmptyInitialiser }); result = EmptyInitialiser; } } else if (typeof obj === 'function') { result = obj; } else { throw couldNotCastError; } return result; }
javascript
function toFunction(obj, couldNotCastError) { if (obj == null) { throw couldNotCastError; } var result; if (typeof obj === 'object') { if (obj.hasOwnProperty('constructor')) { if (obj.constructor.prototype !== obj) { throw couldNotCastError; } result = obj.constructor; } else { var EmptyInitialiser = function() {}; EmptyInitialiser.prototype = obj; Object.defineProperty(obj, 'constructor', { enumerable: false, value: EmptyInitialiser }); result = EmptyInitialiser; } } else if (typeof obj === 'function') { result = obj; } else { throw couldNotCastError; } return result; }
[ "function", "toFunction", "(", "obj", ",", "couldNotCastError", ")", "{", "if", "(", "obj", "==", "null", ")", "{", "throw", "couldNotCastError", ";", "}", "var", "result", ";", "if", "(", "typeof", "obj", "===", "'object'", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "'constructor'", ")", ")", "{", "if", "(", "obj", ".", "constructor", ".", "prototype", "!==", "obj", ")", "{", "throw", "couldNotCastError", ";", "}", "result", "=", "obj", ".", "constructor", ";", "}", "else", "{", "var", "EmptyInitialiser", "=", "function", "(", ")", "{", "}", ";", "EmptyInitialiser", ".", "prototype", "=", "obj", ";", "Object", ".", "defineProperty", "(", "obj", ",", "'constructor'", ",", "{", "enumerable", ":", "false", ",", "value", ":", "EmptyInitialiser", "}", ")", ";", "result", "=", "EmptyInitialiser", ";", "}", "}", "else", "if", "(", "typeof", "obj", "===", "'function'", ")", "{", "result", "=", "obj", ";", "}", "else", "{", "throw", "couldNotCastError", ";", "}", "return", "result", ";", "}" ]
Easier for us if we treat everything as functions with prototypes. This function makes plain objects behave that way. @private
[ "Easier", "for", "us", "if", "we", "treat", "everything", "as", "functions", "with", "prototypes", ".", "This", "function", "makes", "plain", "objects", "behave", "that", "way", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L532-L558
47,997
BladeRunnerJS/topiarist
src/topiarist.js
missingAttributes
function missingAttributes(classdef, protocol) { var result = [], obj = classdef.prototype, requirement = protocol.prototype; var item; for (item in requirement) { if (typeof obj[item] !== typeof requirement[item]) { result.push(item); } } for (item in protocol) { var protocolItemType = typeof protocol[item]; if (protocol.hasOwnProperty(item) && protocolItemType === 'function' && typeof classdef[item] !== protocolItemType) { // If we're in ie8, our internal variables won't be nonenumerable, so we include a check for that here. if (internalUseNames.indexOf(item) < 0) { result.push(item + ' (class method)'); } } } return result; }
javascript
function missingAttributes(classdef, protocol) { var result = [], obj = classdef.prototype, requirement = protocol.prototype; var item; for (item in requirement) { if (typeof obj[item] !== typeof requirement[item]) { result.push(item); } } for (item in protocol) { var protocolItemType = typeof protocol[item]; if (protocol.hasOwnProperty(item) && protocolItemType === 'function' && typeof classdef[item] !== protocolItemType) { // If we're in ie8, our internal variables won't be nonenumerable, so we include a check for that here. if (internalUseNames.indexOf(item) < 0) { result.push(item + ' (class method)'); } } } return result; }
[ "function", "missingAttributes", "(", "classdef", ",", "protocol", ")", "{", "var", "result", "=", "[", "]", ",", "obj", "=", "classdef", ".", "prototype", ",", "requirement", "=", "protocol", ".", "prototype", ";", "var", "item", ";", "for", "(", "item", "in", "requirement", ")", "{", "if", "(", "typeof", "obj", "[", "item", "]", "!==", "typeof", "requirement", "[", "item", "]", ")", "{", "result", ".", "push", "(", "item", ")", ";", "}", "}", "for", "(", "item", "in", "protocol", ")", "{", "var", "protocolItemType", "=", "typeof", "protocol", "[", "item", "]", ";", "if", "(", "protocol", ".", "hasOwnProperty", "(", "item", ")", "&&", "protocolItemType", "===", "'function'", "&&", "typeof", "classdef", "[", "item", "]", "!==", "protocolItemType", ")", "{", "// If we're in ie8, our internal variables won't be nonenumerable, so we include a check for that here.", "if", "(", "internalUseNames", ".", "indexOf", "(", "item", ")", "<", "0", ")", "{", "result", ".", "push", "(", "item", "+", "' (class method)'", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
Returns an array of all of the properties on a protocol that are not on classdef or are of a different type on classdef. @private
[ "Returns", "an", "array", "of", "all", "of", "the", "properties", "on", "a", "protocol", "that", "are", "not", "on", "classdef", "or", "are", "of", "a", "different", "type", "on", "classdef", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L610-L630
47,998
BladeRunnerJS/topiarist
src/topiarist.js
makeMethod
function makeMethod(func) { return function() { var args = [this].concat(slice.call(arguments)); return func.apply(null, args); }; }
javascript
function makeMethod(func) { return function() { var args = [this].concat(slice.call(arguments)); return func.apply(null, args); }; }
[ "function", "makeMethod", "(", "func", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "[", "this", "]", ".", "concat", "(", "slice", ".", "call", "(", "arguments", ")", ")", ";", "return", "func", ".", "apply", "(", "null", ",", "args", ")", ";", "}", ";", "}" ]
Turns a function into a method by using 'this' as the first argument. @private
[ "Turns", "a", "function", "into", "a", "method", "by", "using", "this", "as", "the", "first", "argument", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L653-L658
47,999
BladeRunnerJS/topiarist
src/topiarist.js
getSandboxedFunction
function getSandboxedFunction(myMixId, Mix, func) { var result = function() { var mixInstances = nonenum(this, '__multiparentInstances__', []); var mixInstance = mixInstances[myMixId]; if (mixInstance == null) { if (typeof Mix === 'function') { mixInstance = new Mix(); } else { mixInstance = Object.create(Mix); } // could add a nonenum pointer to __this__ or something if we wanted to allow escape from the sandbox. mixInstances[myMixId] = mixInstance; } return func.apply(mixInstance, arguments); }; nonenum(result, '__original__', func); nonenum(result, '__source__', Mix); return result; }
javascript
function getSandboxedFunction(myMixId, Mix, func) { var result = function() { var mixInstances = nonenum(this, '__multiparentInstances__', []); var mixInstance = mixInstances[myMixId]; if (mixInstance == null) { if (typeof Mix === 'function') { mixInstance = new Mix(); } else { mixInstance = Object.create(Mix); } // could add a nonenum pointer to __this__ or something if we wanted to allow escape from the sandbox. mixInstances[myMixId] = mixInstance; } return func.apply(mixInstance, arguments); }; nonenum(result, '__original__', func); nonenum(result, '__source__', Mix); return result; }
[ "function", "getSandboxedFunction", "(", "myMixId", ",", "Mix", ",", "func", ")", "{", "var", "result", "=", "function", "(", ")", "{", "var", "mixInstances", "=", "nonenum", "(", "this", ",", "'__multiparentInstances__'", ",", "[", "]", ")", ";", "var", "mixInstance", "=", "mixInstances", "[", "myMixId", "]", ";", "if", "(", "mixInstance", "==", "null", ")", "{", "if", "(", "typeof", "Mix", "===", "'function'", ")", "{", "mixInstance", "=", "new", "Mix", "(", ")", ";", "}", "else", "{", "mixInstance", "=", "Object", ".", "create", "(", "Mix", ")", ";", "}", "// could add a nonenum pointer to __this__ or something if we wanted to allow escape from the sandbox.", "mixInstances", "[", "myMixId", "]", "=", "mixInstance", ";", "}", "return", "func", ".", "apply", "(", "mixInstance", ",", "arguments", ")", ";", "}", ";", "nonenum", "(", "result", ",", "'__original__'", ",", "func", ")", ";", "nonenum", "(", "result", ",", "'__source__'", ",", "Mix", ")", ";", "return", "result", ";", "}" ]
Mixin functions are sandboxed into their own instance. @private
[ "Mixin", "functions", "are", "sandboxed", "into", "their", "own", "instance", "." ]
b21636953c602f969adde2c3bd342c4b17e91968
https://github.com/BladeRunnerJS/topiarist/blob/b21636953c602f969adde2c3bd342c4b17e91968/src/topiarist.js#L664-L684