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
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
55,200
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function(plane) { if (this.polygons.length === 0) { return new CSG(); } // Ideally we would like to do an intersection with a polygon of inifinite size // but this is not supported by our implementation. As a workaround, we will create // a cube, with one face on the plane, and a size larger enough so that the entire // solid fits in the cube. // find the max distance of any vertex to the center of the plane: var planecenter = plane.normal.times(plane.w); var maxdistance = 0; this.polygons.map(function(polygon) { polygon.vertices.map(function(vertex) { var distance = vertex.pos.distanceToSquared(planecenter); if (distance > maxdistance) maxdistance = distance; }); }); maxdistance = Math.sqrt(maxdistance); maxdistance *= 1.01; // make sure it's really larger // Now build a polygon on the plane, at any point farther than maxdistance from the plane center: var vertices = []; var orthobasis = new CSG.OrthoNormalBasis(plane); vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, -maxdistance)))); vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, -maxdistance)))); vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, maxdistance)))); vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, maxdistance)))); var polygon = new CSG.Polygon(vertices, null, plane.flipped()); // and extrude the polygon into a cube, backwards of the plane: var cube = polygon.extrude(plane.normal.times(-maxdistance)); // Now we can do the intersection: var result = this.intersect(cube); result.properties = this.properties; // keep original properties return result; }
javascript
function(plane) { if (this.polygons.length === 0) { return new CSG(); } // Ideally we would like to do an intersection with a polygon of inifinite size // but this is not supported by our implementation. As a workaround, we will create // a cube, with one face on the plane, and a size larger enough so that the entire // solid fits in the cube. // find the max distance of any vertex to the center of the plane: var planecenter = plane.normal.times(plane.w); var maxdistance = 0; this.polygons.map(function(polygon) { polygon.vertices.map(function(vertex) { var distance = vertex.pos.distanceToSquared(planecenter); if (distance > maxdistance) maxdistance = distance; }); }); maxdistance = Math.sqrt(maxdistance); maxdistance *= 1.01; // make sure it's really larger // Now build a polygon on the plane, at any point farther than maxdistance from the plane center: var vertices = []; var orthobasis = new CSG.OrthoNormalBasis(plane); vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, -maxdistance)))); vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, -maxdistance)))); vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(-maxdistance, maxdistance)))); vertices.push(new CSG.Vertex(orthobasis.to3D(new CSG.Vector2D(maxdistance, maxdistance)))); var polygon = new CSG.Polygon(vertices, null, plane.flipped()); // and extrude the polygon into a cube, backwards of the plane: var cube = polygon.extrude(plane.normal.times(-maxdistance)); // Now we can do the intersection: var result = this.intersect(cube); result.properties = this.properties; // keep original properties return result; }
[ "function", "(", "plane", ")", "{", "if", "(", "this", ".", "polygons", ".", "length", "===", "0", ")", "{", "return", "new", "CSG", "(", ")", ";", "}", "// Ideally we would like to do an intersection with a polygon of inifinite size", "// but this is not supported by our implementation. As a workaround, we will create", "// a cube, with one face on the plane, and a size larger enough so that the entire", "// solid fits in the cube.", "// find the max distance of any vertex to the center of the plane:", "var", "planecenter", "=", "plane", ".", "normal", ".", "times", "(", "plane", ".", "w", ")", ";", "var", "maxdistance", "=", "0", ";", "this", ".", "polygons", ".", "map", "(", "function", "(", "polygon", ")", "{", "polygon", ".", "vertices", ".", "map", "(", "function", "(", "vertex", ")", "{", "var", "distance", "=", "vertex", ".", "pos", ".", "distanceToSquared", "(", "planecenter", ")", ";", "if", "(", "distance", ">", "maxdistance", ")", "maxdistance", "=", "distance", ";", "}", ")", ";", "}", ")", ";", "maxdistance", "=", "Math", ".", "sqrt", "(", "maxdistance", ")", ";", "maxdistance", "*=", "1.01", ";", "// make sure it's really larger", "// Now build a polygon on the plane, at any point farther than maxdistance from the plane center:", "var", "vertices", "=", "[", "]", ";", "var", "orthobasis", "=", "new", "CSG", ".", "OrthoNormalBasis", "(", "plane", ")", ";", "vertices", ".", "push", "(", "new", "CSG", ".", "Vertex", "(", "orthobasis", ".", "to3D", "(", "new", "CSG", ".", "Vector2D", "(", "maxdistance", ",", "-", "maxdistance", ")", ")", ")", ")", ";", "vertices", ".", "push", "(", "new", "CSG", ".", "Vertex", "(", "orthobasis", ".", "to3D", "(", "new", "CSG", ".", "Vector2D", "(", "-", "maxdistance", ",", "-", "maxdistance", ")", ")", ")", ")", ";", "vertices", ".", "push", "(", "new", "CSG", ".", "Vertex", "(", "orthobasis", ".", "to3D", "(", "new", "CSG", ".", "Vector2D", "(", "-", "maxdistance", ",", "maxdistance", ")", ")", ")", ")", ";", "vertices", ".", "push", "(", "new", "CSG", ".", "Vertex", "(", "orthobasis", ".", "to3D", "(", "new", "CSG", ".", "Vector2D", "(", "maxdistance", ",", "maxdistance", ")", ")", ")", ")", ";", "var", "polygon", "=", "new", "CSG", ".", "Polygon", "(", "vertices", ",", "null", ",", "plane", ".", "flipped", "(", ")", ")", ";", "// and extrude the polygon into a cube, backwards of the plane:", "var", "cube", "=", "polygon", ".", "extrude", "(", "plane", ".", "normal", ".", "times", "(", "-", "maxdistance", ")", ")", ";", "// Now we can do the intersection:", "var", "result", "=", "this", ".", "intersect", "(", "cube", ")", ";", "result", ".", "properties", "=", "this", ".", "properties", ";", "// keep original properties", "return", "result", ";", "}" ]
Cut the solid by a plane. Returns the solid on the back side of the plane
[ "Cut", "the", "solid", "by", "a", "plane", ".", "Returns", "the", "solid", "on", "the", "back", "side", "of", "the", "plane" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L765-L800
55,201
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function(shared) { var polygons = this.polygons.map(function(p) { return new CSG.Polygon(p.vertices, shared, p.plane); }); var result = CSG.fromPolygons(polygons); result.properties = this.properties; // keep original properties result.isRetesselated = this.isRetesselated; result.isCanonicalized = this.isCanonicalized; return result; }
javascript
function(shared) { var polygons = this.polygons.map(function(p) { return new CSG.Polygon(p.vertices, shared, p.plane); }); var result = CSG.fromPolygons(polygons); result.properties = this.properties; // keep original properties result.isRetesselated = this.isRetesselated; result.isCanonicalized = this.isCanonicalized; return result; }
[ "function", "(", "shared", ")", "{", "var", "polygons", "=", "this", ".", "polygons", ".", "map", "(", "function", "(", "p", ")", "{", "return", "new", "CSG", ".", "Polygon", "(", "p", ".", "vertices", ",", "shared", ",", "p", ".", "plane", ")", ";", "}", ")", ";", "var", "result", "=", "CSG", ".", "fromPolygons", "(", "polygons", ")", ";", "result", ".", "properties", "=", "this", ".", "properties", ";", "// keep original properties", "result", ".", "isRetesselated", "=", "this", ".", "isRetesselated", ";", "result", ".", "isCanonicalized", "=", "this", ".", "isCanonicalized", ";", "return", "result", ";", "}" ]
set the .shared property of all polygons Returns a new CSG solid, the original is unmodified!
[ "set", "the", ".", "shared", "property", "of", "all", "polygons", "Returns", "a", "new", "CSG", "solid", "the", "original", "is", "unmodified!" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L816-L825
55,202
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function(cuberadius) { var csg = this.reTesselated(); var result = new CSG(); // make a list of all unique vertices // For each vertex we also collect the list of normals of the planes touching the vertices var vertexmap = {}; csg.polygons.map(function(polygon) { polygon.vertices.map(function(vertex) { vertexmap[vertex.getTag()] = vertex.pos; }); }); for (var vertextag in vertexmap) { var pos = vertexmap[vertextag]; var cube = CSG.cube({ center: pos, radius: cuberadius }); result = result.unionSub(cube, false, false); } result = result.reTesselated(); return result; }
javascript
function(cuberadius) { var csg = this.reTesselated(); var result = new CSG(); // make a list of all unique vertices // For each vertex we also collect the list of normals of the planes touching the vertices var vertexmap = {}; csg.polygons.map(function(polygon) { polygon.vertices.map(function(vertex) { vertexmap[vertex.getTag()] = vertex.pos; }); }); for (var vertextag in vertexmap) { var pos = vertexmap[vertextag]; var cube = CSG.cube({ center: pos, radius: cuberadius }); result = result.unionSub(cube, false, false); } result = result.reTesselated(); return result; }
[ "function", "(", "cuberadius", ")", "{", "var", "csg", "=", "this", ".", "reTesselated", "(", ")", ";", "var", "result", "=", "new", "CSG", "(", ")", ";", "// make a list of all unique vertices", "// For each vertex we also collect the list of normals of the planes touching the vertices", "var", "vertexmap", "=", "{", "}", ";", "csg", ".", "polygons", ".", "map", "(", "function", "(", "polygon", ")", "{", "polygon", ".", "vertices", ".", "map", "(", "function", "(", "vertex", ")", "{", "vertexmap", "[", "vertex", ".", "getTag", "(", ")", "]", "=", "vertex", ".", "pos", ";", "}", ")", ";", "}", ")", ";", "for", "(", "var", "vertextag", "in", "vertexmap", ")", "{", "var", "pos", "=", "vertexmap", "[", "vertextag", "]", ";", "var", "cube", "=", "CSG", ".", "cube", "(", "{", "center", ":", "pos", ",", "radius", ":", "cuberadius", "}", ")", ";", "result", "=", "result", ".", "unionSub", "(", "cube", ",", "false", ",", "false", ")", ";", "}", "result", "=", "result", ".", "reTesselated", "(", ")", ";", "return", "result", ";", "}" ]
For debugging Creates a new solid with a tiny cube at every vertex of the source solid
[ "For", "debugging", "Creates", "a", "new", "solid", "with", "a", "tiny", "cube", "at", "every", "vertex", "of", "the", "source", "solid" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L930-L954
55,203
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function(orthobasis) { var EPS = 1e-5; var cags = []; this.polygons.filter(function(p) { // only return polys in plane, others may disturb result return p.plane.normal.minus(orthobasis.plane.normal).lengthSquared() < EPS*EPS; }) .map(function(polygon) { var cag = polygon.projectToOrthoNormalBasis(orthobasis); if (cag.sides.length > 0) { cags.push(cag); } }); var result = new CAG().union(cags); return result; }
javascript
function(orthobasis) { var EPS = 1e-5; var cags = []; this.polygons.filter(function(p) { // only return polys in plane, others may disturb result return p.plane.normal.minus(orthobasis.plane.normal).lengthSquared() < EPS*EPS; }) .map(function(polygon) { var cag = polygon.projectToOrthoNormalBasis(orthobasis); if (cag.sides.length > 0) { cags.push(cag); } }); var result = new CAG().union(cags); return result; }
[ "function", "(", "orthobasis", ")", "{", "var", "EPS", "=", "1e-5", ";", "var", "cags", "=", "[", "]", ";", "this", ".", "polygons", ".", "filter", "(", "function", "(", "p", ")", "{", "// only return polys in plane, others may disturb result", "return", "p", ".", "plane", ".", "normal", ".", "minus", "(", "orthobasis", ".", "plane", ".", "normal", ")", ".", "lengthSquared", "(", ")", "<", "EPS", "*", "EPS", ";", "}", ")", ".", "map", "(", "function", "(", "polygon", ")", "{", "var", "cag", "=", "polygon", ".", "projectToOrthoNormalBasis", "(", "orthobasis", ")", ";", "if", "(", "cag", ".", "sides", ".", "length", ">", "0", ")", "{", "cags", ".", "push", "(", "cag", ")", ";", "}", "}", ")", ";", "var", "result", "=", "new", "CAG", "(", ")", ".", "union", "(", "cags", ")", ";", "return", "result", ";", "}" ]
project the 3D CSG onto a plane This returns a 2D CAG with the 'shadow' shape of the 3D solid when projected onto the plane represented by the orthonormal basis
[ "project", "the", "3D", "CSG", "onto", "a", "plane", "This", "returns", "a", "2D", "CAG", "with", "the", "shadow", "shape", "of", "the", "3D", "solid", "when", "projected", "onto", "the", "plane", "represented", "by", "the", "orthonormal", "basis" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L1044-L1059
55,204
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function() { var abs = this.abs(); if ((abs._x <= abs._y) && (abs._x <= abs._z)) { return CSG.Vector3D.Create(1, 0, 0); } else if ((abs._y <= abs._x) && (abs._y <= abs._z)) { return CSG.Vector3D.Create(0, 1, 0); } else { return CSG.Vector3D.Create(0, 0, 1); } }
javascript
function() { var abs = this.abs(); if ((abs._x <= abs._y) && (abs._x <= abs._z)) { return CSG.Vector3D.Create(1, 0, 0); } else if ((abs._y <= abs._x) && (abs._y <= abs._z)) { return CSG.Vector3D.Create(0, 1, 0); } else { return CSG.Vector3D.Create(0, 0, 1); } }
[ "function", "(", ")", "{", "var", "abs", "=", "this", ".", "abs", "(", ")", ";", "if", "(", "(", "abs", ".", "_x", "<=", "abs", ".", "_y", ")", "&&", "(", "abs", ".", "_x", "<=", "abs", ".", "_z", ")", ")", "{", "return", "CSG", ".", "Vector3D", ".", "Create", "(", "1", ",", "0", ",", "0", ")", ";", "}", "else", "if", "(", "(", "abs", ".", "_y", "<=", "abs", ".", "_x", ")", "&&", "(", "abs", ".", "_y", "<=", "abs", ".", "_z", ")", ")", "{", "return", "CSG", ".", "Vector3D", ".", "Create", "(", "0", ",", "1", ",", "0", ")", ";", "}", "else", "{", "return", "CSG", ".", "Vector3D", ".", "Create", "(", "0", ",", "0", ",", "1", ")", ";", "}", "}" ]
find a vector that is somewhat perpendicular to this one
[ "find", "a", "vector", "that", "is", "somewhat", "perpendicular", "to", "this", "one" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L2124-L2133
55,205
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function(other, t) { var newpos = this.pos.lerp(other.pos, t); return new CSG.Vertex(newpos); }
javascript
function(other, t) { var newpos = this.pos.lerp(other.pos, t); return new CSG.Vertex(newpos); }
[ "function", "(", "other", ",", "t", ")", "{", "var", "newpos", "=", "this", ".", "pos", ".", "lerp", "(", "other", ".", "pos", ",", "t", ")", ";", "return", "new", "CSG", ".", "Vertex", "(", "newpos", ")", ";", "}" ]
Create a new vertex between this vertex and `other` by linearly interpolating all properties using a parameter of `t`. Subclasses should override this to interpolate additional properties.
[ "Create", "a", "new", "vertex", "between", "this", "vertex", "and", "other", "by", "linearly", "interpolating", "all", "properties", "using", "a", "parameter", "of", "t", ".", "Subclasses", "should", "override", "this", "to", "interpolate", "additional", "properties", "." ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L2181-L2184
55,206
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function(features) { var result = []; features.forEach(function(feature) { if (feature == 'volume') { result.push(this.getSignedVolume()); } else if (feature == 'area') { result.push(this.getArea()); } }, this); return result; }
javascript
function(features) { var result = []; features.forEach(function(feature) { if (feature == 'volume') { result.push(this.getSignedVolume()); } else if (feature == 'area') { result.push(this.getArea()); } }, this); return result; }
[ "function", "(", "features", ")", "{", "var", "result", "=", "[", "]", ";", "features", ".", "forEach", "(", "function", "(", "feature", ")", "{", "if", "(", "feature", "==", "'volume'", ")", "{", "result", ".", "push", "(", "this", ".", "getSignedVolume", "(", ")", ")", ";", "}", "else", "if", "(", "feature", "==", "'area'", ")", "{", "result", ".", "push", "(", "this", ".", "getArea", "(", ")", ")", ";", "}", "}", ",", "this", ")", ";", "return", "result", ";", "}" ]
accepts array of features to calculate returns array of results
[ "accepts", "array", "of", "features", "to", "calculate", "returns", "array", "of", "results" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L2531-L2541
55,207
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function(offsetvector) { var newpolygons = []; var polygon1 = this; var direction = polygon1.plane.normal.dot(offsetvector); if (direction > 0) { polygon1 = polygon1.flipped(); } newpolygons.push(polygon1); var polygon2 = polygon1.translate(offsetvector); var numvertices = this.vertices.length; for (var i = 0; i < numvertices; i++) { var sidefacepoints = []; var nexti = (i < (numvertices - 1)) ? i + 1 : 0; sidefacepoints.push(polygon1.vertices[i].pos); sidefacepoints.push(polygon2.vertices[i].pos); sidefacepoints.push(polygon2.vertices[nexti].pos); sidefacepoints.push(polygon1.vertices[nexti].pos); var sidefacepolygon = CSG.Polygon.createFromPoints(sidefacepoints, this.shared); newpolygons.push(sidefacepolygon); } polygon2 = polygon2.flipped(); newpolygons.push(polygon2); return CSG.fromPolygons(newpolygons); }
javascript
function(offsetvector) { var newpolygons = []; var polygon1 = this; var direction = polygon1.plane.normal.dot(offsetvector); if (direction > 0) { polygon1 = polygon1.flipped(); } newpolygons.push(polygon1); var polygon2 = polygon1.translate(offsetvector); var numvertices = this.vertices.length; for (var i = 0; i < numvertices; i++) { var sidefacepoints = []; var nexti = (i < (numvertices - 1)) ? i + 1 : 0; sidefacepoints.push(polygon1.vertices[i].pos); sidefacepoints.push(polygon2.vertices[i].pos); sidefacepoints.push(polygon2.vertices[nexti].pos); sidefacepoints.push(polygon1.vertices[nexti].pos); var sidefacepolygon = CSG.Polygon.createFromPoints(sidefacepoints, this.shared); newpolygons.push(sidefacepolygon); } polygon2 = polygon2.flipped(); newpolygons.push(polygon2); return CSG.fromPolygons(newpolygons); }
[ "function", "(", "offsetvector", ")", "{", "var", "newpolygons", "=", "[", "]", ";", "var", "polygon1", "=", "this", ";", "var", "direction", "=", "polygon1", ".", "plane", ".", "normal", ".", "dot", "(", "offsetvector", ")", ";", "if", "(", "direction", ">", "0", ")", "{", "polygon1", "=", "polygon1", ".", "flipped", "(", ")", ";", "}", "newpolygons", ".", "push", "(", "polygon1", ")", ";", "var", "polygon2", "=", "polygon1", ".", "translate", "(", "offsetvector", ")", ";", "var", "numvertices", "=", "this", ".", "vertices", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numvertices", ";", "i", "++", ")", "{", "var", "sidefacepoints", "=", "[", "]", ";", "var", "nexti", "=", "(", "i", "<", "(", "numvertices", "-", "1", ")", ")", "?", "i", "+", "1", ":", "0", ";", "sidefacepoints", ".", "push", "(", "polygon1", ".", "vertices", "[", "i", "]", ".", "pos", ")", ";", "sidefacepoints", ".", "push", "(", "polygon2", ".", "vertices", "[", "i", "]", ".", "pos", ")", ";", "sidefacepoints", ".", "push", "(", "polygon2", ".", "vertices", "[", "nexti", "]", ".", "pos", ")", ";", "sidefacepoints", ".", "push", "(", "polygon1", ".", "vertices", "[", "nexti", "]", ".", "pos", ")", ";", "var", "sidefacepolygon", "=", "CSG", ".", "Polygon", ".", "createFromPoints", "(", "sidefacepoints", ",", "this", ".", "shared", ")", ";", "newpolygons", ".", "push", "(", "sidefacepolygon", ")", ";", "}", "polygon2", "=", "polygon2", ".", "flipped", "(", ")", ";", "newpolygons", ".", "push", "(", "polygon2", ")", ";", "return", "CSG", ".", "fromPolygons", "(", "newpolygons", ")", ";", "}" ]
Extrude a polygon into the direction offsetvector Returns a CSG object
[ "Extrude", "a", "polygon", "into", "the", "direction", "offsetvector", "Returns", "a", "CSG", "object" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L2545-L2569
55,208
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function(matrix4x4) { var newvertices = this.vertices.map(function(v) { return v.transform(matrix4x4); }); var newplane = this.plane.transform(matrix4x4); if (matrix4x4.isMirroring()) { // need to reverse the vertex order // in order to preserve the inside/outside orientation: newvertices.reverse(); } return new CSG.Polygon(newvertices, this.shared, newplane); }
javascript
function(matrix4x4) { var newvertices = this.vertices.map(function(v) { return v.transform(matrix4x4); }); var newplane = this.plane.transform(matrix4x4); if (matrix4x4.isMirroring()) { // need to reverse the vertex order // in order to preserve the inside/outside orientation: newvertices.reverse(); } return new CSG.Polygon(newvertices, this.shared, newplane); }
[ "function", "(", "matrix4x4", ")", "{", "var", "newvertices", "=", "this", ".", "vertices", ".", "map", "(", "function", "(", "v", ")", "{", "return", "v", ".", "transform", "(", "matrix4x4", ")", ";", "}", ")", ";", "var", "newplane", "=", "this", ".", "plane", ".", "transform", "(", "matrix4x4", ")", ";", "if", "(", "matrix4x4", ".", "isMirroring", "(", ")", ")", "{", "// need to reverse the vertex order", "// in order to preserve the inside/outside orientation:", "newvertices", ".", "reverse", "(", ")", ";", "}", "return", "new", "CSG", ".", "Polygon", "(", "newvertices", ",", "this", ".", "shared", ",", "newplane", ")", ";", "}" ]
Affine transformation of polygon. Returns a new CSG.Polygon
[ "Affine", "transformation", "of", "polygon", ".", "Returns", "a", "new", "CSG", ".", "Polygon" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L2619-L2630
55,209
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function(orthobasis) { var points2d = this.vertices.map(function(vertex) { return orthobasis.to2D(vertex.pos); }); var result = CAG.fromPointsNoCheck(points2d); var area = result.area(); if (Math.abs(area) < 1e-5) { // the polygon was perpendicular to the orthnormal plane. The resulting 2D polygon would be degenerate // return an empty area instead: result = new CAG(); } else if (area < 0) { result = result.flipped(); } return result; }
javascript
function(orthobasis) { var points2d = this.vertices.map(function(vertex) { return orthobasis.to2D(vertex.pos); }); var result = CAG.fromPointsNoCheck(points2d); var area = result.area(); if (Math.abs(area) < 1e-5) { // the polygon was perpendicular to the orthnormal plane. The resulting 2D polygon would be degenerate // return an empty area instead: result = new CAG(); } else if (area < 0) { result = result.flipped(); } return result; }
[ "function", "(", "orthobasis", ")", "{", "var", "points2d", "=", "this", ".", "vertices", ".", "map", "(", "function", "(", "vertex", ")", "{", "return", "orthobasis", ".", "to2D", "(", "vertex", ".", "pos", ")", ";", "}", ")", ";", "var", "result", "=", "CAG", ".", "fromPointsNoCheck", "(", "points2d", ")", ";", "var", "area", "=", "result", ".", "area", "(", ")", ";", "if", "(", "Math", ".", "abs", "(", "area", ")", "<", "1e-5", ")", "{", "// the polygon was perpendicular to the orthnormal plane. The resulting 2D polygon would be degenerate", "// return an empty area instead:", "result", "=", "new", "CAG", "(", ")", ";", "}", "else", "if", "(", "area", "<", "0", ")", "{", "result", "=", "result", ".", "flipped", "(", ")", ";", "}", "return", "result", ";", "}" ]
project the 3D polygon onto a plane
[ "project", "the", "3D", "polygon", "onto", "a", "plane" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L2641-L2655
55,210
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function() { if (!this.removed) { this.removed = true; if (_CSGDEBUG) { if (this.isRootNode()) throw new Error("Assertion failed"); // can't remove root node if (this.children.length) throw new Error("Assertion failed"); // we shouldn't remove nodes with children } // remove ourselves from the parent's children list: var parentschildren = this.parent.children; var i = parentschildren.indexOf(this); if (i < 0) throw new Error("Assertion failed"); parentschildren.splice(i, 1); // invalidate the parent's polygon, and of all parents above it: this.parent.recursivelyInvalidatePolygon(); } }
javascript
function() { if (!this.removed) { this.removed = true; if (_CSGDEBUG) { if (this.isRootNode()) throw new Error("Assertion failed"); // can't remove root node if (this.children.length) throw new Error("Assertion failed"); // we shouldn't remove nodes with children } // remove ourselves from the parent's children list: var parentschildren = this.parent.children; var i = parentschildren.indexOf(this); if (i < 0) throw new Error("Assertion failed"); parentschildren.splice(i, 1); // invalidate the parent's polygon, and of all parents above it: this.parent.recursivelyInvalidatePolygon(); } }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "removed", ")", "{", "this", ".", "removed", "=", "true", ";", "if", "(", "_CSGDEBUG", ")", "{", "if", "(", "this", ".", "isRootNode", "(", ")", ")", "throw", "new", "Error", "(", "\"Assertion failed\"", ")", ";", "// can't remove root node", "if", "(", "this", ".", "children", ".", "length", ")", "throw", "new", "Error", "(", "\"Assertion failed\"", ")", ";", "// we shouldn't remove nodes with children", "}", "// remove ourselves from the parent's children list:", "var", "parentschildren", "=", "this", ".", "parent", ".", "children", ";", "var", "i", "=", "parentschildren", ".", "indexOf", "(", "this", ")", ";", "if", "(", "i", "<", "0", ")", "throw", "new", "Error", "(", "\"Assertion failed\"", ")", ";", "parentschildren", ".", "splice", "(", "i", ",", "1", ")", ";", "// invalidate the parent's polygon, and of all parents above it:", "this", ".", "parent", ".", "recursivelyInvalidatePolygon", "(", ")", ";", "}", "}" ]
remove a node - the siblings become toplevel nodes - the parent is removed recursively
[ "remove", "a", "node", "-", "the", "siblings", "become", "toplevel", "nodes", "-", "the", "parent", "is", "removed", "recursively" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L3014-L3032
55,211
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function() { var queue = [this]; var i, node; for (var i = 0; i < queue.length; i++) { node = queue[i]; if(node.plane) node.plane = node.plane.flipped(); if(node.front) queue.push(node.front); if(node.back) queue.push(node.back); var temp = node.front; node.front = node.back; node.back = temp; } }
javascript
function() { var queue = [this]; var i, node; for (var i = 0; i < queue.length; i++) { node = queue[i]; if(node.plane) node.plane = node.plane.flipped(); if(node.front) queue.push(node.front); if(node.back) queue.push(node.back); var temp = node.front; node.front = node.back; node.back = temp; } }
[ "function", "(", ")", "{", "var", "queue", "=", "[", "this", "]", ";", "var", "i", ",", "node", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "queue", ".", "length", ";", "i", "++", ")", "{", "node", "=", "queue", "[", "i", "]", ";", "if", "(", "node", ".", "plane", ")", "node", ".", "plane", "=", "node", ".", "plane", ".", "flipped", "(", ")", ";", "if", "(", "node", ".", "front", ")", "queue", ".", "push", "(", "node", ".", "front", ")", ";", "if", "(", "node", ".", "back", ")", "queue", ".", "push", "(", "node", ".", "back", ")", ";", "var", "temp", "=", "node", ".", "front", ";", "node", ".", "front", "=", "node", ".", "back", ";", "node", ".", "back", "=", "temp", ";", "}", "}" ]
Convert solid space to empty space and empty space to solid space.
[ "Convert", "solid", "space", "to", "empty", "space", "and", "empty", "space", "to", "solid", "space", "." ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L3247-L3259
55,212
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function() { var u = new CSG.Vector3D(this.elements[0], this.elements[4], this.elements[8]); var v = new CSG.Vector3D(this.elements[1], this.elements[5], this.elements[9]); var w = new CSG.Vector3D(this.elements[2], this.elements[6], this.elements[10]); // for a true orthogonal, non-mirrored base, u.cross(v) == w // If they have an opposite direction then we are mirroring var mirrorvalue = u.cross(v).dot(w); var ismirror = (mirrorvalue < 0); return ismirror; }
javascript
function() { var u = new CSG.Vector3D(this.elements[0], this.elements[4], this.elements[8]); var v = new CSG.Vector3D(this.elements[1], this.elements[5], this.elements[9]); var w = new CSG.Vector3D(this.elements[2], this.elements[6], this.elements[10]); // for a true orthogonal, non-mirrored base, u.cross(v) == w // If they have an opposite direction then we are mirroring var mirrorvalue = u.cross(v).dot(w); var ismirror = (mirrorvalue < 0); return ismirror; }
[ "function", "(", ")", "{", "var", "u", "=", "new", "CSG", ".", "Vector3D", "(", "this", ".", "elements", "[", "0", "]", ",", "this", ".", "elements", "[", "4", "]", ",", "this", ".", "elements", "[", "8", "]", ")", ";", "var", "v", "=", "new", "CSG", ".", "Vector3D", "(", "this", ".", "elements", "[", "1", "]", ",", "this", ".", "elements", "[", "5", "]", ",", "this", ".", "elements", "[", "9", "]", ")", ";", "var", "w", "=", "new", "CSG", ".", "Vector3D", "(", "this", ".", "elements", "[", "2", "]", ",", "this", ".", "elements", "[", "6", "]", ",", "this", ".", "elements", "[", "10", "]", ")", ";", "// for a true orthogonal, non-mirrored base, u.cross(v) == w", "// If they have an opposite direction then we are mirroring", "var", "mirrorvalue", "=", "u", ".", "cross", "(", "v", ")", ".", "dot", "(", "w", ")", ";", "var", "ismirror", "=", "(", "mirrorvalue", "<", "0", ")", ";", "return", "ismirror", ";", "}" ]
determine whether this matrix is a mirroring transformation
[ "determine", "whether", "this", "matrix", "is", "a", "mirroring", "transformation" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L3545-L3555
55,213
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function(distance) { var newpoint = this.point.plus(this.axisvector.unit().times(distance)); return new CSG.Connector(newpoint, this.axisvector, this.normalvector); }
javascript
function(distance) { var newpoint = this.point.plus(this.axisvector.unit().times(distance)); return new CSG.Connector(newpoint, this.axisvector, this.normalvector); }
[ "function", "(", "distance", ")", "{", "var", "newpoint", "=", "this", ".", "point", ".", "plus", "(", "this", ".", "axisvector", ".", "unit", "(", ")", ".", "times", "(", "distance", ")", ")", ";", "return", "new", "CSG", ".", "Connector", "(", "newpoint", ",", "this", ".", "axisvector", ",", "this", ".", "normalvector", ")", ";", "}" ]
creates a new Connector, with the connection point moved in the direction of the axisvector
[ "creates", "a", "new", "Connector", "with", "the", "connection", "point", "moved", "in", "the", "direction", "of", "the", "axisvector" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L4881-L4884
55,214
johnwebbcole/gulp-openjscad-standalone
docs/csg.js
function(pathradius, resolution) { var sides = []; var numpoints = this.points.length; var startindex = 0; if (this.closed && (numpoints > 2)) startindex = -1; var prevvertex; for (var i = startindex; i < numpoints; i++) { var pointindex = i; if (pointindex < 0) pointindex = numpoints - 1; var point = this.points[pointindex]; var vertex = new CAG.Vertex(point); if (i > startindex) { var side = new CAG.Side(prevvertex, vertex); sides.push(side); } prevvertex = vertex; } var shellcag = CAG.fromSides(sides); var expanded = shellcag.expandedShell(pathradius, resolution); return expanded; }
javascript
function(pathradius, resolution) { var sides = []; var numpoints = this.points.length; var startindex = 0; if (this.closed && (numpoints > 2)) startindex = -1; var prevvertex; for (var i = startindex; i < numpoints; i++) { var pointindex = i; if (pointindex < 0) pointindex = numpoints - 1; var point = this.points[pointindex]; var vertex = new CAG.Vertex(point); if (i > startindex) { var side = new CAG.Side(prevvertex, vertex); sides.push(side); } prevvertex = vertex; } var shellcag = CAG.fromSides(sides); var expanded = shellcag.expandedShell(pathradius, resolution); return expanded; }
[ "function", "(", "pathradius", ",", "resolution", ")", "{", "var", "sides", "=", "[", "]", ";", "var", "numpoints", "=", "this", ".", "points", ".", "length", ";", "var", "startindex", "=", "0", ";", "if", "(", "this", ".", "closed", "&&", "(", "numpoints", ">", "2", ")", ")", "startindex", "=", "-", "1", ";", "var", "prevvertex", ";", "for", "(", "var", "i", "=", "startindex", ";", "i", "<", "numpoints", ";", "i", "++", ")", "{", "var", "pointindex", "=", "i", ";", "if", "(", "pointindex", "<", "0", ")", "pointindex", "=", "numpoints", "-", "1", ";", "var", "point", "=", "this", ".", "points", "[", "pointindex", "]", ";", "var", "vertex", "=", "new", "CAG", ".", "Vertex", "(", "point", ")", ";", "if", "(", "i", ">", "startindex", ")", "{", "var", "side", "=", "new", "CAG", ".", "Side", "(", "prevvertex", ",", "vertex", ")", ";", "sides", ".", "push", "(", "side", ")", ";", "}", "prevvertex", "=", "vertex", ";", "}", "var", "shellcag", "=", "CAG", ".", "fromSides", "(", "sides", ")", ";", "var", "expanded", "=", "shellcag", ".", "expandedShell", "(", "pathradius", ",", "resolution", ")", ";", "return", "expanded", ";", "}" ]
Expand the path to a CAG This traces the path with a circle with radius pathradius
[ "Expand", "the", "path", "to", "a", "CAG", "This", "traces", "the", "path", "with", "a", "circle", "with", "radius", "pathradius" ]
0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c
https://github.com/johnwebbcole/gulp-openjscad-standalone/blob/0727d09fc2b6b20a0e7dac4d2bb44e706c1b442c/docs/csg.js#L5142-L5162
55,215
epii-io/epii-node-render
index.js
buildOnce
function buildOnce(config) { // verify config if (!lintConfig(config)) throw new Error('invalid config') // set default holder if (!config.holder) { config.holder = { name: 'app', stub: 'epii' } } // prepare static dir shell.mkdir('-p', config.$path.target.client) shell.mkdir('-p', config.$path.target.vendor) // process source pureRecipe(config, CONTEXT) viewRecipe(config, CONTEXT) sassRecipe(config, CONTEXT) fileRecipe(config, CONTEXT) }
javascript
function buildOnce(config) { // verify config if (!lintConfig(config)) throw new Error('invalid config') // set default holder if (!config.holder) { config.holder = { name: 'app', stub: 'epii' } } // prepare static dir shell.mkdir('-p', config.$path.target.client) shell.mkdir('-p', config.$path.target.vendor) // process source pureRecipe(config, CONTEXT) viewRecipe(config, CONTEXT) sassRecipe(config, CONTEXT) fileRecipe(config, CONTEXT) }
[ "function", "buildOnce", "(", "config", ")", "{", "// verify config", "if", "(", "!", "lintConfig", "(", "config", ")", ")", "throw", "new", "Error", "(", "'invalid config'", ")", "// set default holder", "if", "(", "!", "config", ".", "holder", ")", "{", "config", ".", "holder", "=", "{", "name", ":", "'app'", ",", "stub", ":", "'epii'", "}", "}", "// prepare static dir", "shell", ".", "mkdir", "(", "'-p'", ",", "config", ".", "$path", ".", "target", ".", "client", ")", "shell", ".", "mkdir", "(", "'-p'", ",", "config", ".", "$path", ".", "target", ".", "vendor", ")", "// process source", "pureRecipe", "(", "config", ",", "CONTEXT", ")", "viewRecipe", "(", "config", ",", "CONTEXT", ")", "sassRecipe", "(", "config", ",", "CONTEXT", ")", "fileRecipe", "(", "config", ",", "CONTEXT", ")", "}" ]
build once, default production
[ "build", "once", "default", "production" ]
e8afa57066251e173b3a6455d47218c95f30f563
https://github.com/epii-io/epii-node-render/blob/e8afa57066251e173b3a6455d47218c95f30f563/index.js#L53-L71
55,216
epii-io/epii-node-render
index.js
watchBuild
function watchBuild(config) { // verify config if (!lintConfig(config)) throw new Error('invalid config') // set development env CONTEXT.env = 'development' // build once immediately buildOnce(config) // bind watch handler assist.tryWatch( config.$path.source.client, function (e, file) { if (!file) return CONTEXT.entries.push(path.join(config.$path.source.client, file)) buildOnce(config, CONTEXT) CONTEXT.entries = [] } ) }
javascript
function watchBuild(config) { // verify config if (!lintConfig(config)) throw new Error('invalid config') // set development env CONTEXT.env = 'development' // build once immediately buildOnce(config) // bind watch handler assist.tryWatch( config.$path.source.client, function (e, file) { if (!file) return CONTEXT.entries.push(path.join(config.$path.source.client, file)) buildOnce(config, CONTEXT) CONTEXT.entries = [] } ) }
[ "function", "watchBuild", "(", "config", ")", "{", "// verify config", "if", "(", "!", "lintConfig", "(", "config", ")", ")", "throw", "new", "Error", "(", "'invalid config'", ")", "// set development env", "CONTEXT", ".", "env", "=", "'development'", "// build once immediately", "buildOnce", "(", "config", ")", "// bind watch handler", "assist", ".", "tryWatch", "(", "config", ".", "$path", ".", "source", ".", "client", ",", "function", "(", "e", ",", "file", ")", "{", "if", "(", "!", "file", ")", "return", "CONTEXT", ".", "entries", ".", "push", "(", "path", ".", "join", "(", "config", ".", "$path", ".", "source", ".", "client", ",", "file", ")", ")", "buildOnce", "(", "config", ",", "CONTEXT", ")", "CONTEXT", ".", "entries", "=", "[", "]", "}", ")", "}" ]
watch & build, development
[ "watch", "&", "build", "development" ]
e8afa57066251e173b3a6455d47218c95f30f563
https://github.com/epii-io/epii-node-render/blob/e8afa57066251e173b3a6455d47218c95f30f563/index.js#L76-L96
55,217
ozum/replace-between
index.js
replaceBetween
function replaceBetween(args) { const getSourceContent = args.source ? fs.readFile(path.normalize(args.source), { encoding: 'utf8' }) : getStdin(); const getTargetContent = fs.readFile(path.normalize(args.target), { encoding: 'utf8' }); const commentBegin = args.comment ? commentTypes[args.comment].begin : args.begin; const commentEnd = args.comment ? commentTypes[args.comment].end : args.end; const beginTokenPattern = `(${commentBegin}\\s*?${args.token} BEGIN\\s*?${commentEnd}.*?[\\r\\n]+)`; const endTokenPattern = `(${commentBegin}\\s*?${args.token} END\\s*?${commentEnd})`; const contentPattern = '[\\s\\S]*?'; const RX = new RegExp(`${beginTokenPattern}${contentPattern}${endTokenPattern}`, 'm'); return Promise.all([getSourceContent, getTargetContent]) .then(([sourceContent, targetContent]) => { if (!sourceContent) { throw new Error('Source content is empty.'); } if (!targetContent.match(RX)) { const error = `Target file content does not have necessary tokens ${chalk.yellow(`${commentBegin} ${args.token} BEGIN ${commentEnd}`)} ` + `and ${chalk.yellow(`${commentBegin} ${args.token} END ${commentEnd}`)}.`; throw new Error(error); } return targetContent.replace(RX, `$1${sourceContent}$2`); }) .then(newContent => fs.outputFile(path.normalize(args.target), newContent)); }
javascript
function replaceBetween(args) { const getSourceContent = args.source ? fs.readFile(path.normalize(args.source), { encoding: 'utf8' }) : getStdin(); const getTargetContent = fs.readFile(path.normalize(args.target), { encoding: 'utf8' }); const commentBegin = args.comment ? commentTypes[args.comment].begin : args.begin; const commentEnd = args.comment ? commentTypes[args.comment].end : args.end; const beginTokenPattern = `(${commentBegin}\\s*?${args.token} BEGIN\\s*?${commentEnd}.*?[\\r\\n]+)`; const endTokenPattern = `(${commentBegin}\\s*?${args.token} END\\s*?${commentEnd})`; const contentPattern = '[\\s\\S]*?'; const RX = new RegExp(`${beginTokenPattern}${contentPattern}${endTokenPattern}`, 'm'); return Promise.all([getSourceContent, getTargetContent]) .then(([sourceContent, targetContent]) => { if (!sourceContent) { throw new Error('Source content is empty.'); } if (!targetContent.match(RX)) { const error = `Target file content does not have necessary tokens ${chalk.yellow(`${commentBegin} ${args.token} BEGIN ${commentEnd}`)} ` + `and ${chalk.yellow(`${commentBegin} ${args.token} END ${commentEnd}`)}.`; throw new Error(error); } return targetContent.replace(RX, `$1${sourceContent}$2`); }) .then(newContent => fs.outputFile(path.normalize(args.target), newContent)); }
[ "function", "replaceBetween", "(", "args", ")", "{", "const", "getSourceContent", "=", "args", ".", "source", "?", "fs", ".", "readFile", "(", "path", ".", "normalize", "(", "args", ".", "source", ")", ",", "{", "encoding", ":", "'utf8'", "}", ")", ":", "getStdin", "(", ")", ";", "const", "getTargetContent", "=", "fs", ".", "readFile", "(", "path", ".", "normalize", "(", "args", ".", "target", ")", ",", "{", "encoding", ":", "'utf8'", "}", ")", ";", "const", "commentBegin", "=", "args", ".", "comment", "?", "commentTypes", "[", "args", ".", "comment", "]", ".", "begin", ":", "args", ".", "begin", ";", "const", "commentEnd", "=", "args", ".", "comment", "?", "commentTypes", "[", "args", ".", "comment", "]", ".", "end", ":", "args", ".", "end", ";", "const", "beginTokenPattern", "=", "`", "${", "commentBegin", "}", "\\\\", "${", "args", ".", "token", "}", "\\\\", "${", "commentEnd", "}", "\\\\", "\\\\", "`", ";", "const", "endTokenPattern", "=", "`", "${", "commentBegin", "}", "\\\\", "${", "args", ".", "token", "}", "\\\\", "${", "commentEnd", "}", "`", ";", "const", "contentPattern", "=", "'[\\\\s\\\\S]*?'", ";", "const", "RX", "=", "new", "RegExp", "(", "`", "${", "beginTokenPattern", "}", "${", "contentPattern", "}", "${", "endTokenPattern", "}", "`", ",", "'m'", ")", ";", "return", "Promise", ".", "all", "(", "[", "getSourceContent", ",", "getTargetContent", "]", ")", ".", "then", "(", "(", "[", "sourceContent", ",", "targetContent", "]", ")", "=>", "{", "if", "(", "!", "sourceContent", ")", "{", "throw", "new", "Error", "(", "'Source content is empty.'", ")", ";", "}", "if", "(", "!", "targetContent", ".", "match", "(", "RX", ")", ")", "{", "const", "error", "=", "`", "${", "chalk", ".", "yellow", "(", "`", "${", "commentBegin", "}", "${", "args", ".", "token", "}", "${", "commentEnd", "}", "`", ")", "}", "`", "+", "`", "${", "chalk", ".", "yellow", "(", "`", "${", "commentBegin", "}", "${", "args", ".", "token", "}", "${", "commentEnd", "}", "`", ")", "}", "`", ";", "throw", "new", "Error", "(", "error", ")", ";", "}", "return", "targetContent", ".", "replace", "(", "RX", ",", "`", "${", "sourceContent", "}", "`", ")", ";", "}", ")", ".", "then", "(", "newContent", "=>", "fs", ".", "outputFile", "(", "path", ".", "normalize", "(", "args", ".", "target", ")", ",", "newContent", ")", ")", ";", "}" ]
Replaces text between markers with text from a file or stdin. @param {Object} args - Options @param {string} args.token - Token text to look for between start and end comment. BEGIN and END words are added automatically. @param {string} args.target - Target file to replace text in. @param {string} [args.source] - Source file to get replacement text from. If not provided STDIN is used instead. @param {string} [args.comment] - Predefined comment types to be used for replacement markers. (i.e. 'markdown' for '<!---' '--->'. If not provided, it is tried to be get from target file extension. @param {string} [args.begin] - Beginning of the comment syntax. i.e <!--- for markdown. @param {string} [args.end] - End of the comment syntax. i.e ---> for markdown. @returns {Promise.<void>} - Promise
[ "Replaces", "text", "between", "markers", "with", "text", "from", "a", "file", "or", "stdin", "." ]
35263dff3992286eacd8c78e3b4e50bdebc9af96
https://github.com/ozum/replace-between/blob/35263dff3992286eacd8c78e3b4e50bdebc9af96/index.js#L23-L50
55,218
camshaft/component-github-content-api
lib/index.js
GitHubContentAPI
function GitHubContentAPI(opts) { if (!(this instanceof GitHubContentAPI)) return new GitHubContentAPI(opts); opts = Object.create(opts || {}); if (!opts.auth && GITHUB_USERNAME && GITHUB_PASSWORD) opts.auth = GITHUB_USERNAME + ':' + GITHUB_PASSWORD; this._host = opts.host || 'https://api.github.com'; GitHub.call(this, opts); Remote.call(this, opts); this._gh_request = this.request; delete this.request; main = this; }
javascript
function GitHubContentAPI(opts) { if (!(this instanceof GitHubContentAPI)) return new GitHubContentAPI(opts); opts = Object.create(opts || {}); if (!opts.auth && GITHUB_USERNAME && GITHUB_PASSWORD) opts.auth = GITHUB_USERNAME + ':' + GITHUB_PASSWORD; this._host = opts.host || 'https://api.github.com'; GitHub.call(this, opts); Remote.call(this, opts); this._gh_request = this.request; delete this.request; main = this; }
[ "function", "GitHubContentAPI", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "GitHubContentAPI", ")", ")", "return", "new", "GitHubContentAPI", "(", "opts", ")", ";", "opts", "=", "Object", ".", "create", "(", "opts", "||", "{", "}", ")", ";", "if", "(", "!", "opts", ".", "auth", "&&", "GITHUB_USERNAME", "&&", "GITHUB_PASSWORD", ")", "opts", ".", "auth", "=", "GITHUB_USERNAME", "+", "':'", "+", "GITHUB_PASSWORD", ";", "this", ".", "_host", "=", "opts", ".", "host", "||", "'https://api.github.com'", ";", "GitHub", ".", "call", "(", "this", ",", "opts", ")", ";", "Remote", ".", "call", "(", "this", ",", "opts", ")", ";", "this", ".", "_gh_request", "=", "this", ".", "request", ";", "delete", "this", ".", "request", ";", "main", "=", "this", ";", "}" ]
Create a GitHub content API remote @param {Object} opts
[ "Create", "a", "GitHub", "content", "API", "remote" ]
4b0461b8c676bb3a11d3dc882d2bc3b47101f9bd
https://github.com/camshaft/component-github-content-api/blob/4b0461b8c676bb3a11d3dc882d2bc3b47101f9bd/lib/index.js#L40-L55
55,219
camshaft/component-github-content-api
lib/index.js
errorRateLimitExceeded
function errorRateLimitExceeded(res) { var err = new Error('GitHub rate limit exceeded.'); err.res = res; err.remote = 'github-content-api'; throw err; }
javascript
function errorRateLimitExceeded(res) { var err = new Error('GitHub rate limit exceeded.'); err.res = res; err.remote = 'github-content-api'; throw err; }
[ "function", "errorRateLimitExceeded", "(", "res", ")", "{", "var", "err", "=", "new", "Error", "(", "'GitHub rate limit exceeded.'", ")", ";", "err", ".", "res", "=", "res", ";", "err", ".", "remote", "=", "'github-content-api'", ";", "throw", "err", ";", "}" ]
Better error message when rate limit exceeded. @param {Object} response @api private
[ "Better", "error", "message", "when", "rate", "limit", "exceeded", "." ]
4b0461b8c676bb3a11d3dc882d2bc3b47101f9bd
https://github.com/camshaft/component-github-content-api/blob/4b0461b8c676bb3a11d3dc882d2bc3b47101f9bd/lib/index.js#L130-L135
55,220
camshaft/component-github-content-api
lib/index.js
checkRateLimitRemaining
function checkRateLimitRemaining(res) { var remaining = parseInt(res.headers['x-ratelimit-remaining'], 10); if (remaining <= 50) { console.warn('github-content-api remote: only %d requests remaining.', remaining); } }
javascript
function checkRateLimitRemaining(res) { var remaining = parseInt(res.headers['x-ratelimit-remaining'], 10); if (remaining <= 50) { console.warn('github-content-api remote: only %d requests remaining.', remaining); } }
[ "function", "checkRateLimitRemaining", "(", "res", ")", "{", "var", "remaining", "=", "parseInt", "(", "res", ".", "headers", "[", "'x-ratelimit-remaining'", "]", ",", "10", ")", ";", "if", "(", "remaining", "<=", "50", ")", "{", "console", ".", "warn", "(", "'github-content-api remote: only %d requests remaining.'", ",", "remaining", ")", ";", "}", "}" ]
Warn when rate limit is low. @param {Object} response @api private
[ "Warn", "when", "rate", "limit", "is", "low", "." ]
4b0461b8c676bb3a11d3dc882d2bc3b47101f9bd
https://github.com/camshaft/component-github-content-api/blob/4b0461b8c676bb3a11d3dc882d2bc3b47101f9bd/lib/index.js#L144-L149
55,221
camshaft/component-github-content-api
lib/index.js
errorBadCredentials
function errorBadCredentials(res) { var err = new Error('Invalid credentials'); err.res = res; err.remote = 'github-content-api'; throw err; }
javascript
function errorBadCredentials(res) { var err = new Error('Invalid credentials'); err.res = res; err.remote = 'github-content-api'; throw err; }
[ "function", "errorBadCredentials", "(", "res", ")", "{", "var", "err", "=", "new", "Error", "(", "'Invalid credentials'", ")", ";", "err", ".", "res", "=", "res", ";", "err", ".", "remote", "=", "'github-content-api'", ";", "throw", "err", ";", "}" ]
Better error message when credentials are not supplied. @param {Object} response @api private
[ "Better", "error", "message", "when", "credentials", "are", "not", "supplied", "." ]
4b0461b8c676bb3a11d3dc882d2bc3b47101f9bd
https://github.com/camshaft/component-github-content-api/blob/4b0461b8c676bb3a11d3dc882d2bc3b47101f9bd/lib/index.js#L158-L163
55,222
xpepermint/config-keys
lib/index.js
function(what) { var mainData = what; var localData = {}; if (typeof what == 'string') { // main var mainFile = path.resolve(process.cwd(), what); delete require.cache[mainFile]; mainData = require(mainFile); // local var localFile = mainFile.substr(0, mainFile.lastIndexOf('.'))+'.local'+path.extname(mainFile); if (fs.existsSync(localFile)) { delete require.cache[localFile]; localData = require(localFile); } } // main and local merged return _.merge({}, _.merge({}, mainData.default, mainData[this.env]), _.merge({}, localData.default, localData[this.env]) ); }
javascript
function(what) { var mainData = what; var localData = {}; if (typeof what == 'string') { // main var mainFile = path.resolve(process.cwd(), what); delete require.cache[mainFile]; mainData = require(mainFile); // local var localFile = mainFile.substr(0, mainFile.lastIndexOf('.'))+'.local'+path.extname(mainFile); if (fs.existsSync(localFile)) { delete require.cache[localFile]; localData = require(localFile); } } // main and local merged return _.merge({}, _.merge({}, mainData.default, mainData[this.env]), _.merge({}, localData.default, localData[this.env]) ); }
[ "function", "(", "what", ")", "{", "var", "mainData", "=", "what", ";", "var", "localData", "=", "{", "}", ";", "if", "(", "typeof", "what", "==", "'string'", ")", "{", "// main", "var", "mainFile", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "what", ")", ";", "delete", "require", ".", "cache", "[", "mainFile", "]", ";", "mainData", "=", "require", "(", "mainFile", ")", ";", "// local", "var", "localFile", "=", "mainFile", ".", "substr", "(", "0", ",", "mainFile", ".", "lastIndexOf", "(", "'.'", ")", ")", "+", "'.local'", "+", "path", ".", "extname", "(", "mainFile", ")", ";", "if", "(", "fs", ".", "existsSync", "(", "localFile", ")", ")", "{", "delete", "require", ".", "cache", "[", "localFile", "]", ";", "localData", "=", "require", "(", "localFile", ")", ";", "}", "}", "// main and local merged", "return", "_", ".", "merge", "(", "{", "}", ",", "_", ".", "merge", "(", "{", "}", ",", "mainData", ".", "default", ",", "mainData", "[", "this", ".", "env", "]", ")", ",", "_", ".", "merge", "(", "{", "}", ",", "localData", ".", "default", ",", "localData", "[", "this", ".", "env", "]", ")", ")", ";", "}" ]
Reads the `what` parameter and returns it's content. @param {object|string} what @return {object}
[ "Reads", "the", "what", "parameter", "and", "returns", "it", "s", "content", "." ]
8dfcfa7cd3af039b6f80e8c0f58346018b5925b4
https://github.com/xpepermint/config-keys/blob/8dfcfa7cd3af039b6f80e8c0f58346018b5925b4/lib/index.js#L57-L77
55,223
sinai-doron/Cynwrig
cynwrig.js
addProperty
function addProperty(prop, func){ Object.defineProperty(String.prototype, prop, { enumerable: true, configurable: false, get: func }); }
javascript
function addProperty(prop, func){ Object.defineProperty(String.prototype, prop, { enumerable: true, configurable: false, get: func }); }
[ "function", "addProperty", "(", "prop", ",", "func", ")", "{", "Object", ".", "defineProperty", "(", "String", ".", "prototype", ",", "prop", ",", "{", "enumerable", ":", "true", ",", "configurable", ":", "false", ",", "get", ":", "func", "}", ")", ";", "}" ]
add the property to be used with the String object
[ "add", "the", "property", "to", "be", "used", "with", "the", "String", "object" ]
e8a930745e7626fdcb10f4ae4b8df32a2ed3d6dd
https://github.com/sinai-doron/Cynwrig/blob/e8a930745e7626fdcb10f4ae4b8df32a2ed3d6dd/cynwrig.js#L72-L78
55,224
SakartveloSoft/jade-dynamic-includes
lib/templates-loader.js
function() { return function (req, res, next) { if (!req.locals) { req.locals = {}; } var requestTemplates = getTemplates(res); req.locals.templates = requestTemplates; req.locals.knownTemplates = knownTemplates; if (!res.locals) { res.locals = {}; } res.locals.templates = requestTemplates; res.locals.knownTemplates = knownTemplates; res.locals.renderTemplate = invokeRenderTemplate.bind(null, res.locals); return next(); }; }
javascript
function() { return function (req, res, next) { if (!req.locals) { req.locals = {}; } var requestTemplates = getTemplates(res); req.locals.templates = requestTemplates; req.locals.knownTemplates = knownTemplates; if (!res.locals) { res.locals = {}; } res.locals.templates = requestTemplates; res.locals.knownTemplates = knownTemplates; res.locals.renderTemplate = invokeRenderTemplate.bind(null, res.locals); return next(); }; }
[ "function", "(", ")", "{", "return", "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "!", "req", ".", "locals", ")", "{", "req", ".", "locals", "=", "{", "}", ";", "}", "var", "requestTemplates", "=", "getTemplates", "(", "res", ")", ";", "req", ".", "locals", ".", "templates", "=", "requestTemplates", ";", "req", ".", "locals", ".", "knownTemplates", "=", "knownTemplates", ";", "if", "(", "!", "res", ".", "locals", ")", "{", "res", ".", "locals", "=", "{", "}", ";", "}", "res", ".", "locals", ".", "templates", "=", "requestTemplates", ";", "res", ".", "locals", ".", "knownTemplates", "=", "knownTemplates", ";", "res", ".", "locals", ".", "renderTemplate", "=", "invokeRenderTemplate", ".", "bind", "(", "null", ",", "res", ".", "locals", ")", ";", "return", "next", "(", ")", ";", "}", ";", "}" ]
Attaches the 'templates' property to 'locals' pf request and response objects. if no 'locals' found, it is created on demand. @param req {IncomingMessage} @param res {ServerResponse} @param next {Function} @returns {function} configured middleware function @api public
[ "Attaches", "the", "templates", "property", "to", "locals", "pf", "request", "and", "response", "objects", ".", "if", "no", "locals", "found", "it", "is", "created", "on", "demand", "." ]
139f904e879b78834b4edf4ea9899b341dcf790e
https://github.com/SakartveloSoft/jade-dynamic-includes/blob/139f904e879b78834b4edf4ea9899b341dcf790e/lib/templates-loader.js#L95-L113
55,225
mayanklahiri/node-runtype
lib/loadIntoLibrary.js
loadIntoLibrary
function loadIntoLibrary(schemas) { assert(_.isObject(schemas)); _.extend(library, schemas); }
javascript
function loadIntoLibrary(schemas) { assert(_.isObject(schemas)); _.extend(library, schemas); }
[ "function", "loadIntoLibrary", "(", "schemas", ")", "{", "assert", "(", "_", ".", "isObject", "(", "schemas", ")", ")", ";", "_", ".", "extend", "(", "library", ",", "schemas", ")", ";", "}" ]
Load an map of type names to type definitions into the global type library. @memberof runtype @static @param {object} schemas Map of type names to schemas.
[ "Load", "an", "map", "of", "type", "names", "to", "type", "definitions", "into", "the", "global", "type", "library", "." ]
efcf457ae797535b0e6e98bbeac461e66327c88e
https://github.com/mayanklahiri/node-runtype/blob/efcf457ae797535b0e6e98bbeac461e66327c88e/lib/loadIntoLibrary.js#L14-L17
55,226
tanepiper/nell
lib/generate.js
function(site_path, arg, cmd, done) { var start = Date.now(); var nell_site = { site_path: site_path }; async.series([ function(callback) { nell_site.config_path = path.join(site_path, 'nell.json'); fs.exists(nell_site.config_path, function(exists) { if (!exists) { return callback(new Error(__('Unable to load nell.json config file'))); } callback(); }); }, function(callback) { nell_site.config = require(nell_site.config_path); nell_site.output_path = (nell_site.config.output && nell_site.config.output.path) ? path.join(nell_site.site_path, nell_site.config.output.path) : path.join(nell_site.site_path, 'output'); async.forEach(Object.keys(nell_site.config), function(key, key_done) { nell_site[key] = nell_site.config[key] || {}; key_done(); }, callback); }, function(callback) { loadSwig(nell_site, callback); }, function(callback) { loadItems(nell_site, 'post', callback); }, function(callback) { loadItems(nell_site, 'page', callback); }, function(callback) { if (nell_site.config.output && nell_site.config.output.delete) { fs.unlink(nell_site.output_path, callback); } else { callback(); } }, function(callback) { outputItems(nell_site, 'post', callback); }, function(callback) { outputItems(nell_site, 'page', callback); }, function(callback) { outputIndex(nell_site, callback); }, function(callback) { moveStatic(nell_site, callback); } ], function(err) { var end = Date.now(); if (err) { return done(err); } done(null, __('Site "%s" generated in %ds', nell_site.site.title, (end - start) / 1000)); }); }
javascript
function(site_path, arg, cmd, done) { var start = Date.now(); var nell_site = { site_path: site_path }; async.series([ function(callback) { nell_site.config_path = path.join(site_path, 'nell.json'); fs.exists(nell_site.config_path, function(exists) { if (!exists) { return callback(new Error(__('Unable to load nell.json config file'))); } callback(); }); }, function(callback) { nell_site.config = require(nell_site.config_path); nell_site.output_path = (nell_site.config.output && nell_site.config.output.path) ? path.join(nell_site.site_path, nell_site.config.output.path) : path.join(nell_site.site_path, 'output'); async.forEach(Object.keys(nell_site.config), function(key, key_done) { nell_site[key] = nell_site.config[key] || {}; key_done(); }, callback); }, function(callback) { loadSwig(nell_site, callback); }, function(callback) { loadItems(nell_site, 'post', callback); }, function(callback) { loadItems(nell_site, 'page', callback); }, function(callback) { if (nell_site.config.output && nell_site.config.output.delete) { fs.unlink(nell_site.output_path, callback); } else { callback(); } }, function(callback) { outputItems(nell_site, 'post', callback); }, function(callback) { outputItems(nell_site, 'page', callback); }, function(callback) { outputIndex(nell_site, callback); }, function(callback) { moveStatic(nell_site, callback); } ], function(err) { var end = Date.now(); if (err) { return done(err); } done(null, __('Site "%s" generated in %ds', nell_site.site.title, (end - start) / 1000)); }); }
[ "function", "(", "site_path", ",", "arg", ",", "cmd", ",", "done", ")", "{", "var", "start", "=", "Date", ".", "now", "(", ")", ";", "var", "nell_site", "=", "{", "site_path", ":", "site_path", "}", ";", "async", ".", "series", "(", "[", "function", "(", "callback", ")", "{", "nell_site", ".", "config_path", "=", "path", ".", "join", "(", "site_path", ",", "'nell.json'", ")", ";", "fs", ".", "exists", "(", "nell_site", ".", "config_path", ",", "function", "(", "exists", ")", "{", "if", "(", "!", "exists", ")", "{", "return", "callback", "(", "new", "Error", "(", "__", "(", "'Unable to load nell.json config file'", ")", ")", ")", ";", "}", "callback", "(", ")", ";", "}", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "nell_site", ".", "config", "=", "require", "(", "nell_site", ".", "config_path", ")", ";", "nell_site", ".", "output_path", "=", "(", "nell_site", ".", "config", ".", "output", "&&", "nell_site", ".", "config", ".", "output", ".", "path", ")", "?", "path", ".", "join", "(", "nell_site", ".", "site_path", ",", "nell_site", ".", "config", ".", "output", ".", "path", ")", ":", "path", ".", "join", "(", "nell_site", ".", "site_path", ",", "'output'", ")", ";", "async", ".", "forEach", "(", "Object", ".", "keys", "(", "nell_site", ".", "config", ")", ",", "function", "(", "key", ",", "key_done", ")", "{", "nell_site", "[", "key", "]", "=", "nell_site", ".", "config", "[", "key", "]", "||", "{", "}", ";", "key_done", "(", ")", ";", "}", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "loadSwig", "(", "nell_site", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "loadItems", "(", "nell_site", ",", "'post'", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "loadItems", "(", "nell_site", ",", "'page'", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "if", "(", "nell_site", ".", "config", ".", "output", "&&", "nell_site", ".", "config", ".", "output", ".", "delete", ")", "{", "fs", ".", "unlink", "(", "nell_site", ".", "output_path", ",", "callback", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}", ",", "function", "(", "callback", ")", "{", "outputItems", "(", "nell_site", ",", "'post'", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "outputItems", "(", "nell_site", ",", "'page'", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "outputIndex", "(", "nell_site", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "moveStatic", "(", "nell_site", ",", "callback", ")", ";", "}", "]", ",", "function", "(", "err", ")", "{", "var", "end", "=", "Date", ".", "now", "(", ")", ";", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", ";", "}", "done", "(", "null", ",", "__", "(", "'Site \"%s\" generated in %ds'", ",", "nell_site", ".", "site", ".", "title", ",", "(", "end", "-", "start", ")", "/", "1000", ")", ")", ";", "}", ")", ";", "}" ]
This function allows us to generate the complete site output. It first needs to read all the source data, this way we have all the available post and page data used to generate our page content, and also make available to other sections like sidebars
[ "This", "function", "allows", "us", "to", "generate", "the", "complete", "site", "output", ".", "It", "first", "needs", "to", "read", "all", "the", "source", "data", "this", "way", "we", "have", "all", "the", "available", "post", "and", "page", "data", "used", "to", "generate", "our", "page", "content", "and", "also", "make", "available", "to", "other", "sections", "like", "sidebars" ]
ecceaf63e8d685e08081e2d5f5fb85e71b17a037
https://github.com/tanepiper/nell/blob/ecceaf63e8d685e08081e2d5f5fb85e71b17a037/lib/generate.js#L32-L91
55,227
Industryswarm/isnode-mod-data
lib/mongodb/bson/lib/bson/decimal128.js
function(value) { var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); var _rem = Long.fromNumber(0); var i = 0; if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { return { quotient: value, rem: _rem }; } for (i = 0; i <= 3; i++) { // Adjust remainder to match value of next dividend _rem = _rem.shiftLeft(32); // Add the divided to _rem _rem = _rem.add(new Long(value.parts[i], 0)); value.parts[i] = _rem.div(DIVISOR).low_; _rem = _rem.modulo(DIVISOR); } return { quotient: value, rem: _rem }; }
javascript
function(value) { var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); var _rem = Long.fromNumber(0); var i = 0; if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { return { quotient: value, rem: _rem }; } for (i = 0; i <= 3; i++) { // Adjust remainder to match value of next dividend _rem = _rem.shiftLeft(32); // Add the divided to _rem _rem = _rem.add(new Long(value.parts[i], 0)); value.parts[i] = _rem.div(DIVISOR).low_; _rem = _rem.modulo(DIVISOR); } return { quotient: value, rem: _rem }; }
[ "function", "(", "value", ")", "{", "var", "DIVISOR", "=", "Long", ".", "fromNumber", "(", "1000", "*", "1000", "*", "1000", ")", ";", "var", "_rem", "=", "Long", ".", "fromNumber", "(", "0", ")", ";", "var", "i", "=", "0", ";", "if", "(", "!", "value", ".", "parts", "[", "0", "]", "&&", "!", "value", ".", "parts", "[", "1", "]", "&&", "!", "value", ".", "parts", "[", "2", "]", "&&", "!", "value", ".", "parts", "[", "3", "]", ")", "{", "return", "{", "quotient", ":", "value", ",", "rem", ":", "_rem", "}", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<=", "3", ";", "i", "++", ")", "{", "// Adjust remainder to match value of next dividend", "_rem", "=", "_rem", ".", "shiftLeft", "(", "32", ")", ";", "// Add the divided to _rem", "_rem", "=", "_rem", ".", "add", "(", "new", "Long", "(", "value", ".", "parts", "[", "i", "]", ",", "0", ")", ")", ";", "value", ".", "parts", "[", "i", "]", "=", "_rem", ".", "div", "(", "DIVISOR", ")", ".", "low_", ";", "_rem", "=", "_rem", ".", "modulo", "(", "DIVISOR", ")", ";", "}", "return", "{", "quotient", ":", "value", ",", "rem", ":", "_rem", "}", ";", "}" ]
Divide two uint128 values
[ "Divide", "two", "uint128", "values" ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/bson/lib/bson/decimal128.js#L79-L98
55,228
Industryswarm/isnode-mod-data
lib/mongodb/bson/lib/bson/decimal128.js
function(left, right) { if (!left && !right) { return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; } var leftHigh = left.shiftRightUnsigned(32); var leftLow = new Long(left.getLowBits(), 0); var rightHigh = right.shiftRightUnsigned(32); var rightLow = new Long(right.getLowBits(), 0); var productHigh = leftHigh.multiply(rightHigh); var productMid = leftHigh.multiply(rightLow); var productMid2 = leftLow.multiply(rightHigh); var productLow = leftLow.multiply(rightLow); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productMid = new Long(productMid.getLowBits(), 0) .add(productMid2) .add(productLow.shiftRightUnsigned(32)); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); // Return the 128 bit result return { high: productHigh, low: productLow }; }
javascript
function(left, right) { if (!left && !right) { return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; } var leftHigh = left.shiftRightUnsigned(32); var leftLow = new Long(left.getLowBits(), 0); var rightHigh = right.shiftRightUnsigned(32); var rightLow = new Long(right.getLowBits(), 0); var productHigh = leftHigh.multiply(rightHigh); var productMid = leftHigh.multiply(rightLow); var productMid2 = leftLow.multiply(rightHigh); var productLow = leftLow.multiply(rightLow); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productMid = new Long(productMid.getLowBits(), 0) .add(productMid2) .add(productLow.shiftRightUnsigned(32)); productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); // Return the 128 bit result return { high: productHigh, low: productLow }; }
[ "function", "(", "left", ",", "right", ")", "{", "if", "(", "!", "left", "&&", "!", "right", ")", "{", "return", "{", "high", ":", "Long", ".", "fromNumber", "(", "0", ")", ",", "low", ":", "Long", ".", "fromNumber", "(", "0", ")", "}", ";", "}", "var", "leftHigh", "=", "left", ".", "shiftRightUnsigned", "(", "32", ")", ";", "var", "leftLow", "=", "new", "Long", "(", "left", ".", "getLowBits", "(", ")", ",", "0", ")", ";", "var", "rightHigh", "=", "right", ".", "shiftRightUnsigned", "(", "32", ")", ";", "var", "rightLow", "=", "new", "Long", "(", "right", ".", "getLowBits", "(", ")", ",", "0", ")", ";", "var", "productHigh", "=", "leftHigh", ".", "multiply", "(", "rightHigh", ")", ";", "var", "productMid", "=", "leftHigh", ".", "multiply", "(", "rightLow", ")", ";", "var", "productMid2", "=", "leftLow", ".", "multiply", "(", "rightHigh", ")", ";", "var", "productLow", "=", "leftLow", ".", "multiply", "(", "rightLow", ")", ";", "productHigh", "=", "productHigh", ".", "add", "(", "productMid", ".", "shiftRightUnsigned", "(", "32", ")", ")", ";", "productMid", "=", "new", "Long", "(", "productMid", ".", "getLowBits", "(", ")", ",", "0", ")", ".", "add", "(", "productMid2", ")", ".", "add", "(", "productLow", ".", "shiftRightUnsigned", "(", "32", ")", ")", ";", "productHigh", "=", "productHigh", ".", "add", "(", "productMid", ".", "shiftRightUnsigned", "(", "32", ")", ")", ";", "productLow", "=", "productMid", ".", "shiftLeft", "(", "32", ")", ".", "add", "(", "new", "Long", "(", "productLow", ".", "getLowBits", "(", ")", ",", "0", ")", ")", ";", "// Return the 128 bit result", "return", "{", "high", ":", "productHigh", ",", "low", ":", "productLow", "}", ";", "}" ]
Multiply two Long values and return the 128 bit value
[ "Multiply", "two", "Long", "values", "and", "return", "the", "128", "bit", "value" ]
5adc639b88a0d72cbeef23a6b5df7f4540745089
https://github.com/Industryswarm/isnode-mod-data/blob/5adc639b88a0d72cbeef23a6b5df7f4540745089/lib/mongodb/bson/lib/bson/decimal128.js#L101-L126
55,229
chip-js/chip-utils
class.js
addStatics
function addStatics(statics, Subclass) { // static method inheritance (including `extend`) Object.keys(statics).forEach(function(key) { var descriptor = Object.getOwnPropertyDescriptor(statics, key); if (!descriptor.configurable) return; Object.defineProperty(Subclass, key, descriptor); }); }
javascript
function addStatics(statics, Subclass) { // static method inheritance (including `extend`) Object.keys(statics).forEach(function(key) { var descriptor = Object.getOwnPropertyDescriptor(statics, key); if (!descriptor.configurable) return; Object.defineProperty(Subclass, key, descriptor); }); }
[ "function", "addStatics", "(", "statics", ",", "Subclass", ")", "{", "// static method inheritance (including `extend`)", "Object", ".", "keys", "(", "statics", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "var", "descriptor", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "statics", ",", "key", ")", ";", "if", "(", "!", "descriptor", ".", "configurable", ")", "return", ";", "Object", ".", "defineProperty", "(", "Subclass", ",", "key", ",", "descriptor", ")", ";", "}", ")", ";", "}" ]
Copies static methods over for static inheritance
[ "Copies", "static", "methods", "over", "for", "static", "inheritance" ]
c8c2b233fbfd20e68fc84e5ea3d6a17de33a04ed
https://github.com/chip-js/chip-utils/blob/c8c2b233fbfd20e68fc84e5ea3d6a17de33a04ed/class.js#L101-L110
55,230
alessioalex/npm-dep-chain
examples/ls-tree-pkg-json.js
getTree
function getTree(root, deps) { var tree; tree = {}; populateItem(tree, root, deps); return tree; }
javascript
function getTree(root, deps) { var tree; tree = {}; populateItem(tree, root, deps); return tree; }
[ "function", "getTree", "(", "root", ",", "deps", ")", "{", "var", "tree", ";", "tree", "=", "{", "}", ";", "populateItem", "(", "tree", ",", "root", ",", "deps", ")", ";", "return", "tree", ";", "}" ]
Returns the dependency tree for a NPM module
[ "Returns", "the", "dependency", "tree", "for", "a", "NPM", "module" ]
2ec7c18dc48fbdf1a997760321c75e984f73810c
https://github.com/alessioalex/npm-dep-chain/blob/2ec7c18dc48fbdf1a997760321c75e984f73810c/examples/ls-tree-pkg-json.js#L52-L60
55,231
ruysu/gulp-core
lib/optimize.js
function(options) { var stream = through.obj(function(file, enc, cb) { var out = options.out; // Convert to the main file to a vinyl file options.out = function(text) { cb(null, new gutil.File({ path: out, contents: new Buffer(text) })); }; // Optimize the main file requirejs.optimize(options, null, function(err) { stream.emit('error', new gutil.PluginError('gulp-rjs', err.message)); }); }); return stream; }
javascript
function(options) { var stream = through.obj(function(file, enc, cb) { var out = options.out; // Convert to the main file to a vinyl file options.out = function(text) { cb(null, new gutil.File({ path: out, contents: new Buffer(text) })); }; // Optimize the main file requirejs.optimize(options, null, function(err) { stream.emit('error', new gutil.PluginError('gulp-rjs', err.message)); }); }); return stream; }
[ "function", "(", "options", ")", "{", "var", "stream", "=", "through", ".", "obj", "(", "function", "(", "file", ",", "enc", ",", "cb", ")", "{", "var", "out", "=", "options", ".", "out", ";", "// Convert to the main file to a vinyl file", "options", ".", "out", "=", "function", "(", "text", ")", "{", "cb", "(", "null", ",", "new", "gutil", ".", "File", "(", "{", "path", ":", "out", ",", "contents", ":", "new", "Buffer", "(", "text", ")", "}", ")", ")", ";", "}", ";", "// Optimize the main file", "requirejs", ".", "optimize", "(", "options", ",", "null", ",", "function", "(", "err", ")", "{", "stream", ".", "emit", "(", "'error'", ",", "new", "gutil", ".", "PluginError", "(", "'gulp-rjs'", ",", "err", ".", "message", ")", ")", ";", "}", ")", ";", "}", ")", ";", "return", "stream", ";", "}" ]
Optimize gulp task @param {object} options The options object passed to rjs command
[ "Optimize", "gulp", "task" ]
2abb2e7b60dc5c30f2610f982672e112b5e1e436
https://github.com/ruysu/gulp-core/blob/2abb2e7b60dc5c30f2610f982672e112b5e1e436/lib/optimize.js#L13-L32
55,232
MiguelCastillo/log2console
src/index.js
log
function log(data) { if (type.isError(data)) { if (!data.handled) { _setHandled(data); _console.error(data); } } else { _console.log(_transform(data)); } return data; }
javascript
function log(data) { if (type.isError(data)) { if (!data.handled) { _setHandled(data); _console.error(data); } } else { _console.log(_transform(data)); } return data; }
[ "function", "log", "(", "data", ")", "{", "if", "(", "type", ".", "isError", "(", "data", ")", ")", "{", "if", "(", "!", "data", ".", "handled", ")", "{", "_setHandled", "(", "data", ")", ";", "_console", ".", "error", "(", "data", ")", ";", "}", "}", "else", "{", "_console", ".", "log", "(", "_transform", "(", "data", ")", ")", ";", "}", "return", "data", ";", "}" ]
Logs error to the console and makes sure it is only logged once.
[ "Logs", "error", "to", "the", "console", "and", "makes", "sure", "it", "is", "only", "logged", "once", "." ]
ca34d19509f82ec59101b45cbbf7729ba2b64274
https://github.com/MiguelCastillo/log2console/blob/ca34d19509f82ec59101b45cbbf7729ba2b64274/src/index.js#L38-L49
55,233
bug-buster/sesame-lib
lib/client.js
function () { // don't do it twice if (!tcpConnections[msg.tcpId]) return; exports.verbose(new Date(), 'Connection closed by remote peer for: ' + addressForLog(msg.address, msg.port)); newCon.removeAllListeners(); delete tcpConnections[msg.tcpId]; send(channel, new MSG.Close(msg.tcpId)); }
javascript
function () { // don't do it twice if (!tcpConnections[msg.tcpId]) return; exports.verbose(new Date(), 'Connection closed by remote peer for: ' + addressForLog(msg.address, msg.port)); newCon.removeAllListeners(); delete tcpConnections[msg.tcpId]; send(channel, new MSG.Close(msg.tcpId)); }
[ "function", "(", ")", "{", "// don't do it twice", "if", "(", "!", "tcpConnections", "[", "msg", ".", "tcpId", "]", ")", "return", ";", "exports", ".", "verbose", "(", "new", "Date", "(", ")", ",", "'Connection closed by remote peer for: '", "+", "addressForLog", "(", "msg", ".", "address", ",", "msg", ".", "port", ")", ")", ";", "newCon", ".", "removeAllListeners", "(", ")", ";", "delete", "tcpConnections", "[", "msg", ".", "tcpId", "]", ";", "send", "(", "channel", ",", "new", "MSG", ".", "Close", "(", "msg", ".", "tcpId", ")", ")", ";", "}" ]
add connected listeners for clean up
[ "add", "connected", "listeners", "for", "clean", "up" ]
23631f39d4dee9d742ceaf7528b67aa5204da2dc
https://github.com/bug-buster/sesame-lib/blob/23631f39d4dee9d742ceaf7528b67aa5204da2dc/lib/client.js#L85-L94
55,234
bug-buster/sesame-lib
lib/client.js
function (error) { send(channel, new MSG.OpenResult(msg.tcpId, Protocol.toOpenResultStatus(error), null, null)); }
javascript
function (error) { send(channel, new MSG.OpenResult(msg.tcpId, Protocol.toOpenResultStatus(error), null, null)); }
[ "function", "(", "error", ")", "{", "send", "(", "channel", ",", "new", "MSG", ".", "OpenResult", "(", "msg", ".", "tcpId", ",", "Protocol", ".", "toOpenResultStatus", "(", "error", ")", ",", "null", ",", "null", ")", ")", ";", "}" ]
Special handling case for erroneous connection
[ "Special", "handling", "case", "for", "erroneous", "connection" ]
23631f39d4dee9d742ceaf7528b67aa5204da2dc
https://github.com/bug-buster/sesame-lib/blob/23631f39d4dee9d742ceaf7528b67aa5204da2dc/lib/client.js#L107-L109
55,235
leocornus/leocornus-visualdata
src/zoomable-circles-demo.js
loadData
function loadData(dataUrl, jsonEditor) { // jQuery getJSON will read the file from a Web resources. $.getJSON(dataUrl, function(data) { //$.getJSON('data/simple-zoomable-circle.json', function(data) { // set data to JSON editor. jsonEditor.set(data); // update the JSON source code $('#jsonstring').html(JSON.stringify(data, null, 2)); // remove the existing one. $('#svgpreview').empty(); // build the circles... var options = { "margin":10, "diameter":500 }; $("#svgpreview").zoomableCircles(options, data); //console.log(JSON.stringify(data)); }); }
javascript
function loadData(dataUrl, jsonEditor) { // jQuery getJSON will read the file from a Web resources. $.getJSON(dataUrl, function(data) { //$.getJSON('data/simple-zoomable-circle.json', function(data) { // set data to JSON editor. jsonEditor.set(data); // update the JSON source code $('#jsonstring').html(JSON.stringify(data, null, 2)); // remove the existing one. $('#svgpreview').empty(); // build the circles... var options = { "margin":10, "diameter":500 }; $("#svgpreview").zoomableCircles(options, data); //console.log(JSON.stringify(data)); }); }
[ "function", "loadData", "(", "dataUrl", ",", "jsonEditor", ")", "{", "// jQuery getJSON will read the file from a Web resources.", "$", ".", "getJSON", "(", "dataUrl", ",", "function", "(", "data", ")", "{", "//$.getJSON('data/simple-zoomable-circle.json', function(data) {", "// set data to JSON editor.", "jsonEditor", ".", "set", "(", "data", ")", ";", "// update the JSON source code", "$", "(", "'#jsonstring'", ")", ".", "html", "(", "JSON", ".", "stringify", "(", "data", ",", "null", ",", "2", ")", ")", ";", "// remove the existing one.", "$", "(", "'#svgpreview'", ")", ".", "empty", "(", ")", ";", "// build the circles...", "var", "options", "=", "{", "\"margin\"", ":", "10", ",", "\"diameter\"", ":", "500", "}", ";", "$", "(", "\"#svgpreview\"", ")", ".", "zoomableCircles", "(", "options", ",", "data", ")", ";", "//console.log(JSON.stringify(data));", "}", ")", ";", "}" ]
load data from the given url, set it to JSON editor and load the zoomable circles.
[ "load", "data", "from", "the", "given", "url", "set", "it", "to", "JSON", "editor", "and", "load", "the", "zoomable", "circles", "." ]
9d9714ca11c126f0250e650f3c1c4086709af3ab
https://github.com/leocornus/leocornus-visualdata/blob/9d9714ca11c126f0250e650f3c1c4086709af3ab/src/zoomable-circles-demo.js#L156-L175
55,236
HyeonuPark/babel-preset-escompile
generate.js
getVersion
function getVersion (plugin) { return new Promise(function (resolve, reject) { npm.commands.view([plugin, 'version'], function (err, data) { if (err) return reject(err) resolve(Object.keys(data)[0]) }) }) }
javascript
function getVersion (plugin) { return new Promise(function (resolve, reject) { npm.commands.view([plugin, 'version'], function (err, data) { if (err) return reject(err) resolve(Object.keys(data)[0]) }) }) }
[ "function", "getVersion", "(", "plugin", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "npm", ".", "commands", ".", "view", "(", "[", "plugin", ",", "'version'", "]", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", "resolve", "(", "Object", ".", "keys", "(", "data", ")", "[", "0", "]", ")", "}", ")", "}", ")", "}" ]
return last published version of this package
[ "return", "last", "published", "version", "of", "this", "package" ]
15f86a42e15efeee34e6a3dbd099acadf62ca4ad
https://github.com/HyeonuPark/babel-preset-escompile/blob/15f86a42e15efeee34e6a3dbd099acadf62ca4ad/generate.js#L97-L104
55,237
apentle/redux-actions-hub
index.js
defineActionProp
function defineActionProp(type) { ActionsHub[type] = function() { var creators = _actions[type]; if (creators.length === 1) { // Simply forward to original action creator return creators[0].apply(null, arguments); } else if (creators.length > 1) { // ThunkAction var args = arguments; return function(dispatch) { // dispatch all action creator for (var i = 0, cLength = creators.length; i < cLength; i++) { dispatch(creators[i].apply(null, args)); } }; } } }
javascript
function defineActionProp(type) { ActionsHub[type] = function() { var creators = _actions[type]; if (creators.length === 1) { // Simply forward to original action creator return creators[0].apply(null, arguments); } else if (creators.length > 1) { // ThunkAction var args = arguments; return function(dispatch) { // dispatch all action creator for (var i = 0, cLength = creators.length; i < cLength; i++) { dispatch(creators[i].apply(null, args)); } }; } } }
[ "function", "defineActionProp", "(", "type", ")", "{", "ActionsHub", "[", "type", "]", "=", "function", "(", ")", "{", "var", "creators", "=", "_actions", "[", "type", "]", ";", "if", "(", "creators", ".", "length", "===", "1", ")", "{", "// Simply forward to original action creator", "return", "creators", "[", "0", "]", ".", "apply", "(", "null", ",", "arguments", ")", ";", "}", "else", "if", "(", "creators", ".", "length", ">", "1", ")", "{", "// ThunkAction", "var", "args", "=", "arguments", ";", "return", "function", "(", "dispatch", ")", "{", "// dispatch all action creator", "for", "(", "var", "i", "=", "0", ",", "cLength", "=", "creators", ".", "length", ";", "i", "<", "cLength", ";", "i", "++", ")", "{", "dispatch", "(", "creators", "[", "i", "]", ".", "apply", "(", "null", ",", "args", ")", ")", ";", "}", "}", ";", "}", "}", "}" ]
defineActionProp - define action property @param {string} type action's type @returns {undefined}
[ "defineActionProp", "-", "define", "action", "property" ]
87634b7856d90607ff86e47c1d03f7c4747796ba
https://github.com/apentle/redux-actions-hub/blob/87634b7856d90607ff86e47c1d03f7c4747796ba/index.js#L11-L28
55,238
Concurix/module-stats
lib/wrapper.js
wrapFunctions
function wrapFunctions(name, obj, protoLevel, hooks, state, rules){ if (!(obj && (util.isObject(obj) || util.isFunction(obj)))){ return; } if (obj.__concurix_blacklisted || (obj.constructor && obj.constructor.__concurix_blacklisted)) { return; } if (obj.__concurix_wrapped_obj__ || !Object.isExtensible(obj)){ return; } tagObject(obj, '__concurix_wrapped_obj__'); protoLevel = protoLevel ? protoLevel : 0; util.iterateOwnProperties(obj, function(key){ var desc = Object.getOwnPropertyDescriptor(obj, key); // We got a property that wasn't a property. if (desc == null) { return; } // ignore properties that cannot be set if (!desc.configurable || !desc.writable || desc.set){ return; } // ignore blacklisted properties if (desc.value && desc.value.__concurix_blacklisted) { return; } // if we are supposed to skip a function, blacklist it so we don't wrap it. if( !rules.wrapKey(key) ){ blacklist(obj[key]); return; } if ( util.isFunction(desc.value) && !wrap.isWrapper(obj[key]) && rules.wrapKey(key) ) { //console.log('wrapping ', key, ' for ', name, state.modInfo.top); obj[key] = wrap(obj[key]) .before(hooks.beforeHook) .after(hooks.afterHook) .module(name) .state(state) .nameIfNeeded(key) .getProxy(); } else if (util.isObject(desc.value) && !wrap.isWrapper(obj[key]) && rules.wrapKey(key)) { // to save cycles do not go up through the prototype chain for object-type properties wrapFunctions(name, desc.value, 0, hooks, state, rules); } }); // protoLevel is how deep you want to traverse the prototype chain. // protoLevel = -1 - this will go all the way up excluding Object.prototype if (protoLevel != 0){ protoLevel--; var proto = Object.getPrototypeOf(obj); wrapFunctions(name, proto, protoLevel, hooks, state, rules); } }
javascript
function wrapFunctions(name, obj, protoLevel, hooks, state, rules){ if (!(obj && (util.isObject(obj) || util.isFunction(obj)))){ return; } if (obj.__concurix_blacklisted || (obj.constructor && obj.constructor.__concurix_blacklisted)) { return; } if (obj.__concurix_wrapped_obj__ || !Object.isExtensible(obj)){ return; } tagObject(obj, '__concurix_wrapped_obj__'); protoLevel = protoLevel ? protoLevel : 0; util.iterateOwnProperties(obj, function(key){ var desc = Object.getOwnPropertyDescriptor(obj, key); // We got a property that wasn't a property. if (desc == null) { return; } // ignore properties that cannot be set if (!desc.configurable || !desc.writable || desc.set){ return; } // ignore blacklisted properties if (desc.value && desc.value.__concurix_blacklisted) { return; } // if we are supposed to skip a function, blacklist it so we don't wrap it. if( !rules.wrapKey(key) ){ blacklist(obj[key]); return; } if ( util.isFunction(desc.value) && !wrap.isWrapper(obj[key]) && rules.wrapKey(key) ) { //console.log('wrapping ', key, ' for ', name, state.modInfo.top); obj[key] = wrap(obj[key]) .before(hooks.beforeHook) .after(hooks.afterHook) .module(name) .state(state) .nameIfNeeded(key) .getProxy(); } else if (util.isObject(desc.value) && !wrap.isWrapper(obj[key]) && rules.wrapKey(key)) { // to save cycles do not go up through the prototype chain for object-type properties wrapFunctions(name, desc.value, 0, hooks, state, rules); } }); // protoLevel is how deep you want to traverse the prototype chain. // protoLevel = -1 - this will go all the way up excluding Object.prototype if (protoLevel != 0){ protoLevel--; var proto = Object.getPrototypeOf(obj); wrapFunctions(name, proto, protoLevel, hooks, state, rules); } }
[ "function", "wrapFunctions", "(", "name", ",", "obj", ",", "protoLevel", ",", "hooks", ",", "state", ",", "rules", ")", "{", "if", "(", "!", "(", "obj", "&&", "(", "util", ".", "isObject", "(", "obj", ")", "||", "util", ".", "isFunction", "(", "obj", ")", ")", ")", ")", "{", "return", ";", "}", "if", "(", "obj", ".", "__concurix_blacklisted", "||", "(", "obj", ".", "constructor", "&&", "obj", ".", "constructor", ".", "__concurix_blacklisted", ")", ")", "{", "return", ";", "}", "if", "(", "obj", ".", "__concurix_wrapped_obj__", "||", "!", "Object", ".", "isExtensible", "(", "obj", ")", ")", "{", "return", ";", "}", "tagObject", "(", "obj", ",", "'__concurix_wrapped_obj__'", ")", ";", "protoLevel", "=", "protoLevel", "?", "protoLevel", ":", "0", ";", "util", ".", "iterateOwnProperties", "(", "obj", ",", "function", "(", "key", ")", "{", "var", "desc", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "obj", ",", "key", ")", ";", "// We got a property that wasn't a property.", "if", "(", "desc", "==", "null", ")", "{", "return", ";", "}", "// ignore properties that cannot be set", "if", "(", "!", "desc", ".", "configurable", "||", "!", "desc", ".", "writable", "||", "desc", ".", "set", ")", "{", "return", ";", "}", "// ignore blacklisted properties", "if", "(", "desc", ".", "value", "&&", "desc", ".", "value", ".", "__concurix_blacklisted", ")", "{", "return", ";", "}", "// if we are supposed to skip a function, blacklist it so we don't wrap it.", "if", "(", "!", "rules", ".", "wrapKey", "(", "key", ")", ")", "{", "blacklist", "(", "obj", "[", "key", "]", ")", ";", "return", ";", "}", "if", "(", "util", ".", "isFunction", "(", "desc", ".", "value", ")", "&&", "!", "wrap", ".", "isWrapper", "(", "obj", "[", "key", "]", ")", "&&", "rules", ".", "wrapKey", "(", "key", ")", ")", "{", "//console.log('wrapping ', key, ' for ', name, state.modInfo.top);", "obj", "[", "key", "]", "=", "wrap", "(", "obj", "[", "key", "]", ")", ".", "before", "(", "hooks", ".", "beforeHook", ")", ".", "after", "(", "hooks", ".", "afterHook", ")", ".", "module", "(", "name", ")", ".", "state", "(", "state", ")", ".", "nameIfNeeded", "(", "key", ")", ".", "getProxy", "(", ")", ";", "}", "else", "if", "(", "util", ".", "isObject", "(", "desc", ".", "value", ")", "&&", "!", "wrap", ".", "isWrapper", "(", "obj", "[", "key", "]", ")", "&&", "rules", ".", "wrapKey", "(", "key", ")", ")", "{", "// to save cycles do not go up through the prototype chain for object-type properties", "wrapFunctions", "(", "name", ",", "desc", ".", "value", ",", "0", ",", "hooks", ",", "state", ",", "rules", ")", ";", "}", "}", ")", ";", "// protoLevel is how deep you want to traverse the prototype chain.", "// protoLevel = -1 - this will go all the way up excluding Object.prototype", "if", "(", "protoLevel", "!=", "0", ")", "{", "protoLevel", "--", ";", "var", "proto", "=", "Object", ".", "getPrototypeOf", "(", "obj", ")", ";", "wrapFunctions", "(", "name", ",", "proto", ",", "protoLevel", ",", "hooks", ",", "state", ",", "rules", ")", ";", "}", "}" ]
iterate through all configurable properties and hook into each function
[ "iterate", "through", "all", "configurable", "properties", "and", "hook", "into", "each", "function" ]
940c76ca8b44ccd6bb5b34fa1305c52a8157c2cb
https://github.com/Concurix/module-stats/blob/940c76ca8b44ccd6bb5b34fa1305c52a8157c2cb/lib/wrapper.js#L159-L221
55,239
Concurix/module-stats
lib/wrapper.js
wrapArguments
function wrapArguments(trace, clientState, hooks) { //wrap any callbacks found in the arguments var args = trace.args; var handler = clientState.rules.handleArgs(trace.funInfo.name); if (handler) { handler(trace, clientState); } for (var i = args.length - 1; i >= 0; i--) { var a = args[i]; if (util.isFunction(a) && !a.__concurix_blacklisted) { var callbackState = { modInfo: clientState.modInfo, rules: clientState.rules, callbackOf: trace }; if (wrap.isWrapper(args[i])) { args[i].__concurix_proxy_state__ .module((trace.calledBy && trace.calledBy.moduleName) || 'root') .state(callbackState) .nameIfNeeded(trace.funInfo.name + ' callback') .getProxy(); } else { args[i] = wrap(a) .before(hooks.beforeHook) .after(hooks.afterHook) .module((trace.calledBy && trace.calledBy.moduleName) || 'root') .state(callbackState) .nameIfNeeded(trace.funInfo.name + ' callback') .getProxy(); } trace.origFunctionArguments = trace.origFunctionArguments || []; trace.origFunctionArguments.push(a); } } }
javascript
function wrapArguments(trace, clientState, hooks) { //wrap any callbacks found in the arguments var args = trace.args; var handler = clientState.rules.handleArgs(trace.funInfo.name); if (handler) { handler(trace, clientState); } for (var i = args.length - 1; i >= 0; i--) { var a = args[i]; if (util.isFunction(a) && !a.__concurix_blacklisted) { var callbackState = { modInfo: clientState.modInfo, rules: clientState.rules, callbackOf: trace }; if (wrap.isWrapper(args[i])) { args[i].__concurix_proxy_state__ .module((trace.calledBy && trace.calledBy.moduleName) || 'root') .state(callbackState) .nameIfNeeded(trace.funInfo.name + ' callback') .getProxy(); } else { args[i] = wrap(a) .before(hooks.beforeHook) .after(hooks.afterHook) .module((trace.calledBy && trace.calledBy.moduleName) || 'root') .state(callbackState) .nameIfNeeded(trace.funInfo.name + ' callback') .getProxy(); } trace.origFunctionArguments = trace.origFunctionArguments || []; trace.origFunctionArguments.push(a); } } }
[ "function", "wrapArguments", "(", "trace", ",", "clientState", ",", "hooks", ")", "{", "//wrap any callbacks found in the arguments", "var", "args", "=", "trace", ".", "args", ";", "var", "handler", "=", "clientState", ".", "rules", ".", "handleArgs", "(", "trace", ".", "funInfo", ".", "name", ")", ";", "if", "(", "handler", ")", "{", "handler", "(", "trace", ",", "clientState", ")", ";", "}", "for", "(", "var", "i", "=", "args", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "var", "a", "=", "args", "[", "i", "]", ";", "if", "(", "util", ".", "isFunction", "(", "a", ")", "&&", "!", "a", ".", "__concurix_blacklisted", ")", "{", "var", "callbackState", "=", "{", "modInfo", ":", "clientState", ".", "modInfo", ",", "rules", ":", "clientState", ".", "rules", ",", "callbackOf", ":", "trace", "}", ";", "if", "(", "wrap", ".", "isWrapper", "(", "args", "[", "i", "]", ")", ")", "{", "args", "[", "i", "]", ".", "__concurix_proxy_state__", ".", "module", "(", "(", "trace", ".", "calledBy", "&&", "trace", ".", "calledBy", ".", "moduleName", ")", "||", "'root'", ")", ".", "state", "(", "callbackState", ")", ".", "nameIfNeeded", "(", "trace", ".", "funInfo", ".", "name", "+", "' callback'", ")", ".", "getProxy", "(", ")", ";", "}", "else", "{", "args", "[", "i", "]", "=", "wrap", "(", "a", ")", ".", "before", "(", "hooks", ".", "beforeHook", ")", ".", "after", "(", "hooks", ".", "afterHook", ")", ".", "module", "(", "(", "trace", ".", "calledBy", "&&", "trace", ".", "calledBy", ".", "moduleName", ")", "||", "'root'", ")", ".", "state", "(", "callbackState", ")", ".", "nameIfNeeded", "(", "trace", ".", "funInfo", ".", "name", "+", "' callback'", ")", ".", "getProxy", "(", ")", ";", "}", "trace", ".", "origFunctionArguments", "=", "trace", ".", "origFunctionArguments", "||", "[", "]", ";", "trace", ".", "origFunctionArguments", ".", "push", "(", "a", ")", ";", "}", "}", "}" ]
iterate through arguments and wrap functions as callbacks
[ "iterate", "through", "arguments", "and", "wrap", "functions", "as", "callbacks" ]
940c76ca8b44ccd6bb5b34fa1305c52a8157c2cb
https://github.com/Concurix/module-stats/blob/940c76ca8b44ccd6bb5b34fa1305c52a8157c2cb/lib/wrapper.js#L224-L260
55,240
structAnkit/limireq
index.js
next
function next() { var limireq = this; var conn = limireq.connections.shift() if (!conn) return request(conn.options, function(err, res, body) { if (typeof conn.callback === 'function') conn.callback(err, res, body) else limireq.emit('data', err, res, body) // Signal the end of processing if (++limireq.completed === limireq.total) { limireq.active = false limireq.emit('end') } else next.call(limireq) }) }
javascript
function next() { var limireq = this; var conn = limireq.connections.shift() if (!conn) return request(conn.options, function(err, res, body) { if (typeof conn.callback === 'function') conn.callback(err, res, body) else limireq.emit('data', err, res, body) // Signal the end of processing if (++limireq.completed === limireq.total) { limireq.active = false limireq.emit('end') } else next.call(limireq) }) }
[ "function", "next", "(", ")", "{", "var", "limireq", "=", "this", ";", "var", "conn", "=", "limireq", ".", "connections", ".", "shift", "(", ")", "if", "(", "!", "conn", ")", "return", "request", "(", "conn", ".", "options", ",", "function", "(", "err", ",", "res", ",", "body", ")", "{", "if", "(", "typeof", "conn", ".", "callback", "===", "'function'", ")", "conn", ".", "callback", "(", "err", ",", "res", ",", "body", ")", "else", "limireq", ".", "emit", "(", "'data'", ",", "err", ",", "res", ",", "body", ")", "// Signal the end of processing", "if", "(", "++", "limireq", ".", "completed", "===", "limireq", ".", "total", ")", "{", "limireq", ".", "active", "=", "false", "limireq", ".", "emit", "(", "'end'", ")", "}", "else", "next", ".", "call", "(", "limireq", ")", "}", ")", "}" ]
Don't expose this function to the public prototype
[ "Don", "t", "expose", "this", "function", "to", "the", "public", "prototype" ]
d6bb145e9d6974c73efa87ac5c1c4fc20e3acf41
https://github.com/structAnkit/limireq/blob/d6bb145e9d6974c73efa87ac5c1c4fc20e3acf41/index.js#L99-L116
55,241
MarkGriffiths/xo-tidy
src/lib/engine.js
configureESFormatter
function configureESFormatter(options) { const ESFormatConfig = { root: true, allowShebang: true, indent: {value: '\t'}, whiteSpace: { before: { IfStatementConditionalOpening: -1 }, after: { IfStatementConditionalClosing: -1, FunctionReservedWord: 1 } }, lineBreak: {after: {ClassDeclarationClosingBrace: 0}} } if (options.space > 0) { ESFormatConfig.indent.value = ' '.repeat(parseInt(options.space, 10)) } console.debug(stripIndent` ${clr.title}esFormatter Options${clr.title.out}: `) if (console.canWrite(5)) { console.pretty(ESFormatConfig, 2) } return () => esFormatter.rc(ESFormatConfig) }
javascript
function configureESFormatter(options) { const ESFormatConfig = { root: true, allowShebang: true, indent: {value: '\t'}, whiteSpace: { before: { IfStatementConditionalOpening: -1 }, after: { IfStatementConditionalClosing: -1, FunctionReservedWord: 1 } }, lineBreak: {after: {ClassDeclarationClosingBrace: 0}} } if (options.space > 0) { ESFormatConfig.indent.value = ' '.repeat(parseInt(options.space, 10)) } console.debug(stripIndent` ${clr.title}esFormatter Options${clr.title.out}: `) if (console.canWrite(5)) { console.pretty(ESFormatConfig, 2) } return () => esFormatter.rc(ESFormatConfig) }
[ "function", "configureESFormatter", "(", "options", ")", "{", "const", "ESFormatConfig", "=", "{", "root", ":", "true", ",", "allowShebang", ":", "true", ",", "indent", ":", "{", "value", ":", "'\\t'", "}", ",", "whiteSpace", ":", "{", "before", ":", "{", "IfStatementConditionalOpening", ":", "-", "1", "}", ",", "after", ":", "{", "IfStatementConditionalClosing", ":", "-", "1", ",", "FunctionReservedWord", ":", "1", "}", "}", ",", "lineBreak", ":", "{", "after", ":", "{", "ClassDeclarationClosingBrace", ":", "0", "}", "}", "}", "if", "(", "options", ".", "space", ">", "0", ")", "{", "ESFormatConfig", ".", "indent", ".", "value", "=", "' '", ".", "repeat", "(", "parseInt", "(", "options", ".", "space", ",", "10", ")", ")", "}", "console", ".", "debug", "(", "stripIndent", "`", "${", "clr", ".", "title", "}", "${", "clr", ".", "title", ".", "out", "}", "`", ")", "if", "(", "console", ".", "canWrite", "(", "5", ")", ")", "{", "console", ".", "pretty", "(", "ESFormatConfig", ",", "2", ")", "}", "return", "(", ")", "=>", "esFormatter", ".", "rc", "(", "ESFormatConfig", ")", "}" ]
Create a configured ESformatter factory @private @param {options} options - Job options @return {Function} - Generate an ESFormatter configuration
[ "Create", "a", "configured", "ESformatter", "factory" ]
8f58bde3587c3cd88a777380499529282b0d386d
https://github.com/MarkGriffiths/xo-tidy/blob/8f58bde3587c3cd88a777380499529282b0d386d/src/lib/engine.js#L54-L82
55,242
MarkGriffiths/xo-tidy
src/lib/engine.js
configureESLint
function configureESLint(options) { const ESLintConfig = { rules: options.rules } ESLintConfig.extends = 'xo' if (options.esnext) { ESLintConfig.extends = 'xo/esnext' } if (!options.semicolon) { ESLintConfig.rules.semi = [2, 'never'] } if (options.space === false) { ESLintConfig.rules.indent = [ 2, 'tab', { SwitchCase: 1 } ] } else { ESLintConfig.rules.indent = [ 2, parseInt(options.space, 10), { SwitchCase: 0 } ] } ESLintConfig.rules['valid-jsdoc'] = [0] ESLintConfig.rules['require-jsdoc'] = [0] console.debug(stripIndent` ${clr.title}ESlint Options${clr.title.out}: `) if (console.canWrite(5)) { console.pretty(ESLintConfig, 2) } return () => new ESLint({ baseConfig: ESLintConfig, fix: true, rules: options.rules }) }
javascript
function configureESLint(options) { const ESLintConfig = { rules: options.rules } ESLintConfig.extends = 'xo' if (options.esnext) { ESLintConfig.extends = 'xo/esnext' } if (!options.semicolon) { ESLintConfig.rules.semi = [2, 'never'] } if (options.space === false) { ESLintConfig.rules.indent = [ 2, 'tab', { SwitchCase: 1 } ] } else { ESLintConfig.rules.indent = [ 2, parseInt(options.space, 10), { SwitchCase: 0 } ] } ESLintConfig.rules['valid-jsdoc'] = [0] ESLintConfig.rules['require-jsdoc'] = [0] console.debug(stripIndent` ${clr.title}ESlint Options${clr.title.out}: `) if (console.canWrite(5)) { console.pretty(ESLintConfig, 2) } return () => new ESLint({ baseConfig: ESLintConfig, fix: true, rules: options.rules }) }
[ "function", "configureESLint", "(", "options", ")", "{", "const", "ESLintConfig", "=", "{", "rules", ":", "options", ".", "rules", "}", "ESLintConfig", ".", "extends", "=", "'xo'", "if", "(", "options", ".", "esnext", ")", "{", "ESLintConfig", ".", "extends", "=", "'xo/esnext'", "}", "if", "(", "!", "options", ".", "semicolon", ")", "{", "ESLintConfig", ".", "rules", ".", "semi", "=", "[", "2", ",", "'never'", "]", "}", "if", "(", "options", ".", "space", "===", "false", ")", "{", "ESLintConfig", ".", "rules", ".", "indent", "=", "[", "2", ",", "'tab'", ",", "{", "SwitchCase", ":", "1", "}", "]", "}", "else", "{", "ESLintConfig", ".", "rules", ".", "indent", "=", "[", "2", ",", "parseInt", "(", "options", ".", "space", ",", "10", ")", ",", "{", "SwitchCase", ":", "0", "}", "]", "}", "ESLintConfig", ".", "rules", "[", "'valid-jsdoc'", "]", "=", "[", "0", "]", "ESLintConfig", ".", "rules", "[", "'require-jsdoc'", "]", "=", "[", "0", "]", "console", ".", "debug", "(", "stripIndent", "`", "${", "clr", ".", "title", "}", "${", "clr", ".", "title", ".", "out", "}", "`", ")", "if", "(", "console", ".", "canWrite", "(", "5", ")", ")", "{", "console", ".", "pretty", "(", "ESLintConfig", ",", "2", ")", "}", "return", "(", ")", "=>", "new", "ESLint", "(", "{", "baseConfig", ":", "ESLintConfig", ",", "fix", ":", "true", ",", "rules", ":", "options", ".", "rules", "}", ")", "}" ]
Create a configured ESLint factory @private @param {options} options - Job options @return {Function} - Generate an ESLint configuration
[ "Create", "a", "configured", "ESLint", "factory" ]
8f58bde3587c3cd88a777380499529282b0d386d
https://github.com/MarkGriffiths/xo-tidy/blob/8f58bde3587c3cd88a777380499529282b0d386d/src/lib/engine.js#L90-L133
55,243
nopnop/grunt-transfo
tasks/transfo.js
function(next) { async.map([src,dest], function(path, done) { fs.stat(path, function(err, stat) { done(null, stat); // Ignore error }); }, function(err, results) { statSrc = results[0]; statDest = results[1]; if(!statSrc) { // src is needed next(new Error('File not found: ' + src)); } // Ignore anything that is not directory or file if(!(statSrc.isFile() || statSrc.isDirectory())) { grunt.verbose.writeln(' Ignore:'+' Source is not a file or a directory.'.grey); return done(null, false); } // Add stat to options for user defined transform & process options.statSrc = statSrc; options.statDest = statDest; next(); }); }
javascript
function(next) { async.map([src,dest], function(path, done) { fs.stat(path, function(err, stat) { done(null, stat); // Ignore error }); }, function(err, results) { statSrc = results[0]; statDest = results[1]; if(!statSrc) { // src is needed next(new Error('File not found: ' + src)); } // Ignore anything that is not directory or file if(!(statSrc.isFile() || statSrc.isDirectory())) { grunt.verbose.writeln(' Ignore:'+' Source is not a file or a directory.'.grey); return done(null, false); } // Add stat to options for user defined transform & process options.statSrc = statSrc; options.statDest = statDest; next(); }); }
[ "function", "(", "next", ")", "{", "async", ".", "map", "(", "[", "src", ",", "dest", "]", ",", "function", "(", "path", ",", "done", ")", "{", "fs", ".", "stat", "(", "path", ",", "function", "(", "err", ",", "stat", ")", "{", "done", "(", "null", ",", "stat", ")", ";", "// Ignore error", "}", ")", ";", "}", ",", "function", "(", "err", ",", "results", ")", "{", "statSrc", "=", "results", "[", "0", "]", ";", "statDest", "=", "results", "[", "1", "]", ";", "if", "(", "!", "statSrc", ")", "{", "// src is needed", "next", "(", "new", "Error", "(", "'File not found: '", "+", "src", ")", ")", ";", "}", "// Ignore anything that is not directory or file", "if", "(", "!", "(", "statSrc", ".", "isFile", "(", ")", "||", "statSrc", ".", "isDirectory", "(", ")", ")", ")", "{", "grunt", ".", "verbose", ".", "writeln", "(", "' Ignore:'", "+", "' Source is not a file or a directory.'", ".", "grey", ")", ";", "return", "done", "(", "null", ",", "false", ")", ";", "}", "// Add stat to options for user defined transform & process", "options", ".", "statSrc", "=", "statSrc", ";", "options", ".", "statDest", "=", "statDest", ";", "next", "(", ")", ";", "}", ")", ";", "}" ]
Get src and dest stat asynchronously
[ "Get", "src", "and", "dest", "stat", "asynchronously" ]
cfa00f07cbf97d48b39bd958abc2f889ba3bbce5
https://github.com/nopnop/grunt-transfo/blob/cfa00f07cbf97d48b39bd958abc2f889ba3bbce5/tasks/transfo.js#L282-L307
55,244
nopnop/grunt-transfo
tasks/transfo.js
function(next) { if(!statDest || !lazy || readOnly) { return next(); } if(statDest.mtime.getTime() >= statSrc.mtime.getTime()) { tally.useCached++; grunt.verbose.writeln(' Ignore %s:'+' Destination file is allready transformed (See options.lazy).'.grey, src.blue); // Leave proceed return done(null, false); } else { next(); } }
javascript
function(next) { if(!statDest || !lazy || readOnly) { return next(); } if(statDest.mtime.getTime() >= statSrc.mtime.getTime()) { tally.useCached++; grunt.verbose.writeln(' Ignore %s:'+' Destination file is allready transformed (See options.lazy).'.grey, src.blue); // Leave proceed return done(null, false); } else { next(); } }
[ "function", "(", "next", ")", "{", "if", "(", "!", "statDest", "||", "!", "lazy", "||", "readOnly", ")", "{", "return", "next", "(", ")", ";", "}", "if", "(", "statDest", ".", "mtime", ".", "getTime", "(", ")", ">=", "statSrc", ".", "mtime", ".", "getTime", "(", ")", ")", "{", "tally", ".", "useCached", "++", ";", "grunt", ".", "verbose", ".", "writeln", "(", "' Ignore %s:'", "+", "' Destination file is allready transformed (See options.lazy).'", ".", "grey", ",", "src", ".", "blue", ")", ";", "// Leave proceed", "return", "done", "(", "null", ",", "false", ")", ";", "}", "else", "{", "next", "(", ")", ";", "}", "}" ]
Ignore file processing if the destination allready exist with an equal or posterior mtime
[ "Ignore", "file", "processing", "if", "the", "destination", "allready", "exist", "with", "an", "equal", "or", "posterior", "mtime" ]
cfa00f07cbf97d48b39bd958abc2f889ba3bbce5
https://github.com/nopnop/grunt-transfo/blob/cfa00f07cbf97d48b39bd958abc2f889ba3bbce5/tasks/transfo.js#L311-L323
55,245
nopnop/grunt-transfo
tasks/transfo.js
addToQueueConcat
function addToQueueConcat(sources, dest, options) { queueConcat.push({ src: sources, dest: dest, options: _.extend({}, defaultOptions, options || {}) }); }
javascript
function addToQueueConcat(sources, dest, options) { queueConcat.push({ src: sources, dest: dest, options: _.extend({}, defaultOptions, options || {}) }); }
[ "function", "addToQueueConcat", "(", "sources", ",", "dest", ",", "options", ")", "{", "queueConcat", ".", "push", "(", "{", "src", ":", "sources", ",", "dest", ":", "dest", ",", "options", ":", "_", ".", "extend", "(", "{", "}", ",", "defaultOptions", ",", "options", "||", "{", "}", ")", "}", ")", ";", "}" ]
Concat many source to dest @param {Array} sources Array of source path @param {String} dest Destination path @param {Object} options Transfo options object @return {Promise} TODO
[ "Concat", "many", "source", "to", "dest" ]
cfa00f07cbf97d48b39bd958abc2f889ba3bbce5
https://github.com/nopnop/grunt-transfo/blob/cfa00f07cbf97d48b39bd958abc2f889ba3bbce5/tasks/transfo.js#L514-L520
55,246
nopnop/grunt-transfo
tasks/transfo.js
function(next) { Q.all(sources.map(function(src) { return Q.nfcall(fs.stat, src) .then(function(stat) { statSources[src] = stat; }); })) .then(function() { next(); }) .fail(function(err) {next(err);}); }
javascript
function(next) { Q.all(sources.map(function(src) { return Q.nfcall(fs.stat, src) .then(function(stat) { statSources[src] = stat; }); })) .then(function() { next(); }) .fail(function(err) {next(err);}); }
[ "function", "(", "next", ")", "{", "Q", ".", "all", "(", "sources", ".", "map", "(", "function", "(", "src", ")", "{", "return", "Q", ".", "nfcall", "(", "fs", ".", "stat", ",", "src", ")", ".", "then", "(", "function", "(", "stat", ")", "{", "statSources", "[", "src", "]", "=", "stat", ";", "}", ")", ";", "}", ")", ")", ".", "then", "(", "function", "(", ")", "{", "next", "(", ")", ";", "}", ")", ".", "fail", "(", "function", "(", "err", ")", "{", "next", "(", "err", ")", ";", "}", ")", ";", "}" ]
All sources stats
[ "All", "sources", "stats" ]
cfa00f07cbf97d48b39bd958abc2f889ba3bbce5
https://github.com/nopnop/grunt-transfo/blob/cfa00f07cbf97d48b39bd958abc2f889ba3bbce5/tasks/transfo.js#L550-L559
55,247
nopnop/grunt-transfo
tasks/transfo.js
function(next) { // Here destination is allways a file. // Only the parent folder is required var dir = dirname(dest); if(dirExists[dir]) { return next(); } grunt.verbose.writeln(' Make directory %s', dir.blue); mkdirp(dir, function(err) { if(err) { return next(err); } tally.dirs++; dirExists[dir] = true; return next(); }); }
javascript
function(next) { // Here destination is allways a file. // Only the parent folder is required var dir = dirname(dest); if(dirExists[dir]) { return next(); } grunt.verbose.writeln(' Make directory %s', dir.blue); mkdirp(dir, function(err) { if(err) { return next(err); } tally.dirs++; dirExists[dir] = true; return next(); }); }
[ "function", "(", "next", ")", "{", "// Here destination is allways a file.", "// Only the parent folder is required", "var", "dir", "=", "dirname", "(", "dest", ")", ";", "if", "(", "dirExists", "[", "dir", "]", ")", "{", "return", "next", "(", ")", ";", "}", "grunt", ".", "verbose", ".", "writeln", "(", "' Make directory %s'", ",", "dir", ".", "blue", ")", ";", "mkdirp", "(", "dir", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "tally", ".", "dirs", "++", ";", "dirExists", "[", "dir", "]", "=", "true", ";", "return", "next", "(", ")", ";", "}", ")", ";", "}" ]
Make parent directory
[ "Make", "parent", "directory" ]
cfa00f07cbf97d48b39bd958abc2f889ba3bbce5
https://github.com/nopnop/grunt-transfo/blob/cfa00f07cbf97d48b39bd958abc2f889ba3bbce5/tasks/transfo.js#L589-L607
55,248
greggman/hft-game-utils
src/hft/scripts/misc/gameclock.js
function(clock) { clock = clock || new LocalClock(); this.gameTime = 0; this.callCount = 0; var then = clock.getTime(); /** * Gets the time elapsed in seconds since the last time this was * called * @return {number} The time elapsed in seconds since this was * last called. Note will never return a time more than * 1/20th of second. This is to help prevent giant time * range that might overflow the math on a game. * */ this.getElapsedTime = function() { ++this.callCount; var now = clock.getTime(); var elapsedTime = Math.min(now - then, 0.05); // Don't return a time less than 0.05 second this.gameTime += elapsedTime; then = now; return elapsedTime; }.bind(this); }
javascript
function(clock) { clock = clock || new LocalClock(); this.gameTime = 0; this.callCount = 0; var then = clock.getTime(); /** * Gets the time elapsed in seconds since the last time this was * called * @return {number} The time elapsed in seconds since this was * last called. Note will never return a time more than * 1/20th of second. This is to help prevent giant time * range that might overflow the math on a game. * */ this.getElapsedTime = function() { ++this.callCount; var now = clock.getTime(); var elapsedTime = Math.min(now - then, 0.05); // Don't return a time less than 0.05 second this.gameTime += elapsedTime; then = now; return elapsedTime; }.bind(this); }
[ "function", "(", "clock", ")", "{", "clock", "=", "clock", "||", "new", "LocalClock", "(", ")", ";", "this", ".", "gameTime", "=", "0", ";", "this", ".", "callCount", "=", "0", ";", "var", "then", "=", "clock", ".", "getTime", "(", ")", ";", "/**\n * Gets the time elapsed in seconds since the last time this was\n * called\n * @return {number} The time elapsed in seconds since this was\n * last called. Note will never return a time more than\n * 1/20th of second. This is to help prevent giant time\n * range that might overflow the math on a game.\n *\n */", "this", ".", "getElapsedTime", "=", "function", "(", ")", "{", "++", "this", ".", "callCount", ";", "var", "now", "=", "clock", ".", "getTime", "(", ")", ";", "var", "elapsedTime", "=", "Math", ".", "min", "(", "now", "-", "then", ",", "0.05", ")", ";", "// Don't return a time less than 0.05 second", "this", ".", "gameTime", "+=", "elapsedTime", ";", "then", "=", "now", ";", "return", "elapsedTime", ";", "}", ".", "bind", "(", "this", ")", ";", "}" ]
A clock that returns the time elapsed since the last time it was queried @constructor @alias GameClock @param {Clock?} The clock to use for this GameClock (pass it a SyncedClock of you want the clock to be synced or nothing if you just want a local clock.
[ "A", "clock", "that", "returns", "the", "time", "elapsed", "since", "the", "last", "time", "it", "was", "queried" ]
071a0feebeed79d3597efd63e682392179cf0d30
https://github.com/greggman/hft-game-utils/blob/071a0feebeed79d3597efd63e682392179cf0d30/src/hft/scripts/misc/gameclock.js#L51-L79
55,249
sbruchmann/fn-stack
index.js
FNStack
function FNStack() { var stack = slice.call(arguments, 0).filter(function iterator(val) { return typeof val === "function"; }); this._context = null; this.stack = stack; return this; }
javascript
function FNStack() { var stack = slice.call(arguments, 0).filter(function iterator(val) { return typeof val === "function"; }); this._context = null; this.stack = stack; return this; }
[ "function", "FNStack", "(", ")", "{", "var", "stack", "=", "slice", ".", "call", "(", "arguments", ",", "0", ")", ".", "filter", "(", "function", "iterator", "(", "val", ")", "{", "return", "typeof", "val", "===", "\"function\"", ";", "}", ")", ";", "this", ".", "_context", "=", "null", ";", "this", ".", "stack", "=", "stack", ";", "return", "this", ";", "}" ]
Initializes a new function stack. @constructor
[ "Initializes", "a", "new", "function", "stack", "." ]
2c68ad15d952ce8c348ed9995c22c9edb936ef99
https://github.com/sbruchmann/fn-stack/blob/2c68ad15d952ce8c348ed9995c22c9edb936ef99/index.js#L15-L24
55,250
marcusklaas/grunt-inline-alt
tasks/inline.js
function(matchedWord, imgUrl) { if (!imgUrl || !matchedWord) { return; } var flag = imgUrl.indexOf(options.tag) != -1; // urls like "img/bg.png?__inline" will be transformed to base64 //grunt.log.write('urlMatcher :: matchedWord=' + matchedWord + ',imgUrl=' + imgUrl + '\n$$$\n'); if((isBase64Path(imgUrl)) || isRemotePath(imgUrl)) { return matchedWord; } var absoluteImgUrl = path.resolve(path.dirname(filepath), imgUrl); // img url relative to project root var newUrl = path.relative(path.dirname(htmlFilepath), absoluteImgUrl); // img url relative to the html file absoluteImgUrl = absoluteImgUrl.replace(/\?.*$/, ''); if(flag && grunt.file.exists(absoluteImgUrl)) { newUrl = new datauri(absoluteImgUrl); } else { newUrl = newUrl.replace(/\\/g, '/'); } return matchedWord.replace(imgUrl, newUrl); }
javascript
function(matchedWord, imgUrl) { if (!imgUrl || !matchedWord) { return; } var flag = imgUrl.indexOf(options.tag) != -1; // urls like "img/bg.png?__inline" will be transformed to base64 //grunt.log.write('urlMatcher :: matchedWord=' + matchedWord + ',imgUrl=' + imgUrl + '\n$$$\n'); if((isBase64Path(imgUrl)) || isRemotePath(imgUrl)) { return matchedWord; } var absoluteImgUrl = path.resolve(path.dirname(filepath), imgUrl); // img url relative to project root var newUrl = path.relative(path.dirname(htmlFilepath), absoluteImgUrl); // img url relative to the html file absoluteImgUrl = absoluteImgUrl.replace(/\?.*$/, ''); if(flag && grunt.file.exists(absoluteImgUrl)) { newUrl = new datauri(absoluteImgUrl); } else { newUrl = newUrl.replace(/\\/g, '/'); } return matchedWord.replace(imgUrl, newUrl); }
[ "function", "(", "matchedWord", ",", "imgUrl", ")", "{", "if", "(", "!", "imgUrl", "||", "!", "matchedWord", ")", "{", "return", ";", "}", "var", "flag", "=", "imgUrl", ".", "indexOf", "(", "options", ".", "tag", ")", "!=", "-", "1", ";", "// urls like \"img/bg.png?__inline\" will be transformed to base64", "//grunt.log.write('urlMatcher :: matchedWord=' + matchedWord + ',imgUrl=' + imgUrl + '\\n$$$\\n');", "if", "(", "(", "isBase64Path", "(", "imgUrl", ")", ")", "||", "isRemotePath", "(", "imgUrl", ")", ")", "{", "return", "matchedWord", ";", "}", "var", "absoluteImgUrl", "=", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "filepath", ")", ",", "imgUrl", ")", ";", "// img url relative to project root", "var", "newUrl", "=", "path", ".", "relative", "(", "path", ".", "dirname", "(", "htmlFilepath", ")", ",", "absoluteImgUrl", ")", ";", "// img url relative to the html file", "absoluteImgUrl", "=", "absoluteImgUrl", ".", "replace", "(", "/", "\\?.*$", "/", ",", "''", ")", ";", "if", "(", "flag", "&&", "grunt", ".", "file", ".", "exists", "(", "absoluteImgUrl", ")", ")", "{", "newUrl", "=", "new", "datauri", "(", "absoluteImgUrl", ")", ";", "}", "else", "{", "newUrl", "=", "newUrl", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'/'", ")", ";", "}", "return", "matchedWord", ".", "replace", "(", "imgUrl", ",", "newUrl", ")", ";", "}" ]
match tokens with "url" in content
[ "match", "tokens", "with", "url", "in", "content" ]
da7d2306183b6eb9546322cdbfd8a2c2e4230972
https://github.com/marcusklaas/grunt-inline-alt/blob/da7d2306183b6eb9546322cdbfd8a2c2e4230972/tasks/inline.js#L190-L212
55,251
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/node.js
function( includeChildren, cloneId ) { var $clone = this.$.cloneNode( includeChildren ); var removeIds = function( node ) { // Reset data-cke-expando only when has been cloned (IE and only for some types of objects). if ( node[ 'data-cke-expando' ] ) node[ 'data-cke-expando' ] = false; if ( node.nodeType != CKEDITOR.NODE_ELEMENT ) return; if ( !cloneId ) node.removeAttribute( 'id', false ); if ( includeChildren ) { var childs = node.childNodes; for ( var i = 0; i < childs.length; i++ ) removeIds( childs[ i ] ); } }; // The "id" attribute should never be cloned to avoid duplication. removeIds( $clone ); return new CKEDITOR.dom.node( $clone ); }
javascript
function( includeChildren, cloneId ) { var $clone = this.$.cloneNode( includeChildren ); var removeIds = function( node ) { // Reset data-cke-expando only when has been cloned (IE and only for some types of objects). if ( node[ 'data-cke-expando' ] ) node[ 'data-cke-expando' ] = false; if ( node.nodeType != CKEDITOR.NODE_ELEMENT ) return; if ( !cloneId ) node.removeAttribute( 'id', false ); if ( includeChildren ) { var childs = node.childNodes; for ( var i = 0; i < childs.length; i++ ) removeIds( childs[ i ] ); } }; // The "id" attribute should never be cloned to avoid duplication. removeIds( $clone ); return new CKEDITOR.dom.node( $clone ); }
[ "function", "(", "includeChildren", ",", "cloneId", ")", "{", "var", "$clone", "=", "this", ".", "$", ".", "cloneNode", "(", "includeChildren", ")", ";", "var", "removeIds", "=", "function", "(", "node", ")", "{", "// Reset data-cke-expando only when has been cloned (IE and only for some types of objects).", "if", "(", "node", "[", "'data-cke-expando'", "]", ")", "node", "[", "'data-cke-expando'", "]", "=", "false", ";", "if", "(", "node", ".", "nodeType", "!=", "CKEDITOR", ".", "NODE_ELEMENT", ")", "return", ";", "if", "(", "!", "cloneId", ")", "node", ".", "removeAttribute", "(", "'id'", ",", "false", ")", ";", "if", "(", "includeChildren", ")", "{", "var", "childs", "=", "node", ".", "childNodes", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "childs", ".", "length", ";", "i", "++", ")", "removeIds", "(", "childs", "[", "i", "]", ")", ";", "}", "}", ";", "// The \"id\" attribute should never be cloned to avoid duplication.", "removeIds", "(", "$clone", ")", ";", "return", "new", "CKEDITOR", ".", "dom", ".", "node", "(", "$clone", ")", ";", "}" ]
Clones this node. **Note**: Values set by {#setCustomData} will not be available in the clone. @param {Boolean} [includeChildren=false] If `true` then all node's children will be cloned recursively. @param {Boolean} [cloneId=false] Whether ID attributes should be cloned, too. @returns {CKEDITOR.dom.node} Clone of this node.
[ "Clones", "this", "node", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/node.js#L121-L145
55,252
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/node.js
function( normalized ) { var address = []; var $documentElement = this.getDocument().$.documentElement; var node = this.$; while ( node && node != $documentElement ) { var parentNode = node.parentNode; if ( parentNode ) { // Get the node index. For performance, call getIndex // directly, instead of creating a new node object. address.unshift( this.getIndex.call( { $: node }, normalized ) ); } node = parentNode; } return address; }
javascript
function( normalized ) { var address = []; var $documentElement = this.getDocument().$.documentElement; var node = this.$; while ( node && node != $documentElement ) { var parentNode = node.parentNode; if ( parentNode ) { // Get the node index. For performance, call getIndex // directly, instead of creating a new node object. address.unshift( this.getIndex.call( { $: node }, normalized ) ); } node = parentNode; } return address; }
[ "function", "(", "normalized", ")", "{", "var", "address", "=", "[", "]", ";", "var", "$documentElement", "=", "this", ".", "getDocument", "(", ")", ".", "$", ".", "documentElement", ";", "var", "node", "=", "this", ".", "$", ";", "while", "(", "node", "&&", "node", "!=", "$documentElement", ")", "{", "var", "parentNode", "=", "node", ".", "parentNode", ";", "if", "(", "parentNode", ")", "{", "// Get the node index. For performance, call getIndex", "// directly, instead of creating a new node object.", "address", ".", "unshift", "(", "this", ".", "getIndex", ".", "call", "(", "{", "$", ":", "node", "}", ",", "normalized", ")", ")", ";", "}", "node", "=", "parentNode", ";", "}", "return", "address", ";", "}" ]
Retrieves a uniquely identifiable tree address for this node. The tree address returned is an array of integers, with each integer indicating a child index of a DOM node, starting from `document.documentElement`. For example, assuming `<body>` is the second child of `<html>` (`<head>` being the first), and we would like to address the third child under the fourth child of `<body>`, the tree address returned would be: `[1, 3, 2]`. The tree address cannot be used for finding back the DOM tree node once the DOM tree structure has been modified. @param {Boolean} [normalized=false] See {@link #getIndex}. @returns {Array} The address.
[ "Retrieves", "a", "uniquely", "identifiable", "tree", "address", "for", "this", "node", ".", "The", "tree", "address", "returned", "is", "an", "array", "of", "integers", "with", "each", "integer", "indicating", "a", "child", "index", "of", "a", "DOM", "node", "starting", "from", "document", ".", "documentElement", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/node.js#L234-L252
55,253
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/node.js
function( normalized ) { // Attention: getAddress depends on this.$ // getIndex is called on a plain object: { $ : node } var current = this.$, index = -1, isNormalizing; if ( !this.$.parentNode ) return index; do { // Bypass blank node and adjacent text nodes. if ( normalized && current != this.$ && current.nodeType == CKEDITOR.NODE_TEXT && ( isNormalizing || !current.nodeValue ) ) continue; index++; isNormalizing = current.nodeType == CKEDITOR.NODE_TEXT; } while ( ( current = current.previousSibling ) ); return index; }
javascript
function( normalized ) { // Attention: getAddress depends on this.$ // getIndex is called on a plain object: { $ : node } var current = this.$, index = -1, isNormalizing; if ( !this.$.parentNode ) return index; do { // Bypass blank node and adjacent text nodes. if ( normalized && current != this.$ && current.nodeType == CKEDITOR.NODE_TEXT && ( isNormalizing || !current.nodeValue ) ) continue; index++; isNormalizing = current.nodeType == CKEDITOR.NODE_TEXT; } while ( ( current = current.previousSibling ) ); return index; }
[ "function", "(", "normalized", ")", "{", "// Attention: getAddress depends on this.$", "// getIndex is called on a plain object: { $ : node }", "var", "current", "=", "this", ".", "$", ",", "index", "=", "-", "1", ",", "isNormalizing", ";", "if", "(", "!", "this", ".", "$", ".", "parentNode", ")", "return", "index", ";", "do", "{", "// Bypass blank node and adjacent text nodes.", "if", "(", "normalized", "&&", "current", "!=", "this", ".", "$", "&&", "current", ".", "nodeType", "==", "CKEDITOR", ".", "NODE_TEXT", "&&", "(", "isNormalizing", "||", "!", "current", ".", "nodeValue", ")", ")", "continue", ";", "index", "++", ";", "isNormalizing", "=", "current", ".", "nodeType", "==", "CKEDITOR", ".", "NODE_TEXT", ";", "}", "while", "(", "(", "current", "=", "current", ".", "previousSibling", ")", ")", ";", "return", "index", ";", "}" ]
Gets the index of a node in an array of its `parent.childNodes`. Let us assume having the following `childNodes` array: [ emptyText, element1, text, text, element2 ] element1.getIndex(); // 1 element1.getIndex( true ); // 0 element2.getIndex(); // 4 element2.getIndex( true ); // 2 @param {Boolean} normalized When `true`, empty text nodes and one followed by another one text node are not counted in. @returns {Number} Index of a node.
[ "Gets", "the", "index", "of", "a", "node", "in", "an", "array", "of", "its", "parent", ".", "childNodes", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/node.js#L281-L303
55,254
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/node.js
function( closerFirst ) { var node = this; var parents = []; do { parents[ closerFirst ? 'push' : 'unshift' ]( node ); } while ( ( node = node.getParent() ) ); return parents; }
javascript
function( closerFirst ) { var node = this; var parents = []; do { parents[ closerFirst ? 'push' : 'unshift' ]( node ); } while ( ( node = node.getParent() ) ); return parents; }
[ "function", "(", "closerFirst", ")", "{", "var", "node", "=", "this", ";", "var", "parents", "=", "[", "]", ";", "do", "{", "parents", "[", "closerFirst", "?", "'push'", ":", "'unshift'", "]", "(", "node", ")", ";", "}", "while", "(", "(", "node", "=", "node", ".", "getParent", "(", ")", ")", ")", ";", "return", "parents", ";", "}" ]
Returns an array containing node parents and the node itself. By default nodes are in _descending_ order. // Assuming that body has paragraph as the first child. var node = editor.document.getBody().getFirst(); var parents = node.getParents(); alert( parents[ 0 ].getName() + ',' + parents[ 2 ].getName() ); // 'html,p' @param {Boolean} [closerFirst=false] Determines the order of returned nodes. @returns {Array} Returns an array of {@link CKEDITOR.dom.node}.
[ "Returns", "an", "array", "containing", "node", "parents", "and", "the", "node", "itself", ".", "By", "default", "nodes", "are", "in", "_descending_", "order", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/node.js#L464-L474
55,255
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/dom/node.js
function( query, includeSelf ) { var $ = this.$, evaluator, isCustomEvaluator; if ( !includeSelf ) { $ = $.parentNode; } // Custom checker provided in an argument. if ( typeof query == 'function' ) { isCustomEvaluator = true; evaluator = query; } else { // Predefined tag name checker. isCustomEvaluator = false; evaluator = function( $ ) { var name = ( typeof $.nodeName == 'string' ? $.nodeName.toLowerCase() : '' ); return ( typeof query == 'string' ? name == query : name in query ); }; } while ( $ ) { // For user provided checker we use CKEDITOR.dom.node. if ( evaluator( isCustomEvaluator ? new CKEDITOR.dom.node( $ ) : $ ) ) { return new CKEDITOR.dom.node( $ ); } try { $ = $.parentNode; } catch ( e ) { $ = null; } } return null; }
javascript
function( query, includeSelf ) { var $ = this.$, evaluator, isCustomEvaluator; if ( !includeSelf ) { $ = $.parentNode; } // Custom checker provided in an argument. if ( typeof query == 'function' ) { isCustomEvaluator = true; evaluator = query; } else { // Predefined tag name checker. isCustomEvaluator = false; evaluator = function( $ ) { var name = ( typeof $.nodeName == 'string' ? $.nodeName.toLowerCase() : '' ); return ( typeof query == 'string' ? name == query : name in query ); }; } while ( $ ) { // For user provided checker we use CKEDITOR.dom.node. if ( evaluator( isCustomEvaluator ? new CKEDITOR.dom.node( $ ) : $ ) ) { return new CKEDITOR.dom.node( $ ); } try { $ = $.parentNode; } catch ( e ) { $ = null; } } return null; }
[ "function", "(", "query", ",", "includeSelf", ")", "{", "var", "$", "=", "this", ".", "$", ",", "evaluator", ",", "isCustomEvaluator", ";", "if", "(", "!", "includeSelf", ")", "{", "$", "=", "$", ".", "parentNode", ";", "}", "// Custom checker provided in an argument.", "if", "(", "typeof", "query", "==", "'function'", ")", "{", "isCustomEvaluator", "=", "true", ";", "evaluator", "=", "query", ";", "}", "else", "{", "// Predefined tag name checker.", "isCustomEvaluator", "=", "false", ";", "evaluator", "=", "function", "(", "$", ")", "{", "var", "name", "=", "(", "typeof", "$", ".", "nodeName", "==", "'string'", "?", "$", ".", "nodeName", ".", "toLowerCase", "(", ")", ":", "''", ")", ";", "return", "(", "typeof", "query", "==", "'string'", "?", "name", "==", "query", ":", "name", "in", "query", ")", ";", "}", ";", "}", "while", "(", "$", ")", "{", "// For user provided checker we use CKEDITOR.dom.node.", "if", "(", "evaluator", "(", "isCustomEvaluator", "?", "new", "CKEDITOR", ".", "dom", ".", "node", "(", "$", ")", ":", "$", ")", ")", "{", "return", "new", "CKEDITOR", ".", "dom", ".", "node", "(", "$", ")", ";", "}", "try", "{", "$", "=", "$", ".", "parentNode", ";", "}", "catch", "(", "e", ")", "{", "$", "=", "null", ";", "}", "}", "return", "null", ";", "}" ]
Gets the closest ancestor node of this node, specified by its name or using an evaluator function. // Suppose we have the following HTML structure: // <div id="outer"><div id="inner"><p><b>Some text</b></p></div></div> // If node == <b> ascendant = node.getAscendant( 'div' ); // ascendant == <div id="inner"> ascendant = node.getAscendant( 'b' ); // ascendant == null ascendant = node.getAscendant( 'b', true ); // ascendant == <b> ascendant = node.getAscendant( { div:1, p:1 } ); // Searches for the first 'div' or 'p': ascendant == <div id="inner"> // Using custom evaluator: ascendant = node.getAscendant( function( el ) { return el.getId() == 'inner'; } ); // ascendant == <div id="inner"> @since 3.6.1 @param {String/Function/Object} query The name of the ancestor node to search or an object with the node names to search for or an evaluator function. @param {Boolean} [includeSelf] Whether to include the current node in the search. @returns {CKEDITOR.dom.node} The located ancestor node or `null` if not found.
[ "Gets", "the", "closest", "ancestor", "node", "of", "this", "node", "specified", "by", "its", "name", "or", "using", "an", "evaluator", "function", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/dom/node.js#L571-L608
55,256
byu-oit/fully-typed
bin/function.js
TypedFunction
function TypedFunction (config) { const fn = this; if (config.hasOwnProperty('minArguments') && (!util.isInteger(config.minArguments) || config.minArguments < 0)) { const message = util.propertyErrorMessage('minArguments', config.minArguments, 'Expected a non-negative integer.'); throw Error(message); } const min = config.hasOwnProperty('minArguments') ? config.minArguments : 0; if (config.hasOwnProperty('maxArguments') && (!util.isInteger(config.maxArguments) || config.maxArguments < min)) { const message = util.propertyErrorMessage('minArguments', config.maxArguments, 'Expected a integer greater than minArgument value of ' + min + '.'); throw Error(message); } // define properties Object.defineProperties(fn, { maxArguments: { /** * @property * @name TypedString#maxArguments * @type {number} */ value: config.maxArguments, writable: false }, minArguments: { /** * @property * @name TypedString#minArguments * @type {number} */ value: min, writable: false }, named: { /** * @property * @name TypedString#strict * @type {boolean} */ value: config.hasOwnProperty('named') ? !!config.named : false, writable: false } }); return fn; }
javascript
function TypedFunction (config) { const fn = this; if (config.hasOwnProperty('minArguments') && (!util.isInteger(config.minArguments) || config.minArguments < 0)) { const message = util.propertyErrorMessage('minArguments', config.minArguments, 'Expected a non-negative integer.'); throw Error(message); } const min = config.hasOwnProperty('minArguments') ? config.minArguments : 0; if (config.hasOwnProperty('maxArguments') && (!util.isInteger(config.maxArguments) || config.maxArguments < min)) { const message = util.propertyErrorMessage('minArguments', config.maxArguments, 'Expected a integer greater than minArgument value of ' + min + '.'); throw Error(message); } // define properties Object.defineProperties(fn, { maxArguments: { /** * @property * @name TypedString#maxArguments * @type {number} */ value: config.maxArguments, writable: false }, minArguments: { /** * @property * @name TypedString#minArguments * @type {number} */ value: min, writable: false }, named: { /** * @property * @name TypedString#strict * @type {boolean} */ value: config.hasOwnProperty('named') ? !!config.named : false, writable: false } }); return fn; }
[ "function", "TypedFunction", "(", "config", ")", "{", "const", "fn", "=", "this", ";", "if", "(", "config", ".", "hasOwnProperty", "(", "'minArguments'", ")", "&&", "(", "!", "util", ".", "isInteger", "(", "config", ".", "minArguments", ")", "||", "config", ".", "minArguments", "<", "0", ")", ")", "{", "const", "message", "=", "util", ".", "propertyErrorMessage", "(", "'minArguments'", ",", "config", ".", "minArguments", ",", "'Expected a non-negative integer.'", ")", ";", "throw", "Error", "(", "message", ")", ";", "}", "const", "min", "=", "config", ".", "hasOwnProperty", "(", "'minArguments'", ")", "?", "config", ".", "minArguments", ":", "0", ";", "if", "(", "config", ".", "hasOwnProperty", "(", "'maxArguments'", ")", "&&", "(", "!", "util", ".", "isInteger", "(", "config", ".", "maxArguments", ")", "||", "config", ".", "maxArguments", "<", "min", ")", ")", "{", "const", "message", "=", "util", ".", "propertyErrorMessage", "(", "'minArguments'", ",", "config", ".", "maxArguments", ",", "'Expected a integer greater than minArgument value of '", "+", "min", "+", "'.'", ")", ";", "throw", "Error", "(", "message", ")", ";", "}", "// define properties", "Object", ".", "defineProperties", "(", "fn", ",", "{", "maxArguments", ":", "{", "/**\n * @property\n * @name TypedString#maxArguments\n * @type {number}\n */", "value", ":", "config", ".", "maxArguments", ",", "writable", ":", "false", "}", ",", "minArguments", ":", "{", "/**\n * @property\n * @name TypedString#minArguments\n * @type {number}\n */", "value", ":", "min", ",", "writable", ":", "false", "}", ",", "named", ":", "{", "/**\n * @property\n * @name TypedString#strict\n * @type {boolean}\n */", "value", ":", "config", ".", "hasOwnProperty", "(", "'named'", ")", "?", "!", "!", "config", ".", "named", ":", "false", ",", "writable", ":", "false", "}", "}", ")", ";", "return", "fn", ";", "}" ]
Create a TypedFunction instance. @param {object} config @returns {TypedFunction} @augments Typed @constructor
[ "Create", "a", "TypedFunction", "instance", "." ]
ed6b3ed88ffc72990acffb765232eaaee261afef
https://github.com/byu-oit/fully-typed/blob/ed6b3ed88ffc72990acffb765232eaaee261afef/bin/function.js#L29-L79
55,257
trentmillar/hash-o-matic
lib/hashomatic.js
function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; hashomatic._gap = ''; hashomatic._indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { hashomatic._indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { hashomatic._indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. hashomatic._rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return hashomatic._str('', {'': value}); }
javascript
function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; hashomatic._gap = ''; hashomatic._indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { hashomatic._indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { hashomatic._indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. hashomatic._rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return hashomatic._str('', {'': value}); }
[ "function", "(", "value", ",", "replacer", ",", "space", ")", "{", "// The stringify method takes a value and an optional replacer, and an optional", "// space parameter, and returns a JSON text. The replacer can be a function", "// that can replace values, or an array of strings that will select the keys.", "// A default replacer method can be provided. Use of the space parameter can", "// produce text that is more easily readable.", "var", "i", ";", "hashomatic", ".", "_gap", "=", "''", ";", "hashomatic", ".", "_indent", "=", "''", ";", "// If the space parameter is a number, make an indent string containing that", "// many spaces.", "if", "(", "typeof", "space", "===", "'number'", ")", "{", "for", "(", "i", "=", "0", ";", "i", "<", "space", ";", "i", "+=", "1", ")", "{", "hashomatic", ".", "_indent", "+=", "' '", ";", "}", "// If the space parameter is a string, it will be used as the indent string.", "}", "else", "if", "(", "typeof", "space", "===", "'string'", ")", "{", "hashomatic", ".", "_indent", "=", "space", ";", "}", "// If there is a replacer, it must be a function or an array.", "// Otherwise, throw an error.", "hashomatic", ".", "_rep", "=", "replacer", ";", "if", "(", "replacer", "&&", "typeof", "replacer", "!==", "'function'", "&&", "(", "typeof", "replacer", "!==", "'object'", "||", "typeof", "replacer", ".", "length", "!==", "'number'", ")", ")", "{", "throw", "new", "Error", "(", "'JSON.stringify'", ")", ";", "}", "// Make a fake root object containing our value under the key of ''.", "// Return the result of stringifying the value.", "return", "hashomatic", ".", "_str", "(", "''", ",", "{", "''", ":", "value", "}", ")", ";", "}" ]
If the JSON object does not yet have a stringify method, give it one.
[ "If", "the", "JSON", "object", "does", "not", "yet", "have", "a", "stringify", "method", "give", "it", "one", "." ]
7193c3fd60e08e245f34d48fc48985298af8c6e1
https://github.com/trentmillar/hash-o-matic/blob/7193c3fd60e08e245f34d48fc48985298af8c6e1/lib/hashomatic.js#L207-L248
55,258
odentools/denhub-device
models/helper.js
function () { if (packageInfo) return packageInfo; var fs = require('fs'); packageInfo = JSON.parse(fs.readFileSync(__dirname + '/../package.json', 'utf8')); return packageInfo; }
javascript
function () { if (packageInfo) return packageInfo; var fs = require('fs'); packageInfo = JSON.parse(fs.readFileSync(__dirname + '/../package.json', 'utf8')); return packageInfo; }
[ "function", "(", ")", "{", "if", "(", "packageInfo", ")", "return", "packageInfo", ";", "var", "fs", "=", "require", "(", "'fs'", ")", ";", "packageInfo", "=", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "__dirname", "+", "'/../package.json'", ",", "'utf8'", ")", ")", ";", "return", "packageInfo", ";", "}" ]
Read the package information @return {Object} Package information
[ "Read", "the", "package", "information" ]
50d35aca96db3a07a3272f1765a660ea893735ce
https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/models/helper.js#L14-L23
55,259
odentools/denhub-device
models/helper.js
function (is_ignore_errors, opt_config_filename) { var self = this; var config_paths = []; if (opt_config_filename) { config_paths.push(opt_config_filename); } else { // root of dependence source directory config_paths.push('./config.json'); // root of denhub-device directory config_paths.push(__dirname + '/../config.json'); } var config_file = null; for (var i = 0, l = config_paths.length; i < l; i++) { try { config_file = require('fs').readFileSync(config_paths[i]); } catch (e) { continue; } if (config_file) break; } if (!config_file && !is_ignore_errors) { console.log(colors.bold.red('Error: Could not read the configuration file.')); console.log(config_paths.join('\n')); console.log(colors.bold('If you never created it, please try the following command:')); console.log('$ denhub-device-generator init\n'); process.exit(255); } var config = {}; if (config_file) { try { config = JSON.parse(config_file.toString()); } catch (e) { if (!is_ignore_errors) throw e; } } config.commands = self._getLocalCommands(is_ignore_errors) || null; return config; }
javascript
function (is_ignore_errors, opt_config_filename) { var self = this; var config_paths = []; if (opt_config_filename) { config_paths.push(opt_config_filename); } else { // root of dependence source directory config_paths.push('./config.json'); // root of denhub-device directory config_paths.push(__dirname + '/../config.json'); } var config_file = null; for (var i = 0, l = config_paths.length; i < l; i++) { try { config_file = require('fs').readFileSync(config_paths[i]); } catch (e) { continue; } if (config_file) break; } if (!config_file && !is_ignore_errors) { console.log(colors.bold.red('Error: Could not read the configuration file.')); console.log(config_paths.join('\n')); console.log(colors.bold('If you never created it, please try the following command:')); console.log('$ denhub-device-generator init\n'); process.exit(255); } var config = {}; if (config_file) { try { config = JSON.parse(config_file.toString()); } catch (e) { if (!is_ignore_errors) throw e; } } config.commands = self._getLocalCommands(is_ignore_errors) || null; return config; }
[ "function", "(", "is_ignore_errors", ",", "opt_config_filename", ")", "{", "var", "self", "=", "this", ";", "var", "config_paths", "=", "[", "]", ";", "if", "(", "opt_config_filename", ")", "{", "config_paths", ".", "push", "(", "opt_config_filename", ")", ";", "}", "else", "{", "// root of dependence source directory", "config_paths", ".", "push", "(", "'./config.json'", ")", ";", "// root of denhub-device directory", "config_paths", ".", "push", "(", "__dirname", "+", "'/../config.json'", ")", ";", "}", "var", "config_file", "=", "null", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "config_paths", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "try", "{", "config_file", "=", "require", "(", "'fs'", ")", ".", "readFileSync", "(", "config_paths", "[", "i", "]", ")", ";", "}", "catch", "(", "e", ")", "{", "continue", ";", "}", "if", "(", "config_file", ")", "break", ";", "}", "if", "(", "!", "config_file", "&&", "!", "is_ignore_errors", ")", "{", "console", ".", "log", "(", "colors", ".", "bold", ".", "red", "(", "'Error: Could not read the configuration file.'", ")", ")", ";", "console", ".", "log", "(", "config_paths", ".", "join", "(", "'\\n'", ")", ")", ";", "console", ".", "log", "(", "colors", ".", "bold", "(", "'If you never created it, please try the following command:'", ")", ")", ";", "console", ".", "log", "(", "'$ denhub-device-generator init\\n'", ")", ";", "process", ".", "exit", "(", "255", ")", ";", "}", "var", "config", "=", "{", "}", ";", "if", "(", "config_file", ")", "{", "try", "{", "config", "=", "JSON", ".", "parse", "(", "config_file", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "!", "is_ignore_errors", ")", "throw", "e", ";", "}", "}", "config", ".", "commands", "=", "self", ".", "_getLocalCommands", "(", "is_ignore_errors", ")", "||", "null", ";", "return", "config", ";", "}" ]
Read the configuration file @return {Object} Configuration
[ "Read", "the", "configuration", "file" ]
50d35aca96db3a07a3272f1765a660ea893735ce
https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/models/helper.js#L62-L107
55,260
odentools/denhub-device
models/helper.js
function (is_ignore_errors) { var file_paths = []; // root of dependence source directory file_paths.push('./commands.json'); // root of denhub-device directory file_paths.push(__dirname + '/../commands.json'); var file = null; for (var i = 0, l = file_paths.length; i < l; i++) { try { file = require('fs').readFileSync(file_paths[i]); } catch (e) { continue; } if (file) break; } if (!file && !is_ignore_errors) { console.log(colors.bold.red('Error: Could not read the commands file.')); console.log(file_paths.join('\n')); console.log(colors.bold('If you never created it, please try the following command:')); console.log('$ denhub-device-generator --init\n'); process.exit(255); } var commands = {}; if (file) { try { commands = JSON.parse(file); } catch (e) { if (!is_ignore_errors) throw e; commands = null; } } return commands; }
javascript
function (is_ignore_errors) { var file_paths = []; // root of dependence source directory file_paths.push('./commands.json'); // root of denhub-device directory file_paths.push(__dirname + '/../commands.json'); var file = null; for (var i = 0, l = file_paths.length; i < l; i++) { try { file = require('fs').readFileSync(file_paths[i]); } catch (e) { continue; } if (file) break; } if (!file && !is_ignore_errors) { console.log(colors.bold.red('Error: Could not read the commands file.')); console.log(file_paths.join('\n')); console.log(colors.bold('If you never created it, please try the following command:')); console.log('$ denhub-device-generator --init\n'); process.exit(255); } var commands = {}; if (file) { try { commands = JSON.parse(file); } catch (e) { if (!is_ignore_errors) throw e; commands = null; } } return commands; }
[ "function", "(", "is_ignore_errors", ")", "{", "var", "file_paths", "=", "[", "]", ";", "// root of dependence source directory", "file_paths", ".", "push", "(", "'./commands.json'", ")", ";", "// root of denhub-device directory", "file_paths", ".", "push", "(", "__dirname", "+", "'/../commands.json'", ")", ";", "var", "file", "=", "null", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "file_paths", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "try", "{", "file", "=", "require", "(", "'fs'", ")", ".", "readFileSync", "(", "file_paths", "[", "i", "]", ")", ";", "}", "catch", "(", "e", ")", "{", "continue", ";", "}", "if", "(", "file", ")", "break", ";", "}", "if", "(", "!", "file", "&&", "!", "is_ignore_errors", ")", "{", "console", ".", "log", "(", "colors", ".", "bold", ".", "red", "(", "'Error: Could not read the commands file.'", ")", ")", ";", "console", ".", "log", "(", "file_paths", ".", "join", "(", "'\\n'", ")", ")", ";", "console", ".", "log", "(", "colors", ".", "bold", "(", "'If you never created it, please try the following command:'", ")", ")", ";", "console", ".", "log", "(", "'$ denhub-device-generator --init\\n'", ")", ";", "process", ".", "exit", "(", "255", ")", ";", "}", "var", "commands", "=", "{", "}", ";", "if", "(", "file", ")", "{", "try", "{", "commands", "=", "JSON", ".", "parse", "(", "file", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "!", "is_ignore_errors", ")", "throw", "e", ";", "commands", "=", "null", ";", "}", "}", "return", "commands", ";", "}" ]
Read the user's commands definition @return {Object} Commands definition
[ "Read", "the", "user", "s", "commands", "definition" ]
50d35aca96db3a07a3272f1765a660ea893735ce
https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/models/helper.js#L127-L166
55,261
odentools/denhub-device
models/helper.js
function (str) { var self = this; if ('i' !== 'I'.toLowerCase()) { // Thanks for http://qiita.com/niusounds/items/fff91f3f236c31ca910f return str.replace(/[a-z]/g, function(ch) { return String.fromCharCode(ch.charCodeAt(0) & ~32); }); } return str.toUpperCase(); }
javascript
function (str) { var self = this; if ('i' !== 'I'.toLowerCase()) { // Thanks for http://qiita.com/niusounds/items/fff91f3f236c31ca910f return str.replace(/[a-z]/g, function(ch) { return String.fromCharCode(ch.charCodeAt(0) & ~32); }); } return str.toUpperCase(); }
[ "function", "(", "str", ")", "{", "var", "self", "=", "this", ";", "if", "(", "'i'", "!==", "'I'", ".", "toLowerCase", "(", ")", ")", "{", "// Thanks for http://qiita.com/niusounds/items/fff91f3f236c31ca910f", "return", "str", ".", "replace", "(", "/", "[a-z]", "/", "g", ",", "function", "(", "ch", ")", "{", "return", "String", ".", "fromCharCode", "(", "ch", ".", "charCodeAt", "(", "0", ")", "&", "~", "32", ")", ";", "}", ")", ";", "}", "return", "str", ".", "toUpperCase", "(", ")", ";", "}" ]
Conver the string to upper case @return {String} Converted string
[ "Conver", "the", "string", "to", "upper", "case" ]
50d35aca96db3a07a3272f1765a660ea893735ce
https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/models/helper.js#L173-L186
55,262
odentools/denhub-device
models/helper.js
function (obj, var_type) { var text_class = Object.prototype.toString.call(obj).slice(8, -1); return (text_class == var_type); }
javascript
function (obj, var_type) { var text_class = Object.prototype.toString.call(obj).slice(8, -1); return (text_class == var_type); }
[ "function", "(", "obj", ",", "var_type", ")", "{", "var", "text_class", "=", "Object", ".", "prototype", ".", "toString", ".", "call", "(", "obj", ")", ".", "slice", "(", "8", ",", "-", "1", ")", ";", "return", "(", "text_class", "==", "var_type", ")", ";", "}" ]
Whether the variable type is matched with the specified variable type @param {Object} obj Target variable @param {String} var_type Expected variable type @return {Boolean} Whether the type is matched
[ "Whether", "the", "variable", "type", "is", "matched", "with", "the", "specified", "variable", "type" ]
50d35aca96db3a07a3272f1765a660ea893735ce
https://github.com/odentools/denhub-device/blob/50d35aca96db3a07a3272f1765a660ea893735ce/models/helper.js#L195-L200
55,263
dpjanes/iotdb-phant-client
phant.js
function(paramd) { var self = this paramd = defaults(paramd, { iri: "http://data.sparkfun.com" }) self.iri = paramd.iri }
javascript
function(paramd) { var self = this paramd = defaults(paramd, { iri: "http://data.sparkfun.com" }) self.iri = paramd.iri }
[ "function", "(", "paramd", ")", "{", "var", "self", "=", "this", "paramd", "=", "defaults", "(", "paramd", ",", "{", "iri", ":", "\"http://data.sparkfun.com\"", "}", ")", "self", ".", "iri", "=", "paramd", ".", "iri", "}" ]
Connect to a Phant server @param {object} paramd @param {String|undefined} paramd.iri The server to connect to, by default "http://data.sparkfun.com" @constructor
[ "Connect", "to", "a", "Phant", "server" ]
69958f6c532d7ea404d6c2bba8def1feaecddb1d
https://github.com/dpjanes/iotdb-phant-client/blob/69958f6c532d7ea404d6c2bba8def1feaecddb1d/phant.js#L40-L48
55,264
dpjanes/iotdb-phant-client
phant.js
function(paramd, defaultd) { if (paramd === undefined) { return defaultd } for (var key in defaultd) { var pvalue = paramd[key] if (pvalue === undefined) { paramd[key] = defaultd[key] } } return paramd; }
javascript
function(paramd, defaultd) { if (paramd === undefined) { return defaultd } for (var key in defaultd) { var pvalue = paramd[key] if (pvalue === undefined) { paramd[key] = defaultd[key] } } return paramd; }
[ "function", "(", "paramd", ",", "defaultd", ")", "{", "if", "(", "paramd", "===", "undefined", ")", "{", "return", "defaultd", "}", "for", "(", "var", "key", "in", "defaultd", ")", "{", "var", "pvalue", "=", "paramd", "[", "key", "]", "if", "(", "pvalue", "===", "undefined", ")", "{", "paramd", "[", "key", "]", "=", "defaultd", "[", "key", "]", "}", "}", "return", "paramd", ";", "}" ]
Make sure a 'paramd' is properly set up. That is, that it's a dictionary and if any values in defaultd are undefined in paramd, they're copied over
[ "Make", "sure", "a", "paramd", "is", "properly", "set", "up", ".", "That", "is", "that", "it", "s", "a", "dictionary", "and", "if", "any", "values", "in", "defaultd", "are", "undefined", "in", "paramd", "they", "re", "copied", "over" ]
69958f6c532d7ea404d6c2bba8def1feaecddb1d
https://github.com/dpjanes/iotdb-phant-client/blob/69958f6c532d7ea404d6c2bba8def1feaecddb1d/phant.js#L524-L537
55,265
itsa/itsa-event
event-listener.js
function (customEvent, callback, filter, prepend) { return Event.after(customEvent, callback, this, filter, prepend); }
javascript
function (customEvent, callback, filter, prepend) { return Event.after(customEvent, callback, this, filter, prepend); }
[ "function", "(", "customEvent", ",", "callback", ",", "filter", ",", "prepend", ")", "{", "return", "Event", ".", "after", "(", "customEvent", ",", "callback", ",", "this", ",", "filter", ",", "prepend", ")", ";", "}" ]
Subscribes to a customEvent on behalf of the object who calls this method. The callback will be executed `after` the defaultFn. @method after @param customEvent {String|Array} the custom-event (or Array of events) to subscribe to. CustomEvents should have the syntax: `emitterName:eventName`. Wildcard `*` may be used for both `emitterName` as well as `eventName`. If `emitterName` is not defined, `UI` is assumed. @param callback {Function} subscriber:will be invoked when the event occurs. An `eventobject` will be passed as its only argument. @param [filter] {String|Function} to filter the event. Use a String if you want to filter DOM-events by a `selector` Use a function if you want to filter by any other means. If the function returns a trully value, the subscriber gets invoked. The function gets the `eventobject` as its only argument and the context is the subscriber. @param [prepend=false] {Boolean} whether the subscriber should be the first in the list of after-subscribers. @return {Object} handler with a `detach()`-method which can be used to detach the subscriber @since 0.0.1
[ "Subscribes", "to", "a", "customEvent", "on", "behalf", "of", "the", "object", "who", "calls", "this", "method", ".", "The", "callback", "will", "be", "executed", "after", "the", "defaultFn", "." ]
fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa
https://github.com/itsa/itsa-event/blob/fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa/event-listener.js#L49-L51
55,266
itsa/itsa-event
event-listener.js
function (customEvent, callback, filter, prepend) { return Event.before(customEvent, callback, this, filter, prepend); }
javascript
function (customEvent, callback, filter, prepend) { return Event.before(customEvent, callback, this, filter, prepend); }
[ "function", "(", "customEvent", ",", "callback", ",", "filter", ",", "prepend", ")", "{", "return", "Event", ".", "before", "(", "customEvent", ",", "callback", ",", "this", ",", "filter", ",", "prepend", ")", ";", "}" ]
Subscribes to a customEvent on behalf of the object who calls this method. The callback will be executed `before` the defaultFn. @method before @param customEvent {String|Array} the custom-event (or Array of events) to subscribe to. CustomEvents should have the syntax: `emitterName:eventName`. Wildcard `*` may be used for both `emitterName` as well as `eventName`. If `emitterName` is not defined, `UI` is assumed. @param callback {Function} subscriber:will be invoked when the event occurs. An `eventobject` will be passed as its only argument. @param [filter] {String|Function} to filter the event. Use a String if you want to filter DOM-events by a `selector` Use a function if you want to filter by any other means. If the function returns a trully value, the subscriber gets invoked. The function gets the `eventobject` as its only argument and the context is the subscriber. @param [prepend=false] {Boolean} whether the subscriber should be the first in the list of before-subscribers. @return {Object} handler with a `detach()`-method which can be used to detach the subscriber @since 0.0.1
[ "Subscribes", "to", "a", "customEvent", "on", "behalf", "of", "the", "object", "who", "calls", "this", "method", ".", "The", "callback", "will", "be", "executed", "before", "the", "defaultFn", "." ]
fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa
https://github.com/itsa/itsa-event/blob/fd7b5ede1a5e8b6a237f60bd8373f570d014f5fa/event-listener.js#L72-L74
55,267
chiasm-project/chiasm-layout
src/layout.js
setBox
function setBox(){ if(my.container){ my.box = { x: 0, y: 0, width: my.container.clientWidth, height: my.container.clientHeight }; } }
javascript
function setBox(){ if(my.container){ my.box = { x: 0, y: 0, width: my.container.clientWidth, height: my.container.clientHeight }; } }
[ "function", "setBox", "(", ")", "{", "if", "(", "my", ".", "container", ")", "{", "my", ".", "box", "=", "{", "x", ":", "0", ",", "y", ":", "0", ",", "width", ":", "my", ".", "container", ".", "clientWidth", ",", "height", ":", "my", ".", "container", ".", "clientHeight", "}", ";", "}", "}" ]
Sets the `box` my property based on actual container size .
[ "Sets", "the", "box", "my", "property", "based", "on", "actual", "container", "size", "." ]
245ddd2d8c1d19fa08b085cd6b8920be85453530
https://github.com/chiasm-project/chiasm-layout/blob/245ddd2d8c1d19fa08b085cd6b8920be85453530/src/layout.js#L33-L42
55,268
chiasm-project/chiasm-layout
src/layout.js
aliasesInLayout
function aliasesInLayout(layout, sizes){ return Object.keys(computeLayout(layout, sizes, { width: 100, height: 100 })); }
javascript
function aliasesInLayout(layout, sizes){ return Object.keys(computeLayout(layout, sizes, { width: 100, height: 100 })); }
[ "function", "aliasesInLayout", "(", "layout", ",", "sizes", ")", "{", "return", "Object", ".", "keys", "(", "computeLayout", "(", "layout", ",", "sizes", ",", "{", "width", ":", "100", ",", "height", ":", "100", "}", ")", ")", ";", "}" ]
Computes which aliases are referenced in the given layout.
[ "Computes", "which", "aliases", "are", "referenced", "in", "the", "given", "layout", "." ]
245ddd2d8c1d19fa08b085cd6b8920be85453530
https://github.com/chiasm-project/chiasm-layout/blob/245ddd2d8c1d19fa08b085cd6b8920be85453530/src/layout.js#L110-L115
55,269
camshaft/links-parser
index.js
parseParams
function parseParams(params, init) { return reduce(params, function(obj, param) { var parts = param.split(/ *= */); var key = removeQuote(parts[0]); obj[key] = removeQuote(parts[1]); return obj; }, init); }
javascript
function parseParams(params, init) { return reduce(params, function(obj, param) { var parts = param.split(/ *= */); var key = removeQuote(parts[0]); obj[key] = removeQuote(parts[1]); return obj; }, init); }
[ "function", "parseParams", "(", "params", ",", "init", ")", "{", "return", "reduce", "(", "params", ",", "function", "(", "obj", ",", "param", ")", "{", "var", "parts", "=", "param", ".", "split", "(", "/", " *= *", "/", ")", ";", "var", "key", "=", "removeQuote", "(", "parts", "[", "0", "]", ")", ";", "obj", "[", "key", "]", "=", "removeQuote", "(", "parts", "[", "1", "]", ")", ";", "return", "obj", ";", "}", ",", "init", ")", ";", "}" ]
Parse key=value parameters @param {Object} params @param {Object} init @return {Object}
[ "Parse", "key", "=", "value", "parameters" ]
358afb23cb28f9c8a24d0b3d795a07ec1ab87c18
https://github.com/camshaft/links-parser/blob/358afb23cb28f9c8a24d0b3d795a07ec1ab87c18/index.js#L49-L56
55,270
eventualbuddha/broccoli-compile-modules
index.js
CompileModules
function CompileModules(inputTree, options) { this.setInputTree(inputTree); this.setInputFiles(options.inputFiles); this.setResolvers(options.resolvers || []); this.setOutput(options.output); this.setFormatter(options.formatter); if (options.output) { this.description = 'CompileModules (' + options.output + ')'; } }
javascript
function CompileModules(inputTree, options) { this.setInputTree(inputTree); this.setInputFiles(options.inputFiles); this.setResolvers(options.resolvers || []); this.setOutput(options.output); this.setFormatter(options.formatter); if (options.output) { this.description = 'CompileModules (' + options.output + ')'; } }
[ "function", "CompileModules", "(", "inputTree", ",", "options", ")", "{", "this", ".", "setInputTree", "(", "inputTree", ")", ";", "this", ".", "setInputFiles", "(", "options", ".", "inputFiles", ")", ";", "this", ".", "setResolvers", "(", "options", ".", "resolvers", "||", "[", "]", ")", ";", "this", ".", "setOutput", "(", "options", ".", "output", ")", ";", "this", ".", "setFormatter", "(", "options", ".", "formatter", ")", ";", "if", "(", "options", ".", "output", ")", "{", "this", ".", "description", "=", "'CompileModules ('", "+", "options", ".", "output", "+", "')'", ";", "}", "}" ]
Creates a new compiled modules writer. @param inputTree @param {{inputFiles: ?string[], resolvers: ?object[], output: string, formatter: object}} options @extends {Writer} @constructor
[ "Creates", "a", "new", "compiled", "modules", "writer", "." ]
9bab25bdc22399b0961fb44aa2aa5f012e020ea6
https://github.com/eventualbuddha/broccoli-compile-modules/blob/9bab25bdc22399b0961fb44aa2aa5f012e020ea6/index.js#L35-L45
55,271
nicktindall/cyclon.p2p-common
lib/ObfuscatingStorageWrapper.js
ObfuscatingStorageWrapper
function ObfuscatingStorageWrapper(storage) { var SECRET_KEY_KEY = "___XX"; var wellKnownKey = "ce56c9aa-d287-4e7c-b9d5-edca7a985487"; function getSecretKey() { var secretKeyName = scrambleKey(SECRET_KEY_KEY, wellKnownKey); var secretKey = storage.getItem(secretKeyName); if (secretKey === null) { secretKey = GuidGenerator(); storage.setItem(secretKeyName, encryptValue(secretKey, wellKnownKey)); } else { secretKey = decryptValue(secretKey, wellKnownKey); } return secretKey; } function scrambleKey(key, encryptionKey) { return CryptoJS.HmacMD5(key, encryptionKey || getSecretKey()).toString(); } function encryptValue(value, encryptionKey) { return CryptoJS.AES.encrypt(JSON.stringify(value), encryptionKey || getSecretKey()).toString(); } function decryptValue(value, encryptionKey) { if (value === null) { return null; } try { var decryptedValue = CryptoJS.AES.decrypt(value, encryptionKey || getSecretKey()).toString(CryptoJS.enc.Utf8); return JSON.parse(decryptedValue); } catch (e) { return null; } } this.getItem = function (key) { return decryptValue(storage.getItem(scrambleKey(key))); }; this.setItem = function (key, value) { storage.setItem(scrambleKey(key), encryptValue(value)); }; this.removeItem = function (key) { storage.removeItem(scrambleKey(key)); }; this.clear = function () { storage.clear(); }; getSecretKey(); }
javascript
function ObfuscatingStorageWrapper(storage) { var SECRET_KEY_KEY = "___XX"; var wellKnownKey = "ce56c9aa-d287-4e7c-b9d5-edca7a985487"; function getSecretKey() { var secretKeyName = scrambleKey(SECRET_KEY_KEY, wellKnownKey); var secretKey = storage.getItem(secretKeyName); if (secretKey === null) { secretKey = GuidGenerator(); storage.setItem(secretKeyName, encryptValue(secretKey, wellKnownKey)); } else { secretKey = decryptValue(secretKey, wellKnownKey); } return secretKey; } function scrambleKey(key, encryptionKey) { return CryptoJS.HmacMD5(key, encryptionKey || getSecretKey()).toString(); } function encryptValue(value, encryptionKey) { return CryptoJS.AES.encrypt(JSON.stringify(value), encryptionKey || getSecretKey()).toString(); } function decryptValue(value, encryptionKey) { if (value === null) { return null; } try { var decryptedValue = CryptoJS.AES.decrypt(value, encryptionKey || getSecretKey()).toString(CryptoJS.enc.Utf8); return JSON.parse(decryptedValue); } catch (e) { return null; } } this.getItem = function (key) { return decryptValue(storage.getItem(scrambleKey(key))); }; this.setItem = function (key, value) { storage.setItem(scrambleKey(key), encryptValue(value)); }; this.removeItem = function (key) { storage.removeItem(scrambleKey(key)); }; this.clear = function () { storage.clear(); }; getSecretKey(); }
[ "function", "ObfuscatingStorageWrapper", "(", "storage", ")", "{", "var", "SECRET_KEY_KEY", "=", "\"___XX\"", ";", "var", "wellKnownKey", "=", "\"ce56c9aa-d287-4e7c-b9d5-edca7a985487\"", ";", "function", "getSecretKey", "(", ")", "{", "var", "secretKeyName", "=", "scrambleKey", "(", "SECRET_KEY_KEY", ",", "wellKnownKey", ")", ";", "var", "secretKey", "=", "storage", ".", "getItem", "(", "secretKeyName", ")", ";", "if", "(", "secretKey", "===", "null", ")", "{", "secretKey", "=", "GuidGenerator", "(", ")", ";", "storage", ".", "setItem", "(", "secretKeyName", ",", "encryptValue", "(", "secretKey", ",", "wellKnownKey", ")", ")", ";", "}", "else", "{", "secretKey", "=", "decryptValue", "(", "secretKey", ",", "wellKnownKey", ")", ";", "}", "return", "secretKey", ";", "}", "function", "scrambleKey", "(", "key", ",", "encryptionKey", ")", "{", "return", "CryptoJS", ".", "HmacMD5", "(", "key", ",", "encryptionKey", "||", "getSecretKey", "(", ")", ")", ".", "toString", "(", ")", ";", "}", "function", "encryptValue", "(", "value", ",", "encryptionKey", ")", "{", "return", "CryptoJS", ".", "AES", ".", "encrypt", "(", "JSON", ".", "stringify", "(", "value", ")", ",", "encryptionKey", "||", "getSecretKey", "(", ")", ")", ".", "toString", "(", ")", ";", "}", "function", "decryptValue", "(", "value", ",", "encryptionKey", ")", "{", "if", "(", "value", "===", "null", ")", "{", "return", "null", ";", "}", "try", "{", "var", "decryptedValue", "=", "CryptoJS", ".", "AES", ".", "decrypt", "(", "value", ",", "encryptionKey", "||", "getSecretKey", "(", ")", ")", ".", "toString", "(", "CryptoJS", ".", "enc", ".", "Utf8", ")", ";", "return", "JSON", ".", "parse", "(", "decryptedValue", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "null", ";", "}", "}", "this", ".", "getItem", "=", "function", "(", "key", ")", "{", "return", "decryptValue", "(", "storage", ".", "getItem", "(", "scrambleKey", "(", "key", ")", ")", ")", ";", "}", ";", "this", ".", "setItem", "=", "function", "(", "key", ",", "value", ")", "{", "storage", ".", "setItem", "(", "scrambleKey", "(", "key", ")", ",", "encryptValue", "(", "value", ")", ")", ";", "}", ";", "this", ".", "removeItem", "=", "function", "(", "key", ")", "{", "storage", ".", "removeItem", "(", "scrambleKey", "(", "key", ")", ")", ";", "}", ";", "this", ".", "clear", "=", "function", "(", ")", "{", "storage", ".", "clear", "(", ")", ";", "}", ";", "getSecretKey", "(", ")", ";", "}" ]
You don't need to be a genius to break this "security" but it should slow tinkerers down a little @param GuidService @returns {{wrapStorage: Function}} @constructor
[ "You", "don", "t", "need", "to", "be", "a", "genius", "to", "break", "this", "security", "but", "it", "should", "slow", "tinkerers", "down", "a", "little" ]
04ee34984c9d5145e265a886bf261cb64dc20e3c
https://github.com/nicktindall/cyclon.p2p-common/blob/04ee34984c9d5145e265a886bf261cb64dc20e3c/lib/ObfuscatingStorageWrapper.js#L14-L70
55,272
the-simian/phaser-shim-loader
phaser-debug.js
phaserShimDebug
function phaserShimDebug(source) { this.cacheable && this.cacheable(); source = source.replace(/(var\s+ui\s*=\s*require\('\.\/util\/ui'\))/, 'var Phaser = _Phaser; $1'); source = '(function () { var _Phaser = require("phaser").Phaser;\n\n' + source + '\n\n}());'; return source; }
javascript
function phaserShimDebug(source) { this.cacheable && this.cacheable(); source = source.replace(/(var\s+ui\s*=\s*require\('\.\/util\/ui'\))/, 'var Phaser = _Phaser; $1'); source = '(function () { var _Phaser = require("phaser").Phaser;\n\n' + source + '\n\n}());'; return source; }
[ "function", "phaserShimDebug", "(", "source", ")", "{", "this", ".", "cacheable", "&&", "this", ".", "cacheable", "(", ")", ";", "source", "=", "source", ".", "replace", "(", "/", "(var\\s+ui\\s*=\\s*require\\('\\.\\/util\\/ui'\\))", "/", ",", "'var Phaser = _Phaser; $1'", ")", ";", "source", "=", "'(function () { var _Phaser = require(\"phaser\").Phaser;\\n\\n'", "+", "source", "+", "'\\n\\n}());'", ";", "return", "source", ";", "}" ]
phaser-debug-webpack-loader
[ "phaser", "-", "debug", "-", "webpack", "-", "loader" ]
ff22b8903de18d6d9eff1765722366892daf929a
https://github.com/the-simian/phaser-shim-loader/blob/ff22b8903de18d6d9eff1765722366892daf929a/phaser-debug.js#L4-L11
55,273
AndreasMadsen/steer-screenshot
steer-screenshot.js
retry
function retry(err) { if (currentAttempt >= retryCount) { return callback(err, null, currentAttempt); } currentAttempt += 1; // Since the currentAttempt starts at 1 and it was just incremented // currentAttempt - 2 will be the actual timeout index. return setTimeout(attempt, timeouts[currentAttempt - 2]); }
javascript
function retry(err) { if (currentAttempt >= retryCount) { return callback(err, null, currentAttempt); } currentAttempt += 1; // Since the currentAttempt starts at 1 and it was just incremented // currentAttempt - 2 will be the actual timeout index. return setTimeout(attempt, timeouts[currentAttempt - 2]); }
[ "function", "retry", "(", "err", ")", "{", "if", "(", "currentAttempt", ">=", "retryCount", ")", "{", "return", "callback", "(", "err", ",", "null", ",", "currentAttempt", ")", ";", "}", "currentAttempt", "+=", "1", ";", "// Since the currentAttempt starts at 1 and it was just incremented", "// currentAttempt - 2 will be the actual timeout index.", "return", "setTimeout", "(", "attempt", ",", "timeouts", "[", "currentAttempt", "-", "2", "]", ")", ";", "}" ]
The error is never null in this function call
[ "The", "error", "is", "never", "null", "in", "this", "function", "call" ]
7059be89f14b35e1e3f8eaadc0fff2ef0f749fa0
https://github.com/AndreasMadsen/steer-screenshot/blob/7059be89f14b35e1e3f8eaadc0fff2ef0f749fa0/steer-screenshot.js#L48-L58
55,274
cwebbdesign/component-maker
index.js
make
function make(component, config) { var Constructor, Subclass, conf = config || {}; // Config exists as a way to create pass a set of derived options. In the original use case a function was created // to parse the DOM and pass information to the component at the time of creation. // Allow the $el to be passed directly as part of component instead of with the configuration. if (component.$el && !conf.$el) { conf.$el = component.$el; } Constructor = Component.subclass(new ApiInstance()); if (!subclasses[component.name]) { // Cache initialized subclasses so we can reuse them with custom configuration. subclasses[component.name] = Constructor.subclass(component); } // Create the subclass constructor Subclass = subclasses[component.name].subclass(conf); // Return an instance return new Subclass(); }
javascript
function make(component, config) { var Constructor, Subclass, conf = config || {}; // Config exists as a way to create pass a set of derived options. In the original use case a function was created // to parse the DOM and pass information to the component at the time of creation. // Allow the $el to be passed directly as part of component instead of with the configuration. if (component.$el && !conf.$el) { conf.$el = component.$el; } Constructor = Component.subclass(new ApiInstance()); if (!subclasses[component.name]) { // Cache initialized subclasses so we can reuse them with custom configuration. subclasses[component.name] = Constructor.subclass(component); } // Create the subclass constructor Subclass = subclasses[component.name].subclass(conf); // Return an instance return new Subclass(); }
[ "function", "make", "(", "component", ",", "config", ")", "{", "var", "Constructor", ",", "Subclass", ",", "conf", "=", "config", "||", "{", "}", ";", "// Config exists as a way to create pass a set of derived options. In the original use case a function was created", "// to parse the DOM and pass information to the component at the time of creation.", "// Allow the $el to be passed directly as part of component instead of with the configuration.", "if", "(", "component", ".", "$el", "&&", "!", "conf", ".", "$el", ")", "{", "conf", ".", "$el", "=", "component", ".", "$el", ";", "}", "Constructor", "=", "Component", ".", "subclass", "(", "new", "ApiInstance", "(", ")", ")", ";", "if", "(", "!", "subclasses", "[", "component", ".", "name", "]", ")", "{", "// Cache initialized subclasses so we can reuse them with custom configuration.", "subclasses", "[", "component", ".", "name", "]", "=", "Constructor", ".", "subclass", "(", "component", ")", ";", "}", "// Create the subclass constructor", "Subclass", "=", "subclasses", "[", "component", ".", "name", "]", ".", "subclass", "(", "conf", ")", ";", "// Return an instance", "return", "new", "Subclass", "(", ")", ";", "}" ]
Important to note that the components which are initialized, inherit the same event emitter. this enables all components of the same type to listen to events. As the emitter is intended to listen to application level events, it makes sense to me that all instances would respond to the event
[ "Important", "to", "note", "that", "the", "components", "which", "are", "initialized", "inherit", "the", "same", "event", "emitter", ".", "this", "enables", "all", "components", "of", "the", "same", "type", "to", "listen", "to", "events", ".", "As", "the", "emitter", "is", "intended", "to", "listen", "to", "application", "level", "events", "it", "makes", "sense", "to", "me", "that", "all", "instances", "would", "respond", "to", "the", "event" ]
1b4edafd3090f2f6e42d61a8d612b9ef791fcab2
https://github.com/cwebbdesign/component-maker/blob/1b4edafd3090f2f6e42d61a8d612b9ef791fcab2/index.js#L191-L216
55,275
fastest963/DelimiterStream
DelimiterStream.js
emitEvents
function emitEvents(stream) { //if emitEvents gets called while in emitEvents we don't want to screw up the order if (stream._emittingMatches) { return; } var matches = stream.matches, i = matches.length; stream.matches = []; stream._emittingMatches = true; while (i--) { stream.emit('data', matches[i]); } stream._emittingMatches = false; //test to see if someone tried to emit events within emitting events if (stream.emitEvents && stream.matches[0] !== undefined) { emitEvents(stream); } }
javascript
function emitEvents(stream) { //if emitEvents gets called while in emitEvents we don't want to screw up the order if (stream._emittingMatches) { return; } var matches = stream.matches, i = matches.length; stream.matches = []; stream._emittingMatches = true; while (i--) { stream.emit('data', matches[i]); } stream._emittingMatches = false; //test to see if someone tried to emit events within emitting events if (stream.emitEvents && stream.matches[0] !== undefined) { emitEvents(stream); } }
[ "function", "emitEvents", "(", "stream", ")", "{", "//if emitEvents gets called while in emitEvents we don't want to screw up the order", "if", "(", "stream", ".", "_emittingMatches", ")", "{", "return", ";", "}", "var", "matches", "=", "stream", ".", "matches", ",", "i", "=", "matches", ".", "length", ";", "stream", ".", "matches", "=", "[", "]", ";", "stream", ".", "_emittingMatches", "=", "true", ";", "while", "(", "i", "--", ")", "{", "stream", ".", "emit", "(", "'data'", ",", "matches", "[", "i", "]", ")", ";", "}", "stream", ".", "_emittingMatches", "=", "false", ";", "//test to see if someone tried to emit events within emitting events", "if", "(", "stream", ".", "emitEvents", "&&", "stream", ".", "matches", "[", "0", "]", "!==", "undefined", ")", "{", "emitEvents", "(", "stream", ")", ";", "}", "}" ]
Emit "data" events for each match
[ "Emit", "data", "events", "for", "each", "match" ]
1e31f16efca182d5e0d1eb04bce4740af8d2746e
https://github.com/fastest963/DelimiterStream/blob/1e31f16efca182d5e0d1eb04bce4740af8d2746e/DelimiterStream.js#L37-L55
55,276
fastest963/DelimiterStream
DelimiterStream.js
handleData
function handleData(stream, asString, data, dataLimit) { var dataLen = data.length, i = dataLen, trailingDataIndex = -1, //index of data after the last delimiter match in data lastMatchIndex = 0, matchLimit = dataLimit || Infinity, len = 0; //first start going back through data to find the last match //we do this loop separately so we can just store the index of the last match and then add that to the buffer at the end for the next packet while (i--) { if (data[i] === stream.delimiter) { //now that we found the match, store the index (+1 so we don't store the delimiter) trailingDataIndex = i + 1; break; } } //if we didn't find a match at all, just push the data onto the buffer if (trailingDataIndex === -1) { //don't use dataLimit here since we shouldn't pass in infinity to concatBuffer stream.buffer = concatBuffer(stream.buffer, data, dataLimit); return; } lastMatchIndex = i; while (i--) { if (data[i] === stream.delimiter) { //make sure we ignore back-to-back delimiters len = lastMatchIndex - (i + 1); //i + 1 so we don't include the delimiter we just matched if (len > matchLimit) { stream.matches.push(data.slice(lastMatchIndex - matchLimit, lastMatchIndex)); } else if (len > 0) { stream.matches.push(data.slice(i + 1, lastMatchIndex)); } lastMatchIndex = i; } } //since the loop stops at the beginning of data we need to store the bytes before the first match in the string if (lastMatchIndex > 0) { stream.buffer = concatBuffer(stream.buffer, data.slice(0, lastMatchIndex), dataLimit); } //add the leftover buffer to the matches at the end (beginning when we emit events) if (asString) { if (isNode) { stream.matches.push(stream.buffer.toString()); stream.buffer = new BUFFER_CONSTRUCTOR(0); } else { stream.matches.push(stream.buffer.splice(0, stream.buffer.length).join('')); } } else { stream.matches.push(stream.buffer); stream.buffer = new BUFFER_CONSTRUCTOR(0); } //todo: optimize this to not make an empty buffer just to fill it with a new thing immediately after //make sure the lastMatchIndex isn't the end if (lastMatchIndex < dataLen) { //don't use dataLimit here since we shouldn't pass in infinity to concatBuffer stream.buffer = concatBuffer(stream.buffer, data.slice(trailingDataIndex), dataLimit); } if (stream.emitEvents) { emitEvents(stream); } }
javascript
function handleData(stream, asString, data, dataLimit) { var dataLen = data.length, i = dataLen, trailingDataIndex = -1, //index of data after the last delimiter match in data lastMatchIndex = 0, matchLimit = dataLimit || Infinity, len = 0; //first start going back through data to find the last match //we do this loop separately so we can just store the index of the last match and then add that to the buffer at the end for the next packet while (i--) { if (data[i] === stream.delimiter) { //now that we found the match, store the index (+1 so we don't store the delimiter) trailingDataIndex = i + 1; break; } } //if we didn't find a match at all, just push the data onto the buffer if (trailingDataIndex === -1) { //don't use dataLimit here since we shouldn't pass in infinity to concatBuffer stream.buffer = concatBuffer(stream.buffer, data, dataLimit); return; } lastMatchIndex = i; while (i--) { if (data[i] === stream.delimiter) { //make sure we ignore back-to-back delimiters len = lastMatchIndex - (i + 1); //i + 1 so we don't include the delimiter we just matched if (len > matchLimit) { stream.matches.push(data.slice(lastMatchIndex - matchLimit, lastMatchIndex)); } else if (len > 0) { stream.matches.push(data.slice(i + 1, lastMatchIndex)); } lastMatchIndex = i; } } //since the loop stops at the beginning of data we need to store the bytes before the first match in the string if (lastMatchIndex > 0) { stream.buffer = concatBuffer(stream.buffer, data.slice(0, lastMatchIndex), dataLimit); } //add the leftover buffer to the matches at the end (beginning when we emit events) if (asString) { if (isNode) { stream.matches.push(stream.buffer.toString()); stream.buffer = new BUFFER_CONSTRUCTOR(0); } else { stream.matches.push(stream.buffer.splice(0, stream.buffer.length).join('')); } } else { stream.matches.push(stream.buffer); stream.buffer = new BUFFER_CONSTRUCTOR(0); } //todo: optimize this to not make an empty buffer just to fill it with a new thing immediately after //make sure the lastMatchIndex isn't the end if (lastMatchIndex < dataLen) { //don't use dataLimit here since we shouldn't pass in infinity to concatBuffer stream.buffer = concatBuffer(stream.buffer, data.slice(trailingDataIndex), dataLimit); } if (stream.emitEvents) { emitEvents(stream); } }
[ "function", "handleData", "(", "stream", ",", "asString", ",", "data", ",", "dataLimit", ")", "{", "var", "dataLen", "=", "data", ".", "length", ",", "i", "=", "dataLen", ",", "trailingDataIndex", "=", "-", "1", ",", "//index of data after the last delimiter match in data", "lastMatchIndex", "=", "0", ",", "matchLimit", "=", "dataLimit", "||", "Infinity", ",", "len", "=", "0", ";", "//first start going back through data to find the last match", "//we do this loop separately so we can just store the index of the last match and then add that to the buffer at the end for the next packet", "while", "(", "i", "--", ")", "{", "if", "(", "data", "[", "i", "]", "===", "stream", ".", "delimiter", ")", "{", "//now that we found the match, store the index (+1 so we don't store the delimiter)", "trailingDataIndex", "=", "i", "+", "1", ";", "break", ";", "}", "}", "//if we didn't find a match at all, just push the data onto the buffer", "if", "(", "trailingDataIndex", "===", "-", "1", ")", "{", "//don't use dataLimit here since we shouldn't pass in infinity to concatBuffer", "stream", ".", "buffer", "=", "concatBuffer", "(", "stream", ".", "buffer", ",", "data", ",", "dataLimit", ")", ";", "return", ";", "}", "lastMatchIndex", "=", "i", ";", "while", "(", "i", "--", ")", "{", "if", "(", "data", "[", "i", "]", "===", "stream", ".", "delimiter", ")", "{", "//make sure we ignore back-to-back delimiters", "len", "=", "lastMatchIndex", "-", "(", "i", "+", "1", ")", ";", "//i + 1 so we don't include the delimiter we just matched", "if", "(", "len", ">", "matchLimit", ")", "{", "stream", ".", "matches", ".", "push", "(", "data", ".", "slice", "(", "lastMatchIndex", "-", "matchLimit", ",", "lastMatchIndex", ")", ")", ";", "}", "else", "if", "(", "len", ">", "0", ")", "{", "stream", ".", "matches", ".", "push", "(", "data", ".", "slice", "(", "i", "+", "1", ",", "lastMatchIndex", ")", ")", ";", "}", "lastMatchIndex", "=", "i", ";", "}", "}", "//since the loop stops at the beginning of data we need to store the bytes before the first match in the string", "if", "(", "lastMatchIndex", ">", "0", ")", "{", "stream", ".", "buffer", "=", "concatBuffer", "(", "stream", ".", "buffer", ",", "data", ".", "slice", "(", "0", ",", "lastMatchIndex", ")", ",", "dataLimit", ")", ";", "}", "//add the leftover buffer to the matches at the end (beginning when we emit events)", "if", "(", "asString", ")", "{", "if", "(", "isNode", ")", "{", "stream", ".", "matches", ".", "push", "(", "stream", ".", "buffer", ".", "toString", "(", ")", ")", ";", "stream", ".", "buffer", "=", "new", "BUFFER_CONSTRUCTOR", "(", "0", ")", ";", "}", "else", "{", "stream", ".", "matches", ".", "push", "(", "stream", ".", "buffer", ".", "splice", "(", "0", ",", "stream", ".", "buffer", ".", "length", ")", ".", "join", "(", "''", ")", ")", ";", "}", "}", "else", "{", "stream", ".", "matches", ".", "push", "(", "stream", ".", "buffer", ")", ";", "stream", ".", "buffer", "=", "new", "BUFFER_CONSTRUCTOR", "(", "0", ")", ";", "}", "//todo: optimize this to not make an empty buffer just to fill it with a new thing immediately after", "//make sure the lastMatchIndex isn't the end", "if", "(", "lastMatchIndex", "<", "dataLen", ")", "{", "//don't use dataLimit here since we shouldn't pass in infinity to concatBuffer", "stream", ".", "buffer", "=", "concatBuffer", "(", "stream", ".", "buffer", ",", "data", ".", "slice", "(", "trailingDataIndex", ")", ",", "dataLimit", ")", ";", "}", "if", "(", "stream", ".", "emitEvents", ")", "{", "emitEvents", "(", "stream", ")", ";", "}", "}" ]
Handle data from a string stream
[ "Handle", "data", "from", "a", "string", "stream" ]
1e31f16efca182d5e0d1eb04bce4740af8d2746e
https://github.com/fastest963/DelimiterStream/blob/1e31f16efca182d5e0d1eb04bce4740af8d2746e/DelimiterStream.js#L60-L124
55,277
nachos/nachos-api
lib/api/settings/index.js
function (pkg, options) { var settingsFile = new SettingsFile(pkg, options); var save = settingsFile.save; settingsFile.save = _.bind(function (config) { return save.call(settingsFile, config) .then(function () { client.emit('config.global-changed', { app: pkg, config: config }); }); }, settingsFile); var settingsSet = settingsFile.set; settingsFile.set = _.bind(function (config) { return settingsSet.call(settingsFile, config) .then(function () { client.emit('config.global-changed', { app: pkg, config: config }); }); }, settingsFile); /** * Register for global settings changes * * @param {function} cb Event callback */ settingsFile.onChange = function (cb) { client.on('settings.global-changed:' + pkg, cb); }; var instance = settingsFile.instance; settingsFile.instance = _.bind(function (id) { var returnedInstance = instance.call(settingsFile, id); var save = returnedInstance.save; returnedInstance.save = _.bind(function (config) { return save.call(returnedInstance, config) .then(function () { client.emit('settings.instance-changed:' + returnedInstance._id, { instance: returnedInstance._id, config: config }); }); }, returnedInstance); var instanceSet = returnedInstance.set; returnedInstance.set = _.bind(function (config) { return instanceSet.call(returnedInstance, config) .then(function () { client.emit('settings.instance-changed:' + returnedInstance._id, { instance: returnedInstance._id, config: config }); }); }, returnedInstance); /** * Register for instance settings changes * * @param {function} cb Event callback */ returnedInstance.onChange = function (cb) { client.on('settings.instance-changed:' + returnedInstance._id, cb); }; return returnedInstance; }, settingsFile); return settingsFile; }
javascript
function (pkg, options) { var settingsFile = new SettingsFile(pkg, options); var save = settingsFile.save; settingsFile.save = _.bind(function (config) { return save.call(settingsFile, config) .then(function () { client.emit('config.global-changed', { app: pkg, config: config }); }); }, settingsFile); var settingsSet = settingsFile.set; settingsFile.set = _.bind(function (config) { return settingsSet.call(settingsFile, config) .then(function () { client.emit('config.global-changed', { app: pkg, config: config }); }); }, settingsFile); /** * Register for global settings changes * * @param {function} cb Event callback */ settingsFile.onChange = function (cb) { client.on('settings.global-changed:' + pkg, cb); }; var instance = settingsFile.instance; settingsFile.instance = _.bind(function (id) { var returnedInstance = instance.call(settingsFile, id); var save = returnedInstance.save; returnedInstance.save = _.bind(function (config) { return save.call(returnedInstance, config) .then(function () { client.emit('settings.instance-changed:' + returnedInstance._id, { instance: returnedInstance._id, config: config }); }); }, returnedInstance); var instanceSet = returnedInstance.set; returnedInstance.set = _.bind(function (config) { return instanceSet.call(returnedInstance, config) .then(function () { client.emit('settings.instance-changed:' + returnedInstance._id, { instance: returnedInstance._id, config: config }); }); }, returnedInstance); /** * Register for instance settings changes * * @param {function} cb Event callback */ returnedInstance.onChange = function (cb) { client.on('settings.instance-changed:' + returnedInstance._id, cb); }; return returnedInstance; }, settingsFile); return settingsFile; }
[ "function", "(", "pkg", ",", "options", ")", "{", "var", "settingsFile", "=", "new", "SettingsFile", "(", "pkg", ",", "options", ")", ";", "var", "save", "=", "settingsFile", ".", "save", ";", "settingsFile", ".", "save", "=", "_", ".", "bind", "(", "function", "(", "config", ")", "{", "return", "save", ".", "call", "(", "settingsFile", ",", "config", ")", ".", "then", "(", "function", "(", ")", "{", "client", ".", "emit", "(", "'config.global-changed'", ",", "{", "app", ":", "pkg", ",", "config", ":", "config", "}", ")", ";", "}", ")", ";", "}", ",", "settingsFile", ")", ";", "var", "settingsSet", "=", "settingsFile", ".", "set", ";", "settingsFile", ".", "set", "=", "_", ".", "bind", "(", "function", "(", "config", ")", "{", "return", "settingsSet", ".", "call", "(", "settingsFile", ",", "config", ")", ".", "then", "(", "function", "(", ")", "{", "client", ".", "emit", "(", "'config.global-changed'", ",", "{", "app", ":", "pkg", ",", "config", ":", "config", "}", ")", ";", "}", ")", ";", "}", ",", "settingsFile", ")", ";", "/**\n * Register for global settings changes\n *\n * @param {function} cb Event callback\n */", "settingsFile", ".", "onChange", "=", "function", "(", "cb", ")", "{", "client", ".", "on", "(", "'settings.global-changed:'", "+", "pkg", ",", "cb", ")", ";", "}", ";", "var", "instance", "=", "settingsFile", ".", "instance", ";", "settingsFile", ".", "instance", "=", "_", ".", "bind", "(", "function", "(", "id", ")", "{", "var", "returnedInstance", "=", "instance", ".", "call", "(", "settingsFile", ",", "id", ")", ";", "var", "save", "=", "returnedInstance", ".", "save", ";", "returnedInstance", ".", "save", "=", "_", ".", "bind", "(", "function", "(", "config", ")", "{", "return", "save", ".", "call", "(", "returnedInstance", ",", "config", ")", ".", "then", "(", "function", "(", ")", "{", "client", ".", "emit", "(", "'settings.instance-changed:'", "+", "returnedInstance", ".", "_id", ",", "{", "instance", ":", "returnedInstance", ".", "_id", ",", "config", ":", "config", "}", ")", ";", "}", ")", ";", "}", ",", "returnedInstance", ")", ";", "var", "instanceSet", "=", "returnedInstance", ".", "set", ";", "returnedInstance", ".", "set", "=", "_", ".", "bind", "(", "function", "(", "config", ")", "{", "return", "instanceSet", ".", "call", "(", "returnedInstance", ",", "config", ")", ".", "then", "(", "function", "(", ")", "{", "client", ".", "emit", "(", "'settings.instance-changed:'", "+", "returnedInstance", ".", "_id", ",", "{", "instance", ":", "returnedInstance", ".", "_id", ",", "config", ":", "config", "}", ")", ";", "}", ")", ";", "}", ",", "returnedInstance", ")", ";", "/**\n * Register for instance settings changes\n *\n * @param {function} cb Event callback\n */", "returnedInstance", ".", "onChange", "=", "function", "(", "cb", ")", "{", "client", ".", "on", "(", "'settings.instance-changed:'", "+", "returnedInstance", ".", "_id", ",", "cb", ")", ";", "}", ";", "return", "returnedInstance", ";", "}", ",", "settingsFile", ")", ";", "return", "settingsFile", ";", "}" ]
Build a wrapped instance of settings file @param {string} pkg Package name @param {object} options Default settings of the package @returns {SettingsFile} Wrapped settings file
[ "Build", "a", "wrapped", "instance", "of", "settings", "file" ]
a0f4633967fab37a1ab1066a053f31563b303c4e
https://github.com/nachos/nachos-api/blob/a0f4633967fab37a1ab1066a053f31563b303c4e/lib/api/settings/index.js#L15-L93
55,278
patgrasso/parsey
lib/rules.js
Rule
function Rule(lhs, rhs, valuator) { let arr = []; if (!rhs || rhs.length === 0) { throw new Error('Rule does not produce anything'); } arr.push.apply(arr, rhs); arr.lhs = lhs; Object.defineProperty(arr, 'lhs', { value: lhs }); Object.defineProperty(arr, 'evaluate', { value: (values) => (valuator) ? valuator.apply(null, values) : null }); arr.__proto__ = Rule.prototype; return arr; }
javascript
function Rule(lhs, rhs, valuator) { let arr = []; if (!rhs || rhs.length === 0) { throw new Error('Rule does not produce anything'); } arr.push.apply(arr, rhs); arr.lhs = lhs; Object.defineProperty(arr, 'lhs', { value: lhs }); Object.defineProperty(arr, 'evaluate', { value: (values) => (valuator) ? valuator.apply(null, values) : null }); arr.__proto__ = Rule.prototype; return arr; }
[ "function", "Rule", "(", "lhs", ",", "rhs", ",", "valuator", ")", "{", "let", "arr", "=", "[", "]", ";", "if", "(", "!", "rhs", "||", "rhs", ".", "length", "===", "0", ")", "{", "throw", "new", "Error", "(", "'Rule does not produce anything'", ")", ";", "}", "arr", ".", "push", ".", "apply", "(", "arr", ",", "rhs", ")", ";", "arr", ".", "lhs", "=", "lhs", ";", "Object", ".", "defineProperty", "(", "arr", ",", "'lhs'", ",", "{", "value", ":", "lhs", "}", ")", ";", "Object", ".", "defineProperty", "(", "arr", ",", "'evaluate'", ",", "{", "value", ":", "(", "values", ")", "=>", "(", "valuator", ")", "?", "valuator", ".", "apply", "(", "null", ",", "values", ")", ":", "null", "}", ")", ";", "arr", ".", "__proto__", "=", "Rule", ".", "prototype", ";", "return", "arr", ";", "}" ]
Defines a production rule, with a sole symbol on the left-hand side and a list of symbols on the right-hand side. The constructor also accepts a third argument, a valuator function, which can be used to evaluate values that are obtained by matching this production @class Rule @extends Array @constructor @memberof module:lib/rules @param {Sym} lhs - Sym representing the left hand side of the production @param {Array.<Sym|string|RegExp>} rhs - Sequence of Syms, plain strings, or RegExp objects that represents the right hand side of the production @param {Function=} valuator - Function used to evaluate values obtained by matching this production
[ "Defines", "a", "production", "rule", "with", "a", "sole", "symbol", "on", "the", "left", "-", "hand", "side", "and", "a", "list", "of", "symbols", "on", "the", "right", "-", "hand", "side", ".", "The", "constructor", "also", "accepts", "a", "third", "argument", "a", "valuator", "function", "which", "can", "be", "used", "to", "evaluate", "values", "that", "are", "obtained", "by", "matching", "this", "production" ]
d28b3f330ee03b5c273f1ce5871a5b86dac79fb0
https://github.com/patgrasso/parsey/blob/d28b3f330ee03b5c273f1ce5871a5b86dac79fb0/lib/rules.js#L26-L43
55,279
patgrasso/parsey
lib/rules.js
Sym
function Sym(name) { let symbol = {}; symbol.__proto__ = Sym.prototype; symbol.name = name; return symbol; }
javascript
function Sym(name) { let symbol = {}; symbol.__proto__ = Sym.prototype; symbol.name = name; return symbol; }
[ "function", "Sym", "(", "name", ")", "{", "let", "symbol", "=", "{", "}", ";", "symbol", ".", "__proto__", "=", "Sym", ".", "prototype", ";", "symbol", ".", "name", "=", "name", ";", "return", "symbol", ";", "}" ]
Constructor for the Sym class, which simply represents a non-terminal symbol in a grammar. While parsing, Syms are compared by reference, not by name. So, the name argument is optional as it serves no purpose for parsing. For debugging and evaluation of a parse tree, however, the name could be quite useful @class Sym @constructor @memberof module:lib/rules @param {string=} name - Name to give to the newly created symbol. Names do not need to be unique among Syms in a grammar, as they are not used to compare equality
[ "Constructor", "for", "the", "Sym", "class", "which", "simply", "represents", "a", "non", "-", "terminal", "symbol", "in", "a", "grammar", ".", "While", "parsing", "Syms", "are", "compared", "by", "reference", "not", "by", "name", ".", "So", "the", "name", "argument", "is", "optional", "as", "it", "serves", "no", "purpose", "for", "parsing", ".", "For", "debugging", "and", "evaluation", "of", "a", "parse", "tree", "however", "the", "name", "could", "be", "quite", "useful" ]
d28b3f330ee03b5c273f1ce5871a5b86dac79fb0
https://github.com/patgrasso/parsey/blob/d28b3f330ee03b5c273f1ce5871a5b86dac79fb0/lib/rules.js#L61-L66
55,280
substance/commander
src/keyboard.js
_getMatches
function _getMatches(character, modifiers, e, sequenceName, combination, level) { var i, callback, matches = [], action = e.type; // if there are no events related to this keycode if (!this._callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < this._callbacks[character].length; ++i) { callback = this._callbacks[character][i]; // if a sequence name is not specified, but this is a sequence at // the wrong level then move onto the next match if (!sequenceName && callback.seq && this._sequenceLevels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event and the meta key and control key // are not pressed that means that we need to only look at the // character, otherwise check the modifiers as well // // chrome will not fire a keypress if meta or control is down // safari will fire a keypress if meta or meta+shift is down // firefox will fire a keypress if meta or control is down if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) { // when you bind a combination or sequence a second time it // should overwrite the first one. if a sequenceName or // combination is specified in this call it does just that // // @todo make deleting its own method? var deleteCombo = !sequenceName && callback.combo == combination; var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level; if (deleteCombo || deleteSequence) { this._callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; }
javascript
function _getMatches(character, modifiers, e, sequenceName, combination, level) { var i, callback, matches = [], action = e.type; // if there are no events related to this keycode if (!this._callbacks[character]) { return []; } // if a modifier key is coming up on its own we should allow it if (action == 'keyup' && _isModifier(character)) { modifiers = [character]; } // loop through all callbacks for the key that was pressed // and see if any of them match for (i = 0; i < this._callbacks[character].length; ++i) { callback = this._callbacks[character][i]; // if a sequence name is not specified, but this is a sequence at // the wrong level then move onto the next match if (!sequenceName && callback.seq && this._sequenceLevels[callback.seq] != callback.level) { continue; } // if the action we are looking for doesn't match the action we got // then we should keep going if (action != callback.action) { continue; } // if this is a keypress event and the meta key and control key // are not pressed that means that we need to only look at the // character, otherwise check the modifiers as well // // chrome will not fire a keypress if meta or control is down // safari will fire a keypress if meta or meta+shift is down // firefox will fire a keypress if meta or control is down if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) { // when you bind a combination or sequence a second time it // should overwrite the first one. if a sequenceName or // combination is specified in this call it does just that // // @todo make deleting its own method? var deleteCombo = !sequenceName && callback.combo == combination; var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level; if (deleteCombo || deleteSequence) { this._callbacks[character].splice(i, 1); } matches.push(callback); } } return matches; }
[ "function", "_getMatches", "(", "character", ",", "modifiers", ",", "e", ",", "sequenceName", ",", "combination", ",", "level", ")", "{", "var", "i", ",", "callback", ",", "matches", "=", "[", "]", ",", "action", "=", "e", ".", "type", ";", "// if there are no events related to this keycode", "if", "(", "!", "this", ".", "_callbacks", "[", "character", "]", ")", "{", "return", "[", "]", ";", "}", "// if a modifier key is coming up on its own we should allow it", "if", "(", "action", "==", "'keyup'", "&&", "_isModifier", "(", "character", ")", ")", "{", "modifiers", "=", "[", "character", "]", ";", "}", "// loop through all callbacks for the key that was pressed", "// and see if any of them match", "for", "(", "i", "=", "0", ";", "i", "<", "this", ".", "_callbacks", "[", "character", "]", ".", "length", ";", "++", "i", ")", "{", "callback", "=", "this", ".", "_callbacks", "[", "character", "]", "[", "i", "]", ";", "// if a sequence name is not specified, but this is a sequence at", "// the wrong level then move onto the next match", "if", "(", "!", "sequenceName", "&&", "callback", ".", "seq", "&&", "this", ".", "_sequenceLevels", "[", "callback", ".", "seq", "]", "!=", "callback", ".", "level", ")", "{", "continue", ";", "}", "// if the action we are looking for doesn't match the action we got", "// then we should keep going", "if", "(", "action", "!=", "callback", ".", "action", ")", "{", "continue", ";", "}", "// if this is a keypress event and the meta key and control key", "// are not pressed that means that we need to only look at the", "// character, otherwise check the modifiers as well", "//", "// chrome will not fire a keypress if meta or control is down", "// safari will fire a keypress if meta or meta+shift is down", "// firefox will fire a keypress if meta or control is down", "if", "(", "(", "action", "==", "'keypress'", "&&", "!", "e", ".", "metaKey", "&&", "!", "e", ".", "ctrlKey", ")", "||", "_modifiersMatch", "(", "modifiers", ",", "callback", ".", "modifiers", ")", ")", "{", "// when you bind a combination or sequence a second time it", "// should overwrite the first one. if a sequenceName or", "// combination is specified in this call it does just that", "//", "// @todo make deleting its own method?", "var", "deleteCombo", "=", "!", "sequenceName", "&&", "callback", ".", "combo", "==", "combination", ";", "var", "deleteSequence", "=", "sequenceName", "&&", "callback", ".", "seq", "==", "sequenceName", "&&", "callback", ".", "level", "==", "level", ";", "if", "(", "deleteCombo", "||", "deleteSequence", ")", "{", "this", ".", "_callbacks", "[", "character", "]", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "matches", ".", "push", "(", "callback", ")", ";", "}", "}", "return", "matches", ";", "}" ]
finds all callbacks that match based on the keycode, modifiers, and action @param {string} character @param {Array} modifiers @param {Event|Object} e @param {string=} sequenceName - name of the sequence we are looking for @param {string=} combination @param {number=} level @returns {Array}
[ "finds", "all", "callbacks", "that", "match", "based", "on", "the", "keycode", "modifiers", "and", "action" ]
c16d22056d1cc4e1f190bd2084af6bd241c76197
https://github.com/substance/commander/blob/c16d22056d1cc4e1f190bd2084af6bd241c76197/src/keyboard.js#L369-L427
55,281
substance/commander
src/keyboard.js
_getReverseMap
function _getReverseMap() { if (!this._REVERSE_MAP) { this._REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { this._REVERSE_MAP[_MAP[key]] = key; } } } return this._REVERSE_MAP; }
javascript
function _getReverseMap() { if (!this._REVERSE_MAP) { this._REVERSE_MAP = {}; for (var key in _MAP) { // pull out the numeric keypad from here cause keypress should // be able to detect the keys from the character if (key > 95 && key < 112) { continue; } if (_MAP.hasOwnProperty(key)) { this._REVERSE_MAP[_MAP[key]] = key; } } } return this._REVERSE_MAP; }
[ "function", "_getReverseMap", "(", ")", "{", "if", "(", "!", "this", ".", "_REVERSE_MAP", ")", "{", "this", ".", "_REVERSE_MAP", "=", "{", "}", ";", "for", "(", "var", "key", "in", "_MAP", ")", "{", "// pull out the numeric keypad from here cause keypress should", "// be able to detect the keys from the character", "if", "(", "key", ">", "95", "&&", "key", "<", "112", ")", "{", "continue", ";", "}", "if", "(", "_MAP", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "this", ".", "_REVERSE_MAP", "[", "_MAP", "[", "key", "]", "]", "=", "key", ";", "}", "}", "}", "return", "this", ".", "_REVERSE_MAP", ";", "}" ]
reverses the map lookup so that we can look for specific keys to see what can and can't use keypress @return {Object}
[ "reverses", "the", "map", "lookup", "so", "that", "we", "can", "look", "for", "specific", "keys", "to", "see", "what", "can", "and", "can", "t", "use", "keypress" ]
c16d22056d1cc4e1f190bd2084af6bd241c76197
https://github.com/substance/commander/blob/c16d22056d1cc4e1f190bd2084af6bd241c76197/src/keyboard.js#L723-L740
55,282
substance/commander
src/keyboard.js
_bindSequence
function _bindSequence(combo, keys, callback, action) { var that = this; // start off by adding a sequence level record for this combination // and setting the level to 0 this._sequenceLevels[combo] = 0; /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {string} nextAction * @returns {Function} */ function _increaseSequence(nextAction) { return function() { that._nextExpectedAction = nextAction; ++that._sequenceLevels[combo]; _resetSequenceTimer.call(that); }; } /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ function _callbackAndReset(e) { _fireCallback.call(this, callback, e, combo); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { this._ignoreNextKeyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences.bind(this), 10); } // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences // // if an action is specified in the original bind call then that will // be used throughout. otherwise we will pass the action that the // next key in the sequence should match. this allows a sequence // to mix and match keypress and keydown events depending on which // ones are better suited to the key provided for (var i = 0; i < keys.length; ++i) { var isFinal = i + 1 === keys.length; var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence.call(this, action || _getKeyInfo(keys[i + 1]).action); _bindSingle.call(this, keys[i], wrappedCallback, action, combo, i); } }
javascript
function _bindSequence(combo, keys, callback, action) { var that = this; // start off by adding a sequence level record for this combination // and setting the level to 0 this._sequenceLevels[combo] = 0; /** * callback to increase the sequence level for this sequence and reset * all other sequences that were active * * @param {string} nextAction * @returns {Function} */ function _increaseSequence(nextAction) { return function() { that._nextExpectedAction = nextAction; ++that._sequenceLevels[combo]; _resetSequenceTimer.call(that); }; } /** * wraps the specified callback inside of another function in order * to reset all sequence counters as soon as this sequence is done * * @param {Event} e * @returns void */ function _callbackAndReset(e) { _fireCallback.call(this, callback, e, combo); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { this._ignoreNextKeyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences.bind(this), 10); } // loop through keys one at a time and bind the appropriate callback // function. for any key leading up to the final one it should // increase the sequence. after the final, it should reset all sequences // // if an action is specified in the original bind call then that will // be used throughout. otherwise we will pass the action that the // next key in the sequence should match. this allows a sequence // to mix and match keypress and keydown events depending on which // ones are better suited to the key provided for (var i = 0; i < keys.length; ++i) { var isFinal = i + 1 === keys.length; var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence.call(this, action || _getKeyInfo(keys[i + 1]).action); _bindSingle.call(this, keys[i], wrappedCallback, action, combo, i); } }
[ "function", "_bindSequence", "(", "combo", ",", "keys", ",", "callback", ",", "action", ")", "{", "var", "that", "=", "this", ";", "// start off by adding a sequence level record for this combination", "// and setting the level to 0", "this", ".", "_sequenceLevels", "[", "combo", "]", "=", "0", ";", "/**\n * callback to increase the sequence level for this sequence and reset\n * all other sequences that were active\n *\n * @param {string} nextAction\n * @returns {Function}\n */", "function", "_increaseSequence", "(", "nextAction", ")", "{", "return", "function", "(", ")", "{", "that", ".", "_nextExpectedAction", "=", "nextAction", ";", "++", "that", ".", "_sequenceLevels", "[", "combo", "]", ";", "_resetSequenceTimer", ".", "call", "(", "that", ")", ";", "}", ";", "}", "/**\n * wraps the specified callback inside of another function in order\n * to reset all sequence counters as soon as this sequence is done\n *\n * @param {Event} e\n * @returns void\n */", "function", "_callbackAndReset", "(", "e", ")", "{", "_fireCallback", ".", "call", "(", "this", ",", "callback", ",", "e", ",", "combo", ")", ";", "// we should ignore the next key up if the action is key down", "// or keypress. this is so if you finish a sequence and", "// release the key the final key will not trigger a keyup", "if", "(", "action", "!==", "'keyup'", ")", "{", "this", ".", "_ignoreNextKeyup", "=", "_characterFromEvent", "(", "e", ")", ";", "}", "// weird race condition if a sequence ends with the key", "// another sequence begins with", "setTimeout", "(", "_resetSequences", ".", "bind", "(", "this", ")", ",", "10", ")", ";", "}", "// loop through keys one at a time and bind the appropriate callback", "// function. for any key leading up to the final one it should", "// increase the sequence. after the final, it should reset all sequences", "//", "// if an action is specified in the original bind call then that will", "// be used throughout. otherwise we will pass the action that the", "// next key in the sequence should match. this allows a sequence", "// to mix and match keypress and keydown events depending on which", "// ones are better suited to the key provided", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "{", "var", "isFinal", "=", "i", "+", "1", "===", "keys", ".", "length", ";", "var", "wrappedCallback", "=", "isFinal", "?", "_callbackAndReset", ":", "_increaseSequence", ".", "call", "(", "this", ",", "action", "||", "_getKeyInfo", "(", "keys", "[", "i", "+", "1", "]", ")", ".", "action", ")", ";", "_bindSingle", ".", "call", "(", "this", ",", "keys", "[", "i", "]", ",", "wrappedCallback", ",", "action", ",", "combo", ",", "i", ")", ";", "}", "}" ]
binds a key sequence to an event @param {string} combo - combo specified in bind call @param {Array} keys @param {Function} callback @param {string=} action @returns void
[ "binds", "a", "key", "sequence", "to", "an", "event" ]
c16d22056d1cc4e1f190bd2084af6bd241c76197
https://github.com/substance/commander/blob/c16d22056d1cc4e1f190bd2084af6bd241c76197/src/keyboard.js#L775-L834
55,283
substance/commander
src/keyboard.js
_increaseSequence
function _increaseSequence(nextAction) { return function() { that._nextExpectedAction = nextAction; ++that._sequenceLevels[combo]; _resetSequenceTimer.call(that); }; }
javascript
function _increaseSequence(nextAction) { return function() { that._nextExpectedAction = nextAction; ++that._sequenceLevels[combo]; _resetSequenceTimer.call(that); }; }
[ "function", "_increaseSequence", "(", "nextAction", ")", "{", "return", "function", "(", ")", "{", "that", ".", "_nextExpectedAction", "=", "nextAction", ";", "++", "that", ".", "_sequenceLevels", "[", "combo", "]", ";", "_resetSequenceTimer", ".", "call", "(", "that", ")", ";", "}", ";", "}" ]
callback to increase the sequence level for this sequence and reset all other sequences that were active @param {string} nextAction @returns {Function}
[ "callback", "to", "increase", "the", "sequence", "level", "for", "this", "sequence", "and", "reset", "all", "other", "sequences", "that", "were", "active" ]
c16d22056d1cc4e1f190bd2084af6bd241c76197
https://github.com/substance/commander/blob/c16d22056d1cc4e1f190bd2084af6bd241c76197/src/keyboard.js#L790-L796
55,284
substance/commander
src/keyboard.js
_callbackAndReset
function _callbackAndReset(e) { _fireCallback.call(this, callback, e, combo); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { this._ignoreNextKeyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences.bind(this), 10); }
javascript
function _callbackAndReset(e) { _fireCallback.call(this, callback, e, combo); // we should ignore the next key up if the action is key down // or keypress. this is so if you finish a sequence and // release the key the final key will not trigger a keyup if (action !== 'keyup') { this._ignoreNextKeyup = _characterFromEvent(e); } // weird race condition if a sequence ends with the key // another sequence begins with setTimeout(_resetSequences.bind(this), 10); }
[ "function", "_callbackAndReset", "(", "e", ")", "{", "_fireCallback", ".", "call", "(", "this", ",", "callback", ",", "e", ",", "combo", ")", ";", "// we should ignore the next key up if the action is key down", "// or keypress. this is so if you finish a sequence and", "// release the key the final key will not trigger a keyup", "if", "(", "action", "!==", "'keyup'", ")", "{", "this", ".", "_ignoreNextKeyup", "=", "_characterFromEvent", "(", "e", ")", ";", "}", "// weird race condition if a sequence ends with the key", "// another sequence begins with", "setTimeout", "(", "_resetSequences", ".", "bind", "(", "this", ")", ",", "10", ")", ";", "}" ]
wraps the specified callback inside of another function in order to reset all sequence counters as soon as this sequence is done @param {Event} e @returns void
[ "wraps", "the", "specified", "callback", "inside", "of", "another", "function", "in", "order", "to", "reset", "all", "sequence", "counters", "as", "soon", "as", "this", "sequence", "is", "done" ]
c16d22056d1cc4e1f190bd2084af6bd241c76197
https://github.com/substance/commander/blob/c16d22056d1cc4e1f190bd2084af6bd241c76197/src/keyboard.js#L805-L818
55,285
skerit/alchemy-styleboost
public/ckeditor/4.4dev/core/lang.js
function( languageCode, defaultLanguage, callback ) { // If no languageCode - fallback to browser or default. // If languageCode - fallback to no-localized version or default. if ( !languageCode || !CKEDITOR.lang.languages[ languageCode ] ) languageCode = this.detect( defaultLanguage, languageCode ); var that = this, loadedCallback = function() { that[ languageCode ].dir = that.rtl[ languageCode ] ? 'rtl' : 'ltr'; callback( languageCode, that[ languageCode ] ); }; if ( !this[ languageCode ] ) CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( 'lang/' + languageCode + '.js' ), loadedCallback, this ); else loadedCallback(); }
javascript
function( languageCode, defaultLanguage, callback ) { // If no languageCode - fallback to browser or default. // If languageCode - fallback to no-localized version or default. if ( !languageCode || !CKEDITOR.lang.languages[ languageCode ] ) languageCode = this.detect( defaultLanguage, languageCode ); var that = this, loadedCallback = function() { that[ languageCode ].dir = that.rtl[ languageCode ] ? 'rtl' : 'ltr'; callback( languageCode, that[ languageCode ] ); }; if ( !this[ languageCode ] ) CKEDITOR.scriptLoader.load( CKEDITOR.getUrl( 'lang/' + languageCode + '.js' ), loadedCallback, this ); else loadedCallback(); }
[ "function", "(", "languageCode", ",", "defaultLanguage", ",", "callback", ")", "{", "// If no languageCode - fallback to browser or default.", "// If languageCode - fallback to no-localized version or default.", "if", "(", "!", "languageCode", "||", "!", "CKEDITOR", ".", "lang", ".", "languages", "[", "languageCode", "]", ")", "languageCode", "=", "this", ".", "detect", "(", "defaultLanguage", ",", "languageCode", ")", ";", "var", "that", "=", "this", ",", "loadedCallback", "=", "function", "(", ")", "{", "that", "[", "languageCode", "]", ".", "dir", "=", "that", ".", "rtl", "[", "languageCode", "]", "?", "'rtl'", ":", "'ltr'", ";", "callback", "(", "languageCode", ",", "that", "[", "languageCode", "]", ")", ";", "}", ";", "if", "(", "!", "this", "[", "languageCode", "]", ")", "CKEDITOR", ".", "scriptLoader", ".", "load", "(", "CKEDITOR", ".", "getUrl", "(", "'lang/'", "+", "languageCode", "+", "'.js'", ")", ",", "loadedCallback", ",", "this", ")", ";", "else", "loadedCallback", "(", ")", ";", "}" ]
Loads a specific language file, or auto detects it. A callback is then called when the file gets loaded. @param {String} languageCode The code of the language file to be loaded. If null or empty, autodetection will be performed. The same happens if the language is not supported. @param {String} defaultLanguage The language to be used if `languageCode` is not supported or if the autodetection fails. @param {Function} callback A function to be called once the language file is loaded. Two parameters are passed to this function: the language code and the loaded language entries.
[ "Loads", "a", "specific", "language", "file", "or", "auto", "detects", "it", ".", "A", "callback", "is", "then", "called", "when", "the", "file", "gets", "loaded", "." ]
2b90b8a6afc9f065f785651292fb193940021d90
https://github.com/skerit/alchemy-styleboost/blob/2b90b8a6afc9f065f785651292fb193940021d90/public/ckeditor/4.4dev/core/lang.js#L46-L62
55,286
georgenorman/tessel-kit
lib/log-helper.js
function(title, obj) { if (arguments.length == 2) { this.msg(title); } else { obj = title; } doLog(generalUtils.getProperties(obj)); }
javascript
function(title, obj) { if (arguments.length == 2) { this.msg(title); } else { obj = title; } doLog(generalUtils.getProperties(obj)); }
[ "function", "(", "title", ",", "obj", ")", "{", "if", "(", "arguments", ".", "length", "==", "2", ")", "{", "this", ".", "msg", "(", "title", ")", ";", "}", "else", "{", "obj", "=", "title", ";", "}", "doLog", "(", "generalUtils", ".", "getProperties", "(", "obj", ")", ")", ";", "}" ]
Logs a String, of the form "propertyName=propertyValue\n", for every property of the given obj. @param title optional title to log above the property listing. @param obj object to retrieve the properties from.
[ "Logs", "a", "String", "of", "the", "form", "propertyName", "=", "propertyValue", "\\", "n", "for", "every", "property", "of", "the", "given", "obj", "." ]
487e91360f0ecf8500d24297228842e2c01ac762
https://github.com/georgenorman/tessel-kit/blob/487e91360f0ecf8500d24297228842e2c01ac762/lib/log-helper.js#L111-L118
55,287
yoshuawuyts/url-querystring
index.js
split
function split(url) { assert.equal(typeof url, 'string', 'url-querystring: url should be a string'); var res = {}; var nw = url.split('?'); res.url = nw[0]; res.qs = nw.length == 2 ? qs.parse(nw[1]) : {}; return res; }
javascript
function split(url) { assert.equal(typeof url, 'string', 'url-querystring: url should be a string'); var res = {}; var nw = url.split('?'); res.url = nw[0]; res.qs = nw.length == 2 ? qs.parse(nw[1]) : {}; return res; }
[ "function", "split", "(", "url", ")", "{", "assert", ".", "equal", "(", "typeof", "url", ",", "'string'", ",", "'url-querystring: url should be a string'", ")", ";", "var", "res", "=", "{", "}", ";", "var", "nw", "=", "url", ".", "split", "(", "'?'", ")", ";", "res", ".", "url", "=", "nw", "[", "0", "]", ";", "res", ".", "qs", "=", "nw", ".", "length", "==", "2", "?", "qs", ".", "parse", "(", "nw", "[", "1", "]", ")", ":", "{", "}", ";", "return", "res", ";", "}" ]
Splice a `querystring` from an `url`; @param {String} url @return {String} @api public
[ "Splice", "a", "querystring", "from", "an", "url", ";" ]
726bbb5a2cde3e08cd0d4b0b1601d6edf5b253cf
https://github.com/yoshuawuyts/url-querystring/blob/726bbb5a2cde3e08cd0d4b0b1601d6edf5b253cf/index.js#L22-L34
55,288
intervolga/bem-utils
lib/dir-exist.js
dirExist
function dirExist(dirName) { return new Promise((resolve, reject) => { fs.stat(dirName, (err, stats) => { if (err === null && stats.isDirectory()) { resolve(dirName); } else { resolve(false); } }); }); }
javascript
function dirExist(dirName) { return new Promise((resolve, reject) => { fs.stat(dirName, (err, stats) => { if (err === null && stats.isDirectory()) { resolve(dirName); } else { resolve(false); } }); }); }
[ "function", "dirExist", "(", "dirName", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "stat", "(", "dirName", ",", "(", "err", ",", "stats", ")", "=>", "{", "if", "(", "err", "===", "null", "&&", "stats", ".", "isDirectory", "(", ")", ")", "{", "resolve", "(", "dirName", ")", ";", "}", "else", "{", "resolve", "(", "false", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Promisified "directory exist" check @param {String} dirName @return {Promise} resolves to dirName if exist, false otherwise
[ "Promisified", "directory", "exist", "check" ]
3b81bb9bc408275486175326dc7f35c563a46563
https://github.com/intervolga/bem-utils/blob/3b81bb9bc408275486175326dc7f35c563a46563/lib/dir-exist.js#L9-L19
55,289
muttr/libmuttr
lib/identity.js
Identity
function Identity(userID, passphrase, keyPair) { if (!(this instanceof Identity)) { return new Identity(userID, passphrase, keyPair); } assert(typeof userID === 'string', 'Invalid userID supplied'); assert(typeof passphrase === 'string', 'Invalid passphrase supplied'); this._publicKeyArmored = keyPair.publicKey.toString(); this._privateKeyArmored = keyPair.privateKey.toString(); this.userID = userID; this.publicKey = pgp.key.readArmored(this._publicKeyArmored).keys[0]; this.privateKey = pgp.key.readArmored(this._privateKeyArmored).keys[0]; assert(this.privateKey.decrypt(passphrase), 'Failed to decrypt private key'); }
javascript
function Identity(userID, passphrase, keyPair) { if (!(this instanceof Identity)) { return new Identity(userID, passphrase, keyPair); } assert(typeof userID === 'string', 'Invalid userID supplied'); assert(typeof passphrase === 'string', 'Invalid passphrase supplied'); this._publicKeyArmored = keyPair.publicKey.toString(); this._privateKeyArmored = keyPair.privateKey.toString(); this.userID = userID; this.publicKey = pgp.key.readArmored(this._publicKeyArmored).keys[0]; this.privateKey = pgp.key.readArmored(this._privateKeyArmored).keys[0]; assert(this.privateKey.decrypt(passphrase), 'Failed to decrypt private key'); }
[ "function", "Identity", "(", "userID", ",", "passphrase", ",", "keyPair", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Identity", ")", ")", "{", "return", "new", "Identity", "(", "userID", ",", "passphrase", ",", "keyPair", ")", ";", "}", "assert", "(", "typeof", "userID", "===", "'string'", ",", "'Invalid userID supplied'", ")", ";", "assert", "(", "typeof", "passphrase", "===", "'string'", ",", "'Invalid passphrase supplied'", ")", ";", "this", ".", "_publicKeyArmored", "=", "keyPair", ".", "publicKey", ".", "toString", "(", ")", ";", "this", ".", "_privateKeyArmored", "=", "keyPair", ".", "privateKey", ".", "toString", "(", ")", ";", "this", ".", "userID", "=", "userID", ";", "this", ".", "publicKey", "=", "pgp", ".", "key", ".", "readArmored", "(", "this", ".", "_publicKeyArmored", ")", ".", "keys", "[", "0", "]", ";", "this", ".", "privateKey", "=", "pgp", ".", "key", ".", "readArmored", "(", "this", ".", "_privateKeyArmored", ")", ".", "keys", "[", "0", "]", ";", "assert", "(", "this", ".", "privateKey", ".", "decrypt", "(", "passphrase", ")", ",", "'Failed to decrypt private key'", ")", ";", "}" ]
An identity is represented by a PGP key pair and user ID @constructor @param {string} userID @param {string} passphrase @param {object} keyPair @param {string} keyPair.publicKey @param {string} keyPair.privateKey
[ "An", "identity", "is", "represented", "by", "a", "PGP", "key", "pair", "and", "user", "ID" ]
2e4fda9cb2b47b8febe30585f54196d39d79e2e5
https://github.com/muttr/libmuttr/blob/2e4fda9cb2b47b8febe30585f54196d39d79e2e5/lib/identity.js#L22-L38
55,290
nutella-framework/nutella_lib.js
src/persist/mongo_persisted_collection.js
extend
function extend(x, y){ for(var key in y) { if (y.hasOwnProperty(key)) { x[key] = y[key]; } } return x; }
javascript
function extend(x, y){ for(var key in y) { if (y.hasOwnProperty(key)) { x[key] = y[key]; } } return x; }
[ "function", "extend", "(", "x", ",", "y", ")", "{", "for", "(", "var", "key", "in", "y", ")", "{", "if", "(", "y", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "x", "[", "key", "]", "=", "y", "[", "key", "]", ";", "}", "}", "return", "x", ";", "}" ]
Helper function used in order to extend the array
[ "Helper", "function", "used", "in", "order", "to", "extend", "the", "array" ]
b3a3406a407e2a1ada6edcc503b70991f9cb249b
https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/persist/mongo_persisted_collection.js#L10-L17
55,291
nutella-framework/nutella_lib.js
src/persist/mongo_persisted_collection.js
function(mongo_host, db, collection) { var arrayMongo = function() { }; arrayMongo.prototype = Array.prototype; extend(arrayMongo.prototype, { /** * Store the parameters */ host: function() { return mongo_host; }, db: function() { return db; }, mongoCollection: function() { return collection; }, load: function(finished) { console.log('HERE'); var self = this; var cname = this.mongoCollection(); mongoCache.getConnection(this.host(), this.db(), (function(err, db) { if(err) return; var collection = db.collection(cname); collection.find().toArray(function(err, docs) { if(err || docs.length < 1) { finished(); return; } // Copy all the documents in the array docs.forEach(function(doc) { self.push(doc); }); finished(); }.bind(this)); }).bind(this)); }, save: function() { var self = this; var cname = this.mongoCollection(); mongoCache.getConnection(this.host(), this.db(), (function(err, db) { if(err) return; var collection = db.collection(cname); self.forEach(function(element) { if(element['_id']) { collection.update({_id: element['_id']}, element, function(){ }); } else { collection.insert(element, function(){ }); } }); }).bind(this)); } }); // Create instance and return it return new arrayMongo(); }
javascript
function(mongo_host, db, collection) { var arrayMongo = function() { }; arrayMongo.prototype = Array.prototype; extend(arrayMongo.prototype, { /** * Store the parameters */ host: function() { return mongo_host; }, db: function() { return db; }, mongoCollection: function() { return collection; }, load: function(finished) { console.log('HERE'); var self = this; var cname = this.mongoCollection(); mongoCache.getConnection(this.host(), this.db(), (function(err, db) { if(err) return; var collection = db.collection(cname); collection.find().toArray(function(err, docs) { if(err || docs.length < 1) { finished(); return; } // Copy all the documents in the array docs.forEach(function(doc) { self.push(doc); }); finished(); }.bind(this)); }).bind(this)); }, save: function() { var self = this; var cname = this.mongoCollection(); mongoCache.getConnection(this.host(), this.db(), (function(err, db) { if(err) return; var collection = db.collection(cname); self.forEach(function(element) { if(element['_id']) { collection.update({_id: element['_id']}, element, function(){ }); } else { collection.insert(element, function(){ }); } }); }).bind(this)); } }); // Create instance and return it return new arrayMongo(); }
[ "function", "(", "mongo_host", ",", "db", ",", "collection", ")", "{", "var", "arrayMongo", "=", "function", "(", ")", "{", "}", ";", "arrayMongo", ".", "prototype", "=", "Array", ".", "prototype", ";", "extend", "(", "arrayMongo", ".", "prototype", ",", "{", "/**\n * Store the parameters\n */", "host", ":", "function", "(", ")", "{", "return", "mongo_host", ";", "}", ",", "db", ":", "function", "(", ")", "{", "return", "db", ";", "}", ",", "mongoCollection", ":", "function", "(", ")", "{", "return", "collection", ";", "}", ",", "load", ":", "function", "(", "finished", ")", "{", "console", ".", "log", "(", "'HERE'", ")", ";", "var", "self", "=", "this", ";", "var", "cname", "=", "this", ".", "mongoCollection", "(", ")", ";", "mongoCache", ".", "getConnection", "(", "this", ".", "host", "(", ")", ",", "this", ".", "db", "(", ")", ",", "(", "function", "(", "err", ",", "db", ")", "{", "if", "(", "err", ")", "return", ";", "var", "collection", "=", "db", ".", "collection", "(", "cname", ")", ";", "collection", ".", "find", "(", ")", ".", "toArray", "(", "function", "(", "err", ",", "docs", ")", "{", "if", "(", "err", "||", "docs", ".", "length", "<", "1", ")", "{", "finished", "(", ")", ";", "return", ";", "}", "// Copy all the documents in the array", "docs", ".", "forEach", "(", "function", "(", "doc", ")", "{", "self", ".", "push", "(", "doc", ")", ";", "}", ")", ";", "finished", "(", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}", ")", ".", "bind", "(", "this", ")", ")", ";", "}", ",", "save", ":", "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "cname", "=", "this", ".", "mongoCollection", "(", ")", ";", "mongoCache", ".", "getConnection", "(", "this", ".", "host", "(", ")", ",", "this", ".", "db", "(", ")", ",", "(", "function", "(", "err", ",", "db", ")", "{", "if", "(", "err", ")", "return", ";", "var", "collection", "=", "db", ".", "collection", "(", "cname", ")", ";", "self", ".", "forEach", "(", "function", "(", "element", ")", "{", "if", "(", "element", "[", "'_id'", "]", ")", "{", "collection", ".", "update", "(", "{", "_id", ":", "element", "[", "'_id'", "]", "}", ",", "element", ",", "function", "(", ")", "{", "}", ")", ";", "}", "else", "{", "collection", ".", "insert", "(", "element", ",", "function", "(", ")", "{", "}", ")", ";", "}", "}", ")", ";", "}", ")", ".", "bind", "(", "this", ")", ")", ";", "}", "}", ")", ";", "// Create instance and return it", "return", "new", "arrayMongo", "(", ")", ";", "}" ]
Creates a new persisted array @param mongo_host @param db @param collection @return {Array}
[ "Creates", "a", "new", "persisted", "array" ]
b3a3406a407e2a1ada6edcc503b70991f9cb249b
https://github.com/nutella-framework/nutella_lib.js/blob/b3a3406a407e2a1ada6edcc503b70991f9cb249b/src/persist/mongo_persisted_collection.js#L27-L90
55,292
sittingbool/sbool-node-utils
util/cipherUtil.js
pwCipher
function pwCipher(string) { if(string) { if ( typeof pw !== 'string' || pw.length < 8 ) { throw new Error('Please set a password with 8 or ' + 'more chars on process.env.CIPHER_UTIL_PW!'); } if ( typeof algo !== 'string' || algo.length < 1 ) { throw new Error('Please choose an algorithm' + ' on process.env.CIPHER_UTIL_ALGO!'); } var ciphered = crypto.createCipher(algo, pw), /* * Array */ encrypted = [ciphered.update(string)]; encrypted.push(ciphered.final()); return Buffer.concat(encrypted).toString(pwEnc); } return null; }
javascript
function pwCipher(string) { if(string) { if ( typeof pw !== 'string' || pw.length < 8 ) { throw new Error('Please set a password with 8 or ' + 'more chars on process.env.CIPHER_UTIL_PW!'); } if ( typeof algo !== 'string' || algo.length < 1 ) { throw new Error('Please choose an algorithm' + ' on process.env.CIPHER_UTIL_ALGO!'); } var ciphered = crypto.createCipher(algo, pw), /* * Array */ encrypted = [ciphered.update(string)]; encrypted.push(ciphered.final()); return Buffer.concat(encrypted).toString(pwEnc); } return null; }
[ "function", "pwCipher", "(", "string", ")", "{", "if", "(", "string", ")", "{", "if", "(", "typeof", "pw", "!==", "'string'", "||", "pw", ".", "length", "<", "8", ")", "{", "throw", "new", "Error", "(", "'Please set a password with 8 or '", "+", "'more chars on process.env.CIPHER_UTIL_PW!'", ")", ";", "}", "if", "(", "typeof", "algo", "!==", "'string'", "||", "algo", ".", "length", "<", "1", ")", "{", "throw", "new", "Error", "(", "'Please choose an algorithm'", "+", "' on process.env.CIPHER_UTIL_ALGO!'", ")", ";", "}", "var", "ciphered", "=", "crypto", ".", "createCipher", "(", "algo", ",", "pw", ")", ",", "/*\n * Array\n */", "encrypted", "=", "[", "ciphered", ".", "update", "(", "string", ")", "]", ";", "encrypted", ".", "push", "(", "ciphered", ".", "final", "(", ")", ")", ";", "return", "Buffer", ".", "concat", "(", "encrypted", ")", ".", "toString", "(", "pwEnc", ")", ";", "}", "return", "null", ";", "}" ]
Encrypt string with password and specified algorithm. @param string {String} String to encrypt. @return {String | Null}
[ "Encrypt", "string", "with", "password", "and", "specified", "algorithm", "." ]
30a5b71bc258b160883451ede8c6c3991294fd68
https://github.com/sittingbool/sbool-node-utils/blob/30a5b71bc258b160883451ede8c6c3991294fd68/util/cipherUtil.js#L63-L92
55,293
sittingbool/sbool-node-utils
util/cipherUtil.js
pwDecipher
function pwDecipher(string) { if(string) { if ( typeof pw !== 'string' || pw.length < 8 ) { throw new Error('Please set a password with 8 or ' + 'more chars on process.env.CIPHER_UTIL_PW!'); } if ( typeof algo !== 'string' || algo.length < 1 ) { throw new Error('Please choose an algorithm' + ' on process.env.CIPHER_UTIL_ALGO!'); } var buffer = new Buffer(string, pwEnc), toDecipher = crypto.createDecipher(algo, pw), deciphered = [toDecipher.update(buffer)]; deciphered.push(toDecipher.final()); return Buffer.concat(deciphered).toString(dec); } return null; }
javascript
function pwDecipher(string) { if(string) { if ( typeof pw !== 'string' || pw.length < 8 ) { throw new Error('Please set a password with 8 or ' + 'more chars on process.env.CIPHER_UTIL_PW!'); } if ( typeof algo !== 'string' || algo.length < 1 ) { throw new Error('Please choose an algorithm' + ' on process.env.CIPHER_UTIL_ALGO!'); } var buffer = new Buffer(string, pwEnc), toDecipher = crypto.createDecipher(algo, pw), deciphered = [toDecipher.update(buffer)]; deciphered.push(toDecipher.final()); return Buffer.concat(deciphered).toString(dec); } return null; }
[ "function", "pwDecipher", "(", "string", ")", "{", "if", "(", "string", ")", "{", "if", "(", "typeof", "pw", "!==", "'string'", "||", "pw", ".", "length", "<", "8", ")", "{", "throw", "new", "Error", "(", "'Please set a password with 8 or '", "+", "'more chars on process.env.CIPHER_UTIL_PW!'", ")", ";", "}", "if", "(", "typeof", "algo", "!==", "'string'", "||", "algo", ".", "length", "<", "1", ")", "{", "throw", "new", "Error", "(", "'Please choose an algorithm'", "+", "' on process.env.CIPHER_UTIL_ALGO!'", ")", ";", "}", "var", "buffer", "=", "new", "Buffer", "(", "string", ",", "pwEnc", ")", ",", "toDecipher", "=", "crypto", ".", "createDecipher", "(", "algo", ",", "pw", ")", ",", "deciphered", "=", "[", "toDecipher", ".", "update", "(", "buffer", ")", "]", ";", "deciphered", ".", "push", "(", "toDecipher", ".", "final", "(", ")", ")", ";", "return", "Buffer", ".", "concat", "(", "deciphered", ")", ".", "toString", "(", "dec", ")", ";", "}", "return", "null", ";", "}" ]
Decrypt string with password and specified algorithm. @param string {String} String to decrypt. @return {String | Null}
[ "Decrypt", "string", "with", "password", "and", "specified", "algorithm", "." ]
30a5b71bc258b160883451ede8c6c3991294fd68
https://github.com/sittingbool/sbool-node-utils/blob/30a5b71bc258b160883451ede8c6c3991294fd68/util/cipherUtil.js#L190-L218
55,294
lucified/lucify-build-tools
src/bundle.js
bundle
function bundle(entryPoint, buildContext, opts) { if (!opts) { opts = {}; } if (!opts.outputFileName) { opts.outputFileName = 'index.js'; } if (!opts.destPath) { opts.destPath = buildContext.destPath; } if (opts.rev !== false) { opts.rev = true; } var shouldUglify = false; var config = { // these are needed for watchify cache: {}, packageCache: {}, fullPaths: false, // Specify the entry point of the bundle entries: entryPoint, // Enable source maps debug: buildContext.dev }; var bundler = browserify(config) .transform(babelify.configure({stage: 1})); if (buildContext.watch) { // Wrap with watchify and rebundle on changes bundler = watchify(bundler); // Rebundle on update bundler.on('update', doBundle.bind(null, bundler, buildContext, opts)); } return doBundle(bundler, buildContext, opts); }
javascript
function bundle(entryPoint, buildContext, opts) { if (!opts) { opts = {}; } if (!opts.outputFileName) { opts.outputFileName = 'index.js'; } if (!opts.destPath) { opts.destPath = buildContext.destPath; } if (opts.rev !== false) { opts.rev = true; } var shouldUglify = false; var config = { // these are needed for watchify cache: {}, packageCache: {}, fullPaths: false, // Specify the entry point of the bundle entries: entryPoint, // Enable source maps debug: buildContext.dev }; var bundler = browserify(config) .transform(babelify.configure({stage: 1})); if (buildContext.watch) { // Wrap with watchify and rebundle on changes bundler = watchify(bundler); // Rebundle on update bundler.on('update', doBundle.bind(null, bundler, buildContext, opts)); } return doBundle(bundler, buildContext, opts); }
[ "function", "bundle", "(", "entryPoint", ",", "buildContext", ",", "opts", ")", "{", "if", "(", "!", "opts", ")", "{", "opts", "=", "{", "}", ";", "}", "if", "(", "!", "opts", ".", "outputFileName", ")", "{", "opts", ".", "outputFileName", "=", "'index.js'", ";", "}", "if", "(", "!", "opts", ".", "destPath", ")", "{", "opts", ".", "destPath", "=", "buildContext", ".", "destPath", ";", "}", "if", "(", "opts", ".", "rev", "!==", "false", ")", "{", "opts", ".", "rev", "=", "true", ";", "}", "var", "shouldUglify", "=", "false", ";", "var", "config", "=", "{", "// these are needed for watchify", "cache", ":", "{", "}", ",", "packageCache", ":", "{", "}", ",", "fullPaths", ":", "false", ",", "// Specify the entry point of the bundle", "entries", ":", "entryPoint", ",", "// Enable source maps", "debug", ":", "buildContext", ".", "dev", "}", ";", "var", "bundler", "=", "browserify", "(", "config", ")", ".", "transform", "(", "babelify", ".", "configure", "(", "{", "stage", ":", "1", "}", ")", ")", ";", "if", "(", "buildContext", ".", "watch", ")", "{", "// Wrap with watchify and rebundle on changes", "bundler", "=", "watchify", "(", "bundler", ")", ";", "// Rebundle on update", "bundler", ".", "on", "(", "'update'", ",", "doBundle", ".", "bind", "(", "null", ",", "bundler", ",", "buildContext", ",", "opts", ")", ")", ";", "}", "return", "doBundle", "(", "bundler", ",", "buildContext", ",", "opts", ")", ";", "}" ]
Create a browserify bundle according to the given configuration entryPoint - the entry point for the bundle buildContext - lucify build context opts.outputFileName - file name for produced bundle opts.destPath - destinatino path for produced bundle
[ "Create", "a", "browserify", "bundle", "according", "to", "the", "given", "configuration" ]
1169821ebcc4a8abaa754d060f2424fa9db0b75f
https://github.com/lucified/lucify-build-tools/blob/1169821ebcc4a8abaa754d060f2424fa9db0b75f/src/bundle.js#L30-L69
55,295
doowb/vinyl-group
index.js
is
function is(obj, name) { if (typeof name !== 'string') { throw new TypeError('expected name to be a string'); } utils.define(obj, 'is' + utils.pascal(name), true); utils.define(obj, '_name', name); }
javascript
function is(obj, name) { if (typeof name !== 'string') { throw new TypeError('expected name to be a string'); } utils.define(obj, 'is' + utils.pascal(name), true); utils.define(obj, '_name', name); }
[ "function", "is", "(", "obj", ",", "name", ")", "{", "if", "(", "typeof", "name", "!==", "'string'", ")", "{", "throw", "new", "TypeError", "(", "'expected name to be a string'", ")", ";", "}", "utils", ".", "define", "(", "obj", ",", "'is'", "+", "utils", ".", "pascal", "(", "name", ")", ",", "true", ")", ";", "utils", ".", "define", "(", "obj", ",", "'_name'", ",", "name", ")", ";", "}" ]
Set the name and type of object.
[ "Set", "the", "name", "and", "type", "of", "object", "." ]
68acd2a45e5b5dcc7a23789f7a92ce1c5551da41
https://github.com/doowb/vinyl-group/blob/68acd2a45e5b5dcc7a23789f7a92ce1c5551da41/index.js#L75-L81
55,296
davidfig/jsdoc-template
plugins/es6-fix.js
beforeParse
function beforeParse(e) { var namespace = e.source.match(rgxNamespace); var className = e.source.match(rgxClassName); // Fix members not showing up attached to class if (namespace && className) { // console.log(`${namespace[1]}.${className[2]}`); // Replaces "@member {Type}"" with "@member {Type} PIXI.ClassName#prop" e.source = e.source.replace(rgxMember, '$1 '+ namespace[1] + '.' + className[2] + '#$4$2$3'); } e.source = e.source.replace(rgxGross, grossReplace); }
javascript
function beforeParse(e) { var namespace = e.source.match(rgxNamespace); var className = e.source.match(rgxClassName); // Fix members not showing up attached to class if (namespace && className) { // console.log(`${namespace[1]}.${className[2]}`); // Replaces "@member {Type}"" with "@member {Type} PIXI.ClassName#prop" e.source = e.source.replace(rgxMember, '$1 '+ namespace[1] + '.' + className[2] + '#$4$2$3'); } e.source = e.source.replace(rgxGross, grossReplace); }
[ "function", "beforeParse", "(", "e", ")", "{", "var", "namespace", "=", "e", ".", "source", ".", "match", "(", "rgxNamespace", ")", ";", "var", "className", "=", "e", ".", "source", ".", "match", "(", "rgxClassName", ")", ";", "// Fix members not showing up attached to class", "if", "(", "namespace", "&&", "className", ")", "{", "// console.log(`${namespace[1]}.${className[2]}`);", "// Replaces \"@member {Type}\"\" with \"@member {Type} PIXI.ClassName#prop\"", "e", ".", "source", "=", "e", ".", "source", ".", "replace", "(", "rgxMember", ",", "'$1 '", "+", "namespace", "[", "1", "]", "+", "'.'", "+", "className", "[", "2", "]", "+", "'#$4$2$3'", ")", ";", "}", "e", ".", "source", "=", "e", ".", "source", ".", "replace", "(", "rgxGross", ",", "grossReplace", ")", ";", "}" ]
Called before parsing a file, giving us a change to replace the source. @param {*} e - The `beforeParse` event data. @param {string} e.filename - The name of the file being parsed. @param {string} e.source - The source of the file being parsed.
[ "Called", "before", "parsing", "a", "file", "giving", "us", "a", "change", "to", "replace", "the", "source", "." ]
b54ea3af8b3368b8604f2f9a493bb169b7e24e27
https://github.com/davidfig/jsdoc-template/blob/b54ea3af8b3368b8604f2f9a493bb169b7e24e27/plugins/es6-fix.js#L24-L38
55,297
peteromano/jetrunner
example/vendor/mocha/lib/suite.js
Suite
function Suite(title, ctx) { this.title = title; this.ctx = ctx; this.suites = []; this.tests = []; this.pending = false; this._beforeEach = []; this._beforeAll = []; this._afterEach = []; this._afterAll = []; this.root = !title; this._timeout = 2000; this._slow = 75; this._bail = false; }
javascript
function Suite(title, ctx) { this.title = title; this.ctx = ctx; this.suites = []; this.tests = []; this.pending = false; this._beforeEach = []; this._beforeAll = []; this._afterEach = []; this._afterAll = []; this.root = !title; this._timeout = 2000; this._slow = 75; this._bail = false; }
[ "function", "Suite", "(", "title", ",", "ctx", ")", "{", "this", ".", "title", "=", "title", ";", "this", ".", "ctx", "=", "ctx", ";", "this", ".", "suites", "=", "[", "]", ";", "this", ".", "tests", "=", "[", "]", ";", "this", ".", "pending", "=", "false", ";", "this", ".", "_beforeEach", "=", "[", "]", ";", "this", ".", "_beforeAll", "=", "[", "]", ";", "this", ".", "_afterEach", "=", "[", "]", ";", "this", ".", "_afterAll", "=", "[", "]", ";", "this", ".", "root", "=", "!", "title", ";", "this", ".", "_timeout", "=", "2000", ";", "this", ".", "_slow", "=", "75", ";", "this", ".", "_bail", "=", "false", ";", "}" ]
Initialize a new `Suite` with the given `title` and `ctx`. @param {String} title @param {Context} ctx @api private
[ "Initialize", "a", "new", "Suite", "with", "the", "given", "title", "and", "ctx", "." ]
1882e0ee83d31fe1c799b42848c8c1357a62c995
https://github.com/peteromano/jetrunner/blob/1882e0ee83d31fe1c799b42848c8c1357a62c995/example/vendor/mocha/lib/suite.js#L49-L63
55,298
jkroso/when-all
deep.js
unbox
function unbox(value){ if (value instanceof ResType) return when(value, unbox) if (value && typeof value == 'object') return unboxAll(value) return value }
javascript
function unbox(value){ if (value instanceof ResType) return when(value, unbox) if (value && typeof value == 'object') return unboxAll(value) return value }
[ "function", "unbox", "(", "value", ")", "{", "if", "(", "value", "instanceof", "ResType", ")", "return", "when", "(", "value", ",", "unbox", ")", "if", "(", "value", "&&", "typeof", "value", "==", "'object'", ")", "return", "unboxAll", "(", "value", ")", "return", "value", "}" ]
unbox all values in `obj` recursively @param {Object|Array} obj @return {Result} for a new `obj`
[ "unbox", "all", "values", "in", "obj", "recursively" ]
cbd30c361c1b8ececf7369339ce6589f03d9fdb0
https://github.com/jkroso/when-all/blob/cbd30c361c1b8ececf7369339ce6589f03d9fdb0/deep.js#L19-L23
55,299
hoyce/passport-cas-kth
index.js
useGatewayAuthentication
function useGatewayAuthentication(req) { // can be set on request if via application supplied callback if (req.useGateway == true) { return true; } // otherwise via query parameter var origUrl = req.originalUrl; var useGateway = false; var idx = origUrl.indexOf(gatewayParameter); if (idx >= 0) { useGateway = true; } return useGateway; }
javascript
function useGatewayAuthentication(req) { // can be set on request if via application supplied callback if (req.useGateway == true) { return true; } // otherwise via query parameter var origUrl = req.originalUrl; var useGateway = false; var idx = origUrl.indexOf(gatewayParameter); if (idx >= 0) { useGateway = true; } return useGateway; }
[ "function", "useGatewayAuthentication", "(", "req", ")", "{", "// can be set on request if via application supplied callback", "if", "(", "req", ".", "useGateway", "==", "true", ")", "{", "return", "true", ";", "}", "// otherwise via query parameter", "var", "origUrl", "=", "req", ".", "originalUrl", ";", "var", "useGateway", "=", "false", ";", "var", "idx", "=", "origUrl", ".", "indexOf", "(", "gatewayParameter", ")", ";", "if", "(", "idx", ">=", "0", ")", "{", "useGateway", "=", "true", ";", "}", "return", "useGateway", ";", "}" ]
Check if we are requested to perform a gateway signon, i.e. a check
[ "Check", "if", "we", "are", "requested", "to", "perform", "a", "gateway", "signon", "i", ".", "e", ".", "a", "check" ]
56bcc5324c0332008cfde37023ed05a22bdf1eb3
https://github.com/hoyce/passport-cas-kth/blob/56bcc5324c0332008cfde37023ed05a22bdf1eb3/index.js#L149-L162