id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
15,800
TooTallNate/NodObjC
lib/types.js
map
function map (type) { if (!type) throw new Error('got falsey "type" to map ('+type+'). this should NOT happen!'); if (type.type) type = type.type; if (isStruct(type)) return getStruct(type); type = type.replace(methodEncodingsTest, '') // if the first letter is a ^ then it's a "pointer" type if (type[0] === '^') return 'pointer' // now we can try matching from the typeEncodings map var rtn = typeEncodings[type] if (rtn) return rtn // last shot... try the last char? this may be a bad idea... rtn = typeEncodings[type[type.length-1]] if (rtn) return rtn // couldn't find the type. throw a descriptive error as to why: if (type[0] == '[') return 'pointer'; //throw new Error('Array types not yet supported: ' + type) if (type[0] == '(') return 'pointer'; //throw new Error('Union types not yet supported: ' + type) if (type[0] == 'b') return 'pointer'; //throw new Error('Bit field types not yet supported: ' + type) throw new Error('Could not convert type: ' + type) }
javascript
function map (type) { if (!type) throw new Error('got falsey "type" to map ('+type+'). this should NOT happen!'); if (type.type) type = type.type; if (isStruct(type)) return getStruct(type); type = type.replace(methodEncodingsTest, '') // if the first letter is a ^ then it's a "pointer" type if (type[0] === '^') return 'pointer' // now we can try matching from the typeEncodings map var rtn = typeEncodings[type] if (rtn) return rtn // last shot... try the last char? this may be a bad idea... rtn = typeEncodings[type[type.length-1]] if (rtn) return rtn // couldn't find the type. throw a descriptive error as to why: if (type[0] == '[') return 'pointer'; //throw new Error('Array types not yet supported: ' + type) if (type[0] == '(') return 'pointer'; //throw new Error('Union types not yet supported: ' + type) if (type[0] == 'b') return 'pointer'; //throw new Error('Bit field types not yet supported: ' + type) throw new Error('Could not convert type: ' + type) }
[ "function", "map", "(", "type", ")", "{", "if", "(", "!", "type", ")", "throw", "new", "Error", "(", "'got falsey \"type\" to map ('", "+", "type", "+", "'). this should NOT happen!'", ")", ";", "if", "(", "type", ".", "type", ")", "type", "=", "type", ".", "type", ";", "if", "(", "isStruct", "(", "type", ")", ")", "return", "getStruct", "(", "type", ")", ";", "type", "=", "type", ".", "replace", "(", "methodEncodingsTest", ",", "''", ")", "// if the first letter is a ^ then it's a \"pointer\" type", "if", "(", "type", "[", "0", "]", "===", "'^'", ")", "return", "'pointer'", "// now we can try matching from the typeEncodings map", "var", "rtn", "=", "typeEncodings", "[", "type", "]", "if", "(", "rtn", ")", "return", "rtn", "// last shot... try the last char? this may be a bad idea...", "rtn", "=", "typeEncodings", "[", "type", "[", "type", ".", "length", "-", "1", "]", "]", "if", "(", "rtn", ")", "return", "rtn", "// couldn't find the type. throw a descriptive error as to why:", "if", "(", "type", "[", "0", "]", "==", "'['", ")", "return", "'pointer'", ";", "//throw new Error('Array types not yet supported: ' + type)", "if", "(", "type", "[", "0", "]", "==", "'('", ")", "return", "'pointer'", ";", "//throw new Error('Union types not yet supported: ' + type)", "if", "(", "type", "[", "0", "]", "==", "'b'", ")", "return", "'pointer'", ";", "//throw new Error('Bit field types not yet supported: ' + type)", "throw", "new", "Error", "(", "'Could not convert type: '", "+", "type", ")", "}" ]
Maps a single Obj-C 'type' into a valid node-ffi type. This mapping logic is kind of a mess...
[ "Maps", "a", "single", "Obj", "-", "C", "type", "into", "a", "valid", "node", "-", "ffi", "type", ".", "This", "mapping", "logic", "is", "kind", "of", "a", "mess", "..." ]
e4710fb8b73d3a2860de1e959e335a6de3e2191c
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/types.js#L204-L225
15,801
TooTallNate/NodObjC
lib/types.js
parse
function parse (types) { if (typeof types === 'string') { var rtn = [] , cur = [] , len = types.length , depth = 0 for (var i=0; i<len; i++) { var c = types[i] if (depth || !/(\d)/.test(c)) { cur.push(c) } if (c == '{' || c == '[' || c == '(') { depth++ } else if (c == '}' || c == ']' || c == ')') { depth-- if (!depth) add() } else if (~DELIMS.indexOf(c) && !depth) { add() } } function add () { rtn.push(cur.join('')) cur = [] depth = 0 } assert.equal(rtn[1], '@', '_self argument expected as first arg: ' + types) assert.equal(rtn[2], ':', 'SEL argument expected as second arg: ' + types) return [ rtn[0], rtn.slice(1) ] } else if (Array.isArray(types)) { return normalizeObjects(types); } else { var args = types.args assert.equal(args[0], '@', '_self argument expected as first arg: ' + types) assert.equal(args[1], ':', 'SEL argument expected as second arg: ' + types) return [ types.retval, args ] } }
javascript
function parse (types) { if (typeof types === 'string') { var rtn = [] , cur = [] , len = types.length , depth = 0 for (var i=0; i<len; i++) { var c = types[i] if (depth || !/(\d)/.test(c)) { cur.push(c) } if (c == '{' || c == '[' || c == '(') { depth++ } else if (c == '}' || c == ']' || c == ')') { depth-- if (!depth) add() } else if (~DELIMS.indexOf(c) && !depth) { add() } } function add () { rtn.push(cur.join('')) cur = [] depth = 0 } assert.equal(rtn[1], '@', '_self argument expected as first arg: ' + types) assert.equal(rtn[2], ':', 'SEL argument expected as second arg: ' + types) return [ rtn[0], rtn.slice(1) ] } else if (Array.isArray(types)) { return normalizeObjects(types); } else { var args = types.args assert.equal(args[0], '@', '_self argument expected as first arg: ' + types) assert.equal(args[1], ':', 'SEL argument expected as second arg: ' + types) return [ types.retval, args ] } }
[ "function", "parse", "(", "types", ")", "{", "if", "(", "typeof", "types", "===", "'string'", ")", "{", "var", "rtn", "=", "[", "]", ",", "cur", "=", "[", "]", ",", "len", "=", "types", ".", "length", ",", "depth", "=", "0", "for", "(", "var", "i", "=", "0", ";", "i", "<", "len", ";", "i", "++", ")", "{", "var", "c", "=", "types", "[", "i", "]", "if", "(", "depth", "||", "!", "/", "(\\d)", "/", ".", "test", "(", "c", ")", ")", "{", "cur", ".", "push", "(", "c", ")", "}", "if", "(", "c", "==", "'{'", "||", "c", "==", "'['", "||", "c", "==", "'('", ")", "{", "depth", "++", "}", "else", "if", "(", "c", "==", "'}'", "||", "c", "==", "']'", "||", "c", "==", "')'", ")", "{", "depth", "--", "if", "(", "!", "depth", ")", "add", "(", ")", "}", "else", "if", "(", "~", "DELIMS", ".", "indexOf", "(", "c", ")", "&&", "!", "depth", ")", "{", "add", "(", ")", "}", "}", "function", "add", "(", ")", "{", "rtn", ".", "push", "(", "cur", ".", "join", "(", "''", ")", ")", "cur", "=", "[", "]", "depth", "=", "0", "}", "assert", ".", "equal", "(", "rtn", "[", "1", "]", ",", "'@'", ",", "'_self argument expected as first arg: '", "+", "types", ")", "assert", ".", "equal", "(", "rtn", "[", "2", "]", ",", "':'", ",", "'SEL argument expected as second arg: '", "+", "types", ")", "return", "[", "rtn", "[", "0", "]", ",", "rtn", ".", "slice", "(", "1", ")", "]", "}", "else", "if", "(", "Array", ".", "isArray", "(", "types", ")", ")", "{", "return", "normalizeObjects", "(", "types", ")", ";", "}", "else", "{", "var", "args", "=", "types", ".", "args", "assert", ".", "equal", "(", "args", "[", "0", "]", ",", "'@'", ",", "'_self argument expected as first arg: '", "+", "types", ")", "assert", ".", "equal", "(", "args", "[", "1", "]", ",", "':'", ",", "'SEL argument expected as second arg: '", "+", "types", ")", "return", "[", "types", ".", "retval", ",", "args", "]", "}", "}" ]
Parses a "types string" (i.e. `'v@:'`) and returns a "types Array", where the return type is the first array value, and an Array of argument types is the array second value.
[ "Parses", "a", "types", "string", "(", "i", ".", "e", ".", "v" ]
e4710fb8b73d3a2860de1e959e335a6de3e2191c
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/types.js#L255-L294
15,802
TooTallNate/NodObjC
lib/id.js
ID
function ID (pointer) { if (typeof this !== 'function') return createFunction(null, 0, ID, arguments); var objClass = core.object_getClass(pointer); // This is absolutely necessary, otherwise we'll seg fault if a user passes in // a simple type or specifies an object on a class that takes a simple type. if (!objClass || ref.isNull(objClass)) { throw new TypeError('An abstract class or delegate implemented a method ' + 'that takes an ID (object), but a simple type or ' + 'structure (such as NSRect) was passed in'); } this.pointer = pointer; this.msgCache = []; this[invoke] = function () { return this.msgSend(arguments, false, this); }.bind(this); }
javascript
function ID (pointer) { if (typeof this !== 'function') return createFunction(null, 0, ID, arguments); var objClass = core.object_getClass(pointer); // This is absolutely necessary, otherwise we'll seg fault if a user passes in // a simple type or specifies an object on a class that takes a simple type. if (!objClass || ref.isNull(objClass)) { throw new TypeError('An abstract class or delegate implemented a method ' + 'that takes an ID (object), but a simple type or ' + 'structure (such as NSRect) was passed in'); } this.pointer = pointer; this.msgCache = []; this[invoke] = function () { return this.msgSend(arguments, false, this); }.bind(this); }
[ "function", "ID", "(", "pointer", ")", "{", "if", "(", "typeof", "this", "!==", "'function'", ")", "return", "createFunction", "(", "null", ",", "0", ",", "ID", ",", "arguments", ")", ";", "var", "objClass", "=", "core", ".", "object_getClass", "(", "pointer", ")", ";", "// This is absolutely necessary, otherwise we'll seg fault if a user passes in", "// a simple type or specifies an object on a class that takes a simple type.", "if", "(", "!", "objClass", "||", "ref", ".", "isNull", "(", "objClass", ")", ")", "{", "throw", "new", "TypeError", "(", "'An abstract class or delegate implemented a method '", "+", "'that takes an ID (object), but a simple type or '", "+", "'structure (such as NSRect) was passed in'", ")", ";", "}", "this", ".", "pointer", "=", "pointer", ";", "this", ".", "msgCache", "=", "[", "]", ";", "this", "[", "invoke", "]", "=", "function", "(", ")", "{", "return", "this", ".", "msgSend", "(", "arguments", ",", "false", ",", "this", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "}" ]
The 'id' function is essentially the "base class" for all Objective-C objects that get passed around JS-land.
[ "The", "id", "function", "is", "essentially", "the", "base", "class", "for", "all", "Objective", "-", "C", "objects", "that", "get", "passed", "around", "JS", "-", "land", "." ]
e4710fb8b73d3a2860de1e959e335a6de3e2191c
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/id.js#L21-L40
15,803
TooTallNate/NodObjC
lib/core.js
copyIvarList
function copyIvarList (classPtr) { var rtn = [] , numIvars = ref.alloc('uint') , ivars = objc.class_copyIvarList(classPtr, numIvars) , count = numIvars.deref(); for (var i=0; i<count; i++) rtn.push(objc.ivar_getName(ivars.readPointer(i * ref.sizeof.pointer))); free(ivars); return rtn; }
javascript
function copyIvarList (classPtr) { var rtn = [] , numIvars = ref.alloc('uint') , ivars = objc.class_copyIvarList(classPtr, numIvars) , count = numIvars.deref(); for (var i=0; i<count; i++) rtn.push(objc.ivar_getName(ivars.readPointer(i * ref.sizeof.pointer))); free(ivars); return rtn; }
[ "function", "copyIvarList", "(", "classPtr", ")", "{", "var", "rtn", "=", "[", "]", ",", "numIvars", "=", "ref", ".", "alloc", "(", "'uint'", ")", ",", "ivars", "=", "objc", ".", "class_copyIvarList", "(", "classPtr", ",", "numIvars", ")", ",", "count", "=", "numIvars", ".", "deref", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "rtn", ".", "push", "(", "objc", ".", "ivar_getName", "(", "ivars", ".", "readPointer", "(", "i", "*", "ref", ".", "sizeof", ".", "pointer", ")", ")", ")", ";", "free", "(", "ivars", ")", ";", "return", "rtn", ";", "}" ]
Copies and returns an Array of the instance variables defined by a given Class pointer. To get class variables, call this function on a metaclass.
[ "Copies", "and", "returns", "an", "Array", "of", "the", "instance", "variables", "defined", "by", "a", "given", "Class", "pointer", ".", "To", "get", "class", "variables", "call", "this", "function", "on", "a", "metaclass", "." ]
e4710fb8b73d3a2860de1e959e335a6de3e2191c
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/core.js#L134-L145
15,804
TooTallNate/NodObjC
lib/core.js
copyMethodList
function copyMethodList (classPtr) { var numMethods = ref.alloc('uint') , rtn = [] , methods = objc.class_copyMethodList(classPtr, numMethods) , count = numMethods.deref(); for (var i=0; i<count; i++) rtn.push(wrapValue(objc.method_getName(methods.readPointer(i * ref.sizeof.pointer)),':')); free(methods); return rtn; }
javascript
function copyMethodList (classPtr) { var numMethods = ref.alloc('uint') , rtn = [] , methods = objc.class_copyMethodList(classPtr, numMethods) , count = numMethods.deref(); for (var i=0; i<count; i++) rtn.push(wrapValue(objc.method_getName(methods.readPointer(i * ref.sizeof.pointer)),':')); free(methods); return rtn; }
[ "function", "copyMethodList", "(", "classPtr", ")", "{", "var", "numMethods", "=", "ref", ".", "alloc", "(", "'uint'", ")", ",", "rtn", "=", "[", "]", ",", "methods", "=", "objc", ".", "class_copyMethodList", "(", "classPtr", ",", "numMethods", ")", ",", "count", "=", "numMethods", ".", "deref", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "rtn", ".", "push", "(", "wrapValue", "(", "objc", ".", "method_getName", "(", "methods", ".", "readPointer", "(", "i", "*", "ref", ".", "sizeof", ".", "pointer", ")", ")", ",", "':'", ")", ")", ";", "free", "(", "methods", ")", ";", "return", "rtn", ";", "}" ]
Copies and returns an Array of the instance methods the given Class pointer implements. To get class methods, call this function with a metaclass.
[ "Copies", "and", "returns", "an", "Array", "of", "the", "instance", "methods", "the", "given", "Class", "pointer", "implements", ".", "To", "get", "class", "methods", "call", "this", "function", "with", "a", "metaclass", "." ]
e4710fb8b73d3a2860de1e959e335a6de3e2191c
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/core.js#L151-L162
15,805
TooTallNate/NodObjC
lib/core.js
wrapValues
function wrapValues (values, objtypes) { var result = []; for(var i=0; i < objtypes.length; i++) result.push(wrapValue(values[i], objtypes[i])); return result; }
javascript
function wrapValues (values, objtypes) { var result = []; for(var i=0; i < objtypes.length; i++) result.push(wrapValue(values[i], objtypes[i])); return result; }
[ "function", "wrapValues", "(", "values", ",", "objtypes", ")", "{", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "objtypes", ".", "length", ";", "i", "++", ")", "result", ".", "push", "(", "wrapValue", "(", "values", "[", "i", "]", ",", "objtypes", "[", "i", "]", ")", ")", ";", "return", "result", ";", "}" ]
Accepts an Array of raw objc pointers and other values, and an array of ObjC types, and returns an array of wrapped values where appropriate.
[ "Accepts", "an", "Array", "of", "raw", "objc", "pointers", "and", "other", "values", "and", "an", "array", "of", "ObjC", "types", "and", "returns", "an", "array", "of", "wrapped", "values", "where", "appropriate", "." ]
e4710fb8b73d3a2860de1e959e335a6de3e2191c
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/core.js#L201-L205
15,806
TooTallNate/NodObjC
lib/core.js
unwrapValue
function unwrapValue (val, type) { var basetype = type.type ? type.type : type; if (basetype == '@?') return createBlock(val, basetype); else if (basetype == '^?') return createWrapperPointer(val, type); else if (basetype == '@' || basetype == '#') { if(Buffer.isBuffer(val)) return val; return val ? val.pointer : null; } else if (basetype == ':') return selCache[val] || (selCache[val] = objc.sel_registerName(val)); else if (val === true) return 1; else if (val === false) return 0; else return val; }
javascript
function unwrapValue (val, type) { var basetype = type.type ? type.type : type; if (basetype == '@?') return createBlock(val, basetype); else if (basetype == '^?') return createWrapperPointer(val, type); else if (basetype == '@' || basetype == '#') { if(Buffer.isBuffer(val)) return val; return val ? val.pointer : null; } else if (basetype == ':') return selCache[val] || (selCache[val] = objc.sel_registerName(val)); else if (val === true) return 1; else if (val === false) return 0; else return val; }
[ "function", "unwrapValue", "(", "val", ",", "type", ")", "{", "var", "basetype", "=", "type", ".", "type", "?", "type", ".", "type", ":", "type", ";", "if", "(", "basetype", "==", "'@?'", ")", "return", "createBlock", "(", "val", ",", "basetype", ")", ";", "else", "if", "(", "basetype", "==", "'^?'", ")", "return", "createWrapperPointer", "(", "val", ",", "type", ")", ";", "else", "if", "(", "basetype", "==", "'@'", "||", "basetype", "==", "'#'", ")", "{", "if", "(", "Buffer", ".", "isBuffer", "(", "val", ")", ")", "return", "val", ";", "return", "val", "?", "val", ".", "pointer", ":", "null", ";", "}", "else", "if", "(", "basetype", "==", "':'", ")", "return", "selCache", "[", "val", "]", "||", "(", "selCache", "[", "val", "]", "=", "objc", ".", "sel_registerName", "(", "val", ")", ")", ";", "else", "if", "(", "val", "===", "true", ")", "return", "1", ";", "else", "if", "(", "val", "===", "false", ")", "return", "0", ";", "else", "return", "val", ";", "}" ]
Unwraps a previously wrapped NodObjC object.
[ "Unwraps", "a", "previously", "wrapped", "NodObjC", "object", "." ]
e4710fb8b73d3a2860de1e959e335a6de3e2191c
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/core.js#L210-L222
15,807
TooTallNate/NodObjC
lib/core.js
unwrapValues
function unwrapValues (values, objtypes) { var result = []; for(var i=0; i < objtypes.length; i++) result.push(unwrapValue(values[i], objtypes[i])); return result; }
javascript
function unwrapValues (values, objtypes) { var result = []; for(var i=0; i < objtypes.length; i++) result.push(unwrapValue(values[i], objtypes[i])); return result; }
[ "function", "unwrapValues", "(", "values", ",", "objtypes", ")", "{", "var", "result", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "objtypes", ".", "length", ";", "i", "++", ")", "result", ".", "push", "(", "unwrapValue", "(", "values", "[", "i", "]", ",", "objtypes", "[", "i", "]", ")", ")", ";", "return", "result", ";", "}" ]
Accepts an Array of wrapped NodObjC objects and other values, and an array of their cooresponding ObjC types, and returns an array of unwrapped values.
[ "Accepts", "an", "Array", "of", "wrapped", "NodObjC", "objects", "and", "other", "values", "and", "an", "array", "of", "their", "cooresponding", "ObjC", "types", "and", "returns", "an", "array", "of", "unwrapped", "values", "." ]
e4710fb8b73d3a2860de1e959e335a6de3e2191c
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/core.js#L228-L232
15,808
TooTallNate/NodObjC
lib/core.js
createUnwrapperFunction
function createUnwrapperFunction (funcPtr, type, isVariadic) { var rtnType = type.retval || type[0] || 'v'; var argTypes = type.args || type[1] || []; var unwrapper; if (isVariadic) { var func = ffi.VariadicForeignFunction(funcPtr, types.map(rtnType), types.mapArray(argTypes)); unwrapper = function() { var newtypes = []; // Detect the types coming in, make sure to ignore previously defined baseTypes, // garner a list of these then send the function through the normal exec. // The types system in objc, should probably be cleaned up considerably. This is // somewhat faulty but since 95% of objects coming through are mostly ID/Class // it works, we may have issues for function pointers/etc. for(var i=argTypes.length; i < arguments.length; i++) { if(arguments[i].type) newtypes.push(arguments[i].type) else if(arguments[i].pointer) newtypes.push('@'); else if(typeof arguments[i] == 'function') newtypes.push('@?'); else if(typeof arguments[i] == 'string') newtypes.push('r*'); else if(typeof arguments[i] == 'number') newtypes.push('d'); else newtypes.push('?'); } return wrapValue(func .apply(null, types.mapArray(newtypes)) .apply(null, unwrapValues(arguments,argTypes.concat(newtypes))), rtnType); }; } else { var func = ffi.ForeignFunction(funcPtr, types.map(rtnType), types.mapArray(argTypes)); unwrapper = function() { return wrapValue(func.apply(null, unwrapValues(arguments, argTypes)), rtnType); } } unwrapper.retval = rtnType; unwrapper.args = argTypes; unwrapper.pointer = funcPtr; return unwrapper; }
javascript
function createUnwrapperFunction (funcPtr, type, isVariadic) { var rtnType = type.retval || type[0] || 'v'; var argTypes = type.args || type[1] || []; var unwrapper; if (isVariadic) { var func = ffi.VariadicForeignFunction(funcPtr, types.map(rtnType), types.mapArray(argTypes)); unwrapper = function() { var newtypes = []; // Detect the types coming in, make sure to ignore previously defined baseTypes, // garner a list of these then send the function through the normal exec. // The types system in objc, should probably be cleaned up considerably. This is // somewhat faulty but since 95% of objects coming through are mostly ID/Class // it works, we may have issues for function pointers/etc. for(var i=argTypes.length; i < arguments.length; i++) { if(arguments[i].type) newtypes.push(arguments[i].type) else if(arguments[i].pointer) newtypes.push('@'); else if(typeof arguments[i] == 'function') newtypes.push('@?'); else if(typeof arguments[i] == 'string') newtypes.push('r*'); else if(typeof arguments[i] == 'number') newtypes.push('d'); else newtypes.push('?'); } return wrapValue(func .apply(null, types.mapArray(newtypes)) .apply(null, unwrapValues(arguments,argTypes.concat(newtypes))), rtnType); }; } else { var func = ffi.ForeignFunction(funcPtr, types.map(rtnType), types.mapArray(argTypes)); unwrapper = function() { return wrapValue(func.apply(null, unwrapValues(arguments, argTypes)), rtnType); } } unwrapper.retval = rtnType; unwrapper.args = argTypes; unwrapper.pointer = funcPtr; return unwrapper; }
[ "function", "createUnwrapperFunction", "(", "funcPtr", ",", "type", ",", "isVariadic", ")", "{", "var", "rtnType", "=", "type", ".", "retval", "||", "type", "[", "0", "]", "||", "'v'", ";", "var", "argTypes", "=", "type", ".", "args", "||", "type", "[", "1", "]", "||", "[", "]", ";", "var", "unwrapper", ";", "if", "(", "isVariadic", ")", "{", "var", "func", "=", "ffi", ".", "VariadicForeignFunction", "(", "funcPtr", ",", "types", ".", "map", "(", "rtnType", ")", ",", "types", ".", "mapArray", "(", "argTypes", ")", ")", ";", "unwrapper", "=", "function", "(", ")", "{", "var", "newtypes", "=", "[", "]", ";", "// Detect the types coming in, make sure to ignore previously defined baseTypes,", "// garner a list of these then send the function through the normal exec.", "// The types system in objc, should probably be cleaned up considerably. This is", "// somewhat faulty but since 95% of objects coming through are mostly ID/Class", "// it works, we may have issues for function pointers/etc.", "for", "(", "var", "i", "=", "argTypes", ".", "length", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "if", "(", "arguments", "[", "i", "]", ".", "type", ")", "newtypes", ".", "push", "(", "arguments", "[", "i", "]", ".", "type", ")", "else", "if", "(", "arguments", "[", "i", "]", ".", "pointer", ")", "newtypes", ".", "push", "(", "'@'", ")", ";", "else", "if", "(", "typeof", "arguments", "[", "i", "]", "==", "'function'", ")", "newtypes", ".", "push", "(", "'@?'", ")", ";", "else", "if", "(", "typeof", "arguments", "[", "i", "]", "==", "'string'", ")", "newtypes", ".", "push", "(", "'r*'", ")", ";", "else", "if", "(", "typeof", "arguments", "[", "i", "]", "==", "'number'", ")", "newtypes", ".", "push", "(", "'d'", ")", ";", "else", "newtypes", ".", "push", "(", "'?'", ")", ";", "}", "return", "wrapValue", "(", "func", ".", "apply", "(", "null", ",", "types", ".", "mapArray", "(", "newtypes", ")", ")", ".", "apply", "(", "null", ",", "unwrapValues", "(", "arguments", ",", "argTypes", ".", "concat", "(", "newtypes", ")", ")", ")", ",", "rtnType", ")", ";", "}", ";", "}", "else", "{", "var", "func", "=", "ffi", ".", "ForeignFunction", "(", "funcPtr", ",", "types", ".", "map", "(", "rtnType", ")", ",", "types", ".", "mapArray", "(", "argTypes", ")", ")", ";", "unwrapper", "=", "function", "(", ")", "{", "return", "wrapValue", "(", "func", ".", "apply", "(", "null", ",", "unwrapValues", "(", "arguments", ",", "argTypes", ")", ")", ",", "rtnType", ")", ";", "}", "}", "unwrapper", ".", "retval", "=", "rtnType", ";", "unwrapper", ".", "args", "=", "argTypes", ";", "unwrapper", ".", "pointer", "=", "funcPtr", ";", "return", "unwrapper", ";", "}" ]
Creates a JS Function from the passed in function pointer. When the returned function is invoked, the passed in arguments are unwrapped before being passed to the native function, and the return value is wrapped up before being returned for real. @param {Pointer} The function pointer to create an unwrapper function around @param {Object|Array} A "type" object or Array containing the 'retval' and 'args' for the Function. @api private
[ "Creates", "a", "JS", "Function", "from", "the", "passed", "in", "function", "pointer", ".", "When", "the", "returned", "function", "is", "invoked", "the", "passed", "in", "arguments", "are", "unwrapped", "before", "being", "passed", "to", "the", "native", "function", "and", "the", "return", "value", "is", "wrapped", "up", "before", "being", "returned", "for", "real", "." ]
e4710fb8b73d3a2860de1e959e335a6de3e2191c
https://github.com/TooTallNate/NodObjC/blob/e4710fb8b73d3a2860de1e959e335a6de3e2191c/lib/core.js#L275-L312
15,809
florianholzapfel/express-restify-mongoose
src/resource_filter.js
Filter
function Filter(opts) { this.model = opts.model this.filteredKeys = isPlainObject(opts.filteredKeys) ? { private: opts.filteredKeys.private || [], protected: opts.filteredKeys.protected || [] } : { private: [], protected: [] } if (this.model && this.model.discriminators && isPlainObject(opts.excludedMap)) { for (const modelName in this.model.discriminators) { if (opts.excludedMap[modelName]) { this.filteredKeys.private = this.filteredKeys.private.concat(opts.excludedMap[modelName].private) this.filteredKeys.protected = this.filteredKeys.protected.concat(opts.excludedMap[modelName].protected) } } } }
javascript
function Filter(opts) { this.model = opts.model this.filteredKeys = isPlainObject(opts.filteredKeys) ? { private: opts.filteredKeys.private || [], protected: opts.filteredKeys.protected || [] } : { private: [], protected: [] } if (this.model && this.model.discriminators && isPlainObject(opts.excludedMap)) { for (const modelName in this.model.discriminators) { if (opts.excludedMap[modelName]) { this.filteredKeys.private = this.filteredKeys.private.concat(opts.excludedMap[modelName].private) this.filteredKeys.protected = this.filteredKeys.protected.concat(opts.excludedMap[modelName].protected) } } } }
[ "function", "Filter", "(", "opts", ")", "{", "this", ".", "model", "=", "opts", ".", "model", "this", ".", "filteredKeys", "=", "isPlainObject", "(", "opts", ".", "filteredKeys", ")", "?", "{", "private", ":", "opts", ".", "filteredKeys", ".", "private", "||", "[", "]", ",", "protected", ":", "opts", ".", "filteredKeys", ".", "protected", "||", "[", "]", "}", ":", "{", "private", ":", "[", "]", ",", "protected", ":", "[", "]", "}", "if", "(", "this", ".", "model", "&&", "this", ".", "model", ".", "discriminators", "&&", "isPlainObject", "(", "opts", ".", "excludedMap", ")", ")", "{", "for", "(", "const", "modelName", "in", "this", ".", "model", ".", "discriminators", ")", "{", "if", "(", "opts", ".", "excludedMap", "[", "modelName", "]", ")", "{", "this", ".", "filteredKeys", ".", "private", "=", "this", ".", "filteredKeys", ".", "private", ".", "concat", "(", "opts", ".", "excludedMap", "[", "modelName", "]", ".", "private", ")", "this", ".", "filteredKeys", ".", "protected", "=", "this", ".", "filteredKeys", ".", "protected", ".", "concat", "(", "opts", ".", "excludedMap", "[", "modelName", "]", ".", "protected", ")", "}", "}", "}", "}" ]
Represents a filter. @constructor @param {Object} opts - Options @param {Object} opts.model - Mongoose model @param {Object} opts.excludedMap {} - Filtered keys for related models @param {Object} opts.filteredKeys {} - Keys to filter for the current model
[ "Represents", "a", "filter", "." ]
f8b1e7990a2ad3f23edc26d2b65061e5949d7d78
https://github.com/florianholzapfel/express-restify-mongoose/blob/f8b1e7990a2ad3f23edc26d2b65061e5949d7d78/src/resource_filter.js#L18-L39
15,810
mysticatea/abort-controller
dist/abort-controller.js
createAbortSignal
function createAbortSignal() { const signal = Object.create(AbortSignal.prototype); eventTargetShim.EventTarget.call(signal); abortedFlags.set(signal, false); return signal; }
javascript
function createAbortSignal() { const signal = Object.create(AbortSignal.prototype); eventTargetShim.EventTarget.call(signal); abortedFlags.set(signal, false); return signal; }
[ "function", "createAbortSignal", "(", ")", "{", "const", "signal", "=", "Object", ".", "create", "(", "AbortSignal", ".", "prototype", ")", ";", "eventTargetShim", ".", "EventTarget", ".", "call", "(", "signal", ")", ";", "abortedFlags", ".", "set", "(", "signal", ",", "false", ")", ";", "return", "signal", ";", "}" ]
Create an AbortSignal object.
[ "Create", "an", "AbortSignal", "object", "." ]
a935d38e09eb95d6b633a8c42fcceec9969e7b05
https://github.com/mysticatea/abort-controller/blob/a935d38e09eb95d6b633a8c42fcceec9969e7b05/dist/abort-controller.js#L38-L43
15,811
mysticatea/abort-controller
dist/abort-controller.js
abortSignal
function abortSignal(signal) { if (abortedFlags.get(signal) !== false) { return; } abortedFlags.set(signal, true); signal.dispatchEvent({ type: "abort" }); }
javascript
function abortSignal(signal) { if (abortedFlags.get(signal) !== false) { return; } abortedFlags.set(signal, true); signal.dispatchEvent({ type: "abort" }); }
[ "function", "abortSignal", "(", "signal", ")", "{", "if", "(", "abortedFlags", ".", "get", "(", "signal", ")", "!==", "false", ")", "{", "return", ";", "}", "abortedFlags", ".", "set", "(", "signal", ",", "true", ")", ";", "signal", ".", "dispatchEvent", "(", "{", "type", ":", "\"abort\"", "}", ")", ";", "}" ]
Abort a given signal.
[ "Abort", "a", "given", "signal", "." ]
a935d38e09eb95d6b633a8c42fcceec9969e7b05
https://github.com/mysticatea/abort-controller/blob/a935d38e09eb95d6b633a8c42fcceec9969e7b05/dist/abort-controller.js#L47-L53
15,812
mysticatea/abort-controller
dist/abort-controller.js
getSignal
function getSignal(controller) { const signal = signals.get(controller); if (signal == null) { throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); } return signal; }
javascript
function getSignal(controller) { const signal = signals.get(controller); if (signal == null) { throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); } return signal; }
[ "function", "getSignal", "(", "controller", ")", "{", "const", "signal", "=", "signals", ".", "get", "(", "controller", ")", ";", "if", "(", "signal", "==", "null", ")", "{", "throw", "new", "TypeError", "(", "`", "${", "controller", "===", "null", "?", "\"null\"", ":", "typeof", "controller", "}", "`", ")", ";", "}", "return", "signal", ";", "}" ]
Get the associated signal of a given controller.
[ "Get", "the", "associated", "signal", "of", "a", "given", "controller", "." ]
a935d38e09eb95d6b633a8c42fcceec9969e7b05
https://github.com/mysticatea/abort-controller/blob/a935d38e09eb95d6b633a8c42fcceec9969e7b05/dist/abort-controller.js#L101-L107
15,813
htmllint/htmllint
lib/config.js
Config
function Config(rules, options) { this.options = {}; if (options) { options.forEach(this.addOption.bind(this)); } this.rulesMap = {}; if (rules) { rules.forEach(this.addRule.bind(this)); } }
javascript
function Config(rules, options) { this.options = {}; if (options) { options.forEach(this.addOption.bind(this)); } this.rulesMap = {}; if (rules) { rules.forEach(this.addRule.bind(this)); } }
[ "function", "Config", "(", "rules", ",", "options", ")", "{", "this", ".", "options", "=", "{", "}", ";", "if", "(", "options", ")", "{", "options", ".", "forEach", "(", "this", ".", "addOption", ".", "bind", "(", "this", ")", ")", ";", "}", "this", ".", "rulesMap", "=", "{", "}", ";", "if", "(", "rules", ")", "{", "rules", ".", "forEach", "(", "this", ".", "addRule", ".", "bind", "(", "this", ")", ")", ";", "}", "}" ]
The config object stores all possible rules and options and manages dependencies based on which options are enabled. As it runs, it updates the subscribers array for each rule to indicate the active rules and options depending on it. @constructor @param {Object[]} rules - The rules to use. @param {Object[]} options - The options.
[ "The", "config", "object", "stores", "all", "possible", "rules", "and", "options", "and", "manages", "dependencies", "based", "on", "which", "options", "are", "enabled", ".", "As", "it", "runs", "it", "updates", "the", "subscribers", "array", "for", "each", "rule", "to", "indicate", "the", "active", "rules", "and", "options", "depending", "on", "it", "." ]
0c23931ef2e2c66e44efad206485eba537a06db3
https://github.com/htmllint/htmllint/blob/0c23931ef2e2c66e44efad206485eba537a06db3/lib/config.js#L14-L19
15,814
htmllint/htmllint
lib/inline_config.js
function (config) { this.setOption = config.setOption.bind(config); this.isOption = function (name) { return name in config.options; }; this.clear(); }
javascript
function (config) { this.setOption = config.setOption.bind(config); this.isOption = function (name) { return name in config.options; }; this.clear(); }
[ "function", "(", "config", ")", "{", "this", ".", "setOption", "=", "config", ".", "setOption", ".", "bind", "(", "config", ")", ";", "this", ".", "isOption", "=", "function", "(", "name", ")", "{", "return", "name", "in", "config", ".", "options", ";", "}", ";", "this", ".", "clear", "(", ")", ";", "}" ]
index used for making sure configs are sent in order An inline configuration class is created to hold each inline configuration and report back what the options should be at a certain index. @constructor @param {Object} config - an option parser If not given here, it must be set with inlineConfig.reset(basis).
[ "index", "used", "for", "making", "sure", "configs", "are", "sent", "in", "order", "An", "inline", "configuration", "class", "is", "created", "to", "hold", "each", "inline", "configuration", "and", "report", "back", "what", "the", "options", "should", "be", "at", "a", "certain", "index", "." ]
0c23931ef2e2c66e44efad206485eba537a06db3
https://github.com/htmllint/htmllint/blob/0c23931ef2e2c66e44efad206485eba537a06db3/lib/inline_config.js#L16-L20
15,815
htmllint/htmllint
lib/inline_config.js
applyConfig
function applyConfig(config) { var previous = {}; config.rules.forEach(function (rule) { var isprev = (rule.value === '$previous'); var setOption = function (name, value) { previous[name] = this.current[name]; this.current[name] = this.setOption(name, value, isprev); }.bind(this); if (rule.type === 'rule') { setOption(rule.name, isprev ? this.previous[rule.name] : rule.value); /* istanbul ignore else */ } else if (rule.type === 'preset') { var preset = isprev ? this.previousPreset : presets.presets[rule.value]; Object.keys(preset).forEach(function (name) { setOption(name, preset[name]); }); } }.bind(this)); lodash.merge(this.previous, this.previousPreset = previous); }
javascript
function applyConfig(config) { var previous = {}; config.rules.forEach(function (rule) { var isprev = (rule.value === '$previous'); var setOption = function (name, value) { previous[name] = this.current[name]; this.current[name] = this.setOption(name, value, isprev); }.bind(this); if (rule.type === 'rule') { setOption(rule.name, isprev ? this.previous[rule.name] : rule.value); /* istanbul ignore else */ } else if (rule.type === 'preset') { var preset = isprev ? this.previousPreset : presets.presets[rule.value]; Object.keys(preset).forEach(function (name) { setOption(name, preset[name]); }); } }.bind(this)); lodash.merge(this.previous, this.previousPreset = previous); }
[ "function", "applyConfig", "(", "config", ")", "{", "var", "previous", "=", "{", "}", ";", "config", ".", "rules", ".", "forEach", "(", "function", "(", "rule", ")", "{", "var", "isprev", "=", "(", "rule", ".", "value", "===", "'$previous'", ")", ";", "var", "setOption", "=", "function", "(", "name", ",", "value", ")", "{", "previous", "[", "name", "]", "=", "this", ".", "current", "[", "name", "]", ";", "this", ".", "current", "[", "name", "]", "=", "this", ".", "setOption", "(", "name", ",", "value", ",", "isprev", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "if", "(", "rule", ".", "type", "===", "'rule'", ")", "{", "setOption", "(", "rule", ".", "name", ",", "isprev", "?", "this", ".", "previous", "[", "rule", ".", "name", "]", ":", "rule", ".", "value", ")", ";", "/* istanbul ignore else */", "}", "else", "if", "(", "rule", ".", "type", "===", "'preset'", ")", "{", "var", "preset", "=", "isprev", "?", "this", ".", "previousPreset", ":", "presets", ".", "presets", "[", "rule", ".", "value", "]", ";", "Object", ".", "keys", "(", "preset", ")", ".", "forEach", "(", "function", "(", "name", ")", "{", "setOption", "(", "name", ",", "preset", "[", "name", "]", ")", ";", "}", ")", ";", "}", "}", ".", "bind", "(", "this", ")", ")", ";", "lodash", ".", "merge", "(", "this", ".", "previous", ",", "this", ".", "previousPreset", "=", "previous", ")", ";", "}" ]
Apply the given cofiguration to this.current. Returns true if the operation resulted in any changes, false otherwise. @param {Object} config - the new config to write onto the current options.
[ "Apply", "the", "given", "cofiguration", "to", "this", ".", "current", ".", "Returns", "true", "if", "the", "operation", "resulted", "in", "any", "changes", "false", "otherwise", "." ]
0c23931ef2e2c66e44efad206485eba537a06db3
https://github.com/htmllint/htmllint/blob/0c23931ef2e2c66e44efad206485eba537a06db3/lib/inline_config.js#L46-L69
15,816
htmllint/htmllint
lib/inline_config.js
parsePair
function parsePair(name, value, pos, isOption) { if (!name || !value || !name.length || !value.length) { return new Issue('E050', pos); } var nameRegex = /^[a-zA-Z0-9-_]+$/; if (!nameRegex.test(name)) { return new Issue('E051', pos, {name: name}); } // Strip quotes and replace single quotes with double quotes var squote = '\'', dquote = '"'; // Single and double quote, for sanity if (value[0] === squote || value[0] === dquote) { value = value.substr(1, value.length - 2); } value = value.replace(/\'/g, dquote); // Treat _ and - interchangeably name = name.replace(/_/g, '-'); // check if our value is for a preset. if (name === 'preset') { if (value !== '$previous' && !presets.presets[value]) { return new Issue('E052', pos, {preset: value}); } else { return { type: 'preset', value: value }; } } // it's not a preset. var parsed = null; if (value === '$previous') { parsed = '$previous'; } else if (value[0] === '$') { var vs = value.substr(1); if (!presets.presets[vs]) { return new Issue('E052', pos, {preset: vs}); } parsed = presets.presets[vs][name]; } else { if (!isOption(name)) { return new Issue('E054', pos, {name: name}); } try { parsed = JSON.parse(value); } catch (e) { if (!nameRegex.test(value)) { return new Issue('E053', pos, {rule: name, value: value}); } parsed = value; } } return { type: 'rule', name: name, value: parsed }; }
javascript
function parsePair(name, value, pos, isOption) { if (!name || !value || !name.length || !value.length) { return new Issue('E050', pos); } var nameRegex = /^[a-zA-Z0-9-_]+$/; if (!nameRegex.test(name)) { return new Issue('E051', pos, {name: name}); } // Strip quotes and replace single quotes with double quotes var squote = '\'', dquote = '"'; // Single and double quote, for sanity if (value[0] === squote || value[0] === dquote) { value = value.substr(1, value.length - 2); } value = value.replace(/\'/g, dquote); // Treat _ and - interchangeably name = name.replace(/_/g, '-'); // check if our value is for a preset. if (name === 'preset') { if (value !== '$previous' && !presets.presets[value]) { return new Issue('E052', pos, {preset: value}); } else { return { type: 'preset', value: value }; } } // it's not a preset. var parsed = null; if (value === '$previous') { parsed = '$previous'; } else if (value[0] === '$') { var vs = value.substr(1); if (!presets.presets[vs]) { return new Issue('E052', pos, {preset: vs}); } parsed = presets.presets[vs][name]; } else { if (!isOption(name)) { return new Issue('E054', pos, {name: name}); } try { parsed = JSON.parse(value); } catch (e) { if (!nameRegex.test(value)) { return new Issue('E053', pos, {rule: name, value: value}); } parsed = value; } } return { type: 'rule', name: name, value: parsed }; }
[ "function", "parsePair", "(", "name", ",", "value", ",", "pos", ",", "isOption", ")", "{", "if", "(", "!", "name", "||", "!", "value", "||", "!", "name", ".", "length", "||", "!", "value", ".", "length", ")", "{", "return", "new", "Issue", "(", "'E050'", ",", "pos", ")", ";", "}", "var", "nameRegex", "=", "/", "^[a-zA-Z0-9-_]+$", "/", ";", "if", "(", "!", "nameRegex", ".", "test", "(", "name", ")", ")", "{", "return", "new", "Issue", "(", "'E051'", ",", "pos", ",", "{", "name", ":", "name", "}", ")", ";", "}", "// Strip quotes and replace single quotes with double quotes", "var", "squote", "=", "'\\''", ",", "dquote", "=", "'\"'", ";", "// Single and double quote, for sanity", "if", "(", "value", "[", "0", "]", "===", "squote", "||", "value", "[", "0", "]", "===", "dquote", ")", "{", "value", "=", "value", ".", "substr", "(", "1", ",", "value", ".", "length", "-", "2", ")", ";", "}", "value", "=", "value", ".", "replace", "(", "/", "\\'", "/", "g", ",", "dquote", ")", ";", "// Treat _ and - interchangeably", "name", "=", "name", ".", "replace", "(", "/", "_", "/", "g", ",", "'-'", ")", ";", "// check if our value is for a preset.", "if", "(", "name", "===", "'preset'", ")", "{", "if", "(", "value", "!==", "'$previous'", "&&", "!", "presets", ".", "presets", "[", "value", "]", ")", "{", "return", "new", "Issue", "(", "'E052'", ",", "pos", ",", "{", "preset", ":", "value", "}", ")", ";", "}", "else", "{", "return", "{", "type", ":", "'preset'", ",", "value", ":", "value", "}", ";", "}", "}", "// it's not a preset.", "var", "parsed", "=", "null", ";", "if", "(", "value", "===", "'$previous'", ")", "{", "parsed", "=", "'$previous'", ";", "}", "else", "if", "(", "value", "[", "0", "]", "===", "'$'", ")", "{", "var", "vs", "=", "value", ".", "substr", "(", "1", ")", ";", "if", "(", "!", "presets", ".", "presets", "[", "vs", "]", ")", "{", "return", "new", "Issue", "(", "'E052'", ",", "pos", ",", "{", "preset", ":", "vs", "}", ")", ";", "}", "parsed", "=", "presets", ".", "presets", "[", "vs", "]", "[", "name", "]", ";", "}", "else", "{", "if", "(", "!", "isOption", "(", "name", ")", ")", "{", "return", "new", "Issue", "(", "'E054'", ",", "pos", ",", "{", "name", ":", "name", "}", ")", ";", "}", "try", "{", "parsed", "=", "JSON", ".", "parse", "(", "value", ")", ";", "}", "catch", "(", "e", ")", "{", "if", "(", "!", "nameRegex", ".", "test", "(", "value", ")", ")", "{", "return", "new", "Issue", "(", "'E053'", ",", "pos", ",", "{", "rule", ":", "name", ",", "value", ":", "value", "}", ")", ";", "}", "parsed", "=", "value", ";", "}", "}", "return", "{", "type", ":", "'rule'", ",", "name", ":", "name", ",", "value", ":", "parsed", "}", ";", "}" ]
Accept an attribute and return either a parsed config pair object or an error string. @param {string} name - The attribute name. @param {string} value - The attribute raw value.
[ "Accept", "an", "attribute", "and", "return", "either", "a", "parsed", "config", "pair", "object", "or", "an", "error", "string", "." ]
0c23931ef2e2c66e44efad206485eba537a06db3
https://github.com/htmllint/htmllint/blob/0c23931ef2e2c66e44efad206485eba537a06db3/lib/inline_config.js#L138-L192
15,817
htmllint/htmllint
lib/linter.js
function (rules, options) { this.rules = new Config(rules, options); this.parser = new Parser(); this.inlineConfig = new InlineConfig(this.rules); }
javascript
function (rules, options) { this.rules = new Config(rules, options); this.parser = new Parser(); this.inlineConfig = new InlineConfig(this.rules); }
[ "function", "(", "rules", ",", "options", ")", "{", "this", ".", "rules", "=", "new", "Config", "(", "rules", ",", "options", ")", ";", "this", ".", "parser", "=", "new", "Parser", "(", ")", ";", "this", ".", "inlineConfig", "=", "new", "InlineConfig", "(", "this", ".", "rules", ")", ";", "}" ]
A linter is configured with a set of rules that are fed the raw html and ast nodes. @constructor
[ "A", "linter", "is", "configured", "with", "a", "set", "of", "rules", "that", "are", "fed", "the", "raw", "html", "and", "ast", "nodes", "." ]
0c23931ef2e2c66e44efad206485eba537a06db3
https://github.com/htmllint/htmllint/blob/0c23931ef2e2c66e44efad206485eba537a06db3/lib/linter.js#L14-L18
15,818
mpowaga/react-slider
react-slider.js
linspace
function linspace(min, max, count) { var range = (max - min) / (count - 1); var res = []; for (var i = 0; i < count; i++) { res.push(min + range * i); } return res; }
javascript
function linspace(min, max, count) { var range = (max - min) / (count - 1); var res = []; for (var i = 0; i < count; i++) { res.push(min + range * i); } return res; }
[ "function", "linspace", "(", "min", ",", "max", ",", "count", ")", "{", "var", "range", "=", "(", "max", "-", "min", ")", "/", "(", "count", "-", "1", ")", ";", "var", "res", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "res", ".", "push", "(", "min", "+", "range", "*", "i", ")", ";", "}", "return", "res", ";", "}" ]
Spreads `count` values equally between `min` and `max`.
[ "Spreads", "count", "values", "equally", "between", "min", "and", "max", "." ]
7602789fd375ed3096cfc78b3e813ed9748ecdd9
https://github.com/mpowaga/react-slider/blob/7602789fd375ed3096cfc78b3e813ed9748ecdd9/react-slider.js#L28-L35
15,819
mpowaga/react-slider
react-slider.js
function (newProps) { var value = this._or(ensureArray(newProps.value), this.state.value); // ensure the array keeps the same size as `value` this.tempArray = value.slice(); for (var i = 0; i < value.length; i++) { this.state.value[i] = this._trimAlignValue(value[i], newProps); } if (this.state.value.length > value.length) this.state.value.length = value.length; // If an upperBound has not yet been determined (due to the component being hidden // during the mount event, or during the last resize), then calculate it now if (this.state.upperBound === 0) { this._resize(); } }
javascript
function (newProps) { var value = this._or(ensureArray(newProps.value), this.state.value); // ensure the array keeps the same size as `value` this.tempArray = value.slice(); for (var i = 0; i < value.length; i++) { this.state.value[i] = this._trimAlignValue(value[i], newProps); } if (this.state.value.length > value.length) this.state.value.length = value.length; // If an upperBound has not yet been determined (due to the component being hidden // during the mount event, or during the last resize), then calculate it now if (this.state.upperBound === 0) { this._resize(); } }
[ "function", "(", "newProps", ")", "{", "var", "value", "=", "this", ".", "_or", "(", "ensureArray", "(", "newProps", ".", "value", ")", ",", "this", ".", "state", ".", "value", ")", ";", "// ensure the array keeps the same size as `value`", "this", ".", "tempArray", "=", "value", ".", "slice", "(", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "value", ".", "length", ";", "i", "++", ")", "{", "this", ".", "state", ".", "value", "[", "i", "]", "=", "this", ".", "_trimAlignValue", "(", "value", "[", "i", "]", ",", "newProps", ")", ";", "}", "if", "(", "this", ".", "state", ".", "value", ".", "length", ">", "value", ".", "length", ")", "this", ".", "state", ".", "value", ".", "length", "=", "value", ".", "length", ";", "// If an upperBound has not yet been determined (due to the component being hidden", "// during the mount event, or during the last resize), then calculate it now", "if", "(", "this", ".", "state", ".", "upperBound", "===", "0", ")", "{", "this", ".", "_resize", "(", ")", ";", "}", "}" ]
Keep the internal `value` consistent with an outside `value` if present. This basically allows the slider to be a controlled component.
[ "Keep", "the", "internal", "value", "consistent", "with", "an", "outside", "value", "if", "present", ".", "This", "basically", "allows", "the", "slider", "to", "be", "a", "controlled", "component", "." ]
7602789fd375ed3096cfc78b3e813ed9748ecdd9
https://github.com/mpowaga/react-slider/blob/7602789fd375ed3096cfc78b3e813ed9748ecdd9/react-slider.js#L224-L241
15,820
mpowaga/react-slider
react-slider.js
function (value) { var range = this.props.max - this.props.min; if (range === 0) { return 0; } var ratio = (value - this.props.min) / range; return ratio * this.state.upperBound; }
javascript
function (value) { var range = this.props.max - this.props.min; if (range === 0) { return 0; } var ratio = (value - this.props.min) / range; return ratio * this.state.upperBound; }
[ "function", "(", "value", ")", "{", "var", "range", "=", "this", ".", "props", ".", "max", "-", "this", ".", "props", ".", "min", ";", "if", "(", "range", "===", "0", ")", "{", "return", "0", ";", "}", "var", "ratio", "=", "(", "value", "-", "this", ".", "props", ".", "min", ")", "/", "range", ";", "return", "ratio", "*", "this", ".", "state", ".", "upperBound", ";", "}" ]
calculates the offset of a handle in pixels based on its value.
[ "calculates", "the", "offset", "of", "a", "handle", "in", "pixels", "based", "on", "its", "value", "." ]
7602789fd375ed3096cfc78b3e813ed9748ecdd9
https://github.com/mpowaga/react-slider/blob/7602789fd375ed3096cfc78b3e813ed9748ecdd9/react-slider.js#L318-L325
15,821
mpowaga/react-slider
react-slider.js
function (offset) { var ratio = offset / this.state.upperBound; return ratio * (this.props.max - this.props.min) + this.props.min; }
javascript
function (offset) { var ratio = offset / this.state.upperBound; return ratio * (this.props.max - this.props.min) + this.props.min; }
[ "function", "(", "offset", ")", "{", "var", "ratio", "=", "offset", "/", "this", ".", "state", ".", "upperBound", ";", "return", "ratio", "*", "(", "this", ".", "props", ".", "max", "-", "this", ".", "props", ".", "min", ")", "+", "this", ".", "props", ".", "min", ";", "}" ]
calculates the value corresponding to a given pixel offset, i.e. the inverse of `_calcOffset`.
[ "calculates", "the", "value", "corresponding", "to", "a", "given", "pixel", "offset", "i", ".", "e", ".", "the", "inverse", "of", "_calcOffset", "." ]
7602789fd375ed3096cfc78b3e813ed9748ecdd9
https://github.com/mpowaga/react-slider/blob/7602789fd375ed3096cfc78b3e813ed9748ecdd9/react-slider.js#L328-L331
15,822
mpowaga/react-slider
react-slider.js
function (position, callback) { var pixelOffset = this._calcOffsetFromPosition(position); var closestIndex = this._getClosestIndex(pixelOffset); var nextValue = this._trimAlignValue(this._calcValue(pixelOffset)); var value = this.state.value.slice(); // Clone this.state.value since we'll modify it temporarily value[closestIndex] = nextValue; // Prevents the slider from shrinking below `props.minDistance` for (var i = 0; i < value.length - 1; i += 1) { if (value[i + 1] - value[i] < this.props.minDistance) return; } this.setState({value: value}, callback.bind(this, closestIndex)); }
javascript
function (position, callback) { var pixelOffset = this._calcOffsetFromPosition(position); var closestIndex = this._getClosestIndex(pixelOffset); var nextValue = this._trimAlignValue(this._calcValue(pixelOffset)); var value = this.state.value.slice(); // Clone this.state.value since we'll modify it temporarily value[closestIndex] = nextValue; // Prevents the slider from shrinking below `props.minDistance` for (var i = 0; i < value.length - 1; i += 1) { if (value[i + 1] - value[i] < this.props.minDistance) return; } this.setState({value: value}, callback.bind(this, closestIndex)); }
[ "function", "(", "position", ",", "callback", ")", "{", "var", "pixelOffset", "=", "this", ".", "_calcOffsetFromPosition", "(", "position", ")", ";", "var", "closestIndex", "=", "this", ".", "_getClosestIndex", "(", "pixelOffset", ")", ";", "var", "nextValue", "=", "this", ".", "_trimAlignValue", "(", "this", ".", "_calcValue", "(", "pixelOffset", ")", ")", ";", "var", "value", "=", "this", ".", "state", ".", "value", ".", "slice", "(", ")", ";", "// Clone this.state.value since we'll modify it temporarily", "value", "[", "closestIndex", "]", "=", "nextValue", ";", "// Prevents the slider from shrinking below `props.minDistance`", "for", "(", "var", "i", "=", "0", ";", "i", "<", "value", ".", "length", "-", "1", ";", "i", "+=", "1", ")", "{", "if", "(", "value", "[", "i", "+", "1", "]", "-", "value", "[", "i", "]", "<", "this", ".", "props", ".", "minDistance", ")", "return", ";", "}", "this", ".", "setState", "(", "{", "value", ":", "value", "}", ",", "callback", ".", "bind", "(", "this", ",", "closestIndex", ")", ")", ";", "}" ]
Snaps the nearest handle to the value corresponding to `position` and calls `callback` with that handle's index.
[ "Snaps", "the", "nearest", "handle", "to", "the", "value", "corresponding", "to", "position", "and", "calls", "callback", "with", "that", "handle", "s", "index", "." ]
7602789fd375ed3096cfc78b3e813ed9748ecdd9
https://github.com/mpowaga/react-slider/blob/7602789fd375ed3096cfc78b3e813ed9748ecdd9/react-slider.js#L380-L394
15,823
mpowaga/react-slider
react-slider.js
function (i) { return function (e) { if (this.props.disabled) return; this._start(i); this._addHandlers(this._getKeyDownEventMap()); pauseEvent(e); }.bind(this); }
javascript
function (i) { return function (e) { if (this.props.disabled) return; this._start(i); this._addHandlers(this._getKeyDownEventMap()); pauseEvent(e); }.bind(this); }
[ "function", "(", "i", ")", "{", "return", "function", "(", "e", ")", "{", "if", "(", "this", ".", "props", ".", "disabled", ")", "return", ";", "this", ".", "_start", "(", "i", ")", ";", "this", ".", "_addHandlers", "(", "this", ".", "_getKeyDownEventMap", "(", ")", ")", ";", "pauseEvent", "(", "e", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "}" ]
create the `keydown` handler for the i-th handle
[ "create", "the", "keydown", "handler", "for", "the", "i", "-", "th", "handle" ]
7602789fd375ed3096cfc78b3e813ed9748ecdd9
https://github.com/mpowaga/react-slider/blob/7602789fd375ed3096cfc78b3e813ed9748ecdd9/react-slider.js#L433-L440
15,824
mpowaga/react-slider
react-slider.js
function (i) { return function (e) { if (this.props.disabled) return; var position = this._getMousePosition(e); this._start(i, position[0]); this._addHandlers(this._getMouseEventMap()); pauseEvent(e); }.bind(this); }
javascript
function (i) { return function (e) { if (this.props.disabled) return; var position = this._getMousePosition(e); this._start(i, position[0]); this._addHandlers(this._getMouseEventMap()); pauseEvent(e); }.bind(this); }
[ "function", "(", "i", ")", "{", "return", "function", "(", "e", ")", "{", "if", "(", "this", ".", "props", ".", "disabled", ")", "return", ";", "var", "position", "=", "this", ".", "_getMousePosition", "(", "e", ")", ";", "this", ".", "_start", "(", "i", ",", "position", "[", "0", "]", ")", ";", "this", ".", "_addHandlers", "(", "this", ".", "_getMouseEventMap", "(", ")", ")", ";", "pauseEvent", "(", "e", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "}" ]
create the `mousedown` handler for the i-th handle
[ "create", "the", "mousedown", "handler", "for", "the", "i", "-", "th", "handle" ]
7602789fd375ed3096cfc78b3e813ed9748ecdd9
https://github.com/mpowaga/react-slider/blob/7602789fd375ed3096cfc78b3e813ed9748ecdd9/react-slider.js#L443-L451
15,825
mpowaga/react-slider
react-slider.js
function (i) { return function (e) { if (this.props.disabled || e.touches.length > 1) return; var position = this._getTouchPosition(e); this.startPosition = position; this.isScrolling = undefined; // don't know yet if the user is trying to scroll this._start(i, position[0]); this._addHandlers(this._getTouchEventMap()); stopPropagation(e); }.bind(this); }
javascript
function (i) { return function (e) { if (this.props.disabled || e.touches.length > 1) return; var position = this._getTouchPosition(e); this.startPosition = position; this.isScrolling = undefined; // don't know yet if the user is trying to scroll this._start(i, position[0]); this._addHandlers(this._getTouchEventMap()); stopPropagation(e); }.bind(this); }
[ "function", "(", "i", ")", "{", "return", "function", "(", "e", ")", "{", "if", "(", "this", ".", "props", ".", "disabled", "||", "e", ".", "touches", ".", "length", ">", "1", ")", "return", ";", "var", "position", "=", "this", ".", "_getTouchPosition", "(", "e", ")", ";", "this", ".", "startPosition", "=", "position", ";", "this", ".", "isScrolling", "=", "undefined", ";", "// don't know yet if the user is trying to scroll", "this", ".", "_start", "(", "i", ",", "position", "[", "0", "]", ")", ";", "this", ".", "_addHandlers", "(", "this", ".", "_getTouchEventMap", "(", ")", ")", ";", "stopPropagation", "(", "e", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "}" ]
create the `touchstart` handler for the i-th handle
[ "create", "the", "touchstart", "handler", "for", "the", "i", "-", "th", "handle" ]
7602789fd375ed3096cfc78b3e813ed9748ecdd9
https://github.com/mpowaga/react-slider/blob/7602789fd375ed3096cfc78b3e813ed9748ecdd9/react-slider.js#L454-L464
15,826
Rovak/InlineAttachment
src/inline-attachment.js
function() { var result = {}; for (var i = arguments.length - 1; i >= 0; i--) { var obj = arguments[i]; for (var k in obj) { if (obj.hasOwnProperty(k)) { result[k] = obj[k]; } } } return result; }
javascript
function() { var result = {}; for (var i = arguments.length - 1; i >= 0; i--) { var obj = arguments[i]; for (var k in obj) { if (obj.hasOwnProperty(k)) { result[k] = obj[k]; } } } return result; }
[ "function", "(", ")", "{", "var", "result", "=", "{", "}", ";", "for", "(", "var", "i", "=", "arguments", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "var", "obj", "=", "arguments", "[", "i", "]", ";", "for", "(", "var", "k", "in", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "result", "[", "k", "]", "=", "obj", "[", "k", "]", ";", "}", "}", "}", "return", "result", ";", "}" ]
Simple function to merge the given objects @param {Object[]} object Multiple object parameters @returns {Object}
[ "Simple", "function", "to", "merge", "the", "given", "objects" ]
b18f8a5973fddd2a7407c3f1a7854cf81f8a60c8
https://github.com/Rovak/InlineAttachment/blob/b18f8a5973fddd2a7407c3f1a7854cf81f8a60c8/src/inline-attachment.js#L37-L48
15,827
Rovak/InlineAttachment
src/inline-attachment.js
function(el, text) { var scrollPos = el.scrollTop, strPos = 0, browser = false, range; if ((el.selectionStart || el.selectionStart === '0')) { browser = "ff"; } else if (document.selection) { browser = "ie"; } if (browser === "ie") { el.focus(); range = document.selection.createRange(); range.moveStart('character', -el.value.length); strPos = range.text.length; } else if (browser === "ff") { strPos = el.selectionStart; } var front = (el.value).substring(0, strPos); var back = (el.value).substring(strPos, el.value.length); el.value = front + text + back; strPos = strPos + text.length; if (browser === "ie") { el.focus(); range = document.selection.createRange(); range.moveStart('character', -el.value.length); range.moveStart('character', strPos); range.moveEnd('character', 0); range.select(); } else if (browser === "ff") { el.selectionStart = strPos; el.selectionEnd = strPos; el.focus(); } el.scrollTop = scrollPos; }
javascript
function(el, text) { var scrollPos = el.scrollTop, strPos = 0, browser = false, range; if ((el.selectionStart || el.selectionStart === '0')) { browser = "ff"; } else if (document.selection) { browser = "ie"; } if (browser === "ie") { el.focus(); range = document.selection.createRange(); range.moveStart('character', -el.value.length); strPos = range.text.length; } else if (browser === "ff") { strPos = el.selectionStart; } var front = (el.value).substring(0, strPos); var back = (el.value).substring(strPos, el.value.length); el.value = front + text + back; strPos = strPos + text.length; if (browser === "ie") { el.focus(); range = document.selection.createRange(); range.moveStart('character', -el.value.length); range.moveStart('character', strPos); range.moveEnd('character', 0); range.select(); } else if (browser === "ff") { el.selectionStart = strPos; el.selectionEnd = strPos; el.focus(); } el.scrollTop = scrollPos; }
[ "function", "(", "el", ",", "text", ")", "{", "var", "scrollPos", "=", "el", ".", "scrollTop", ",", "strPos", "=", "0", ",", "browser", "=", "false", ",", "range", ";", "if", "(", "(", "el", ".", "selectionStart", "||", "el", ".", "selectionStart", "===", "'0'", ")", ")", "{", "browser", "=", "\"ff\"", ";", "}", "else", "if", "(", "document", ".", "selection", ")", "{", "browser", "=", "\"ie\"", ";", "}", "if", "(", "browser", "===", "\"ie\"", ")", "{", "el", ".", "focus", "(", ")", ";", "range", "=", "document", ".", "selection", ".", "createRange", "(", ")", ";", "range", ".", "moveStart", "(", "'character'", ",", "-", "el", ".", "value", ".", "length", ")", ";", "strPos", "=", "range", ".", "text", ".", "length", ";", "}", "else", "if", "(", "browser", "===", "\"ff\"", ")", "{", "strPos", "=", "el", ".", "selectionStart", ";", "}", "var", "front", "=", "(", "el", ".", "value", ")", ".", "substring", "(", "0", ",", "strPos", ")", ";", "var", "back", "=", "(", "el", ".", "value", ")", ".", "substring", "(", "strPos", ",", "el", ".", "value", ".", "length", ")", ";", "el", ".", "value", "=", "front", "+", "text", "+", "back", ";", "strPos", "=", "strPos", "+", "text", ".", "length", ";", "if", "(", "browser", "===", "\"ie\"", ")", "{", "el", ".", "focus", "(", ")", ";", "range", "=", "document", ".", "selection", ".", "createRange", "(", ")", ";", "range", ".", "moveStart", "(", "'character'", ",", "-", "el", ".", "value", ".", "length", ")", ";", "range", ".", "moveStart", "(", "'character'", ",", "strPos", ")", ";", "range", ".", "moveEnd", "(", "'character'", ",", "0", ")", ";", "range", ".", "select", "(", ")", ";", "}", "else", "if", "(", "browser", "===", "\"ff\"", ")", "{", "el", ".", "selectionStart", "=", "strPos", ";", "el", ".", "selectionEnd", "=", "strPos", ";", "el", ".", "focus", "(", ")", ";", "}", "el", ".", "scrollTop", "=", "scrollPos", ";", "}" ]
Inserts the given value at the current cursor position of the textarea element @param {HtmlElement} el @param {String} value Text which will be inserted at the cursor position
[ "Inserts", "the", "given", "value", "at", "the", "current", "cursor", "position", "of", "the", "textarea", "element" ]
b18f8a5973fddd2a7407c3f1a7854cf81f8a60c8
https://github.com/Rovak/InlineAttachment/blob/b18f8a5973fddd2a7407c3f1a7854cf81f8a60c8/src/inline-attachment.js#L68-L106
15,828
Rovak/InlineAttachment
dist/angularjs.inline-attachment.js
readParameters
function readParameters(obj, scope) { var result = {}, attrs = obj.$attr, option, value; for (var key in attrs) { option = lcfirst(key.substr(attrName.length)); value = obj[key]; // Check if the given key is a valid string type, not empty and starts with the attribute name if ((option.length > 0) && (key.substring(0, attrName.length) === attrName)) { result[option] = value; if (typeof scope[value] === 'function') { result[option] = scope[value]; } } } return result; }
javascript
function readParameters(obj, scope) { var result = {}, attrs = obj.$attr, option, value; for (var key in attrs) { option = lcfirst(key.substr(attrName.length)); value = obj[key]; // Check if the given key is a valid string type, not empty and starts with the attribute name if ((option.length > 0) && (key.substring(0, attrName.length) === attrName)) { result[option] = value; if (typeof scope[value] === 'function') { result[option] = scope[value]; } } } return result; }
[ "function", "readParameters", "(", "obj", ",", "scope", ")", "{", "var", "result", "=", "{", "}", ",", "attrs", "=", "obj", ".", "$attr", ",", "option", ",", "value", ";", "for", "(", "var", "key", "in", "attrs", ")", "{", "option", "=", "lcfirst", "(", "key", ".", "substr", "(", "attrName", ".", "length", ")", ")", ";", "value", "=", "obj", "[", "key", "]", ";", "// Check if the given key is a valid string type, not empty and starts with the attribute name", "if", "(", "(", "option", ".", "length", ">", "0", ")", "&&", "(", "key", ".", "substring", "(", "0", ",", "attrName", ".", "length", ")", "===", "attrName", ")", ")", "{", "result", "[", "option", "]", "=", "value", ";", "if", "(", "typeof", "scope", "[", "value", "]", "===", "'function'", ")", "{", "result", "[", "option", "]", "=", "scope", "[", "value", "]", ";", "}", "}", "}", "return", "result", ";", "}" ]
Read all parameters from the given attributes object @param {Object} obj attributes @return {Object}
[ "Read", "all", "parameters", "from", "the", "given", "attributes", "object" ]
b18f8a5973fddd2a7407c3f1a7854cf81f8a60c8
https://github.com/Rovak/InlineAttachment/blob/b18f8a5973fddd2a7407c3f1a7854cf81f8a60c8/dist/angularjs.inline-attachment.js#L477-L495
15,829
Rovak/InlineAttachment
dist/jquery.inline-attachment.js
function(instance) { var $this = $(instance); return { getValue: function() { return $this.val(); }, insertValue: function(val) { inlineAttachment.util.insertTextAtCursor($this[0], val); }, setValue: function(val) { $this.val(val); } }; }
javascript
function(instance) { var $this = $(instance); return { getValue: function() { return $this.val(); }, insertValue: function(val) { inlineAttachment.util.insertTextAtCursor($this[0], val); }, setValue: function(val) { $this.val(val); } }; }
[ "function", "(", "instance", ")", "{", "var", "$this", "=", "$", "(", "instance", ")", ";", "return", "{", "getValue", ":", "function", "(", ")", "{", "return", "$this", ".", "val", "(", ")", ";", "}", ",", "insertValue", ":", "function", "(", "val", ")", "{", "inlineAttachment", ".", "util", ".", "insertTextAtCursor", "(", "$this", "[", "0", "]", ",", "val", ")", ";", "}", ",", "setValue", ":", "function", "(", "val", ")", "{", "$this", ".", "val", "(", "val", ")", ";", "}", "}", ";", "}" ]
Creates a new editor using jQuery
[ "Creates", "a", "new", "editor", "using", "jQuery" ]
b18f8a5973fddd2a7407c3f1a7854cf81f8a60c8
https://github.com/Rovak/InlineAttachment/blob/b18f8a5973fddd2a7407c3f1a7854cf81f8a60c8/dist/jquery.inline-attachment.js#L419-L434
15,830
jscad/csg.js
src/moveOutOfCode/Plane.js
function (matrix4x4) { let ismirror = matrix4x4.isMirroring() // get two vectors in the plane: let r = this.normal.randomNonParallelVector() let u = this.normal.cross(r) let v = this.normal.cross(u) // get 3 points in the plane: let point1 = this.normal.times(this.w) let point2 = point1.plus(u) let point3 = point1.plus(v) // transform the points: point1 = point1.multiply4x4(matrix4x4) point2 = point2.multiply4x4(matrix4x4) point3 = point3.multiply4x4(matrix4x4) // and create a new plane from the transformed points: let newplane = Plane.fromVector3Ds(point1, point2, point3) if (ismirror) { // the transform is mirroring // We should mirror the plane: newplane = newplane.flipped() } return newplane }
javascript
function (matrix4x4) { let ismirror = matrix4x4.isMirroring() // get two vectors in the plane: let r = this.normal.randomNonParallelVector() let u = this.normal.cross(r) let v = this.normal.cross(u) // get 3 points in the plane: let point1 = this.normal.times(this.w) let point2 = point1.plus(u) let point3 = point1.plus(v) // transform the points: point1 = point1.multiply4x4(matrix4x4) point2 = point2.multiply4x4(matrix4x4) point3 = point3.multiply4x4(matrix4x4) // and create a new plane from the transformed points: let newplane = Plane.fromVector3Ds(point1, point2, point3) if (ismirror) { // the transform is mirroring // We should mirror the plane: newplane = newplane.flipped() } return newplane }
[ "function", "(", "matrix4x4", ")", "{", "let", "ismirror", "=", "matrix4x4", ".", "isMirroring", "(", ")", "// get two vectors in the plane:", "let", "r", "=", "this", ".", "normal", ".", "randomNonParallelVector", "(", ")", "let", "u", "=", "this", ".", "normal", ".", "cross", "(", "r", ")", "let", "v", "=", "this", ".", "normal", ".", "cross", "(", "u", ")", "// get 3 points in the plane:", "let", "point1", "=", "this", ".", "normal", ".", "times", "(", "this", ".", "w", ")", "let", "point2", "=", "point1", ".", "plus", "(", "u", ")", "let", "point3", "=", "point1", ".", "plus", "(", "v", ")", "// transform the points:", "point1", "=", "point1", ".", "multiply4x4", "(", "matrix4x4", ")", "point2", "=", "point2", ".", "multiply4x4", "(", "matrix4x4", ")", "point3", "=", "point3", ".", "multiply4x4", "(", "matrix4x4", ")", "// and create a new plane from the transformed points:", "let", "newplane", "=", "Plane", ".", "fromVector3Ds", "(", "point1", ",", "point2", ",", "point3", ")", "if", "(", "ismirror", ")", "{", "// the transform is mirroring", "// We should mirror the plane:", "newplane", "=", "newplane", ".", "flipped", "(", ")", "}", "return", "newplane", "}" ]
CONVERTED TO V2
[ "CONVERTED", "TO", "V2" ]
461bf2c93f175f1e1450506a9f62e737cf81c357
https://github.com/jscad/csg.js/blob/461bf2c93f175f1e1450506a9f62e737cf81c357/src/moveOutOfCode/Plane.js#L91-L113
15,831
jscad/csg.js
src/moveOutOfCode/Plane.js
function (p1, p2) { let direction = p2.minus(p1) let labda = (this.w - this.normal.dot(p1)) / this.normal.dot(direction) if (isNaN(labda)) labda = 0 if (labda > 1) labda = 1 if (labda < 0) labda = 0 let result = p1.plus(direction.times(labda)) return result }
javascript
function (p1, p2) { let direction = p2.minus(p1) let labda = (this.w - this.normal.dot(p1)) / this.normal.dot(direction) if (isNaN(labda)) labda = 0 if (labda > 1) labda = 1 if (labda < 0) labda = 0 let result = p1.plus(direction.times(labda)) return result }
[ "function", "(", "p1", ",", "p2", ")", "{", "let", "direction", "=", "p2", ".", "minus", "(", "p1", ")", "let", "labda", "=", "(", "this", ".", "w", "-", "this", ".", "normal", ".", "dot", "(", "p1", ")", ")", "/", "this", ".", "normal", ".", "dot", "(", "direction", ")", "if", "(", "isNaN", "(", "labda", ")", ")", "labda", "=", "0", "if", "(", "labda", ">", "1", ")", "labda", "=", "1", "if", "(", "labda", "<", "0", ")", "labda", "=", "0", "let", "result", "=", "p1", ".", "plus", "(", "direction", ".", "times", "(", "labda", ")", ")", "return", "result", "}" ]
robust splitting of a line by a plane will work even if the line is parallel to the plane CONVERTED TO V2
[ "robust", "splitting", "of", "a", "line", "by", "a", "plane", "will", "work", "even", "if", "the", "line", "is", "parallel", "to", "the", "plane", "CONVERTED", "TO", "V2" ]
461bf2c93f175f1e1450506a9f62e737cf81c357
https://github.com/jscad/csg.js/blob/461bf2c93f175f1e1450506a9f62e737cf81c357/src/moveOutOfCode/Plane.js#L118-L126
15,832
jscad/csg.js
src/text/vectorParams.js
vectorParams
function vectorParams (options, input) { if (!input && typeof options === 'string') { options = { input: options } } options = options || {} let params = Object.assign({}, defaultsVectorParams, options) params.input = input || params.input return params }
javascript
function vectorParams (options, input) { if (!input && typeof options === 'string') { options = { input: options } } options = options || {} let params = Object.assign({}, defaultsVectorParams, options) params.input = input || params.input return params }
[ "function", "vectorParams", "(", "options", ",", "input", ")", "{", "if", "(", "!", "input", "&&", "typeof", "options", "===", "'string'", ")", "{", "options", "=", "{", "input", ":", "options", "}", "}", "options", "=", "options", "||", "{", "}", "let", "params", "=", "Object", ".", "assign", "(", "{", "}", ",", "defaultsVectorParams", ",", "options", ")", "params", ".", "input", "=", "input", "||", "params", ".", "input", "return", "params", "}" ]
vectorsXXX parameters handler
[ "vectorsXXX", "parameters", "handler" ]
461bf2c93f175f1e1450506a9f62e737cf81c357
https://github.com/jscad/csg.js/blob/461bf2c93f175f1e1450506a9f62e737cf81c357/src/text/vectorParams.js#L16-L24
15,833
jscad/csg.js
src/core/geometry/geom3/setShared.js
setShared
function setShared (shared) { let polygons = this.polygons.map(function (p) { return new Polygon3(p.vertices, shared, p.plane) }) let result = fromPolygons(polygons) result.properties = this.properties // keep original properties result.isRetesselated = this.isRetesselated result.isCanonicalized = this.isCanonicalized return result }
javascript
function setShared (shared) { let polygons = this.polygons.map(function (p) { return new Polygon3(p.vertices, shared, p.plane) }) let result = fromPolygons(polygons) result.properties = this.properties // keep original properties result.isRetesselated = this.isRetesselated result.isCanonicalized = this.isCanonicalized return result }
[ "function", "setShared", "(", "shared", ")", "{", "let", "polygons", "=", "this", ".", "polygons", ".", "map", "(", "function", "(", "p", ")", "{", "return", "new", "Polygon3", "(", "p", ".", "vertices", ",", "shared", ",", "p", ".", "plane", ")", "}", ")", "let", "result", "=", "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 @param {Object} shared @returns {Geom3} Returns a new Geom3 solid, the original is unmodified!
[ "set", "the", ".", "shared", "property", "of", "all", "polygons" ]
461bf2c93f175f1e1450506a9f62e737cf81c357
https://github.com/jscad/csg.js/blob/461bf2c93f175f1e1450506a9f62e737cf81c357/src/core/geometry/geom3/setShared.js#L8-L17
15,834
jscad/csg.js
src/api/primitives/polyhedron.js
function (options) { options = options || {} if (('points' in options) !== ('faces' in options)) { throw new Error("polyhedron needs 'points' and 'faces' arrays") } let vertices = parseOptionAs3DVectorList(options, 'points', [ [1, 1, 0], [1, -1, 0], [-1, -1, 0], [-1, 1, 0], [0, 0, 1] ]) .map(function (pt) { return new Vertex3(pt) }) let faces = parseOption(options, 'faces', [ [0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4], [1, 0, 3], [2, 1, 3] ]) // Openscad convention defines inward normals - so we have to invert here faces.forEach(function (face) { face.reverse() }) let polygons = faces.map(function (face) { return new Polygon3(face.map(function (idx) { return vertices[idx] })) }) // TODO: facecenters as connectors? probably overkill. Maybe centroid // the re-tesselation here happens because it's so easy for a user to // create parametrized polyhedrons that end up with 1-2 dimensional polygons. // These will create infinite loops at CSG.Tree() return fromPolygons(polygons).reTesselated() }
javascript
function (options) { options = options || {} if (('points' in options) !== ('faces' in options)) { throw new Error("polyhedron needs 'points' and 'faces' arrays") } let vertices = parseOptionAs3DVectorList(options, 'points', [ [1, 1, 0], [1, -1, 0], [-1, -1, 0], [-1, 1, 0], [0, 0, 1] ]) .map(function (pt) { return new Vertex3(pt) }) let faces = parseOption(options, 'faces', [ [0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4], [1, 0, 3], [2, 1, 3] ]) // Openscad convention defines inward normals - so we have to invert here faces.forEach(function (face) { face.reverse() }) let polygons = faces.map(function (face) { return new Polygon3(face.map(function (idx) { return vertices[idx] })) }) // TODO: facecenters as connectors? probably overkill. Maybe centroid // the re-tesselation here happens because it's so easy for a user to // create parametrized polyhedrons that end up with 1-2 dimensional polygons. // These will create infinite loops at CSG.Tree() return fromPolygons(polygons).reTesselated() }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", "if", "(", "(", "'points'", "in", "options", ")", "!==", "(", "'faces'", "in", "options", ")", ")", "{", "throw", "new", "Error", "(", "\"polyhedron needs 'points' and 'faces' arrays\"", ")", "}", "let", "vertices", "=", "parseOptionAs3DVectorList", "(", "options", ",", "'points'", ",", "[", "[", "1", ",", "1", ",", "0", "]", ",", "[", "1", ",", "-", "1", ",", "0", "]", ",", "[", "-", "1", ",", "-", "1", ",", "0", "]", ",", "[", "-", "1", ",", "1", ",", "0", "]", ",", "[", "0", ",", "0", ",", "1", "]", "]", ")", ".", "map", "(", "function", "(", "pt", ")", "{", "return", "new", "Vertex3", "(", "pt", ")", "}", ")", "let", "faces", "=", "parseOption", "(", "options", ",", "'faces'", ",", "[", "[", "0", ",", "1", ",", "4", "]", ",", "[", "1", ",", "2", ",", "4", "]", ",", "[", "2", ",", "3", ",", "4", "]", ",", "[", "3", ",", "0", ",", "4", "]", ",", "[", "1", ",", "0", ",", "3", "]", ",", "[", "2", ",", "1", ",", "3", "]", "]", ")", "// Openscad convention defines inward normals - so we have to invert here", "faces", ".", "forEach", "(", "function", "(", "face", ")", "{", "face", ".", "reverse", "(", ")", "}", ")", "let", "polygons", "=", "faces", ".", "map", "(", "function", "(", "face", ")", "{", "return", "new", "Polygon3", "(", "face", ".", "map", "(", "function", "(", "idx", ")", "{", "return", "vertices", "[", "idx", "]", "}", ")", ")", "}", ")", "// TODO: facecenters as connectors? probably overkill. Maybe centroid", "// the re-tesselation here happens because it's so easy for a user to", "// create parametrized polyhedrons that end up with 1-2 dimensional polygons.", "// These will create infinite loops at CSG.Tree()", "return", "fromPolygons", "(", "polygons", ")", ".", "reTesselated", "(", ")", "}" ]
it is defined twice ??? Create a polyhedron using Openscad style arguments. NON API ! Define face vertices clockwise looking from outside. @param {Object} [options] - options for construction @returns {CSG} new 3D solid
[ "it", "is", "defined", "twice", "???", "Create", "a", "polyhedron", "using", "Openscad", "style", "arguments", ".", "NON", "API", "!", "Define", "face", "vertices", "clockwise", "looking", "from", "outside", "." ]
461bf2c93f175f1e1450506a9f62e737cf81c357
https://github.com/jscad/csg.js/blob/461bf2c93f175f1e1450506a9f62e737cf81c357/src/api/primitives/polyhedron.js#L51-L89
15,835
jscad/csg.js
src/core/shape3/connectTo.js
connectTo
function connectTo (shape3, connector, otherConnector, mirror, normalrotation) { let matrix = connector.getTransformationTo(otherConnector, mirror, normalrotation) return transform(matrix, shape3) }
javascript
function connectTo (shape3, connector, otherConnector, mirror, normalrotation) { let matrix = connector.getTransformationTo(otherConnector, mirror, normalrotation) return transform(matrix, shape3) }
[ "function", "connectTo", "(", "shape3", ",", "connector", ",", "otherConnector", ",", "mirror", ",", "normalrotation", ")", "{", "let", "matrix", "=", "connector", ".", "getTransformationTo", "(", "otherConnector", ",", "mirror", ",", "normalrotation", ")", "return", "transform", "(", "matrix", ",", "shape3", ")", "}" ]
Connect a solid to another solid, such that two Connectors become connected @param {Connector} connector a Connector of this solid @param {Connector} otherConnector a Connector to which myConnector should be connected @param {Boolean} mirror false: the 'axis' vectors of the connectors should point in the same direction true: the 'axis' vectors of the connectors should point in opposite direction @param {Float} normalrotation degrees of rotation between the 'normal' vectors of the two connectors @returns {Shape3} this csg, tranformed accordingly
[ "Connect", "a", "solid", "to", "another", "solid", "such", "that", "two", "Connectors", "become", "connected" ]
461bf2c93f175f1e1450506a9f62e737cf81c357
https://github.com/jscad/csg.js/blob/461bf2c93f175f1e1450506a9f62e737cf81c357/src/core/shape3/connectTo.js#L13-L16
15,836
jscad/csg.js
src/math/vec3/rotate.js
rotate
function rotate (...params) { let out let angle let vector if (params.length === 2) { out = create() angle = params[0] vector = params[1] } else { out = params[0] angle = params[1] vector = params[2] } // fIXME: not correct console.log('rotate', angle, vector) const origin = [0, 0, 0] out = rotateZ(angle[2], origin, rotateY(angle[1], origin, rotateX(angle[0], origin, vector))) return out }
javascript
function rotate (...params) { let out let angle let vector if (params.length === 2) { out = create() angle = params[0] vector = params[1] } else { out = params[0] angle = params[1] vector = params[2] } // fIXME: not correct console.log('rotate', angle, vector) const origin = [0, 0, 0] out = rotateZ(angle[2], origin, rotateY(angle[1], origin, rotateX(angle[0], origin, vector))) return out }
[ "function", "rotate", "(", "...", "params", ")", "{", "let", "out", "let", "angle", "let", "vector", "if", "(", "params", ".", "length", "===", "2", ")", "{", "out", "=", "create", "(", ")", "angle", "=", "params", "[", "0", "]", "vector", "=", "params", "[", "1", "]", "}", "else", "{", "out", "=", "params", "[", "0", "]", "angle", "=", "params", "[", "1", "]", "vector", "=", "params", "[", "2", "]", "}", "// fIXME: not correct", "console", ".", "log", "(", "'rotate'", ",", "angle", ",", "vector", ")", "const", "origin", "=", "[", "0", ",", "0", ",", "0", "]", "out", "=", "rotateZ", "(", "angle", "[", "2", "]", ",", "origin", ",", "rotateY", "(", "angle", "[", "1", "]", ",", "origin", ",", "rotateX", "(", "angle", "[", "0", "]", ",", "origin", ",", "vector", ")", ")", ")", "return", "out", "}" ]
Rotate vector 3D vector around the all 3 axes in the order x-axis , yaxis, z axis @param {vec3} out The receiving vec3 (optional) @param {vec3} vector The vec3 point to rotate @returns {vec3} out
[ "Rotate", "vector", "3D", "vector", "around", "the", "all", "3", "axes", "in", "the", "order", "x", "-", "axis", "yaxis", "z", "axis" ]
461bf2c93f175f1e1450506a9f62e737cf81c357
https://github.com/jscad/csg.js/blob/461bf2c93f175f1e1450506a9f62e737cf81c357/src/math/vec3/rotate.js#L11-L30
15,837
jscad/csg.js
src/core/geometry/trees.js
function (plane, coplanarfrontnodes, coplanarbacknodes, frontnodes, backnodes) { if (this.children.length) { let queue = [this.children] let i let j let l let node let nodes for (i = 0; i < queue.length; i++) { // queue.length can increase, do not cache nodes = queue[i] for (j = 0, l = nodes.length; j < l; j++) { // ok to cache length node = nodes[j] if (node.children.length) { queue.push(node.children) } else { // no children. Split the polygon: node._splitByPlane(plane, coplanarfrontnodes, coplanarbacknodes, frontnodes, backnodes) } } } } else { this._splitByPlane(plane, coplanarfrontnodes, coplanarbacknodes, frontnodes, backnodes) } }
javascript
function (plane, coplanarfrontnodes, coplanarbacknodes, frontnodes, backnodes) { if (this.children.length) { let queue = [this.children] let i let j let l let node let nodes for (i = 0; i < queue.length; i++) { // queue.length can increase, do not cache nodes = queue[i] for (j = 0, l = nodes.length; j < l; j++) { // ok to cache length node = nodes[j] if (node.children.length) { queue.push(node.children) } else { // no children. Split the polygon: node._splitByPlane(plane, coplanarfrontnodes, coplanarbacknodes, frontnodes, backnodes) } } } } else { this._splitByPlane(plane, coplanarfrontnodes, coplanarbacknodes, frontnodes, backnodes) } }
[ "function", "(", "plane", ",", "coplanarfrontnodes", ",", "coplanarbacknodes", ",", "frontnodes", ",", "backnodes", ")", "{", "if", "(", "this", ".", "children", ".", "length", ")", "{", "let", "queue", "=", "[", "this", ".", "children", "]", "let", "i", "let", "j", "let", "l", "let", "node", "let", "nodes", "for", "(", "i", "=", "0", ";", "i", "<", "queue", ".", "length", ";", "i", "++", ")", "{", "// queue.length can increase, do not cache", "nodes", "=", "queue", "[", "i", "]", "for", "(", "j", "=", "0", ",", "l", "=", "nodes", ".", "length", ";", "j", "<", "l", ";", "j", "++", ")", "{", "// ok to cache length", "node", "=", "nodes", "[", "j", "]", "if", "(", "node", ".", "children", ".", "length", ")", "{", "queue", ".", "push", "(", "node", ".", "children", ")", "}", "else", "{", "// no children. Split the polygon:", "node", ".", "_splitByPlane", "(", "plane", ",", "coplanarfrontnodes", ",", "coplanarbacknodes", ",", "frontnodes", ",", "backnodes", ")", "}", "}", "}", "}", "else", "{", "this", ".", "_splitByPlane", "(", "plane", ",", "coplanarfrontnodes", ",", "coplanarbacknodes", ",", "frontnodes", ",", "backnodes", ")", "}", "}" ]
split the node by a plane; add the resulting nodes to the frontnodes and backnodes array If the plane doesn't intersect the polygon, the 'this' object is added to one of the arrays If the plane does intersect the polygon, two new child nodes are created for the front and back fragments, and added to both arrays.
[ "split", "the", "node", "by", "a", "plane", ";", "add", "the", "resulting", "nodes", "to", "the", "frontnodes", "and", "backnodes", "array", "If", "the", "plane", "doesn", "t", "intersect", "the", "polygon", "the", "this", "object", "is", "added", "to", "one", "of", "the", "arrays", "If", "the", "plane", "does", "intersect", "the", "polygon", "two", "new", "child", "nodes", "are", "created", "for", "the", "front", "and", "back", "fragments", "and", "added", "to", "both", "arrays", "." ]
461bf2c93f175f1e1450506a9f62e737cf81c357
https://github.com/jscad/csg.js/blob/461bf2c93f175f1e1450506a9f62e737cf81c357/src/core/geometry/trees.js#L227-L250
15,838
jscad/csg.js
src/text/vectorText.js
translateLine
function translateLine (options, line) { const { x, y } = Object.assign({ x: 0, y: 0 }, options || {}) let segments = line.segments let segment = null let point = null for (let i = 0, il = segments.length; i < il; i++) { segment = segments[i] for (let j = 0, jl = segment.length; j < jl; j++) { point = segment[j] segment[j] = [point[0] + x, point[1] + y] } } return line }
javascript
function translateLine (options, line) { const { x, y } = Object.assign({ x: 0, y: 0 }, options || {}) let segments = line.segments let segment = null let point = null for (let i = 0, il = segments.length; i < il; i++) { segment = segments[i] for (let j = 0, jl = segment.length; j < jl; j++) { point = segment[j] segment[j] = [point[0] + x, point[1] + y] } } return line }
[ "function", "translateLine", "(", "options", ",", "line", ")", "{", "const", "{", "x", ",", "y", "}", "=", "Object", ".", "assign", "(", "{", "x", ":", "0", ",", "y", ":", "0", "}", ",", "options", "||", "{", "}", ")", "let", "segments", "=", "line", ".", "segments", "let", "segment", "=", "null", "let", "point", "=", "null", "for", "(", "let", "i", "=", "0", ",", "il", "=", "segments", ".", "length", ";", "i", "<", "il", ";", "i", "++", ")", "{", "segment", "=", "segments", "[", "i", "]", "for", "(", "let", "j", "=", "0", ",", "jl", "=", "segment", ".", "length", ";", "j", "<", "jl", ";", "j", "++", ")", "{", "point", "=", "segment", "[", "j", "]", "segment", "[", "j", "]", "=", "[", "point", "[", "0", "]", "+", "x", ",", "point", "[", "1", "]", "+", "y", "]", "}", "}", "return", "line", "}" ]
translate text line
[ "translate", "text", "line" ]
461bf2c93f175f1e1450506a9f62e737cf81c357
https://github.com/jscad/csg.js/blob/461bf2c93f175f1e1450506a9f62e737cf81c357/src/text/vectorText.js#L5-L18
15,839
jscad/csg.js
src/core/shape3/fromObject.js
fromObject
function fromObject (obj) { let polygons = obj.polygons.map(polygonLike => poly3.fromObject(polygonLike)) let shape3 = fromPolygons(polygons) shape3.isCanonicalized = obj.isCanonicalized shape3.isRetesselated = obj.isRetesselated return shape3 }
javascript
function fromObject (obj) { let polygons = obj.polygons.map(polygonLike => poly3.fromObject(polygonLike)) let shape3 = fromPolygons(polygons) shape3.isCanonicalized = obj.isCanonicalized shape3.isRetesselated = obj.isRetesselated return shape3 }
[ "function", "fromObject", "(", "obj", ")", "{", "let", "polygons", "=", "obj", ".", "polygons", ".", "map", "(", "polygonLike", "=>", "poly3", ".", "fromObject", "(", "polygonLike", ")", ")", "let", "shape3", "=", "fromPolygons", "(", "polygons", ")", "shape3", ".", "isCanonicalized", "=", "obj", ".", "isCanonicalized", "shape3", ".", "isRetesselated", "=", "obj", ".", "isRetesselated", "return", "shape3", "}" ]
Reconstruct a Shape3 solid from an object with identical property names. @param {Object} obj - anonymous object, typically from JSON @returns {Shape3} new Shape3 object
[ "Reconstruct", "a", "Shape3", "solid", "from", "an", "object", "with", "identical", "property", "names", "." ]
461bf2c93f175f1e1450506a9f62e737cf81c357
https://github.com/jscad/csg.js/blob/461bf2c93f175f1e1450506a9f62e737cf81c357/src/core/shape3/fromObject.js#L8-L14
15,840
jscad/csg.js
src/math/OrthoNormalBasis.js
function (plane, rightvector) { if (arguments.length < 2) { // choose an arbitrary right hand vector, making sure it is somewhat orthogonal to the plane normal: rightvector = vec3.random(plane) } else { rightvector = rightvector } this.v = vec3.unit(vec3.cross(plane, rightvector)) this.u = vec3.cross(this.v, plane) this.plane = plane this.planeorigin = vec3.scale(plane[3], plane) }
javascript
function (plane, rightvector) { if (arguments.length < 2) { // choose an arbitrary right hand vector, making sure it is somewhat orthogonal to the plane normal: rightvector = vec3.random(plane) } else { rightvector = rightvector } this.v = vec3.unit(vec3.cross(plane, rightvector)) this.u = vec3.cross(this.v, plane) this.plane = plane this.planeorigin = vec3.scale(plane[3], plane) }
[ "function", "(", "plane", ",", "rightvector", ")", "{", "if", "(", "arguments", ".", "length", "<", "2", ")", "{", "// choose an arbitrary right hand vector, making sure it is somewhat orthogonal to the plane normal:", "rightvector", "=", "vec3", ".", "random", "(", "plane", ")", "}", "else", "{", "rightvector", "=", "rightvector", "}", "this", ".", "v", "=", "vec3", ".", "unit", "(", "vec3", ".", "cross", "(", "plane", ",", "rightvector", ")", ")", "this", ".", "u", "=", "vec3", ".", "cross", "(", "this", ".", "v", ",", "plane", ")", "this", ".", "plane", "=", "plane", "this", ".", "planeorigin", "=", "vec3", ".", "scale", "(", "plane", "[", "3", "]", ",", "plane", ")", "}" ]
class OrthoNormalBasis Reprojects points on a 3D plane onto a 2D plane or from a 2D plane back onto the 3D plane @param {Plane} plane @param {Vector3D|Vector2D} rightvector
[ "class", "OrthoNormalBasis", "Reprojects", "points", "on", "a", "3D", "plane", "onto", "a", "2D", "plane", "or", "from", "a", "2D", "plane", "back", "onto", "the", "3D", "plane" ]
461bf2c93f175f1e1450506a9f62e737cf81c357
https://github.com/jscad/csg.js/blob/461bf2c93f175f1e1450506a9f62e737cf81c357/src/math/OrthoNormalBasis.js#L15-L26
15,841
koddr/vue-goodshare
docs/gitbook/gitbook-plugin-search/search-engine.js
setEngine
function setEngine(Engine, config) { initialized = false; engine = new Engine(config); init(config); }
javascript
function setEngine(Engine, config) { initialized = false; engine = new Engine(config); init(config); }
[ "function", "setEngine", "(", "Engine", ",", "config", ")", "{", "initialized", "=", "false", ";", "engine", "=", "new", "Engine", "(", "config", ")", ";", "init", "(", "config", ")", ";", "}" ]
Set a new search engine
[ "Set", "a", "new", "search", "engine" ]
e5e560f9cd208a81d5684be8581157a0d482bc82
https://github.com/koddr/vue-goodshare/blob/e5e560f9cd208a81d5684be8581157a0d482bc82/docs/gitbook/gitbook-plugin-search/search-engine.js#L7-L12
15,842
koddr/vue-goodshare
docs/gitbook/gitbook-plugin-search/search-engine.js
init
function init(config) { if (!engine) throw new Error( "No engine set for research. Set an engine using gitbook.research.setEngine(Engine)." ); return engine.init(config).then(function() { initialized = true; gitbook.events.trigger("search.ready"); }); }
javascript
function init(config) { if (!engine) throw new Error( "No engine set for research. Set an engine using gitbook.research.setEngine(Engine)." ); return engine.init(config).then(function() { initialized = true; gitbook.events.trigger("search.ready"); }); }
[ "function", "init", "(", "config", ")", "{", "if", "(", "!", "engine", ")", "throw", "new", "Error", "(", "\"No engine set for research. Set an engine using gitbook.research.setEngine(Engine).\"", ")", ";", "return", "engine", ".", "init", "(", "config", ")", ".", "then", "(", "function", "(", ")", "{", "initialized", "=", "true", ";", "gitbook", ".", "events", ".", "trigger", "(", "\"search.ready\"", ")", ";", "}", ")", ";", "}" ]
Initialize search engine with config
[ "Initialize", "search", "engine", "with", "config" ]
e5e560f9cd208a81d5684be8581157a0d482bc82
https://github.com/koddr/vue-goodshare/blob/e5e560f9cd208a81d5684be8581157a0d482bc82/docs/gitbook/gitbook-plugin-search/search-engine.js#L15-L25
15,843
koddr/vue-goodshare
docs/gitbook/gitbook-plugin-search/search-engine.js
query
function query(q, offset, length) { if (!initialized) throw new Error("Search has not been initialized"); return engine.search(q, offset, length); }
javascript
function query(q, offset, length) { if (!initialized) throw new Error("Search has not been initialized"); return engine.search(q, offset, length); }
[ "function", "query", "(", "q", ",", "offset", ",", "length", ")", "{", "if", "(", "!", "initialized", ")", "throw", "new", "Error", "(", "\"Search has not been initialized\"", ")", ";", "return", "engine", ".", "search", "(", "q", ",", "offset", ",", "length", ")", ";", "}" ]
Launch search for query q
[ "Launch", "search", "for", "query", "q" ]
e5e560f9cd208a81d5684be8581157a0d482bc82
https://github.com/koddr/vue-goodshare/blob/e5e560f9cd208a81d5684be8581157a0d482bc82/docs/gitbook/gitbook-plugin-search/search-engine.js#L28-L31
15,844
koddr/vue-goodshare
docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js
enlargeFontSize
function enlargeFontSize(e) { e.preventDefault(); if (fontState.size >= MAX_SIZE) return; fontState.size++; saveFontSettings(); }
javascript
function enlargeFontSize(e) { e.preventDefault(); if (fontState.size >= MAX_SIZE) return; fontState.size++; saveFontSettings(); }
[ "function", "enlargeFontSize", "(", "e", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "if", "(", "fontState", ".", "size", ">=", "MAX_SIZE", ")", "return", ";", "fontState", ".", "size", "++", ";", "saveFontSettings", "(", ")", ";", "}" ]
Increase font size
[ "Increase", "font", "size" ]
e5e560f9cd208a81d5684be8581157a0d482bc82
https://github.com/koddr/vue-goodshare/blob/e5e560f9cd208a81d5684be8581157a0d482bc82/docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js#L72-L78
15,845
koddr/vue-goodshare
docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js
reduceFontSize
function reduceFontSize(e) { e.preventDefault(); if (fontState.size <= MIN_SIZE) return; fontState.size--; saveFontSettings(); }
javascript
function reduceFontSize(e) { e.preventDefault(); if (fontState.size <= MIN_SIZE) return; fontState.size--; saveFontSettings(); }
[ "function", "reduceFontSize", "(", "e", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "if", "(", "fontState", ".", "size", "<=", "MIN_SIZE", ")", "return", ";", "fontState", ".", "size", "--", ";", "saveFontSettings", "(", ")", ";", "}" ]
Decrease font size
[ "Decrease", "font", "size" ]
e5e560f9cd208a81d5684be8581157a0d482bc82
https://github.com/koddr/vue-goodshare/blob/e5e560f9cd208a81d5684be8581157a0d482bc82/docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js#L81-L87
15,846
koddr/vue-goodshare
docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js
changeFontFamily
function changeFontFamily(configName, e) { if (e && e instanceof Event) { e.preventDefault(); } var familyId = getFontFamilyId(configName); fontState.family = familyId; saveFontSettings(); }
javascript
function changeFontFamily(configName, e) { if (e && e instanceof Event) { e.preventDefault(); } var familyId = getFontFamilyId(configName); fontState.family = familyId; saveFontSettings(); }
[ "function", "changeFontFamily", "(", "configName", ",", "e", ")", "{", "if", "(", "e", "&&", "e", "instanceof", "Event", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "}", "var", "familyId", "=", "getFontFamilyId", "(", "configName", ")", ";", "fontState", ".", "family", "=", "familyId", ";", "saveFontSettings", "(", ")", ";", "}" ]
Change font family
[ "Change", "font", "family" ]
e5e560f9cd208a81d5684be8581157a0d482bc82
https://github.com/koddr/vue-goodshare/blob/e5e560f9cd208a81d5684be8581157a0d482bc82/docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js#L90-L98
15,847
koddr/vue-goodshare
docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js
changeColorTheme
function changeColorTheme(configName, e) { if (e && e instanceof Event) { e.preventDefault(); } var $book = gitbook.state.$book; // Remove currently applied color theme if (fontState.theme !== 0) $book.removeClass("color-theme-" + fontState.theme); // Set new color theme var themeId = getThemeId(configName); fontState.theme = themeId; if (fontState.theme !== 0) $book.addClass("color-theme-" + fontState.theme); saveFontSettings(); }
javascript
function changeColorTheme(configName, e) { if (e && e instanceof Event) { e.preventDefault(); } var $book = gitbook.state.$book; // Remove currently applied color theme if (fontState.theme !== 0) $book.removeClass("color-theme-" + fontState.theme); // Set new color theme var themeId = getThemeId(configName); fontState.theme = themeId; if (fontState.theme !== 0) $book.addClass("color-theme-" + fontState.theme); saveFontSettings(); }
[ "function", "changeColorTheme", "(", "configName", ",", "e", ")", "{", "if", "(", "e", "&&", "e", "instanceof", "Event", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "}", "var", "$book", "=", "gitbook", ".", "state", ".", "$book", ";", "// Remove currently applied color theme", "if", "(", "fontState", ".", "theme", "!==", "0", ")", "$book", ".", "removeClass", "(", "\"color-theme-\"", "+", "fontState", ".", "theme", ")", ";", "// Set new color theme", "var", "themeId", "=", "getThemeId", "(", "configName", ")", ";", "fontState", ".", "theme", "=", "themeId", ";", "if", "(", "fontState", ".", "theme", "!==", "0", ")", "$book", ".", "addClass", "(", "\"color-theme-\"", "+", "fontState", ".", "theme", ")", ";", "saveFontSettings", "(", ")", ";", "}" ]
Change type of color theme
[ "Change", "type", "of", "color", "theme" ]
e5e560f9cd208a81d5684be8581157a0d482bc82
https://github.com/koddr/vue-goodshare/blob/e5e560f9cd208a81d5684be8581157a0d482bc82/docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js#L101-L118
15,848
koddr/vue-goodshare
docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js
getFontFamilyId
function getFontFamilyId(configName) { // Search for plugin configured font family var configFamily = $.grep(FAMILIES, function(family) { return family.config == configName; })[0]; // Fallback to default font family return !!configFamily ? configFamily.id : 0; }
javascript
function getFontFamilyId(configName) { // Search for plugin configured font family var configFamily = $.grep(FAMILIES, function(family) { return family.config == configName; })[0]; // Fallback to default font family return !!configFamily ? configFamily.id : 0; }
[ "function", "getFontFamilyId", "(", "configName", ")", "{", "// Search for plugin configured font family", "var", "configFamily", "=", "$", ".", "grep", "(", "FAMILIES", ",", "function", "(", "family", ")", "{", "return", "family", ".", "config", "==", "configName", ";", "}", ")", "[", "0", "]", ";", "// Fallback to default font family", "return", "!", "!", "configFamily", "?", "configFamily", ".", "id", ":", "0", ";", "}" ]
Return the correct id for a font-family config key Default to first font-family
[ "Return", "the", "correct", "id", "for", "a", "font", "-", "family", "config", "key", "Default", "to", "first", "font", "-", "family" ]
e5e560f9cd208a81d5684be8581157a0d482bc82
https://github.com/koddr/vue-goodshare/blob/e5e560f9cd208a81d5684be8581157a0d482bc82/docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js#L122-L129
15,849
koddr/vue-goodshare
docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js
getThemeId
function getThemeId(configName) { // Search for plugin configured theme var configTheme = $.grep(THEMES, function(theme) { return theme.config == configName; })[0]; // Fallback to default theme return !!configTheme ? configTheme.id : 0; }
javascript
function getThemeId(configName) { // Search for plugin configured theme var configTheme = $.grep(THEMES, function(theme) { return theme.config == configName; })[0]; // Fallback to default theme return !!configTheme ? configTheme.id : 0; }
[ "function", "getThemeId", "(", "configName", ")", "{", "// Search for plugin configured theme", "var", "configTheme", "=", "$", ".", "grep", "(", "THEMES", ",", "function", "(", "theme", ")", "{", "return", "theme", ".", "config", "==", "configName", ";", "}", ")", "[", "0", "]", ";", "// Fallback to default theme", "return", "!", "!", "configTheme", "?", "configTheme", ".", "id", ":", "0", ";", "}" ]
Return the correct id for a theme config key Default to first theme
[ "Return", "the", "correct", "id", "for", "a", "theme", "config", "key", "Default", "to", "first", "theme" ]
e5e560f9cd208a81d5684be8581157a0d482bc82
https://github.com/koddr/vue-goodshare/blob/e5e560f9cd208a81d5684be8581157a0d482bc82/docs/gitbook/gitbook-plugin-fontsettings/fontsettings.js#L133-L140
15,850
eggjs/egg-security
lib/helper/sjson.js
sanitizeKey
function sanitizeKey(obj) { if (typeof obj !== 'object') return obj; if (Array.isArray(obj)) return obj; if (obj === null) return null; if (obj instanceof Boolean) return obj; if (obj instanceof Number) return obj; if (obj instanceof Buffer) return obj.toString(); for (const k in obj) { const escapedK = sjs(k); if (escapedK !== k) { obj[escapedK] = sanitizeKey(obj[k]); obj[k] = undefined; } else { obj[k] = sanitizeKey(obj[k]); } } return obj; }
javascript
function sanitizeKey(obj) { if (typeof obj !== 'object') return obj; if (Array.isArray(obj)) return obj; if (obj === null) return null; if (obj instanceof Boolean) return obj; if (obj instanceof Number) return obj; if (obj instanceof Buffer) return obj.toString(); for (const k in obj) { const escapedK = sjs(k); if (escapedK !== k) { obj[escapedK] = sanitizeKey(obj[k]); obj[k] = undefined; } else { obj[k] = sanitizeKey(obj[k]); } } return obj; }
[ "function", "sanitizeKey", "(", "obj", ")", "{", "if", "(", "typeof", "obj", "!==", "'object'", ")", "return", "obj", ";", "if", "(", "Array", ".", "isArray", "(", "obj", ")", ")", "return", "obj", ";", "if", "(", "obj", "===", "null", ")", "return", "null", ";", "if", "(", "obj", "instanceof", "Boolean", ")", "return", "obj", ";", "if", "(", "obj", "instanceof", "Number", ")", "return", "obj", ";", "if", "(", "obj", "instanceof", "Buffer", ")", "return", "obj", ".", "toString", "(", ")", ";", "for", "(", "const", "k", "in", "obj", ")", "{", "const", "escapedK", "=", "sjs", "(", "k", ")", ";", "if", "(", "escapedK", "!==", "k", ")", "{", "obj", "[", "escapedK", "]", "=", "sanitizeKey", "(", "obj", "[", "k", "]", ")", ";", "obj", "[", "k", "]", "=", "undefined", ";", "}", "else", "{", "obj", "[", "k", "]", "=", "sanitizeKey", "(", "obj", "[", "k", "]", ")", ";", "}", "}", "return", "obj", ";", "}" ]
escape json for output json in script
[ "escape", "json", "for", "output", "json", "in", "script" ]
189064406befc7e284f67eb22d95aa1d13079ee9
https://github.com/eggjs/egg-security/blob/189064406befc7e284f67eb22d95aa1d13079ee9/lib/helper/sjson.js#L10-L27
15,851
mikemaccana/outdated-browser-rework
index.js
function(property) { if (!property) { return true } var div = document.createElement("div") var vendorPrefixes = ["khtml", "ms", "o", "moz", "webkit"] var count = vendorPrefixes.length // Note: HTMLElement.style.hasOwnProperty seems broken in Edge if (property in div.style) { return true } property = property.replace(/^[a-z]/, function(val) { return val.toUpperCase() }) while (count--) { var prefixedProperty = vendorPrefixes[count] + property // See comment re: HTMLElement.style.hasOwnProperty above if (prefixedProperty in div.style) { return true } } return false }
javascript
function(property) { if (!property) { return true } var div = document.createElement("div") var vendorPrefixes = ["khtml", "ms", "o", "moz", "webkit"] var count = vendorPrefixes.length // Note: HTMLElement.style.hasOwnProperty seems broken in Edge if (property in div.style) { return true } property = property.replace(/^[a-z]/, function(val) { return val.toUpperCase() }) while (count--) { var prefixedProperty = vendorPrefixes[count] + property // See comment re: HTMLElement.style.hasOwnProperty above if (prefixedProperty in div.style) { return true } } return false }
[ "function", "(", "property", ")", "{", "if", "(", "!", "property", ")", "{", "return", "true", "}", "var", "div", "=", "document", ".", "createElement", "(", "\"div\"", ")", "var", "vendorPrefixes", "=", "[", "\"khtml\"", ",", "\"ms\"", ",", "\"o\"", ",", "\"moz\"", ",", "\"webkit\"", "]", "var", "count", "=", "vendorPrefixes", ".", "length", "// Note: HTMLElement.style.hasOwnProperty seems broken in Edge", "if", "(", "property", "in", "div", ".", "style", ")", "{", "return", "true", "}", "property", "=", "property", ".", "replace", "(", "/", "^[a-z]", "/", ",", "function", "(", "val", ")", "{", "return", "val", ".", "toUpperCase", "(", ")", "}", ")", "while", "(", "count", "--", ")", "{", "var", "prefixedProperty", "=", "vendorPrefixes", "[", "count", "]", "+", "property", "// See comment re: HTMLElement.style.hasOwnProperty above", "if", "(", "prefixedProperty", "in", "div", ".", "style", ")", "{", "return", "true", "}", "}", "return", "false", "}" ]
Returns true if a browser supports a css3 property
[ "Returns", "true", "if", "a", "browser", "supports", "a", "css3", "property" ]
575b2639d37f4a531af1ca32eddd844c7ba05465
https://github.com/mikemaccana/outdated-browser-rework/blob/575b2639d37f4a531af1ca32eddd844c7ba05465/index.js#L144-L169
15,852
appium/appium-uiautomator2-driver
lib/commands/general.js
function (mapping) { const result = {}; for (const [key, value] of _.toPairs(mapping)) { result[key] = _.isString(value) ? value : JSON.stringify(value); } return result; }
javascript
function (mapping) { const result = {}; for (const [key, value] of _.toPairs(mapping)) { result[key] = _.isString(value) ? value : JSON.stringify(value); } return result; }
[ "function", "(", "mapping", ")", "{", "const", "result", "=", "{", "}", ";", "for", "(", "const", "[", "key", ",", "value", "]", "of", "_", ".", "toPairs", "(", "mapping", ")", ")", "{", "result", "[", "key", "]", "=", "_", ".", "isString", "(", "value", ")", "?", "value", ":", "JSON", ".", "stringify", "(", "value", ")", ";", "}", "return", "result", ";", "}" ]
Clients require the resulting mapping to have both keys and values of type string
[ "Clients", "require", "the", "resulting", "mapping", "to", "have", "both", "keys", "and", "values", "of", "type", "string" ]
73a2373af1893e9ef6fbc802ed38d5c0c8fec2d1
https://github.com/appium/appium-uiautomator2-driver/blob/73a2373af1893e9ef6fbc802ed38d5c0c8fec2d1/lib/commands/general.js#L38-L44
15,853
appium/appium-adb
lib/tools/apks-utils.js
extractFromApks
async function extractFromApks (apks, dstPath) { if (!_.isArray(dstPath)) { dstPath = [dstPath]; } return await APKS_CACHE_GUARD.acquire(apks, async () => { // It might be that the original file has been replaced, // so we need to keep the hash sums instead of the actual file paths // as caching keys const apksHash = await fs.hash(apks); log.debug(`Calculated '${apks}' hash: ${apksHash}`); if (APKS_CACHE.has(apksHash)) { const resultPath = path.resolve(APKS_CACHE.get(apksHash), ...dstPath); if (await fs.exists(resultPath)) { return resultPath; } APKS_CACHE.del(apksHash); } const tmpRoot = await tempDir.openDir(); log.debug(`Unpacking application bundle at '${apks}' to '${tmpRoot}'`); await unzipFile(apks, tmpRoot); const resultPath = path.resolve(tmpRoot, ...dstPath); if (!await fs.exists(resultPath)) { throw new Error(`${dstPath.join(path.sep)} cannot be found in '${apks}' bundle. ` + `Does the archive contain a valid application bundle?`); } APKS_CACHE.set(apksHash, tmpRoot); return resultPath; }); }
javascript
async function extractFromApks (apks, dstPath) { if (!_.isArray(dstPath)) { dstPath = [dstPath]; } return await APKS_CACHE_GUARD.acquire(apks, async () => { // It might be that the original file has been replaced, // so we need to keep the hash sums instead of the actual file paths // as caching keys const apksHash = await fs.hash(apks); log.debug(`Calculated '${apks}' hash: ${apksHash}`); if (APKS_CACHE.has(apksHash)) { const resultPath = path.resolve(APKS_CACHE.get(apksHash), ...dstPath); if (await fs.exists(resultPath)) { return resultPath; } APKS_CACHE.del(apksHash); } const tmpRoot = await tempDir.openDir(); log.debug(`Unpacking application bundle at '${apks}' to '${tmpRoot}'`); await unzipFile(apks, tmpRoot); const resultPath = path.resolve(tmpRoot, ...dstPath); if (!await fs.exists(resultPath)) { throw new Error(`${dstPath.join(path.sep)} cannot be found in '${apks}' bundle. ` + `Does the archive contain a valid application bundle?`); } APKS_CACHE.set(apksHash, tmpRoot); return resultPath; }); }
[ "async", "function", "extractFromApks", "(", "apks", ",", "dstPath", ")", "{", "if", "(", "!", "_", ".", "isArray", "(", "dstPath", ")", ")", "{", "dstPath", "=", "[", "dstPath", "]", ";", "}", "return", "await", "APKS_CACHE_GUARD", ".", "acquire", "(", "apks", ",", "async", "(", ")", "=>", "{", "// It might be that the original file has been replaced,", "// so we need to keep the hash sums instead of the actual file paths", "// as caching keys", "const", "apksHash", "=", "await", "fs", ".", "hash", "(", "apks", ")", ";", "log", ".", "debug", "(", "`", "${", "apks", "}", "${", "apksHash", "}", "`", ")", ";", "if", "(", "APKS_CACHE", ".", "has", "(", "apksHash", ")", ")", "{", "const", "resultPath", "=", "path", ".", "resolve", "(", "APKS_CACHE", ".", "get", "(", "apksHash", ")", ",", "...", "dstPath", ")", ";", "if", "(", "await", "fs", ".", "exists", "(", "resultPath", ")", ")", "{", "return", "resultPath", ";", "}", "APKS_CACHE", ".", "del", "(", "apksHash", ")", ";", "}", "const", "tmpRoot", "=", "await", "tempDir", ".", "openDir", "(", ")", ";", "log", ".", "debug", "(", "`", "${", "apks", "}", "${", "tmpRoot", "}", "`", ")", ";", "await", "unzipFile", "(", "apks", ",", "tmpRoot", ")", ";", "const", "resultPath", "=", "path", ".", "resolve", "(", "tmpRoot", ",", "...", "dstPath", ")", ";", "if", "(", "!", "await", "fs", ".", "exists", "(", "resultPath", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "dstPath", ".", "join", "(", "path", ".", "sep", ")", "}", "${", "apks", "}", "`", "+", "`", "`", ")", ";", "}", "APKS_CACHE", ".", "set", "(", "apksHash", ",", "tmpRoot", ")", ";", "return", "resultPath", ";", "}", ")", ";", "}" ]
Extracts the particular apks package into a temporary folder, finds and returns the full path to the file contained in this apk. The resulting temporary path, where the .apks file has been extracted, will be stored into the internal LRU cache for better performance. @param {string} apks - The full path to the .apks file @param {string|Array<String>} dstPath - The relative path to the destination file, which is going to be extracted, where each path component is an array item @returns {string} Full path to the extracted file @throws {Error} If the requested item does not exist in the extracted archive or the provides apks file is not a valid bundle
[ "Extracts", "the", "particular", "apks", "package", "into", "a", "temporary", "folder", "finds", "and", "returns", "the", "full", "path", "to", "the", "file", "contained", "in", "this", "apk", ".", "The", "resulting", "temporary", "path", "where", "the", ".", "apks", "file", "has", "been", "extracted", "will", "be", "stored", "into", "the", "internal", "LRU", "cache", "for", "better", "performance", "." ]
2f9f37ba10db866a939581d5a41b851d8e7d9151
https://github.com/appium/appium-adb/blob/2f9f37ba10db866a939581d5a41b851d8e7d9151/lib/tools/apks-utils.js#L34-L65
15,854
appium/appium-adb
lib/tools/android-manifest.js
extractApkInfoWithApkanalyzer
async function extractApkInfoWithApkanalyzer (localApk, apkanalyzerPath) { const args = ['-h', 'manifest', 'print', localApk]; log.debug(`Starting '${apkanalyzerPath}' with args ${JSON.stringify(args)}`); const manifestXml = (await exec(apkanalyzerPath, args, { shell: true, cwd: path.dirname(apkanalyzerPath) })).stdout; const doc = new xmldom.DOMParser().parseFromString(manifestXml); const apkPackageAttribute = xpath.select1('//manifest/@package', doc); if (!apkPackageAttribute) { throw new Error(`Cannot parse package name from ${manifestXml}`); } const apkPackage = apkPackageAttribute.value; // Look for activity or activity-alias with // action == android.intent.action.MAIN and // category == android.intent.category.LAUNCHER // descendants const apkActivityAttribute = xpath.select1( "//application/*[starts-with(name(), 'activity') " + "and .//action[@*[local-name()='name' and .='android.intent.action.MAIN']] " + "and .//category[@*[local-name()='name' and .='android.intent.category.LAUNCHER']]]" + "/@*[local-name()='name']", doc); if (!apkActivityAttribute) { throw new Error(`Cannot parse main activity name from ${manifestXml}`); } const apkActivity = apkActivityAttribute.value; return {apkPackage, apkActivity}; }
javascript
async function extractApkInfoWithApkanalyzer (localApk, apkanalyzerPath) { const args = ['-h', 'manifest', 'print', localApk]; log.debug(`Starting '${apkanalyzerPath}' with args ${JSON.stringify(args)}`); const manifestXml = (await exec(apkanalyzerPath, args, { shell: true, cwd: path.dirname(apkanalyzerPath) })).stdout; const doc = new xmldom.DOMParser().parseFromString(manifestXml); const apkPackageAttribute = xpath.select1('//manifest/@package', doc); if (!apkPackageAttribute) { throw new Error(`Cannot parse package name from ${manifestXml}`); } const apkPackage = apkPackageAttribute.value; // Look for activity or activity-alias with // action == android.intent.action.MAIN and // category == android.intent.category.LAUNCHER // descendants const apkActivityAttribute = xpath.select1( "//application/*[starts-with(name(), 'activity') " + "and .//action[@*[local-name()='name' and .='android.intent.action.MAIN']] " + "and .//category[@*[local-name()='name' and .='android.intent.category.LAUNCHER']]]" + "/@*[local-name()='name']", doc); if (!apkActivityAttribute) { throw new Error(`Cannot parse main activity name from ${manifestXml}`); } const apkActivity = apkActivityAttribute.value; return {apkPackage, apkActivity}; }
[ "async", "function", "extractApkInfoWithApkanalyzer", "(", "localApk", ",", "apkanalyzerPath", ")", "{", "const", "args", "=", "[", "'-h'", ",", "'manifest'", ",", "'print'", ",", "localApk", "]", ";", "log", ".", "debug", "(", "`", "${", "apkanalyzerPath", "}", "${", "JSON", ".", "stringify", "(", "args", ")", "}", "`", ")", ";", "const", "manifestXml", "=", "(", "await", "exec", "(", "apkanalyzerPath", ",", "args", ",", "{", "shell", ":", "true", ",", "cwd", ":", "path", ".", "dirname", "(", "apkanalyzerPath", ")", "}", ")", ")", ".", "stdout", ";", "const", "doc", "=", "new", "xmldom", ".", "DOMParser", "(", ")", ".", "parseFromString", "(", "manifestXml", ")", ";", "const", "apkPackageAttribute", "=", "xpath", ".", "select1", "(", "'//manifest/@package'", ",", "doc", ")", ";", "if", "(", "!", "apkPackageAttribute", ")", "{", "throw", "new", "Error", "(", "`", "${", "manifestXml", "}", "`", ")", ";", "}", "const", "apkPackage", "=", "apkPackageAttribute", ".", "value", ";", "// Look for activity or activity-alias with", "// action == android.intent.action.MAIN and", "// category == android.intent.category.LAUNCHER", "// descendants", "const", "apkActivityAttribute", "=", "xpath", ".", "select1", "(", "\"//application/*[starts-with(name(), 'activity') \"", "+", "\"and .//action[@*[local-name()='name' and .='android.intent.action.MAIN']] \"", "+", "\"and .//category[@*[local-name()='name' and .='android.intent.category.LAUNCHER']]]\"", "+", "\"/@*[local-name()='name']\"", ",", "doc", ")", ";", "if", "(", "!", "apkActivityAttribute", ")", "{", "throw", "new", "Error", "(", "`", "${", "manifestXml", "}", "`", ")", ";", "}", "const", "apkActivity", "=", "apkActivityAttribute", ".", "value", ";", "return", "{", "apkPackage", ",", "apkActivity", "}", ";", "}" ]
Extract package and main activity name from application manifest using apkanalyzer tool. @param {string} localApk - The full path to application package. @param {string} apkanalyzerPath - The full path to apkanalyzer tool. @return {APKInfo} The parsed application info. @throws {Error} If there was an error while getting the data from the given application package or if the tool itself is not present on the local file system.
[ "Extract", "package", "and", "main", "activity", "name", "from", "application", "manifest", "using", "apkanalyzer", "tool", "." ]
2f9f37ba10db866a939581d5a41b851d8e7d9151
https://github.com/appium/appium-adb/blob/2f9f37ba10db866a939581d5a41b851d8e7d9151/lib/tools/android-manifest.js#L120-L147
15,855
appium/appium-adb
lib/helpers.js
buildStartCmd
function buildStartCmd (startAppOptions, apiLevel) { let cmd = ['am', 'start']; if (util.hasValue(startAppOptions.user)) { cmd.push('--user', startAppOptions.user); } cmd.push('-W', '-n', `${startAppOptions.pkg}/${startAppOptions.activity}`); if (startAppOptions.stopApp && apiLevel >= 15) { cmd.push('-S'); } if (startAppOptions.action) { cmd.push('-a', startAppOptions.action); } if (startAppOptions.category) { cmd.push('-c', startAppOptions.category); } if (startAppOptions.flags) { cmd.push('-f', startAppOptions.flags); } if (startAppOptions.optionalIntentArguments) { // expect optionalIntentArguments to be a single string of the form: // "-flag key" // "-flag key value" // or a combination of these (e.g., "-flag1 key1 -flag2 key2 value2") // take a string and parse out the part before any spaces, and anything after // the first space let parseKeyValue = function (str) { str = str.trim(); let space = str.indexOf(' '); if (space === -1) { return str.length ? [str] : []; } else { return [str.substring(0, space).trim(), str.substring(space + 1).trim()]; } }; // cycle through the optionalIntentArguments and pull out the arguments // add a space initially so flags can be distinguished from arguments that // have internal hyphens let optionalIntentArguments = ` ${startAppOptions.optionalIntentArguments}`; let re = / (-[^\s]+) (.+)/; while (true) { // eslint-disable-line no-constant-condition let args = re.exec(optionalIntentArguments); if (!args) { if (optionalIntentArguments.length) { // no more flags, so the remainder can be treated as 'key' or 'key value' cmd.push.apply(cmd, parseKeyValue(optionalIntentArguments)); } // we are done break; } // take the flag and see if it is at the beginning of the string // if it is not, then it means we have been through already, and // what is before the flag is the argument for the previous flag let flag = args[1]; let flagPos = optionalIntentArguments.indexOf(flag); if (flagPos !== 0) { let prevArgs = optionalIntentArguments.substring(0, flagPos); cmd.push.apply(cmd, parseKeyValue(prevArgs)); } // add the flag, as there are no more earlier arguments cmd.push(flag); // make optionalIntentArguments hold the remainder optionalIntentArguments = args[2]; } } return cmd; }
javascript
function buildStartCmd (startAppOptions, apiLevel) { let cmd = ['am', 'start']; if (util.hasValue(startAppOptions.user)) { cmd.push('--user', startAppOptions.user); } cmd.push('-W', '-n', `${startAppOptions.pkg}/${startAppOptions.activity}`); if (startAppOptions.stopApp && apiLevel >= 15) { cmd.push('-S'); } if (startAppOptions.action) { cmd.push('-a', startAppOptions.action); } if (startAppOptions.category) { cmd.push('-c', startAppOptions.category); } if (startAppOptions.flags) { cmd.push('-f', startAppOptions.flags); } if (startAppOptions.optionalIntentArguments) { // expect optionalIntentArguments to be a single string of the form: // "-flag key" // "-flag key value" // or a combination of these (e.g., "-flag1 key1 -flag2 key2 value2") // take a string and parse out the part before any spaces, and anything after // the first space let parseKeyValue = function (str) { str = str.trim(); let space = str.indexOf(' '); if (space === -1) { return str.length ? [str] : []; } else { return [str.substring(0, space).trim(), str.substring(space + 1).trim()]; } }; // cycle through the optionalIntentArguments and pull out the arguments // add a space initially so flags can be distinguished from arguments that // have internal hyphens let optionalIntentArguments = ` ${startAppOptions.optionalIntentArguments}`; let re = / (-[^\s]+) (.+)/; while (true) { // eslint-disable-line no-constant-condition let args = re.exec(optionalIntentArguments); if (!args) { if (optionalIntentArguments.length) { // no more flags, so the remainder can be treated as 'key' or 'key value' cmd.push.apply(cmd, parseKeyValue(optionalIntentArguments)); } // we are done break; } // take the flag and see if it is at the beginning of the string // if it is not, then it means we have been through already, and // what is before the flag is the argument for the previous flag let flag = args[1]; let flagPos = optionalIntentArguments.indexOf(flag); if (flagPos !== 0) { let prevArgs = optionalIntentArguments.substring(0, flagPos); cmd.push.apply(cmd, parseKeyValue(prevArgs)); } // add the flag, as there are no more earlier arguments cmd.push(flag); // make optionalIntentArguments hold the remainder optionalIntentArguments = args[2]; } } return cmd; }
[ "function", "buildStartCmd", "(", "startAppOptions", ",", "apiLevel", ")", "{", "let", "cmd", "=", "[", "'am'", ",", "'start'", "]", ";", "if", "(", "util", ".", "hasValue", "(", "startAppOptions", ".", "user", ")", ")", "{", "cmd", ".", "push", "(", "'--user'", ",", "startAppOptions", ".", "user", ")", ";", "}", "cmd", ".", "push", "(", "'-W'", ",", "'-n'", ",", "`", "${", "startAppOptions", ".", "pkg", "}", "${", "startAppOptions", ".", "activity", "}", "`", ")", ";", "if", "(", "startAppOptions", ".", "stopApp", "&&", "apiLevel", ">=", "15", ")", "{", "cmd", ".", "push", "(", "'-S'", ")", ";", "}", "if", "(", "startAppOptions", ".", "action", ")", "{", "cmd", ".", "push", "(", "'-a'", ",", "startAppOptions", ".", "action", ")", ";", "}", "if", "(", "startAppOptions", ".", "category", ")", "{", "cmd", ".", "push", "(", "'-c'", ",", "startAppOptions", ".", "category", ")", ";", "}", "if", "(", "startAppOptions", ".", "flags", ")", "{", "cmd", ".", "push", "(", "'-f'", ",", "startAppOptions", ".", "flags", ")", ";", "}", "if", "(", "startAppOptions", ".", "optionalIntentArguments", ")", "{", "// expect optionalIntentArguments to be a single string of the form:", "// \"-flag key\"", "// \"-flag key value\"", "// or a combination of these (e.g., \"-flag1 key1 -flag2 key2 value2\")", "// take a string and parse out the part before any spaces, and anything after", "// the first space", "let", "parseKeyValue", "=", "function", "(", "str", ")", "{", "str", "=", "str", ".", "trim", "(", ")", ";", "let", "space", "=", "str", ".", "indexOf", "(", "' '", ")", ";", "if", "(", "space", "===", "-", "1", ")", "{", "return", "str", ".", "length", "?", "[", "str", "]", ":", "[", "]", ";", "}", "else", "{", "return", "[", "str", ".", "substring", "(", "0", ",", "space", ")", ".", "trim", "(", ")", ",", "str", ".", "substring", "(", "space", "+", "1", ")", ".", "trim", "(", ")", "]", ";", "}", "}", ";", "// cycle through the optionalIntentArguments and pull out the arguments", "// add a space initially so flags can be distinguished from arguments that", "// have internal hyphens", "let", "optionalIntentArguments", "=", "`", "${", "startAppOptions", ".", "optionalIntentArguments", "}", "`", ";", "let", "re", "=", "/", " (-[^\\s]+) (.+)", "/", ";", "while", "(", "true", ")", "{", "// eslint-disable-line no-constant-condition", "let", "args", "=", "re", ".", "exec", "(", "optionalIntentArguments", ")", ";", "if", "(", "!", "args", ")", "{", "if", "(", "optionalIntentArguments", ".", "length", ")", "{", "// no more flags, so the remainder can be treated as 'key' or 'key value'", "cmd", ".", "push", ".", "apply", "(", "cmd", ",", "parseKeyValue", "(", "optionalIntentArguments", ")", ")", ";", "}", "// we are done", "break", ";", "}", "// take the flag and see if it is at the beginning of the string", "// if it is not, then it means we have been through already, and", "// what is before the flag is the argument for the previous flag", "let", "flag", "=", "args", "[", "1", "]", ";", "let", "flagPos", "=", "optionalIntentArguments", ".", "indexOf", "(", "flag", ")", ";", "if", "(", "flagPos", "!==", "0", ")", "{", "let", "prevArgs", "=", "optionalIntentArguments", ".", "substring", "(", "0", ",", "flagPos", ")", ";", "cmd", ".", "push", ".", "apply", "(", "cmd", ",", "parseKeyValue", "(", "prevArgs", ")", ")", ";", "}", "// add the flag, as there are no more earlier arguments", "cmd", ".", "push", "(", "flag", ")", ";", "// make optionalIntentArguments hold the remainder", "optionalIntentArguments", "=", "args", "[", "2", "]", ";", "}", "}", "return", "cmd", ";", "}" ]
Builds command line representation for the given application startup options @param {StartAppOptions} startAppOptions - Application options mapping @param {number} apiLevel - The actual OS API level @returns {Array<String>} The actual command line array
[ "Builds", "command", "line", "representation", "for", "the", "given", "application", "startup", "options" ]
2f9f37ba10db866a939581d5a41b851d8e7d9151
https://github.com/appium/appium-adb/blob/2f9f37ba10db866a939581d5a41b851d8e7d9151/lib/helpers.js#L178-L248
15,856
appium/appium-adb
lib/helpers.js
function (str) { str = str.trim(); let space = str.indexOf(' '); if (space === -1) { return str.length ? [str] : []; } else { return [str.substring(0, space).trim(), str.substring(space + 1).trim()]; } }
javascript
function (str) { str = str.trim(); let space = str.indexOf(' '); if (space === -1) { return str.length ? [str] : []; } else { return [str.substring(0, space).trim(), str.substring(space + 1).trim()]; } }
[ "function", "(", "str", ")", "{", "str", "=", "str", ".", "trim", "(", ")", ";", "let", "space", "=", "str", ".", "indexOf", "(", "' '", ")", ";", "if", "(", "space", "===", "-", "1", ")", "{", "return", "str", ".", "length", "?", "[", "str", "]", ":", "[", "]", ";", "}", "else", "{", "return", "[", "str", ".", "substring", "(", "0", ",", "space", ")", ".", "trim", "(", ")", ",", "str", ".", "substring", "(", "space", "+", "1", ")", ".", "trim", "(", ")", "]", ";", "}", "}" ]
take a string and parse out the part before any spaces, and anything after the first space
[ "take", "a", "string", "and", "parse", "out", "the", "part", "before", "any", "spaces", "and", "anything", "after", "the", "first", "space" ]
2f9f37ba10db866a939581d5a41b851d8e7d9151
https://github.com/appium/appium-adb/blob/2f9f37ba10db866a939581d5a41b851d8e7d9151/lib/helpers.js#L204-L212
15,857
appium/appium-adb
lib/helpers.js
function (dumpsysOutput, groupNames, grantedState = null) { const groupPatternByName = (groupName) => new RegExp(`^(\\s*${_.escapeRegExp(groupName)} permissions:[\\s\\S]+)`, 'm'); const indentPattern = /\S|$/; const permissionNamePattern = /android\.permission\.\w+/; const grantedStatePattern = /\bgranted=(\w+)/; const result = []; for (const groupName of groupNames) { const groupMatch = groupPatternByName(groupName).exec(dumpsysOutput); if (!groupMatch) { continue; } const lines = groupMatch[1].split('\n'); if (lines.length < 2) { continue; } const titleIndent = lines[0].search(indentPattern); for (const line of lines.slice(1)) { const currentIndent = line.search(indentPattern); if (currentIndent <= titleIndent) { break; } const permissionNameMatch = permissionNamePattern.exec(line); if (!permissionNameMatch) { continue; } const item = { permission: permissionNameMatch[0], }; const grantedStateMatch = grantedStatePattern.exec(line); if (grantedStateMatch) { item.granted = grantedStateMatch[1] === 'true'; } result.push(item); } } const filteredResult = result .filter((item) => !_.isBoolean(grantedState) || item.granted === grantedState) .map((item) => item.permission); log.debug(`Retrieved ${filteredResult.length} permission(s) from ${JSON.stringify(groupNames)} group(s)`); return filteredResult; }
javascript
function (dumpsysOutput, groupNames, grantedState = null) { const groupPatternByName = (groupName) => new RegExp(`^(\\s*${_.escapeRegExp(groupName)} permissions:[\\s\\S]+)`, 'm'); const indentPattern = /\S|$/; const permissionNamePattern = /android\.permission\.\w+/; const grantedStatePattern = /\bgranted=(\w+)/; const result = []; for (const groupName of groupNames) { const groupMatch = groupPatternByName(groupName).exec(dumpsysOutput); if (!groupMatch) { continue; } const lines = groupMatch[1].split('\n'); if (lines.length < 2) { continue; } const titleIndent = lines[0].search(indentPattern); for (const line of lines.slice(1)) { const currentIndent = line.search(indentPattern); if (currentIndent <= titleIndent) { break; } const permissionNameMatch = permissionNamePattern.exec(line); if (!permissionNameMatch) { continue; } const item = { permission: permissionNameMatch[0], }; const grantedStateMatch = grantedStatePattern.exec(line); if (grantedStateMatch) { item.granted = grantedStateMatch[1] === 'true'; } result.push(item); } } const filteredResult = result .filter((item) => !_.isBoolean(grantedState) || item.granted === grantedState) .map((item) => item.permission); log.debug(`Retrieved ${filteredResult.length} permission(s) from ${JSON.stringify(groupNames)} group(s)`); return filteredResult; }
[ "function", "(", "dumpsysOutput", ",", "groupNames", ",", "grantedState", "=", "null", ")", "{", "const", "groupPatternByName", "=", "(", "groupName", ")", "=>", "new", "RegExp", "(", "`", "\\\\", "${", "_", ".", "escapeRegExp", "(", "groupName", ")", "}", "\\\\", "\\\\", "`", ",", "'m'", ")", ";", "const", "indentPattern", "=", "/", "\\S|$", "/", ";", "const", "permissionNamePattern", "=", "/", "android\\.permission\\.\\w+", "/", ";", "const", "grantedStatePattern", "=", "/", "\\bgranted=(\\w+)", "/", ";", "const", "result", "=", "[", "]", ";", "for", "(", "const", "groupName", "of", "groupNames", ")", "{", "const", "groupMatch", "=", "groupPatternByName", "(", "groupName", ")", ".", "exec", "(", "dumpsysOutput", ")", ";", "if", "(", "!", "groupMatch", ")", "{", "continue", ";", "}", "const", "lines", "=", "groupMatch", "[", "1", "]", ".", "split", "(", "'\\n'", ")", ";", "if", "(", "lines", ".", "length", "<", "2", ")", "{", "continue", ";", "}", "const", "titleIndent", "=", "lines", "[", "0", "]", ".", "search", "(", "indentPattern", ")", ";", "for", "(", "const", "line", "of", "lines", ".", "slice", "(", "1", ")", ")", "{", "const", "currentIndent", "=", "line", ".", "search", "(", "indentPattern", ")", ";", "if", "(", "currentIndent", "<=", "titleIndent", ")", "{", "break", ";", "}", "const", "permissionNameMatch", "=", "permissionNamePattern", ".", "exec", "(", "line", ")", ";", "if", "(", "!", "permissionNameMatch", ")", "{", "continue", ";", "}", "const", "item", "=", "{", "permission", ":", "permissionNameMatch", "[", "0", "]", ",", "}", ";", "const", "grantedStateMatch", "=", "grantedStatePattern", ".", "exec", "(", "line", ")", ";", "if", "(", "grantedStateMatch", ")", "{", "item", ".", "granted", "=", "grantedStateMatch", "[", "1", "]", "===", "'true'", ";", "}", "result", ".", "push", "(", "item", ")", ";", "}", "}", "const", "filteredResult", "=", "result", ".", "filter", "(", "(", "item", ")", "=>", "!", "_", ".", "isBoolean", "(", "grantedState", ")", "||", "item", ".", "granted", "===", "grantedState", ")", ".", "map", "(", "(", "item", ")", "=>", "item", ".", "permission", ")", ";", "log", ".", "debug", "(", "`", "${", "filteredResult", ".", "length", "}", "${", "JSON", ".", "stringify", "(", "groupNames", ")", "}", "`", ")", ";", "return", "filteredResult", ";", "}" ]
Retrieves the list of permission names encoded in `dumpsys package` command output. @param {string} dumpsysOutput - The actual command output. @param {Array<string>} groupNames - The list of group names to list permissions for. @param {?boolean} grantedState - The expected state of `granted` attribute to filter with. No filtering is done if the parameter is not set. @returns {Array<string>} The list of matched permission names or an empty list if no matches were found.
[ "Retrieves", "the", "list", "of", "permission", "names", "encoded", "in", "dumpsys", "package", "command", "output", "." ]
2f9f37ba10db866a939581d5a41b851d8e7d9151
https://github.com/appium/appium-adb/blob/2f9f37ba10db866a939581d5a41b851d8e7d9151/lib/helpers.js#L313-L357
15,858
appium/appium-adb
lib/tools/apk-signing.js
patchApksigner
async function patchApksigner (originalPath) { const originalContent = await fs.readFile(originalPath, 'ascii'); const patchedContent = originalContent.replace('-Djava.ext.dirs="%frameworkdir%"', '-cp "%frameworkdir%\\*"'); if (patchedContent === originalContent) { return originalPath; } log.debug(`Patching '${originalPath}...`); const patchedPath = await tempDir.path({prefix: 'apksigner', suffix: '.bat'}); await mkdirp(path.dirname(patchedPath)); await fs.writeFile(patchedPath, patchedContent, 'ascii'); return patchedPath; }
javascript
async function patchApksigner (originalPath) { const originalContent = await fs.readFile(originalPath, 'ascii'); const patchedContent = originalContent.replace('-Djava.ext.dirs="%frameworkdir%"', '-cp "%frameworkdir%\\*"'); if (patchedContent === originalContent) { return originalPath; } log.debug(`Patching '${originalPath}...`); const patchedPath = await tempDir.path({prefix: 'apksigner', suffix: '.bat'}); await mkdirp(path.dirname(patchedPath)); await fs.writeFile(patchedPath, patchedContent, 'ascii'); return patchedPath; }
[ "async", "function", "patchApksigner", "(", "originalPath", ")", "{", "const", "originalContent", "=", "await", "fs", ".", "readFile", "(", "originalPath", ",", "'ascii'", ")", ";", "const", "patchedContent", "=", "originalContent", ".", "replace", "(", "'-Djava.ext.dirs=\"%frameworkdir%\"'", ",", "'-cp \"%frameworkdir%\\\\*\"'", ")", ";", "if", "(", "patchedContent", "===", "originalContent", ")", "{", "return", "originalPath", ";", "}", "log", ".", "debug", "(", "`", "${", "originalPath", "}", "`", ")", ";", "const", "patchedPath", "=", "await", "tempDir", ".", "path", "(", "{", "prefix", ":", "'apksigner'", ",", "suffix", ":", "'.bat'", "}", ")", ";", "await", "mkdirp", "(", "path", ".", "dirname", "(", "patchedPath", ")", ")", ";", "await", "fs", ".", "writeFile", "(", "patchedPath", ",", "patchedContent", ",", "'ascii'", ")", ";", "return", "patchedPath", ";", "}" ]
Applies the patch, which workarounds'-Djava.ext.dirs is not supported. Use -classpath instead.' error on Windows by creating a temporary patched copy of the original apksigner script. @param {string} originalPath - The original path to apksigner tool @returns {string} The full path to the patched script or the same path if there is no need to patch the original file.
[ "Applies", "the", "patch", "which", "workarounds", "-", "Djava", ".", "ext", ".", "dirs", "is", "not", "supported", ".", "Use", "-", "classpath", "instead", ".", "error", "on", "Windows", "by", "creating", "a", "temporary", "patched", "copy", "of", "the", "original", "apksigner", "script", "." ]
2f9f37ba10db866a939581d5a41b851d8e7d9151
https://github.com/appium/appium-adb/blob/2f9f37ba10db866a939581d5a41b851d8e7d9151/lib/tools/apk-signing.js#L25-L37
15,859
jprichardson/node-google
lib/google.js
google
function google (query, start, callback) { var startIndex = 0 if (typeof callback === 'undefined') { callback = start } else { startIndex = start } igoogle(query, startIndex, callback) }
javascript
function google (query, start, callback) { var startIndex = 0 if (typeof callback === 'undefined') { callback = start } else { startIndex = start } igoogle(query, startIndex, callback) }
[ "function", "google", "(", "query", ",", "start", ",", "callback", ")", "{", "var", "startIndex", "=", "0", "if", "(", "typeof", "callback", "===", "'undefined'", ")", "{", "callback", "=", "start", "}", "else", "{", "startIndex", "=", "start", "}", "igoogle", "(", "query", ",", "startIndex", ",", "callback", ")", "}" ]
start parameter is optional
[ "start", "parameter", "is", "optional" ]
a766f09f1b796d927ee0e94074c511203d5791c2
https://github.com/jprichardson/node-google/blob/a766f09f1b796d927ee0e94074c511203d5791c2/lib/google.js#L17-L25
15,860
godaddy/svgs
index.js
copypaste
function copypaste(from, to, ...props) { props.forEach((prop) => { if (prop in from) to[prop] = from[prop]; }); }
javascript
function copypaste(from, to, ...props) { props.forEach((prop) => { if (prop in from) to[prop] = from[prop]; }); }
[ "function", "copypaste", "(", "from", ",", "to", ",", "...", "props", ")", "{", "props", ".", "forEach", "(", "(", "prop", ")", "=>", "{", "if", "(", "prop", "in", "from", ")", "to", "[", "prop", "]", "=", "from", "[", "prop", "]", ";", "}", ")", ";", "}" ]
Helper function to copy and paste over properties to a different object if they exists. @param {Object} from Object to copy from. @param {Object} to Object to paste to. @param {String} props Name of the property @private
[ "Helper", "function", "to", "copy", "and", "paste", "over", "properties", "to", "a", "different", "object", "if", "they", "exists", "." ]
92e85fb96976da1febcca082887c7920dfe3dd60
https://github.com/godaddy/svgs/blob/92e85fb96976da1febcca082887c7920dfe3dd60/index.js#L25-L29
15,861
godaddy/svgs
index.js
prepare
function prepare(props) { const clean = rip(props, 'translate', 'scale', 'rotate', 'skewX', 'skewY', 'originX', 'originY', 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'style' ); const transform = []; // // Correctly apply the transformation properties. // To apply originX and originY we need to translate the element on those values and // translate them back once the element is scaled, rotated and skewed. // if ('originX' in props || 'originY' in props) transform.push(`translate(${props.originX || 0}, ${props.originY || 0})`); if ('translate' in props) transform.push(`translate(${props.translate})`); if ('scale' in props) transform.push(`scale(${props.scale})`); if ('rotate' in props) transform.push(`rotate(${props.rotate})`); if ('skewX' in props) transform.push(`skewX(${props.skewX})`); if ('skewY' in props) transform.push(`skewY(${props.skewY})`); if ('originX' in props || 'originY' in props) transform.push(`translate(${-props.originX || 0}, ${-props.originY || 0})`); if (transform.length) clean.transform = transform.join(' '); // // Correctly set the initial style value. // const style = ('style' in props) ? props.style : {}; // // This is the nasty part where we depend on React internals to work as // intended. If we add an empty object as style, it shouldn't render a `style` // attribute. So we can safely conditionally add things to our `style` object // and re-introduce it to our `clean` object // copypaste(props, style, 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle'); clean.style = style; // // React-Native svg provides as a default of `xMidYMid` if aspectRatio is not // specified with align information. So we need to support this behavior and // correctly default to `xMidYMid [mode]`. // const preserve = clean.preserveAspectRatio; if (preserve && preserve !== 'none' && !~preserve.indexOf(' ')) { clean.preserveAspectRatio = 'xMidYMid ' + preserve; } return clean; }
javascript
function prepare(props) { const clean = rip(props, 'translate', 'scale', 'rotate', 'skewX', 'skewY', 'originX', 'originY', 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle', 'style' ); const transform = []; // // Correctly apply the transformation properties. // To apply originX and originY we need to translate the element on those values and // translate them back once the element is scaled, rotated and skewed. // if ('originX' in props || 'originY' in props) transform.push(`translate(${props.originX || 0}, ${props.originY || 0})`); if ('translate' in props) transform.push(`translate(${props.translate})`); if ('scale' in props) transform.push(`scale(${props.scale})`); if ('rotate' in props) transform.push(`rotate(${props.rotate})`); if ('skewX' in props) transform.push(`skewX(${props.skewX})`); if ('skewY' in props) transform.push(`skewY(${props.skewY})`); if ('originX' in props || 'originY' in props) transform.push(`translate(${-props.originX || 0}, ${-props.originY || 0})`); if (transform.length) clean.transform = transform.join(' '); // // Correctly set the initial style value. // const style = ('style' in props) ? props.style : {}; // // This is the nasty part where we depend on React internals to work as // intended. If we add an empty object as style, it shouldn't render a `style` // attribute. So we can safely conditionally add things to our `style` object // and re-introduce it to our `clean` object // copypaste(props, style, 'fontFamily', 'fontSize', 'fontWeight', 'fontStyle'); clean.style = style; // // React-Native svg provides as a default of `xMidYMid` if aspectRatio is not // specified with align information. So we need to support this behavior and // correctly default to `xMidYMid [mode]`. // const preserve = clean.preserveAspectRatio; if (preserve && preserve !== 'none' && !~preserve.indexOf(' ')) { clean.preserveAspectRatio = 'xMidYMid ' + preserve; } return clean; }
[ "function", "prepare", "(", "props", ")", "{", "const", "clean", "=", "rip", "(", "props", ",", "'translate'", ",", "'scale'", ",", "'rotate'", ",", "'skewX'", ",", "'skewY'", ",", "'originX'", ",", "'originY'", ",", "'fontFamily'", ",", "'fontSize'", ",", "'fontWeight'", ",", "'fontStyle'", ",", "'style'", ")", ";", "const", "transform", "=", "[", "]", ";", "//", "// Correctly apply the transformation properties.", "// To apply originX and originY we need to translate the element on those values and", "// translate them back once the element is scaled, rotated and skewed.", "//", "if", "(", "'originX'", "in", "props", "||", "'originY'", "in", "props", ")", "transform", ".", "push", "(", "`", "${", "props", ".", "originX", "||", "0", "}", "${", "props", ".", "originY", "||", "0", "}", "`", ")", ";", "if", "(", "'translate'", "in", "props", ")", "transform", ".", "push", "(", "`", "${", "props", ".", "translate", "}", "`", ")", ";", "if", "(", "'scale'", "in", "props", ")", "transform", ".", "push", "(", "`", "${", "props", ".", "scale", "}", "`", ")", ";", "if", "(", "'rotate'", "in", "props", ")", "transform", ".", "push", "(", "`", "${", "props", ".", "rotate", "}", "`", ")", ";", "if", "(", "'skewX'", "in", "props", ")", "transform", ".", "push", "(", "`", "${", "props", ".", "skewX", "}", "`", ")", ";", "if", "(", "'skewY'", "in", "props", ")", "transform", ".", "push", "(", "`", "${", "props", ".", "skewY", "}", "`", ")", ";", "if", "(", "'originX'", "in", "props", "||", "'originY'", "in", "props", ")", "transform", ".", "push", "(", "`", "${", "-", "props", ".", "originX", "||", "0", "}", "${", "-", "props", ".", "originY", "||", "0", "}", "`", ")", ";", "if", "(", "transform", ".", "length", ")", "clean", ".", "transform", "=", "transform", ".", "join", "(", "' '", ")", ";", "//", "// Correctly set the initial style value.", "//", "const", "style", "=", "(", "'style'", "in", "props", ")", "?", "props", ".", "style", ":", "{", "}", ";", "//", "// This is the nasty part where we depend on React internals to work as", "// intended. If we add an empty object as style, it shouldn't render a `style`", "// attribute. So we can safely conditionally add things to our `style` object", "// and re-introduce it to our `clean` object", "//", "copypaste", "(", "props", ",", "style", ",", "'fontFamily'", ",", "'fontSize'", ",", "'fontWeight'", ",", "'fontStyle'", ")", ";", "clean", ".", "style", "=", "style", ";", "//", "// React-Native svg provides as a default of `xMidYMid` if aspectRatio is not", "// specified with align information. So we need to support this behavior and", "// correctly default to `xMidYMid [mode]`.", "//", "const", "preserve", "=", "clean", ".", "preserveAspectRatio", ";", "if", "(", "preserve", "&&", "preserve", "!==", "'none'", "&&", "!", "~", "preserve", ".", "indexOf", "(", "' '", ")", ")", "{", "clean", ".", "preserveAspectRatio", "=", "'xMidYMid '", "+", "preserve", ";", "}", "return", "clean", ";", "}" ]
The `react-native-svg` has some crazy api's that do not match with the properties that can be applied to SVG elements. This prepare function removes those properties and adds the properties back in their correct location. @param {Object} props Properties given to us. @returns {Object} Cleaned object. @private
[ "The", "react", "-", "native", "-", "svg", "has", "some", "crazy", "api", "s", "that", "do", "not", "match", "with", "the", "properties", "that", "can", "be", "applied", "to", "SVG", "elements", ".", "This", "prepare", "function", "removes", "those", "properties", "and", "adds", "the", "properties", "back", "in", "their", "correct", "location", "." ]
92e85fb96976da1febcca082887c7920dfe3dd60
https://github.com/godaddy/svgs/blob/92e85fb96976da1febcca082887c7920dfe3dd60/index.js#L40-L88
15,862
godaddy/svgs
index.js
G
function G(props) { const { x, y, ...rest } = props; if ((x || y) && !rest.translate) { rest.translate = `${x || 0}, ${y || 0}`; } return <g { ...prepare(rest) } />; }
javascript
function G(props) { const { x, y, ...rest } = props; if ((x || y) && !rest.translate) { rest.translate = `${x || 0}, ${y || 0}`; } return <g { ...prepare(rest) } />; }
[ "function", "G", "(", "props", ")", "{", "const", "{", "x", ",", "y", ",", "...", "rest", "}", "=", "props", ";", "if", "(", "(", "x", "||", "y", ")", "&&", "!", "rest", ".", "translate", ")", "{", "rest", ".", "translate", "=", "`", "${", "x", "||", "0", "}", "${", "y", "||", "0", "}", "`", ";", "}", "return", "<", "g", "{", "...", "prepare", "(", "rest", ")", "}", "/", ">", ";", "}" ]
Return a g SVG element. @param {Object} props The properties that are spread on the SVG element. @returns {React.Component} G SVG. @public
[ "Return", "a", "g", "SVG", "element", "." ]
92e85fb96976da1febcca082887c7920dfe3dd60
https://github.com/godaddy/svgs/blob/92e85fb96976da1febcca082887c7920dfe3dd60/index.js#L141-L149
15,863
godaddy/svgs
index.js
Svg
function Svg(props) { const { title, ...rest } = props; if (title) { return ( <svg role='img' aria-label='[title]' { ...prepare(rest) }> <title>{ title }</title> { props.children } </svg> ); } return <svg { ...prepare(rest) } />; }
javascript
function Svg(props) { const { title, ...rest } = props; if (title) { return ( <svg role='img' aria-label='[title]' { ...prepare(rest) }> <title>{ title }</title> { props.children } </svg> ); } return <svg { ...prepare(rest) } />; }
[ "function", "Svg", "(", "props", ")", "{", "const", "{", "title", ",", "...", "rest", "}", "=", "props", ";", "if", "(", "title", ")", "{", "return", "(", "<", "svg", "role", "=", "'img'", "aria-label", "=", "'[title]'", "{", "...", "prepare", "(", "rest", ")", "}", ">", "\n ", "<", "title", ">", "{", "title", "}", "<", "/", "title", ">", "\n ", "{", "props", ".", "children", "}", "\n ", "<", "/", "svg", ">", ")", ";", "}", "return", "<", "svg", "{", "...", "prepare", "(", "rest", ")", "}", "/", ">", ";", "}" ]
Return a SVG element. @param {Object} props The properties that are spread on the SVG element. @returns {React.Component} SVG. @public
[ "Return", "a", "SVG", "element", "." ]
92e85fb96976da1febcca082887c7920dfe3dd60
https://github.com/godaddy/svgs/blob/92e85fb96976da1febcca082887c7920dfe3dd60/index.js#L268-L281
15,864
godaddy/svgs
index.js
Text
function Text(props) { const { x, y, dx, dy, rotate, ...rest } = props; return <text { ...prepare(rest) } { ...{ x, y, dx, dy, rotate } } />; }
javascript
function Text(props) { const { x, y, dx, dy, rotate, ...rest } = props; return <text { ...prepare(rest) } { ...{ x, y, dx, dy, rotate } } />; }
[ "function", "Text", "(", "props", ")", "{", "const", "{", "x", ",", "y", ",", "dx", ",", "dy", ",", "rotate", ",", "...", "rest", "}", "=", "props", ";", "return", "<", "text", "{", "...", "prepare", "(", "rest", ")", "}", "{", "...", "{", "x", ",", "y", ",", "dx", ",", "dy", ",", "rotate", "}", "}", "/", ">", ";", "}" ]
Return a text SVG element. @returns {React.Component} Text SVG. @public @param {Object} props The properties that are spread on the SVG element. @param {String} props.x x position @param {String} props.y y position @param {String} props.dx delta x @param {String} props.dy delta y @param {String} props.rotate rotation
[ "Return", "a", "text", "SVG", "element", "." ]
92e85fb96976da1febcca082887c7920dfe3dd60
https://github.com/godaddy/svgs/blob/92e85fb96976da1febcca082887c7920dfe3dd60/index.js#L317-L321
15,865
godaddy/svgs
index.js
TSpan
function TSpan(props) { const { x, y, dx, dy, rotate, ...rest } = props; return <tspan { ...prepare(rest) } { ...{ x, y, dx, dy, rotate } } />; }
javascript
function TSpan(props) { const { x, y, dx, dy, rotate, ...rest } = props; return <tspan { ...prepare(rest) } { ...{ x, y, dx, dy, rotate } } />; }
[ "function", "TSpan", "(", "props", ")", "{", "const", "{", "x", ",", "y", ",", "dx", ",", "dy", ",", "rotate", ",", "...", "rest", "}", "=", "props", ";", "return", "<", "tspan", "{", "...", "prepare", "(", "rest", ")", "}", "{", "...", "{", "x", ",", "y", ",", "dx", ",", "dy", ",", "rotate", "}", "}", "/", ">", ";", "}" ]
Return a tspan SVG element. @returns {React.Component} TSpan SVG. @public @param {Object} props The properties that are spread on the SVG element. @param {String} props.x x position @param {String} props.y y position @param {String} props.dx delta x @param {String} props.dy delta y @param {String} props.rotate rotation
[ "Return", "a", "tspan", "SVG", "element", "." ]
92e85fb96976da1febcca082887c7920dfe3dd60
https://github.com/godaddy/svgs/blob/92e85fb96976da1febcca082887c7920dfe3dd60/index.js#L349-L353
15,866
OscarGodson/EpicEditor
src/editor.js
_applyAttrs
function _applyAttrs(context, attrs) { for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { context.setAttribute(attr, attrs[attr]); } } }
javascript
function _applyAttrs(context, attrs) { for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { context.setAttribute(attr, attrs[attr]); } } }
[ "function", "_applyAttrs", "(", "context", ",", "attrs", ")", "{", "for", "(", "var", "attr", "in", "attrs", ")", "{", "if", "(", "attrs", ".", "hasOwnProperty", "(", "attr", ")", ")", "{", "context", ".", "setAttribute", "(", "attr", ",", "attrs", "[", "attr", "]", ")", ";", "}", "}", "}" ]
Applies attributes to a DOM object @param {object} context The DOM obj you want to apply the attributes to @param {object} attrs A key/value pair of attributes you want to apply @returns {undefined}
[ "Applies", "attributes", "to", "a", "DOM", "object" ]
66a00cc4b6e5322c3fefb550c538781b97f511bd
https://github.com/OscarGodson/EpicEditor/blob/66a00cc4b6e5322c3fefb550c538781b97f511bd/src/editor.js#L13-L19
15,867
OscarGodson/EpicEditor
src/editor.js
_applyStyles
function _applyStyles(context, attrs) { for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { context.style[attr] = attrs[attr]; } } }
javascript
function _applyStyles(context, attrs) { for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { context.style[attr] = attrs[attr]; } } }
[ "function", "_applyStyles", "(", "context", ",", "attrs", ")", "{", "for", "(", "var", "attr", "in", "attrs", ")", "{", "if", "(", "attrs", ".", "hasOwnProperty", "(", "attr", ")", ")", "{", "context", ".", "style", "[", "attr", "]", "=", "attrs", "[", "attr", "]", ";", "}", "}", "}" ]
Applies styles to a DOM object @param {object} context The DOM obj you want to apply the attributes to @param {object} attrs A key/value pair of attributes you want to apply @returns {undefined}
[ "Applies", "styles", "to", "a", "DOM", "object" ]
66a00cc4b6e5322c3fefb550c538781b97f511bd
https://github.com/OscarGodson/EpicEditor/blob/66a00cc4b6e5322c3fefb550c538781b97f511bd/src/editor.js#L27-L33
15,868
OscarGodson/EpicEditor
src/editor.js
_getStyle
function _getStyle(el, styleProp) { var x = el , y = null; if (window.getComputedStyle) { y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp); } else if (x.currentStyle) { y = x.currentStyle[styleProp]; } return y; }
javascript
function _getStyle(el, styleProp) { var x = el , y = null; if (window.getComputedStyle) { y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp); } else if (x.currentStyle) { y = x.currentStyle[styleProp]; } return y; }
[ "function", "_getStyle", "(", "el", ",", "styleProp", ")", "{", "var", "x", "=", "el", ",", "y", "=", "null", ";", "if", "(", "window", ".", "getComputedStyle", ")", "{", "y", "=", "document", ".", "defaultView", ".", "getComputedStyle", "(", "x", ",", "null", ")", ".", "getPropertyValue", "(", "styleProp", ")", ";", "}", "else", "if", "(", "x", ".", "currentStyle", ")", "{", "y", "=", "x", ".", "currentStyle", "[", "styleProp", "]", ";", "}", "return", "y", ";", "}" ]
Returns a DOM objects computed style @param {object} el The element you want to get the style from @param {string} styleProp The property you want to get from the element @returns {string} Returns a string of the value. If property is not set it will return a blank string
[ "Returns", "a", "DOM", "objects", "computed", "style" ]
66a00cc4b6e5322c3fefb550c538781b97f511bd
https://github.com/OscarGodson/EpicEditor/blob/66a00cc4b6e5322c3fefb550c538781b97f511bd/src/editor.js#L41-L51
15,869
OscarGodson/EpicEditor
src/editor.js
_saveStyleState
function _saveStyleState(el, type, styles) { var returnState = {} , style; if (type === 'save') { for (style in styles) { if (styles.hasOwnProperty(style)) { returnState[style] = _getStyle(el, style); } } // After it's all done saving all the previous states, change the styles _applyStyles(el, styles); } else if (type === 'apply') { _applyStyles(el, styles); } return returnState; }
javascript
function _saveStyleState(el, type, styles) { var returnState = {} , style; if (type === 'save') { for (style in styles) { if (styles.hasOwnProperty(style)) { returnState[style] = _getStyle(el, style); } } // After it's all done saving all the previous states, change the styles _applyStyles(el, styles); } else if (type === 'apply') { _applyStyles(el, styles); } return returnState; }
[ "function", "_saveStyleState", "(", "el", ",", "type", ",", "styles", ")", "{", "var", "returnState", "=", "{", "}", ",", "style", ";", "if", "(", "type", "===", "'save'", ")", "{", "for", "(", "style", "in", "styles", ")", "{", "if", "(", "styles", ".", "hasOwnProperty", "(", "style", ")", ")", "{", "returnState", "[", "style", "]", "=", "_getStyle", "(", "el", ",", "style", ")", ";", "}", "}", "// After it's all done saving all the previous states, change the styles", "_applyStyles", "(", "el", ",", "styles", ")", ";", "}", "else", "if", "(", "type", "===", "'apply'", ")", "{", "_applyStyles", "(", "el", ",", "styles", ")", ";", "}", "return", "returnState", ";", "}" ]
Saves the current style state for the styles requested, then applies styles to overwrite the existing one. The old styles are returned as an object so you can pass it back in when you want to revert back to the old style @param {object} el The element to get the styles of @param {string} type Can be "save" or "apply". apply will just apply styles you give it. Save will write styles @param {object} styles Key/value style/property pairs @returns {object}
[ "Saves", "the", "current", "style", "state", "for", "the", "styles", "requested", "then", "applies", "styles", "to", "overwrite", "the", "existing", "one", ".", "The", "old", "styles", "are", "returned", "as", "an", "object", "so", "you", "can", "pass", "it", "back", "in", "when", "you", "want", "to", "revert", "back", "to", "the", "old", "style" ]
66a00cc4b6e5322c3fefb550c538781b97f511bd
https://github.com/OscarGodson/EpicEditor/blob/66a00cc4b6e5322c3fefb550c538781b97f511bd/src/editor.js#L62-L78
15,870
OscarGodson/EpicEditor
src/editor.js
_outerWidth
function _outerWidth(el) { var b = parseInt(_getStyle(el, 'border-left-width'), 10) + parseInt(_getStyle(el, 'border-right-width'), 10) , p = parseInt(_getStyle(el, 'padding-left'), 10) + parseInt(_getStyle(el, 'padding-right'), 10) , w = el.offsetWidth , t; // For IE in case no border is set and it defaults to "medium" if (isNaN(b)) { b = 0; } t = b + p + w; return t; }
javascript
function _outerWidth(el) { var b = parseInt(_getStyle(el, 'border-left-width'), 10) + parseInt(_getStyle(el, 'border-right-width'), 10) , p = parseInt(_getStyle(el, 'padding-left'), 10) + parseInt(_getStyle(el, 'padding-right'), 10) , w = el.offsetWidth , t; // For IE in case no border is set and it defaults to "medium" if (isNaN(b)) { b = 0; } t = b + p + w; return t; }
[ "function", "_outerWidth", "(", "el", ")", "{", "var", "b", "=", "parseInt", "(", "_getStyle", "(", "el", ",", "'border-left-width'", ")", ",", "10", ")", "+", "parseInt", "(", "_getStyle", "(", "el", ",", "'border-right-width'", ")", ",", "10", ")", ",", "p", "=", "parseInt", "(", "_getStyle", "(", "el", ",", "'padding-left'", ")", ",", "10", ")", "+", "parseInt", "(", "_getStyle", "(", "el", ",", "'padding-right'", ")", ",", "10", ")", ",", "w", "=", "el", ".", "offsetWidth", ",", "t", ";", "// For IE in case no border is set and it defaults to \"medium\"", "if", "(", "isNaN", "(", "b", ")", ")", "{", "b", "=", "0", ";", "}", "t", "=", "b", "+", "p", "+", "w", ";", "return", "t", ";", "}" ]
Gets an elements total width including it's borders and padding @param {object} el The element to get the total width of @returns {int}
[ "Gets", "an", "elements", "total", "width", "including", "it", "s", "borders", "and", "padding" ]
66a00cc4b6e5322c3fefb550c538781b97f511bd
https://github.com/OscarGodson/EpicEditor/blob/66a00cc4b6e5322c3fefb550c538781b97f511bd/src/editor.js#L85-L94
15,871
OscarGodson/EpicEditor
src/editor.js
_outerHeight
function _outerHeight(el) { var b = parseInt(_getStyle(el, 'border-top-width'), 10) + parseInt(_getStyle(el, 'border-bottom-width'), 10) , p = parseInt(_getStyle(el, 'padding-top'), 10) + parseInt(_getStyle(el, 'padding-bottom'), 10) , w = parseInt(_getStyle(el, 'height'), 10) , t; // For IE in case no border is set and it defaults to "medium" if (isNaN(b)) { b = 0; } t = b + p + w; return t; }
javascript
function _outerHeight(el) { var b = parseInt(_getStyle(el, 'border-top-width'), 10) + parseInt(_getStyle(el, 'border-bottom-width'), 10) , p = parseInt(_getStyle(el, 'padding-top'), 10) + parseInt(_getStyle(el, 'padding-bottom'), 10) , w = parseInt(_getStyle(el, 'height'), 10) , t; // For IE in case no border is set and it defaults to "medium" if (isNaN(b)) { b = 0; } t = b + p + w; return t; }
[ "function", "_outerHeight", "(", "el", ")", "{", "var", "b", "=", "parseInt", "(", "_getStyle", "(", "el", ",", "'border-top-width'", ")", ",", "10", ")", "+", "parseInt", "(", "_getStyle", "(", "el", ",", "'border-bottom-width'", ")", ",", "10", ")", ",", "p", "=", "parseInt", "(", "_getStyle", "(", "el", ",", "'padding-top'", ")", ",", "10", ")", "+", "parseInt", "(", "_getStyle", "(", "el", ",", "'padding-bottom'", ")", ",", "10", ")", ",", "w", "=", "parseInt", "(", "_getStyle", "(", "el", ",", "'height'", ")", ",", "10", ")", ",", "t", ";", "// For IE in case no border is set and it defaults to \"medium\"", "if", "(", "isNaN", "(", "b", ")", ")", "{", "b", "=", "0", ";", "}", "t", "=", "b", "+", "p", "+", "w", ";", "return", "t", ";", "}" ]
Gets an elements total height including it's borders and padding @param {object} el The element to get the total width of @returns {int}
[ "Gets", "an", "elements", "total", "height", "including", "it", "s", "borders", "and", "padding" ]
66a00cc4b6e5322c3fefb550c538781b97f511bd
https://github.com/OscarGodson/EpicEditor/blob/66a00cc4b6e5322c3fefb550c538781b97f511bd/src/editor.js#L101-L110
15,872
OscarGodson/EpicEditor
src/editor.js
_getText
function _getText(el) { var theText; // Make sure to check for type of string because if the body of the page // doesn't have any text it'll be "" which is falsey and will go into // the else which is meant for Firefox and shit will break if (typeof document.body.innerText == 'string') { theText = el.innerText; } else { // First replace <br>s before replacing the rest of the HTML theText = el.innerHTML.replace(/<br>/gi, "\n"); // Now we can clean the HTML theText = theText.replace(/<(?:.|\n)*?>/gm, ''); // Now fix HTML entities theText = theText.replace(/&lt;/gi, '<'); theText = theText.replace(/&gt;/gi, '>'); } return theText; }
javascript
function _getText(el) { var theText; // Make sure to check for type of string because if the body of the page // doesn't have any text it'll be "" which is falsey and will go into // the else which is meant for Firefox and shit will break if (typeof document.body.innerText == 'string') { theText = el.innerText; } else { // First replace <br>s before replacing the rest of the HTML theText = el.innerHTML.replace(/<br>/gi, "\n"); // Now we can clean the HTML theText = theText.replace(/<(?:.|\n)*?>/gm, ''); // Now fix HTML entities theText = theText.replace(/&lt;/gi, '<'); theText = theText.replace(/&gt;/gi, '>'); } return theText; }
[ "function", "_getText", "(", "el", ")", "{", "var", "theText", ";", "// Make sure to check for type of string because if the body of the page", "// doesn't have any text it'll be \"\" which is falsey and will go into", "// the else which is meant for Firefox and shit will break", "if", "(", "typeof", "document", ".", "body", ".", "innerText", "==", "'string'", ")", "{", "theText", "=", "el", ".", "innerText", ";", "}", "else", "{", "// First replace <br>s before replacing the rest of the HTML", "theText", "=", "el", ".", "innerHTML", ".", "replace", "(", "/", "<br>", "/", "gi", ",", "\"\\n\"", ")", ";", "// Now we can clean the HTML", "theText", "=", "theText", ".", "replace", "(", "/", "<(?:.|\\n)*?>", "/", "gm", ",", "''", ")", ";", "// Now fix HTML entities", "theText", "=", "theText", ".", "replace", "(", "/", "&lt;", "/", "gi", ",", "'<'", ")", ";", "theText", "=", "theText", ".", "replace", "(", "/", "&gt;", "/", "gi", ",", "'>'", ")", ";", "}", "return", "theText", ";", "}" ]
Grabs the text from an element and preserves whitespace
[ "Grabs", "the", "text", "from", "an", "element", "and", "preserves", "whitespace" ]
66a00cc4b6e5322c3fefb550c538781b97f511bd
https://github.com/OscarGodson/EpicEditor/blob/66a00cc4b6e5322c3fefb550c538781b97f511bd/src/editor.js#L147-L165
15,873
OscarGodson/EpicEditor
src/editor.js
_mergeObjs
function _mergeObjs() { // copy reference to target object var target = arguments[0] || {} , i = 1 , length = arguments.length , deep = false , options , name , src , copy // Handle a deep copy situation if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if (typeof target !== "object" && !_isFunction(target)) { target = {}; } // extend jQuery itself if only one argument is passed if (length === i) { target = this; --i; } for (; i < length; i++) { // Only deal with non-null/undefined values if ((options = arguments[i]) != null) { // Extend the base object for (name in options) { // @NOTE: added hasOwnProperty check if (options.hasOwnProperty(name)) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging object values if (deep && copy && typeof copy === "object" && !copy.nodeType) { target[name] = _mergeObjs(deep, // Never move original objects, clone them src || (copy.length != null ? [] : {}) , copy); } else if (copy !== undefined) { // Don't bring in undefined values target[name] = copy; } } } } } // Return the modified object return target; }
javascript
function _mergeObjs() { // copy reference to target object var target = arguments[0] || {} , i = 1 , length = arguments.length , deep = false , options , name , src , copy // Handle a deep copy situation if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if (typeof target !== "object" && !_isFunction(target)) { target = {}; } // extend jQuery itself if only one argument is passed if (length === i) { target = this; --i; } for (; i < length; i++) { // Only deal with non-null/undefined values if ((options = arguments[i]) != null) { // Extend the base object for (name in options) { // @NOTE: added hasOwnProperty check if (options.hasOwnProperty(name)) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging object values if (deep && copy && typeof copy === "object" && !copy.nodeType) { target[name] = _mergeObjs(deep, // Never move original objects, clone them src || (copy.length != null ? [] : {}) , copy); } else if (copy !== undefined) { // Don't bring in undefined values target[name] = copy; } } } } } // Return the modified object return target; }
[ "function", "_mergeObjs", "(", ")", "{", "// copy reference to target object", "var", "target", "=", "arguments", "[", "0", "]", "||", "{", "}", ",", "i", "=", "1", ",", "length", "=", "arguments", ".", "length", ",", "deep", "=", "false", ",", "options", ",", "name", ",", "src", ",", "copy", "// Handle a deep copy situation", "if", "(", "typeof", "target", "===", "\"boolean\"", ")", "{", "deep", "=", "target", ";", "target", "=", "arguments", "[", "1", "]", "||", "{", "}", ";", "// skip the boolean and the target", "i", "=", "2", ";", "}", "// Handle case when target is a string or something (possible in deep copy)", "if", "(", "typeof", "target", "!==", "\"object\"", "&&", "!", "_isFunction", "(", "target", ")", ")", "{", "target", "=", "{", "}", ";", "}", "// extend jQuery itself if only one argument is passed", "if", "(", "length", "===", "i", ")", "{", "target", "=", "this", ";", "--", "i", ";", "}", "for", "(", ";", "i", "<", "length", ";", "i", "++", ")", "{", "// Only deal with non-null/undefined values", "if", "(", "(", "options", "=", "arguments", "[", "i", "]", ")", "!=", "null", ")", "{", "// Extend the base object", "for", "(", "name", "in", "options", ")", "{", "// @NOTE: added hasOwnProperty check", "if", "(", "options", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "src", "=", "target", "[", "name", "]", ";", "copy", "=", "options", "[", "name", "]", ";", "// Prevent never-ending loop", "if", "(", "target", "===", "copy", ")", "{", "continue", ";", "}", "// Recurse if we're merging object values", "if", "(", "deep", "&&", "copy", "&&", "typeof", "copy", "===", "\"object\"", "&&", "!", "copy", ".", "nodeType", ")", "{", "target", "[", "name", "]", "=", "_mergeObjs", "(", "deep", ",", "// Never move original objects, clone them", "src", "||", "(", "copy", ".", "length", "!=", "null", "?", "[", "]", ":", "{", "}", ")", ",", "copy", ")", ";", "}", "else", "if", "(", "copy", "!==", "undefined", ")", "{", "// Don't bring in undefined values", "target", "[", "name", "]", "=", "copy", ";", "}", "}", "}", "}", "}", "// Return the modified object", "return", "target", ";", "}" ]
Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1 @param {boolean} [deepMerge=false] If true, will deep merge meaning it will merge sub-objects like {obj:obj2{foo:'bar'}} @param {object} first object @param {object} second object @returnss {object} a new object based on obj1 and obj2
[ "Overwrites", "obj1", "s", "values", "with", "obj2", "s", "and", "adds", "obj2", "s", "if", "non", "existent", "in", "obj1" ]
66a00cc4b6e5322c3fefb550c538781b97f511bd
https://github.com/OscarGodson/EpicEditor/blob/66a00cc4b6e5322c3fefb550c538781b97f511bd/src/editor.js#L256-L314
15,874
OscarGodson/EpicEditor
src/editor.js
shortcutHandler
function shortcutHandler(e) { if (e.keyCode == self.settings.shortcut.modifier) { isMod = true } // check for modifier press(default is alt key), save to var if (e.keyCode == 17) { isCtrl = true } // check for ctrl/cmnd press, in order to catch ctrl/cmnd + s if (e.keyCode == 18) { isCtrl = false } // Check for alt+p and make sure were not in fullscreen - default shortcut to switch to preview if (isMod === true && e.keyCode == self.settings.shortcut.preview && !self.is('fullscreen')) { e.preventDefault(); if (self.is('edit') && self._previewEnabled) { self.preview(); } else if (self._editEnabled) { self.edit(); } } // Check for alt+f - default shortcut to make editor fullscreen if (isMod === true && e.keyCode == self.settings.shortcut.fullscreen && self._fullscreenEnabled) { e.preventDefault(); self._goFullscreen(fsElement); } // Set the modifier key to false once *any* key combo is completed // or else, on Windows, hitting the alt key will lock the isMod state to true (ticket #133) if (isMod === true && e.keyCode !== self.settings.shortcut.modifier) { isMod = false; } // When a user presses "esc", revert everything! if (e.keyCode == 27 && self.is('fullscreen')) { self._exitFullscreen(fsElement); } // Check for ctrl + s (since a lot of people do it out of habit) and make it do nothing if (isCtrl === true && e.keyCode == 83) { self.save(); e.preventDefault(); isCtrl = false; } // Do the same for Mac now (metaKey == cmd). if (e.metaKey && e.keyCode == 83) { self.save(); e.preventDefault(); } }
javascript
function shortcutHandler(e) { if (e.keyCode == self.settings.shortcut.modifier) { isMod = true } // check for modifier press(default is alt key), save to var if (e.keyCode == 17) { isCtrl = true } // check for ctrl/cmnd press, in order to catch ctrl/cmnd + s if (e.keyCode == 18) { isCtrl = false } // Check for alt+p and make sure were not in fullscreen - default shortcut to switch to preview if (isMod === true && e.keyCode == self.settings.shortcut.preview && !self.is('fullscreen')) { e.preventDefault(); if (self.is('edit') && self._previewEnabled) { self.preview(); } else if (self._editEnabled) { self.edit(); } } // Check for alt+f - default shortcut to make editor fullscreen if (isMod === true && e.keyCode == self.settings.shortcut.fullscreen && self._fullscreenEnabled) { e.preventDefault(); self._goFullscreen(fsElement); } // Set the modifier key to false once *any* key combo is completed // or else, on Windows, hitting the alt key will lock the isMod state to true (ticket #133) if (isMod === true && e.keyCode !== self.settings.shortcut.modifier) { isMod = false; } // When a user presses "esc", revert everything! if (e.keyCode == 27 && self.is('fullscreen')) { self._exitFullscreen(fsElement); } // Check for ctrl + s (since a lot of people do it out of habit) and make it do nothing if (isCtrl === true && e.keyCode == 83) { self.save(); e.preventDefault(); isCtrl = false; } // Do the same for Mac now (metaKey == cmd). if (e.metaKey && e.keyCode == 83) { self.save(); e.preventDefault(); } }
[ "function", "shortcutHandler", "(", "e", ")", "{", "if", "(", "e", ".", "keyCode", "==", "self", ".", "settings", ".", "shortcut", ".", "modifier", ")", "{", "isMod", "=", "true", "}", "// check for modifier press(default is alt key), save to var", "if", "(", "e", ".", "keyCode", "==", "17", ")", "{", "isCtrl", "=", "true", "}", "// check for ctrl/cmnd press, in order to catch ctrl/cmnd + s", "if", "(", "e", ".", "keyCode", "==", "18", ")", "{", "isCtrl", "=", "false", "}", "// Check for alt+p and make sure were not in fullscreen - default shortcut to switch to preview", "if", "(", "isMod", "===", "true", "&&", "e", ".", "keyCode", "==", "self", ".", "settings", ".", "shortcut", ".", "preview", "&&", "!", "self", ".", "is", "(", "'fullscreen'", ")", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "if", "(", "self", ".", "is", "(", "'edit'", ")", "&&", "self", ".", "_previewEnabled", ")", "{", "self", ".", "preview", "(", ")", ";", "}", "else", "if", "(", "self", ".", "_editEnabled", ")", "{", "self", ".", "edit", "(", ")", ";", "}", "}", "// Check for alt+f - default shortcut to make editor fullscreen", "if", "(", "isMod", "===", "true", "&&", "e", ".", "keyCode", "==", "self", ".", "settings", ".", "shortcut", ".", "fullscreen", "&&", "self", ".", "_fullscreenEnabled", ")", "{", "e", ".", "preventDefault", "(", ")", ";", "self", ".", "_goFullscreen", "(", "fsElement", ")", ";", "}", "// Set the modifier key to false once *any* key combo is completed", "// or else, on Windows, hitting the alt key will lock the isMod state to true (ticket #133)", "if", "(", "isMod", "===", "true", "&&", "e", ".", "keyCode", "!==", "self", ".", "settings", ".", "shortcut", ".", "modifier", ")", "{", "isMod", "=", "false", ";", "}", "// When a user presses \"esc\", revert everything!", "if", "(", "e", ".", "keyCode", "==", "27", "&&", "self", ".", "is", "(", "'fullscreen'", ")", ")", "{", "self", ".", "_exitFullscreen", "(", "fsElement", ")", ";", "}", "// Check for ctrl + s (since a lot of people do it out of habit) and make it do nothing", "if", "(", "isCtrl", "===", "true", "&&", "e", ".", "keyCode", "==", "83", ")", "{", "self", ".", "save", "(", ")", ";", "e", ".", "preventDefault", "(", ")", ";", "isCtrl", "=", "false", ";", "}", "// Do the same for Mac now (metaKey == cmd).", "if", "(", "e", ".", "metaKey", "&&", "e", ".", "keyCode", "==", "83", ")", "{", "self", ".", "save", "(", ")", ";", "e", ".", "preventDefault", "(", ")", ";", "}", "}" ]
Add keyboard shortcuts for convenience.
[ "Add", "keyboard", "shortcuts", "for", "convenience", "." ]
66a00cc4b6e5322c3fefb550c538781b97f511bd
https://github.com/OscarGodson/EpicEditor/blob/66a00cc4b6e5322c3fefb550c538781b97f511bd/src/editor.js#L961-L1006
15,875
IceCreamYou/THREE.Terrain
build/THREE.Terrain.js
deposit
function deposit(g, i, j, xl, displacement) { var currentKey = j * xl + i; // Pick a random neighbor. for (var k = 0; k < 3; k++) { var r = Math.floor(Math.random() * 8); switch (r) { case 0: i++; break; case 1: i--; break; case 2: j++; break; case 3: j--; break; case 4: i++; j++; break; case 5: i++; j--; break; case 6: i--; j++; break; case 7: i--; j--; break; } var neighborKey = j * xl + i; // If the neighbor is lower, move the particle to that neighbor and re-evaluate. if (typeof g[neighborKey] !== 'undefined') { if (g[neighborKey].z < g[currentKey].z) { deposit(g, i, j, xl, displacement); return; } } // Deposit some particles on the edge. else if (Math.random() < 0.2) { g[currentKey].z += displacement; return; } } g[currentKey].z += displacement; }
javascript
function deposit(g, i, j, xl, displacement) { var currentKey = j * xl + i; // Pick a random neighbor. for (var k = 0; k < 3; k++) { var r = Math.floor(Math.random() * 8); switch (r) { case 0: i++; break; case 1: i--; break; case 2: j++; break; case 3: j--; break; case 4: i++; j++; break; case 5: i++; j--; break; case 6: i--; j++; break; case 7: i--; j--; break; } var neighborKey = j * xl + i; // If the neighbor is lower, move the particle to that neighbor and re-evaluate. if (typeof g[neighborKey] !== 'undefined') { if (g[neighborKey].z < g[currentKey].z) { deposit(g, i, j, xl, displacement); return; } } // Deposit some particles on the edge. else if (Math.random() < 0.2) { g[currentKey].z += displacement; return; } } g[currentKey].z += displacement; }
[ "function", "deposit", "(", "g", ",", "i", ",", "j", ",", "xl", ",", "displacement", ")", "{", "var", "currentKey", "=", "j", "*", "xl", "+", "i", ";", "// Pick a random neighbor.", "for", "(", "var", "k", "=", "0", ";", "k", "<", "3", ";", "k", "++", ")", "{", "var", "r", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "8", ")", ";", "switch", "(", "r", ")", "{", "case", "0", ":", "i", "++", ";", "break", ";", "case", "1", ":", "i", "--", ";", "break", ";", "case", "2", ":", "j", "++", ";", "break", ";", "case", "3", ":", "j", "--", ";", "break", ";", "case", "4", ":", "i", "++", ";", "j", "++", ";", "break", ";", "case", "5", ":", "i", "++", ";", "j", "--", ";", "break", ";", "case", "6", ":", "i", "--", ";", "j", "++", ";", "break", ";", "case", "7", ":", "i", "--", ";", "j", "--", ";", "break", ";", "}", "var", "neighborKey", "=", "j", "*", "xl", "+", "i", ";", "// If the neighbor is lower, move the particle to that neighbor and re-evaluate.", "if", "(", "typeof", "g", "[", "neighborKey", "]", "!==", "'undefined'", ")", "{", "if", "(", "g", "[", "neighborKey", "]", ".", "z", "<", "g", "[", "currentKey", "]", ".", "z", ")", "{", "deposit", "(", "g", ",", "i", ",", "j", ",", "xl", ",", "displacement", ")", ";", "return", ";", "}", "}", "// Deposit some particles on the edge.", "else", "if", "(", "Math", ".", "random", "(", ")", "<", "0.2", ")", "{", "g", "[", "currentKey", "]", ".", "z", "+=", "displacement", ";", "return", ";", "}", "}", "g", "[", "currentKey", "]", ".", "z", "+=", "displacement", ";", "}" ]
Deposit a particle at a vertex.
[ "Deposit", "a", "particle", "at", "a", "vertex", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/build/THREE.Terrain.js#L1363-L1393
15,876
IceCreamYou/THREE.Terrain
build/THREE.Terrain.js
WhiteNoise
function WhiteNoise(g, options, scale, segments, range, data) { if (scale > segments) return; var i = 0, j = 0, xl = segments, yl = segments, inc = Math.floor(segments / scale), lastX = -inc, lastY = -inc; // Walk over the target. For a target of size W and a resolution of N, // set every W/N points (in both directions). for (i = 0; i <= xl; i += inc) { for (j = 0; j <= yl; j += inc) { var k = j * xl + i; data[k] = Math.random() * range; if (lastX < 0 && lastY < 0) continue; // jscs:disable disallowSpacesInsideBrackets /* c b * * l t */ var t = data[k], l = data[ j * xl + (i-inc)] || t, // left b = data[(j-inc) * xl + i ] || t, // bottom c = data[(j-inc) * xl + (i-inc)] || t; // corner // jscs:enable disallowSpacesInsideBrackets // Interpolate between adjacent points to set the height of // higher-resolution target data. for (var x = lastX; x < i; x++) { for (var y = lastY; y < j; y++) { if (x === lastX && y === lastY) continue; var z = y * xl + x; if (z < 0) continue; var px = ((x-lastX) / inc), py = ((y-lastY) / inc), r1 = px * b + (1-px) * c, r2 = px * t + (1-px) * l; data[z] = py * r2 + (1-py) * r1; } } lastY = j; } lastX = i; lastY = -inc; } // Assign the temporary data back to the actual terrain heightmap. for (i = 0, xl = options.xSegments + 1; i < xl; i++) { for (j = 0, yl = options.ySegments + 1; j < yl; j++) { // http://stackoverflow.com/q/23708306/843621 var kg = j * xl + i, kd = j * segments + i; g[kg].z += data[kd]; } } }
javascript
function WhiteNoise(g, options, scale, segments, range, data) { if (scale > segments) return; var i = 0, j = 0, xl = segments, yl = segments, inc = Math.floor(segments / scale), lastX = -inc, lastY = -inc; // Walk over the target. For a target of size W and a resolution of N, // set every W/N points (in both directions). for (i = 0; i <= xl; i += inc) { for (j = 0; j <= yl; j += inc) { var k = j * xl + i; data[k] = Math.random() * range; if (lastX < 0 && lastY < 0) continue; // jscs:disable disallowSpacesInsideBrackets /* c b * * l t */ var t = data[k], l = data[ j * xl + (i-inc)] || t, // left b = data[(j-inc) * xl + i ] || t, // bottom c = data[(j-inc) * xl + (i-inc)] || t; // corner // jscs:enable disallowSpacesInsideBrackets // Interpolate between adjacent points to set the height of // higher-resolution target data. for (var x = lastX; x < i; x++) { for (var y = lastY; y < j; y++) { if (x === lastX && y === lastY) continue; var z = y * xl + x; if (z < 0) continue; var px = ((x-lastX) / inc), py = ((y-lastY) / inc), r1 = px * b + (1-px) * c, r2 = px * t + (1-px) * l; data[z] = py * r2 + (1-py) * r1; } } lastY = j; } lastX = i; lastY = -inc; } // Assign the temporary data back to the actual terrain heightmap. for (i = 0, xl = options.xSegments + 1; i < xl; i++) { for (j = 0, yl = options.ySegments + 1; j < yl; j++) { // http://stackoverflow.com/q/23708306/843621 var kg = j * xl + i, kd = j * segments + i; g[kg].z += data[kd]; } } }
[ "function", "WhiteNoise", "(", "g", ",", "options", ",", "scale", ",", "segments", ",", "range", ",", "data", ")", "{", "if", "(", "scale", ">", "segments", ")", "return", ";", "var", "i", "=", "0", ",", "j", "=", "0", ",", "xl", "=", "segments", ",", "yl", "=", "segments", ",", "inc", "=", "Math", ".", "floor", "(", "segments", "/", "scale", ")", ",", "lastX", "=", "-", "inc", ",", "lastY", "=", "-", "inc", ";", "// Walk over the target. For a target of size W and a resolution of N,", "// set every W/N points (in both directions).", "for", "(", "i", "=", "0", ";", "i", "<=", "xl", ";", "i", "+=", "inc", ")", "{", "for", "(", "j", "=", "0", ";", "j", "<=", "yl", ";", "j", "+=", "inc", ")", "{", "var", "k", "=", "j", "*", "xl", "+", "i", ";", "data", "[", "k", "]", "=", "Math", ".", "random", "(", ")", "*", "range", ";", "if", "(", "lastX", "<", "0", "&&", "lastY", "<", "0", ")", "continue", ";", "// jscs:disable disallowSpacesInsideBrackets", "/* c b *\n * l t */", "var", "t", "=", "data", "[", "k", "]", ",", "l", "=", "data", "[", "j", "*", "xl", "+", "(", "i", "-", "inc", ")", "]", "||", "t", ",", "// left", "b", "=", "data", "[", "(", "j", "-", "inc", ")", "*", "xl", "+", "i", "]", "||", "t", ",", "// bottom", "c", "=", "data", "[", "(", "j", "-", "inc", ")", "*", "xl", "+", "(", "i", "-", "inc", ")", "]", "||", "t", ";", "// corner", "// jscs:enable disallowSpacesInsideBrackets", "// Interpolate between adjacent points to set the height of", "// higher-resolution target data.", "for", "(", "var", "x", "=", "lastX", ";", "x", "<", "i", ";", "x", "++", ")", "{", "for", "(", "var", "y", "=", "lastY", ";", "y", "<", "j", ";", "y", "++", ")", "{", "if", "(", "x", "===", "lastX", "&&", "y", "===", "lastY", ")", "continue", ";", "var", "z", "=", "y", "*", "xl", "+", "x", ";", "if", "(", "z", "<", "0", ")", "continue", ";", "var", "px", "=", "(", "(", "x", "-", "lastX", ")", "/", "inc", ")", ",", "py", "=", "(", "(", "y", "-", "lastY", ")", "/", "inc", ")", ",", "r1", "=", "px", "*", "b", "+", "(", "1", "-", "px", ")", "*", "c", ",", "r2", "=", "px", "*", "t", "+", "(", "1", "-", "px", ")", "*", "l", ";", "data", "[", "z", "]", "=", "py", "*", "r2", "+", "(", "1", "-", "py", ")", "*", "r1", ";", "}", "}", "lastY", "=", "j", ";", "}", "lastX", "=", "i", ";", "lastY", "=", "-", "inc", ";", "}", "// Assign the temporary data back to the actual terrain heightmap.", "for", "(", "i", "=", "0", ",", "xl", "=", "options", ".", "xSegments", "+", "1", ";", "i", "<", "xl", ";", "i", "++", ")", "{", "for", "(", "j", "=", "0", ",", "yl", "=", "options", ".", "ySegments", "+", "1", ";", "j", "<", "yl", ";", "j", "++", ")", "{", "// http://stackoverflow.com/q/23708306/843621", "var", "kg", "=", "j", "*", "xl", "+", "i", ",", "kd", "=", "j", "*", "segments", "+", "i", ";", "g", "[", "kg", "]", ".", "z", "+=", "data", "[", "kd", "]", ";", "}", "}", "}" ]
Generate a heightmap using white noise. @param {THREE.Vector3[]} g The terrain vertices. @param {Object} options Settings @param {Number} scale The resolution of the resulting heightmap. @param {Number} segments The width of the target heightmap. @param {Number} range The altitude of the noise. @param {Number[]} data The target heightmap.
[ "Generate", "a", "heightmap", "using", "white", "noise", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/build/THREE.Terrain.js#L1522-L1574
15,877
IceCreamYou/THREE.Terrain
src/weightedBoxBlurGaussian.js
gaussianBoxBlur
function gaussianBoxBlur(scl, w, h, r, n, tcl) { if (typeof r === 'undefined') r = 1; if (typeof n === 'undefined') n = 3; if (typeof tcl === 'undefined') tcl = new Float64Array(scl.length); var boxes = boxesForGauss(r, n); for (var i = 0; i < n; i++) { boxBlur(scl, tcl, w, h, (boxes[i]-1)/2); } return tcl; }
javascript
function gaussianBoxBlur(scl, w, h, r, n, tcl) { if (typeof r === 'undefined') r = 1; if (typeof n === 'undefined') n = 3; if (typeof tcl === 'undefined') tcl = new Float64Array(scl.length); var boxes = boxesForGauss(r, n); for (var i = 0; i < n; i++) { boxBlur(scl, tcl, w, h, (boxes[i]-1)/2); } return tcl; }
[ "function", "gaussianBoxBlur", "(", "scl", ",", "w", ",", "h", ",", "r", ",", "n", ",", "tcl", ")", "{", "if", "(", "typeof", "r", "===", "'undefined'", ")", "r", "=", "1", ";", "if", "(", "typeof", "n", "===", "'undefined'", ")", "n", "=", "3", ";", "if", "(", "typeof", "tcl", "===", "'undefined'", ")", "tcl", "=", "new", "Float64Array", "(", "scl", ".", "length", ")", ";", "var", "boxes", "=", "boxesForGauss", "(", "r", ",", "n", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "boxBlur", "(", "scl", ",", "tcl", ",", "w", ",", "h", ",", "(", "boxes", "[", "i", "]", "-", "1", ")", "/", "2", ")", ";", "}", "return", "tcl", ";", "}" ]
Approximate a Gaussian blur by performing several weighted box blurs. After this function runs, `tcl` will contain the blurred source channel. This operation also modifies `scl`. Lightly modified from http://blog.ivank.net/fastest-gaussian-blur.html under the MIT license: http://opensource.org/licenses/MIT Other than style cleanup, the main significant change is that the original version was used for manipulating RGBA channels in an image, so it assumed that input and output were integers [0, 255]. This version does not make such assumptions about the input or output values. @param Number[] scl The source channel. @param Number w The image width. @param Number h The image height. @param Number [r=1] The standard deviation (how much to blur). @param Number [n=3] The number of box blurs to use in the approximation. @param Number[] [tcl] The target channel. Should be different than the source channel. If not passed, one is created. This is also the return value. @return Number[] An array representing the blurred channel.
[ "Approximate", "a", "Gaussian", "blur", "by", "performing", "several", "weighted", "box", "blurs", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/weightedBoxBlurGaussian.js#L62-L71
15,878
IceCreamYou/THREE.Terrain
src/weightedBoxBlurGaussian.js
boxesForGauss
function boxesForGauss(sigma, n) { // Calculate how far out we need to go to capture the bulk of the distribution. var wIdeal = Math.sqrt(12*sigma*sigma/n + 1); // Ideal averaging filter width var wl = Math.floor(wIdeal); // Lower odd integer bound on the width if (wl % 2 === 0) wl--; var wu = wl+2; // Upper odd integer bound on the width var mIdeal = (12*sigma*sigma - n*wl*wl - 4*n*wl - 3*n)/(-4*wl - 4); var m = Math.round(mIdeal); // var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)/12 ); var sizes = new Int16Array(n); for (var i = 0; i < n; i++) { sizes[i] = i < m ? wl : wu; } return sizes; }
javascript
function boxesForGauss(sigma, n) { // Calculate how far out we need to go to capture the bulk of the distribution. var wIdeal = Math.sqrt(12*sigma*sigma/n + 1); // Ideal averaging filter width var wl = Math.floor(wIdeal); // Lower odd integer bound on the width if (wl % 2 === 0) wl--; var wu = wl+2; // Upper odd integer bound on the width var mIdeal = (12*sigma*sigma - n*wl*wl - 4*n*wl - 3*n)/(-4*wl - 4); var m = Math.round(mIdeal); // var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)/12 ); var sizes = new Int16Array(n); for (var i = 0; i < n; i++) { sizes[i] = i < m ? wl : wu; } return sizes; }
[ "function", "boxesForGauss", "(", "sigma", ",", "n", ")", "{", "// Calculate how far out we need to go to capture the bulk of the distribution.", "var", "wIdeal", "=", "Math", ".", "sqrt", "(", "12", "*", "sigma", "*", "sigma", "/", "n", "+", "1", ")", ";", "// Ideal averaging filter width", "var", "wl", "=", "Math", ".", "floor", "(", "wIdeal", ")", ";", "// Lower odd integer bound on the width", "if", "(", "wl", "%", "2", "===", "0", ")", "wl", "--", ";", "var", "wu", "=", "wl", "+", "2", ";", "// Upper odd integer bound on the width", "var", "mIdeal", "=", "(", "12", "*", "sigma", "*", "sigma", "-", "n", "*", "wl", "*", "wl", "-", "4", "*", "n", "*", "wl", "-", "3", "*", "n", ")", "/", "(", "-", "4", "*", "wl", "-", "4", ")", ";", "var", "m", "=", "Math", ".", "round", "(", "mIdeal", ")", ";", "// var sigmaActual = Math.sqrt( (m*wl*wl + (n-m)*wu*wu - n)/12 );", "var", "sizes", "=", "new", "Int16Array", "(", "n", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "sizes", "[", "i", "]", "=", "i", "<", "m", "?", "wl", ":", "wu", ";", "}", "return", "sizes", ";", "}" ]
Calculate the size of boxes needed to approximate a Gaussian blur. The appropriate box sizes depend on the number of box blur passes required. @param Number sigma The standard deviation (how much to blur). @param Number n The number of boxes (also the number of box blurs you want to perform using those boxes).
[ "Calculate", "the", "size", "of", "boxes", "needed", "to", "approximate", "a", "Gaussian", "blur", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/weightedBoxBlurGaussian.js#L84-L98
15,879
IceCreamYou/THREE.Terrain
src/weightedBoxBlurGaussian.js
boxBlur
function boxBlur(scl, tcl, w, h, r) { for (var i = 0, l = scl.length; i < l; i++) { tcl[i] = scl[i]; } boxBlurH(tcl, scl, w, h, r); boxBlurV(scl, tcl, w, h, r); }
javascript
function boxBlur(scl, tcl, w, h, r) { for (var i = 0, l = scl.length; i < l; i++) { tcl[i] = scl[i]; } boxBlurH(tcl, scl, w, h, r); boxBlurV(scl, tcl, w, h, r); }
[ "function", "boxBlur", "(", "scl", ",", "tcl", ",", "w", ",", "h", ",", "r", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "scl", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "tcl", "[", "i", "]", "=", "scl", "[", "i", "]", ";", "}", "boxBlurH", "(", "tcl", ",", "scl", ",", "w", ",", "h", ",", "r", ")", ";", "boxBlurV", "(", "scl", ",", "tcl", ",", "w", ",", "h", ",", "r", ")", ";", "}" ]
Perform a 2D box blur by doing a 1D box blur in two directions. Uses the same parameters as gaussblur().
[ "Perform", "a", "2D", "box", "blur", "by", "doing", "a", "1D", "box", "blur", "in", "two", "directions", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/weightedBoxBlurGaussian.js#L105-L109
15,880
IceCreamYou/THREE.Terrain
src/weightedBoxBlurGaussian.js
boxBlurH
function boxBlurH(scl, tcl, w, h, r) { var iarr = 1 / (r+r+1); // averaging adjustment parameter for (var i = 0; i < h; i++) { var ti = i * w, // current target index li = ti, // current left side of the examined range ri = ti + r, // current right side of the examined range fv = scl[ti], // first value in the row lv = scl[ti + w - 1], // last value in the row val = (r+1) * fv, // target value, accumulated over examined points j; // Sum the source values in the box for (j = 0; j < r; j++) { val += scl[ti + j]; } // Compute the target value by taking the average of the surrounding // values. This is done by adding the deviations so far and adjusting, // accounting for the edges by extending the first and last values. for (j = 0 ; j <= r ; j++) { val += scl[ri++] - fv ; tcl[ti++] = val*iarr; } for (j = r+1; j < w-r; j++) { val += scl[ri++] - scl[li++]; tcl[ti++] = val*iarr; } for (j = w-r; j < w ; j++) { val += lv - scl[li++]; tcl[ti++] = val*iarr; } } }
javascript
function boxBlurH(scl, tcl, w, h, r) { var iarr = 1 / (r+r+1); // averaging adjustment parameter for (var i = 0; i < h; i++) { var ti = i * w, // current target index li = ti, // current left side of the examined range ri = ti + r, // current right side of the examined range fv = scl[ti], // first value in the row lv = scl[ti + w - 1], // last value in the row val = (r+1) * fv, // target value, accumulated over examined points j; // Sum the source values in the box for (j = 0; j < r; j++) { val += scl[ti + j]; } // Compute the target value by taking the average of the surrounding // values. This is done by adding the deviations so far and adjusting, // accounting for the edges by extending the first and last values. for (j = 0 ; j <= r ; j++) { val += scl[ri++] - fv ; tcl[ti++] = val*iarr; } for (j = r+1; j < w-r; j++) { val += scl[ri++] - scl[li++]; tcl[ti++] = val*iarr; } for (j = w-r; j < w ; j++) { val += lv - scl[li++]; tcl[ti++] = val*iarr; } } }
[ "function", "boxBlurH", "(", "scl", ",", "tcl", ",", "w", ",", "h", ",", "r", ")", "{", "var", "iarr", "=", "1", "/", "(", "r", "+", "r", "+", "1", ")", ";", "// averaging adjustment parameter", "for", "(", "var", "i", "=", "0", ";", "i", "<", "h", ";", "i", "++", ")", "{", "var", "ti", "=", "i", "*", "w", ",", "// current target index", "li", "=", "ti", ",", "// current left side of the examined range", "ri", "=", "ti", "+", "r", ",", "// current right side of the examined range", "fv", "=", "scl", "[", "ti", "]", ",", "// first value in the row", "lv", "=", "scl", "[", "ti", "+", "w", "-", "1", "]", ",", "// last value in the row", "val", "=", "(", "r", "+", "1", ")", "*", "fv", ",", "// target value, accumulated over examined points", "j", ";", "// Sum the source values in the box", "for", "(", "j", "=", "0", ";", "j", "<", "r", ";", "j", "++", ")", "{", "val", "+=", "scl", "[", "ti", "+", "j", "]", ";", "}", "// Compute the target value by taking the average of the surrounding", "// values. This is done by adding the deviations so far and adjusting,", "// accounting for the edges by extending the first and last values.", "for", "(", "j", "=", "0", ";", "j", "<=", "r", ";", "j", "++", ")", "{", "val", "+=", "scl", "[", "ri", "++", "]", "-", "fv", ";", "tcl", "[", "ti", "++", "]", "=", "val", "*", "iarr", ";", "}", "for", "(", "j", "=", "r", "+", "1", ";", "j", "<", "w", "-", "r", ";", "j", "++", ")", "{", "val", "+=", "scl", "[", "ri", "++", "]", "-", "scl", "[", "li", "++", "]", ";", "tcl", "[", "ti", "++", "]", "=", "val", "*", "iarr", ";", "}", "for", "(", "j", "=", "w", "-", "r", ";", "j", "<", "w", ";", "j", "++", ")", "{", "val", "+=", "lv", "-", "scl", "[", "li", "++", "]", ";", "tcl", "[", "ti", "++", "]", "=", "val", "*", "iarr", ";", "}", "}", "}" ]
Perform a horizontal box blur. Uses the same parameters as gaussblur().
[ "Perform", "a", "horizontal", "box", "blur", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/weightedBoxBlurGaussian.js#L116-L135
15,881
IceCreamYou/THREE.Terrain
src/worley.js
distanceToNearest
function distanceToNearest(coords, points, distanceType) { var color = Infinity, distanceFunc = 'distanceTo' + distanceType; for (var k = 0; k < points.length; k++) { var d = points[k][distanceFunc](coords); if (d < color) { color = d; } } return color; }
javascript
function distanceToNearest(coords, points, distanceType) { var color = Infinity, distanceFunc = 'distanceTo' + distanceType; for (var k = 0; k < points.length; k++) { var d = points[k][distanceFunc](coords); if (d < color) { color = d; } } return color; }
[ "function", "distanceToNearest", "(", "coords", ",", "points", ",", "distanceType", ")", "{", "var", "color", "=", "Infinity", ",", "distanceFunc", "=", "'distanceTo'", "+", "distanceType", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "points", ".", "length", ";", "k", "++", ")", "{", "var", "d", "=", "points", "[", "k", "]", "[", "distanceFunc", "]", "(", "coords", ")", ";", "if", "(", "d", "<", "color", ")", "{", "color", "=", "d", ";", "}", "}", "return", "color", ";", "}" ]
Find the Voronoi centroid closest to the current terrain vertex. This approach is naive, but since the number of cells isn't typically very big, it's plenty fast enough. Alternatives approaches include using Fortune's algorithm or tracking cells based on a grid.
[ "Find", "the", "Voronoi", "centroid", "closest", "to", "the", "current", "terrain", "vertex", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/worley.js#L31-L41
15,882
IceCreamYou/THREE.Terrain
demo/index.js
watchFocus
function watchFocus() { var _blurred = false; window.addEventListener('focus', function() { if (_blurred) { _blurred = false; // startAnimating(); // controls.freeze = false; } }); window.addEventListener('blur', function() { // stopAnimating(); _blurred = true; controls.freeze = true; }); }
javascript
function watchFocus() { var _blurred = false; window.addEventListener('focus', function() { if (_blurred) { _blurred = false; // startAnimating(); // controls.freeze = false; } }); window.addEventListener('blur', function() { // stopAnimating(); _blurred = true; controls.freeze = true; }); }
[ "function", "watchFocus", "(", ")", "{", "var", "_blurred", "=", "false", ";", "window", ".", "addEventListener", "(", "'focus'", ",", "function", "(", ")", "{", "if", "(", "_blurred", ")", "{", "_blurred", "=", "false", ";", "// startAnimating();", "// controls.freeze = false;", "}", "}", ")", ";", "window", ".", "addEventListener", "(", "'blur'", ",", "function", "(", ")", "{", "// stopAnimating();", "_blurred", "=", "true", ";", "controls", ".", "freeze", "=", "true", ";", "}", ")", ";", "}" ]
Stop animating if the window is out of focus
[ "Stop", "animating", "if", "the", "window", "is", "out", "of", "focus" ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/demo/index.js#L414-L428
15,883
IceCreamYou/THREE.Terrain
demo/index.js
numberToCategory
function numberToCategory(value, buckets) { if (!buckets) { buckets = [-2, -2/3, 2/3, 2]; } if (typeof buckets.length === 'number' && buckets.length > 3) { if (value < buckets[0]) return 'very low'; if (value < buckets[1]) return 'low'; if (value < buckets[2]) return 'medium'; if (value < buckets[3]) return 'high'; if (value >= buckets[3]) return 'very high'; } var keys = Object.keys(buckets).sort(function(a, b) { return buckets[a] - buckets[b]; }), l = keys.length; for (var i = 0; i < l; i++) { if (value < buckets[keys[i]]) { return keys[i]; } } return keys[l-1]; }
javascript
function numberToCategory(value, buckets) { if (!buckets) { buckets = [-2, -2/3, 2/3, 2]; } if (typeof buckets.length === 'number' && buckets.length > 3) { if (value < buckets[0]) return 'very low'; if (value < buckets[1]) return 'low'; if (value < buckets[2]) return 'medium'; if (value < buckets[3]) return 'high'; if (value >= buckets[3]) return 'very high'; } var keys = Object.keys(buckets).sort(function(a, b) { return buckets[a] - buckets[b]; }), l = keys.length; for (var i = 0; i < l; i++) { if (value < buckets[keys[i]]) { return keys[i]; } } return keys[l-1]; }
[ "function", "numberToCategory", "(", "value", ",", "buckets", ")", "{", "if", "(", "!", "buckets", ")", "{", "buckets", "=", "[", "-", "2", ",", "-", "2", "/", "3", ",", "2", "/", "3", ",", "2", "]", ";", "}", "if", "(", "typeof", "buckets", ".", "length", "===", "'number'", "&&", "buckets", ".", "length", ">", "3", ")", "{", "if", "(", "value", "<", "buckets", "[", "0", "]", ")", "return", "'very low'", ";", "if", "(", "value", "<", "buckets", "[", "1", "]", ")", "return", "'low'", ";", "if", "(", "value", "<", "buckets", "[", "2", "]", ")", "return", "'medium'", ";", "if", "(", "value", "<", "buckets", "[", "3", "]", ")", "return", "'high'", ";", "if", "(", "value", ">=", "buckets", "[", "3", "]", ")", "return", "'very high'", ";", "}", "var", "keys", "=", "Object", ".", "keys", "(", "buckets", ")", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "buckets", "[", "a", "]", "-", "buckets", "[", "b", "]", ";", "}", ")", ",", "l", "=", "keys", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "value", "<", "buckets", "[", "keys", "[", "i", "]", "]", ")", "{", "return", "keys", "[", "i", "]", ";", "}", "}", "return", "keys", "[", "l", "-", "1", "]", ";", "}" ]
Classify a numeric input. @param {Number} value The number to classify. @param {Object/Number[]} [buckets=[-2, -2/3, 2/3, 2]] An object or numeric array used to classify `value`. If `buckets` is an array, the returned category will be the first of "very low," "low," "medium," and "high," in that order, where the correspondingly ordered bucket value is higher than the `value` being classified, or "very high" if all bucket values are smaller than the `value` being classified. If `buckets` is an object, its values will be sorted, and the returned category will be the key of the first bucket value that is higher than the `value` being classified, or the key of the highest bucket value if the `value` being classified is higher than all the values in `buckets`. @return {String} The category into which the numeric input was classified.
[ "Classify", "a", "numeric", "input", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/demo/index.js#L661-L682
15,884
IceCreamYou/THREE.Terrain
src/analysis.js
percentRank
function percentRank(arr, v) { if (typeof v !== 'number') throw new TypeError('v must be a number'); for (var i = 0, l = arr.length; i < l; i++) { if (v <= arr[i]) { while (i < l && v === arr[i]) { i++; } if (i === 0) return 0; if (v !== arr[i-1]) { i += (v - arr[i-1]) / (arr[i] - arr[i-1]); } return i / l; } } return 1; }
javascript
function percentRank(arr, v) { if (typeof v !== 'number') throw new TypeError('v must be a number'); for (var i = 0, l = arr.length; i < l; i++) { if (v <= arr[i]) { while (i < l && v === arr[i]) { i++; } if (i === 0) return 0; if (v !== arr[i-1]) { i += (v - arr[i-1]) / (arr[i] - arr[i-1]); } return i / l; } } return 1; }
[ "function", "percentRank", "(", "arr", ",", "v", ")", "{", "if", "(", "typeof", "v", "!==", "'number'", ")", "throw", "new", "TypeError", "(", "'v must be a number'", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "arr", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "v", "<=", "arr", "[", "i", "]", ")", "{", "while", "(", "i", "<", "l", "&&", "v", "===", "arr", "[", "i", "]", ")", "{", "i", "++", ";", "}", "if", "(", "i", "===", "0", ")", "return", "0", ";", "if", "(", "v", "!==", "arr", "[", "i", "-", "1", "]", ")", "{", "i", "+=", "(", "v", "-", "arr", "[", "i", "-", "1", "]", ")", "/", "(", "arr", "[", "i", "]", "-", "arr", "[", "i", "-", "1", "]", ")", ";", "}", "return", "i", "/", "l", ";", "}", "}", "return", "1", ";", "}" ]
Returns the percentile of the given value in a sorted numeric array. @param {Number[]} arr A sorted numeric array to examine. @param {Number} v The value at which to return the percentile. @return {Number} The percentile at the given value in the given array.
[ "Returns", "the", "percentile", "of", "the", "given", "value", "in", "a", "sorted", "numeric", "array", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/analysis.js#L243-L258
15,885
IceCreamYou/THREE.Terrain
src/analysis.js
getFittedPlaneNormal
function getFittedPlaneNormal(points, centroid) { var n = points.length, xx = 0, xy = 0, xz = 0, yy = 0, yz = 0, zz = 0; if (n < 3) throw new Error('At least three points are required to fit a plane'); var r = new THREE.Vector3(); for (var i = 0, l = points.length; i < l; i++) { r.copy(points[i]).sub(centroid); xx += r.x * r.x; xy += r.x * r.y; xz += r.x * r.z; yy += r.y * r.y; yz += r.y * r.z; zz += r.z * r.z; } var xDeterminant = yy*zz - yz*yz, yDeterminant = xx*zz - xz*xz, zDeterminant = xx*yy - xy*xy, maxDeterminant = Math.max(xDeterminant, yDeterminant, zDeterminant); if (maxDeterminant <= 0) throw new Error("The points don't span a plane"); if (maxDeterminant === xDeterminant) { r.set( 1, (xz*yz - xy*zz) / xDeterminant, (xy*yz - xz*yy) / xDeterminant ); } else if (maxDeterminant === yDeterminant) { r.set( (yz*xz - xy*zz) / yDeterminant, 1, (xy*xz - yz*xx) / yDeterminant ); } else if (maxDeterminant === zDeterminant) { r.set( (yz*xy - xz*yy) / zDeterminant, (xz*xy - yz*xx) / zDeterminant, 1 ); } return r.normalize(); }
javascript
function getFittedPlaneNormal(points, centroid) { var n = points.length, xx = 0, xy = 0, xz = 0, yy = 0, yz = 0, zz = 0; if (n < 3) throw new Error('At least three points are required to fit a plane'); var r = new THREE.Vector3(); for (var i = 0, l = points.length; i < l; i++) { r.copy(points[i]).sub(centroid); xx += r.x * r.x; xy += r.x * r.y; xz += r.x * r.z; yy += r.y * r.y; yz += r.y * r.z; zz += r.z * r.z; } var xDeterminant = yy*zz - yz*yz, yDeterminant = xx*zz - xz*xz, zDeterminant = xx*yy - xy*xy, maxDeterminant = Math.max(xDeterminant, yDeterminant, zDeterminant); if (maxDeterminant <= 0) throw new Error("The points don't span a plane"); if (maxDeterminant === xDeterminant) { r.set( 1, (xz*yz - xy*zz) / xDeterminant, (xy*yz - xz*yy) / xDeterminant ); } else if (maxDeterminant === yDeterminant) { r.set( (yz*xz - xy*zz) / yDeterminant, 1, (xy*xz - yz*xx) / yDeterminant ); } else if (maxDeterminant === zDeterminant) { r.set( (yz*xy - xz*yy) / zDeterminant, (xz*xy - yz*xx) / zDeterminant, 1 ); } return r.normalize(); }
[ "function", "getFittedPlaneNormal", "(", "points", ",", "centroid", ")", "{", "var", "n", "=", "points", ".", "length", ",", "xx", "=", "0", ",", "xy", "=", "0", ",", "xz", "=", "0", ",", "yy", "=", "0", ",", "yz", "=", "0", ",", "zz", "=", "0", ";", "if", "(", "n", "<", "3", ")", "throw", "new", "Error", "(", "'At least three points are required to fit a plane'", ")", ";", "var", "r", "=", "new", "THREE", ".", "Vector3", "(", ")", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "points", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "r", ".", "copy", "(", "points", "[", "i", "]", ")", ".", "sub", "(", "centroid", ")", ";", "xx", "+=", "r", ".", "x", "*", "r", ".", "x", ";", "xy", "+=", "r", ".", "x", "*", "r", ".", "y", ";", "xz", "+=", "r", ".", "x", "*", "r", ".", "z", ";", "yy", "+=", "r", ".", "y", "*", "r", ".", "y", ";", "yz", "+=", "r", ".", "y", "*", "r", ".", "z", ";", "zz", "+=", "r", ".", "z", "*", "r", ".", "z", ";", "}", "var", "xDeterminant", "=", "yy", "*", "zz", "-", "yz", "*", "yz", ",", "yDeterminant", "=", "xx", "*", "zz", "-", "xz", "*", "xz", ",", "zDeterminant", "=", "xx", "*", "yy", "-", "xy", "*", "xy", ",", "maxDeterminant", "=", "Math", ".", "max", "(", "xDeterminant", ",", "yDeterminant", ",", "zDeterminant", ")", ";", "if", "(", "maxDeterminant", "<=", "0", ")", "throw", "new", "Error", "(", "\"The points don't span a plane\"", ")", ";", "if", "(", "maxDeterminant", "===", "xDeterminant", ")", "{", "r", ".", "set", "(", "1", ",", "(", "xz", "*", "yz", "-", "xy", "*", "zz", ")", "/", "xDeterminant", ",", "(", "xy", "*", "yz", "-", "xz", "*", "yy", ")", "/", "xDeterminant", ")", ";", "}", "else", "if", "(", "maxDeterminant", "===", "yDeterminant", ")", "{", "r", ".", "set", "(", "(", "yz", "*", "xz", "-", "xy", "*", "zz", ")", "/", "yDeterminant", ",", "1", ",", "(", "xy", "*", "xz", "-", "yz", "*", "xx", ")", "/", "yDeterminant", ")", ";", "}", "else", "if", "(", "maxDeterminant", "===", "zDeterminant", ")", "{", "r", ".", "set", "(", "(", "yz", "*", "xy", "-", "xz", "*", "yy", ")", "/", "zDeterminant", ",", "(", "xz", "*", "xy", "-", "yz", "*", "xx", ")", "/", "zDeterminant", ",", "1", ")", ";", "}", "return", "r", ".", "normalize", "(", ")", ";", "}" ]
Gets the normal vector of the fitted plane of a 3D array of points. @param {THREE.Vector3[]} points A 3D array of vertices to which to fit a plane. @param {THREE.Vector3} centroid The centroid of the vertex cloud. @return {THREE.Vector3} The normal vector of the fitted plane.
[ "Gets", "the", "normal", "vector", "of", "the", "fitted", "plane", "of", "a", "3D", "array", "of", "points", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/analysis.js#L271-L320
15,886
IceCreamYou/THREE.Terrain
src/analysis.js
bucketNumbersLinearly
function bucketNumbersLinearly(data, bucketCount, min, max) { var i = 0, l = data.length; // If min and max aren't given, set them to the highest and lowest data values if (typeof min === 'undefined') { min = Infinity; max = -Infinity; for (i = 0; i < l; i++) { if (data[i] < min) min = data[i]; if (data[i] > max) max = data[i]; } } var inc = (max - min) / bucketCount, buckets = new Array(bucketCount); // Initialize buckets for (i = 0; i < bucketCount; i++) { buckets[i] = []; } // Put the numbers into buckets for (i = 0; i < l; i++) { // Buckets include the lower bound but not the higher bound, except the top bucket try { if (data[i] === max) buckets[bucketCount-1].push(data[i]); else buckets[((data[i] - min) / inc) | 0].push(data[i]); } catch(e) { console.warn('Numbers in the data are outside of the min and max values used to bucket the data.'); } } return buckets; }
javascript
function bucketNumbersLinearly(data, bucketCount, min, max) { var i = 0, l = data.length; // If min and max aren't given, set them to the highest and lowest data values if (typeof min === 'undefined') { min = Infinity; max = -Infinity; for (i = 0; i < l; i++) { if (data[i] < min) min = data[i]; if (data[i] > max) max = data[i]; } } var inc = (max - min) / bucketCount, buckets = new Array(bucketCount); // Initialize buckets for (i = 0; i < bucketCount; i++) { buckets[i] = []; } // Put the numbers into buckets for (i = 0; i < l; i++) { // Buckets include the lower bound but not the higher bound, except the top bucket try { if (data[i] === max) buckets[bucketCount-1].push(data[i]); else buckets[((data[i] - min) / inc) | 0].push(data[i]); } catch(e) { console.warn('Numbers in the data are outside of the min and max values used to bucket the data.'); } } return buckets; }
[ "function", "bucketNumbersLinearly", "(", "data", ",", "bucketCount", ",", "min", ",", "max", ")", "{", "var", "i", "=", "0", ",", "l", "=", "data", ".", "length", ";", "// If min and max aren't given, set them to the highest and lowest data values", "if", "(", "typeof", "min", "===", "'undefined'", ")", "{", "min", "=", "Infinity", ";", "max", "=", "-", "Infinity", ";", "for", "(", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "data", "[", "i", "]", "<", "min", ")", "min", "=", "data", "[", "i", "]", ";", "if", "(", "data", "[", "i", "]", ">", "max", ")", "max", "=", "data", "[", "i", "]", ";", "}", "}", "var", "inc", "=", "(", "max", "-", "min", ")", "/", "bucketCount", ",", "buckets", "=", "new", "Array", "(", "bucketCount", ")", ";", "// Initialize buckets", "for", "(", "i", "=", "0", ";", "i", "<", "bucketCount", ";", "i", "++", ")", "{", "buckets", "[", "i", "]", "=", "[", "]", ";", "}", "// Put the numbers into buckets", "for", "(", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "// Buckets include the lower bound but not the higher bound, except the top bucket", "try", "{", "if", "(", "data", "[", "i", "]", "===", "max", ")", "buckets", "[", "bucketCount", "-", "1", "]", ".", "push", "(", "data", "[", "i", "]", ")", ";", "else", "buckets", "[", "(", "(", "data", "[", "i", "]", "-", "min", ")", "/", "inc", ")", "|", "0", "]", ".", "push", "(", "data", "[", "i", "]", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "warn", "(", "'Numbers in the data are outside of the min and max values used to bucket the data.'", ")", ";", "}", "}", "return", "buckets", ";", "}" ]
Put numbers into buckets that have equal-size ranges. @param {Number[]} data The data to bucket. @param {Number} bucketCount The number of buckets to use. @param {Number} [min] The minimum allowed data value. Defaults to the smallest value passed. @param {Number} [max] The maximum allowed data value. Defaults to the largest value passed. @return {Number[][]} An array of buckets of numbers.
[ "Put", "numbers", "into", "buckets", "that", "have", "equal", "-", "size", "ranges", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/analysis.js#L336-L365
15,887
IceCreamYou/THREE.Terrain
src/analysis.js
percentVariationExplainedByFittedPlane
function percentVariationExplainedByFittedPlane(vertices, centroid, normal, range) { var numVertices = vertices.length, diff = 0; for (var i = 0; i < numVertices; i++) { var fittedZ = Math.sqrt( (vertices[i].x - centroid.x) * (vertices[i].x - centroid.x) + (vertices[i].y - centroid.y) * (vertices[i].y - centroid.y) ) * Math.tan(normal.z * Math.PI) + centroid.z; diff += (vertices[i].z - fittedZ) * (vertices[i].z - fittedZ); } return 1 - Math.sqrt(diff / numVertices) * 2 / range; }
javascript
function percentVariationExplainedByFittedPlane(vertices, centroid, normal, range) { var numVertices = vertices.length, diff = 0; for (var i = 0; i < numVertices; i++) { var fittedZ = Math.sqrt( (vertices[i].x - centroid.x) * (vertices[i].x - centroid.x) + (vertices[i].y - centroid.y) * (vertices[i].y - centroid.y) ) * Math.tan(normal.z * Math.PI) + centroid.z; diff += (vertices[i].z - fittedZ) * (vertices[i].z - fittedZ); } return 1 - Math.sqrt(diff / numVertices) * 2 / range; }
[ "function", "percentVariationExplainedByFittedPlane", "(", "vertices", ",", "centroid", ",", "normal", ",", "range", ")", "{", "var", "numVertices", "=", "vertices", ".", "length", ",", "diff", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "numVertices", ";", "i", "++", ")", "{", "var", "fittedZ", "=", "Math", ".", "sqrt", "(", "(", "vertices", "[", "i", "]", ".", "x", "-", "centroid", ".", "x", ")", "*", "(", "vertices", "[", "i", "]", ".", "x", "-", "centroid", ".", "x", ")", "+", "(", "vertices", "[", "i", "]", ".", "y", "-", "centroid", ".", "y", ")", "*", "(", "vertices", "[", "i", "]", ".", "y", "-", "centroid", ".", "y", ")", ")", "*", "Math", ".", "tan", "(", "normal", ".", "z", "*", "Math", ".", "PI", ")", "+", "centroid", ".", "z", ";", "diff", "+=", "(", "vertices", "[", "i", "]", ".", "z", "-", "fittedZ", ")", "*", "(", "vertices", "[", "i", "]", ".", "z", "-", "fittedZ", ")", ";", "}", "return", "1", "-", "Math", ".", "sqrt", "(", "diff", "/", "numVertices", ")", "*", "2", "/", "range", ";", "}" ]
A measure of correlation between a terrain and its fitted plane. This uses a different approach than the common one (R^2, aka Pearson's correlation coefficient) because the range is constricted and the data is often non-normal. The approach taken here compares the differences between the terrain elevations and the fitted plane at each vertex, and divides by half the range to arrive at a dimensionless value. @param {THREE.Vector3[]} vertices The terrain vertices. @param {THREE.Vector3} centroid The fitted plane centroid. @param {THREE.Vector3} normal The fitted plane normal. @param {Number} range The allowed range in elevations. @return {Number} Returns a number between 0 and 1 indicating how well the fitted plane explains the variation in terrain elevation. 1 means entirely explained; 0 means not explained at all.
[ "A", "measure", "of", "correlation", "between", "a", "terrain", "and", "its", "fitted", "plane", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/analysis.js#L518-L529
15,888
IceCreamYou/THREE.Terrain
src/gaussian.js
convolve
function convolve(src, kernel, tgt) { // src and kernel must be nonzero rectangular number arrays. if (!src.length || !kernel.length) return src; // Initialize tracking variables. var i = 0, // current src x-position j = 0, // current src y-position a = 0, // current kernel x-position b = 0, // current kernel y-position w = src.length, // src width l = src[0].length, // src length m = kernel.length, // kernel width n = kernel[0].length; // kernel length // If a target isn't passed, initialize it to an array the same size as src. if (typeof tgt === 'undefined') { tgt = new Array(w); for (i = 0; i < w; i++) { tgt[i] = new Float64Array(l); } } // The kernel is a rectangle smaller than the source. Hold it over the // source so that its top-left value sits over the target position. Then, // for each value in the kernel, multiply it by the value in the source // that it is sitting on top of. The target value at that position is the // sum of those products. // For each position in the source: for (i = 0; i < w; i++) { for (j = 0; j < l; j++) { var last = 0; tgt[i][j] = 0; // For each position in the kernel: for (a = 0; a < m; a++) { for (b = 0; b < n; b++) { // If we're along the right or bottom edges of the source, // parts of the kernel will fall outside of the source. In // that case, pretend the source value is the last valid // value we got from the source. This gives reasonable // results. The alternative is to drop the edges and end up // with a target smaller than the source. That is // unreasonable for some applications, so we let the caller // make that choice. if (typeof src[i+a] !== 'undefined' && typeof src[i+a][j+b] !== 'undefined') { last = src[i+a][j+b]; } // Multiply the source and the kernel at this position. // The value at the target position is the sum of these // products. tgt[i][j] += last * kernel[a][b]; } } } } return tgt; }
javascript
function convolve(src, kernel, tgt) { // src and kernel must be nonzero rectangular number arrays. if (!src.length || !kernel.length) return src; // Initialize tracking variables. var i = 0, // current src x-position j = 0, // current src y-position a = 0, // current kernel x-position b = 0, // current kernel y-position w = src.length, // src width l = src[0].length, // src length m = kernel.length, // kernel width n = kernel[0].length; // kernel length // If a target isn't passed, initialize it to an array the same size as src. if (typeof tgt === 'undefined') { tgt = new Array(w); for (i = 0; i < w; i++) { tgt[i] = new Float64Array(l); } } // The kernel is a rectangle smaller than the source. Hold it over the // source so that its top-left value sits over the target position. Then, // for each value in the kernel, multiply it by the value in the source // that it is sitting on top of. The target value at that position is the // sum of those products. // For each position in the source: for (i = 0; i < w; i++) { for (j = 0; j < l; j++) { var last = 0; tgt[i][j] = 0; // For each position in the kernel: for (a = 0; a < m; a++) { for (b = 0; b < n; b++) { // If we're along the right or bottom edges of the source, // parts of the kernel will fall outside of the source. In // that case, pretend the source value is the last valid // value we got from the source. This gives reasonable // results. The alternative is to drop the edges and end up // with a target smaller than the source. That is // unreasonable for some applications, so we let the caller // make that choice. if (typeof src[i+a] !== 'undefined' && typeof src[i+a][j+b] !== 'undefined') { last = src[i+a][j+b]; } // Multiply the source and the kernel at this position. // The value at the target position is the sum of these // products. tgt[i][j] += last * kernel[a][b]; } } } } return tgt; }
[ "function", "convolve", "(", "src", ",", "kernel", ",", "tgt", ")", "{", "// src and kernel must be nonzero rectangular number arrays.", "if", "(", "!", "src", ".", "length", "||", "!", "kernel", ".", "length", ")", "return", "src", ";", "// Initialize tracking variables.", "var", "i", "=", "0", ",", "// current src x-position", "j", "=", "0", ",", "// current src y-position", "a", "=", "0", ",", "// current kernel x-position", "b", "=", "0", ",", "// current kernel y-position", "w", "=", "src", ".", "length", ",", "// src width", "l", "=", "src", "[", "0", "]", ".", "length", ",", "// src length", "m", "=", "kernel", ".", "length", ",", "// kernel width", "n", "=", "kernel", "[", "0", "]", ".", "length", ";", "// kernel length", "// If a target isn't passed, initialize it to an array the same size as src.", "if", "(", "typeof", "tgt", "===", "'undefined'", ")", "{", "tgt", "=", "new", "Array", "(", "w", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "w", ";", "i", "++", ")", "{", "tgt", "[", "i", "]", "=", "new", "Float64Array", "(", "l", ")", ";", "}", "}", "// The kernel is a rectangle smaller than the source. Hold it over the", "// source so that its top-left value sits over the target position. Then,", "// for each value in the kernel, multiply it by the value in the source", "// that it is sitting on top of. The target value at that position is the", "// sum of those products.", "// For each position in the source:", "for", "(", "i", "=", "0", ";", "i", "<", "w", ";", "i", "++", ")", "{", "for", "(", "j", "=", "0", ";", "j", "<", "l", ";", "j", "++", ")", "{", "var", "last", "=", "0", ";", "tgt", "[", "i", "]", "[", "j", "]", "=", "0", ";", "// For each position in the kernel:", "for", "(", "a", "=", "0", ";", "a", "<", "m", ";", "a", "++", ")", "{", "for", "(", "b", "=", "0", ";", "b", "<", "n", ";", "b", "++", ")", "{", "// If we're along the right or bottom edges of the source,", "// parts of the kernel will fall outside of the source. In", "// that case, pretend the source value is the last valid", "// value we got from the source. This gives reasonable", "// results. The alternative is to drop the edges and end up", "// with a target smaller than the source. That is", "// unreasonable for some applications, so we let the caller", "// make that choice.", "if", "(", "typeof", "src", "[", "i", "+", "a", "]", "!==", "'undefined'", "&&", "typeof", "src", "[", "i", "+", "a", "]", "[", "j", "+", "b", "]", "!==", "'undefined'", ")", "{", "last", "=", "src", "[", "i", "+", "a", "]", "[", "j", "+", "b", "]", ";", "}", "// Multiply the source and the kernel at this position.", "// The value at the target position is the sum of these", "// products.", "tgt", "[", "i", "]", "[", "j", "]", "+=", "last", "*", "kernel", "[", "a", "]", "[", "b", "]", ";", "}", "}", "}", "}", "return", "tgt", ";", "}" ]
Convolve an array with a kernel. @param {Number[][]} src The source array to convolve. A nonzero-sized rectangular array of numbers. @param {Number[][]} kernel The kernel array with which to convolve `src`. A nonzero-sized rectangular array of numbers smaller than `src`. @param {Number[][]} [tgt] The target array into which the result of the convolution should be put. If not passed, a new array will be created. This is also the array that this function returns. It must be at least as large as `src`. @return {Number[][]} An array containing the result of the convolution.
[ "Convolve", "an", "array", "with", "a", "kernel", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/gaussian.js#L19-L72
15,889
IceCreamYou/THREE.Terrain
src/gaussian.js
gauss
function gauss(x, s) { // 2.5066282746310005 is sqrt(2*pi) return Math.exp(-0.5 * x*x / (s*s)) / (s * 2.5066282746310005); }
javascript
function gauss(x, s) { // 2.5066282746310005 is sqrt(2*pi) return Math.exp(-0.5 * x*x / (s*s)) / (s * 2.5066282746310005); }
[ "function", "gauss", "(", "x", ",", "s", ")", "{", "// 2.5066282746310005 is sqrt(2*pi)", "return", "Math", ".", "exp", "(", "-", "0.5", "*", "x", "*", "x", "/", "(", "s", "*", "s", ")", ")", "/", "(", "s", "*", "2.5066282746310005", ")", ";", "}" ]
Returns the value at X of a Gaussian distribution with standard deviation S.
[ "Returns", "the", "value", "at", "X", "of", "a", "Gaussian", "distribution", "with", "standard", "deviation", "S", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/gaussian.js#L77-L80
15,890
IceCreamYou/THREE.Terrain
src/gaussian.js
gaussianKernel1D
function gaussianKernel1D(s, n) { if (typeof n !== 'number') n = 7; var kernel = new Float64Array(n), halfN = Math.floor(n * 0.5), odd = n % 2, i; if (!s || !n) return kernel; for (i = 0; i <= halfN; i++) { kernel[i] = gauss(s * (i - halfN - odd * 0.5), s); } for (; i < n; i++) { kernel[i] = kernel[n - 1 - i]; } return kernel; }
javascript
function gaussianKernel1D(s, n) { if (typeof n !== 'number') n = 7; var kernel = new Float64Array(n), halfN = Math.floor(n * 0.5), odd = n % 2, i; if (!s || !n) return kernel; for (i = 0; i <= halfN; i++) { kernel[i] = gauss(s * (i - halfN - odd * 0.5), s); } for (; i < n; i++) { kernel[i] = kernel[n - 1 - i]; } return kernel; }
[ "function", "gaussianKernel1D", "(", "s", ",", "n", ")", "{", "if", "(", "typeof", "n", "!==", "'number'", ")", "n", "=", "7", ";", "var", "kernel", "=", "new", "Float64Array", "(", "n", ")", ",", "halfN", "=", "Math", ".", "floor", "(", "n", "*", "0.5", ")", ",", "odd", "=", "n", "%", "2", ",", "i", ";", "if", "(", "!", "s", "||", "!", "n", ")", "return", "kernel", ";", "for", "(", "i", "=", "0", ";", "i", "<=", "halfN", ";", "i", "++", ")", "{", "kernel", "[", "i", "]", "=", "gauss", "(", "s", "*", "(", "i", "-", "halfN", "-", "odd", "*", "0.5", ")", ",", "s", ")", ";", "}", "for", "(", ";", "i", "<", "n", ";", "i", "++", ")", "{", "kernel", "[", "i", "]", "=", "kernel", "[", "n", "-", "1", "-", "i", "]", ";", "}", "return", "kernel", ";", "}" ]
Generate a Gaussian kernel. Returns a kernel of size N approximating a 1D Gaussian distribution with standard deviation S.
[ "Generate", "a", "Gaussian", "kernel", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/gaussian.js#L88-L102
15,891
IceCreamYou/THREE.Terrain
src/gaussian.js
gaussian
function gaussian(src, s, kernelSize) { if (typeof s === 'undefined') s = 1; if (typeof kernelSize === 'undefined') kernelSize = 7; var kernel = gaussianKernel1D(s, kernelSize), l = kernelSize || kernel.length, kernelH = [kernel], kernelV = new Array(l); for (var i = 0; i < l; i++) { kernelV[i] = [kernel[i]]; } return convolve(convolve(src, kernelH), kernelV); }
javascript
function gaussian(src, s, kernelSize) { if (typeof s === 'undefined') s = 1; if (typeof kernelSize === 'undefined') kernelSize = 7; var kernel = gaussianKernel1D(s, kernelSize), l = kernelSize || kernel.length, kernelH = [kernel], kernelV = new Array(l); for (var i = 0; i < l; i++) { kernelV[i] = [kernel[i]]; } return convolve(convolve(src, kernelH), kernelV); }
[ "function", "gaussian", "(", "src", ",", "s", ",", "kernelSize", ")", "{", "if", "(", "typeof", "s", "===", "'undefined'", ")", "s", "=", "1", ";", "if", "(", "typeof", "kernelSize", "===", "'undefined'", ")", "kernelSize", "=", "7", ";", "var", "kernel", "=", "gaussianKernel1D", "(", "s", ",", "kernelSize", ")", ",", "l", "=", "kernelSize", "||", "kernel", ".", "length", ",", "kernelH", "=", "[", "kernel", "]", ",", "kernelV", "=", "new", "Array", "(", "l", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "kernelV", "[", "i", "]", "=", "[", "kernel", "[", "i", "]", "]", ";", "}", "return", "convolve", "(", "convolve", "(", "src", ",", "kernelH", ")", ",", "kernelV", ")", ";", "}" ]
Perform Gaussian smoothing. @param {Number[][]} src The source array to convolve. A nonzero-sized rectangular array of numbers. @param {Number} [s=1] The standard deviation of the Gaussian kernel to use. Higher values result in smoothing across more cells of the src matrix. @param {Number} [kernelSize=7] The size of the Gaussian kernel to use. Larger kernels result in slower but more accurate smoothing. @return {Number[][]} An array containing the result of smoothing the src.
[ "Perform", "Gaussian", "smoothing", "." ]
1896bd23eb3e0372096d75fa3e46d96eb1a56317
https://github.com/IceCreamYou/THREE.Terrain/blob/1896bd23eb3e0372096d75fa3e46d96eb1a56317/src/gaussian.js#L119-L130
15,892
sympmarc/SPServices
src/core/SPServices.utils.js
function(SOAPEnvelope, siteDataOperation) { var siteDataOp = siteDataOperation.substring(8); SOAPEnvelope.opheader = SOAPEnvelope.opheader.replace(siteDataOperation, siteDataOp); SOAPEnvelope.opfooter = SOAPEnvelope.opfooter.replace(siteDataOperation, siteDataOp); return SOAPEnvelope; }
javascript
function(SOAPEnvelope, siteDataOperation) { var siteDataOp = siteDataOperation.substring(8); SOAPEnvelope.opheader = SOAPEnvelope.opheader.replace(siteDataOperation, siteDataOp); SOAPEnvelope.opfooter = SOAPEnvelope.opfooter.replace(siteDataOperation, siteDataOp); return SOAPEnvelope; }
[ "function", "(", "SOAPEnvelope", ",", "siteDataOperation", ")", "{", "var", "siteDataOp", "=", "siteDataOperation", ".", "substring", "(", "8", ")", ";", "SOAPEnvelope", ".", "opheader", "=", "SOAPEnvelope", ".", "opheader", ".", "replace", "(", "siteDataOperation", ",", "siteDataOp", ")", ";", "SOAPEnvelope", ".", "opfooter", "=", "SOAPEnvelope", ".", "opfooter", ".", "replace", "(", "siteDataOperation", ",", "siteDataOp", ")", ";", "return", "SOAPEnvelope", ";", "}" ]
The SiteData operations have the same names as other Web Service operations. To make them easy to call and unique, I'm using the SiteData prefix on their names. This function replaces that name with the right name in the SPServices.SOAPEnvelope.
[ "The", "SiteData", "operations", "have", "the", "same", "names", "as", "other", "Web", "Service", "operations", ".", "To", "make", "them", "easy", "to", "call", "and", "unique", "I", "m", "using", "the", "SiteData", "prefix", "on", "their", "names", ".", "This", "function", "replaces", "that", "name", "with", "the", "right", "name", "in", "the", "SPServices", ".", "SOAPEnvelope", "." ]
7ff0d24658d1d354a937bc82ab21cb6352025ea3
https://github.com/sympmarc/SPServices/blob/7ff0d24658d1d354a937bc82ab21cb6352025ea3/src/core/SPServices.utils.js#L240-L245
15,893
sympmarc/SPServices
dist/jquery.SPServices.js
getScriptAttribute
function getScriptAttribute(source, attribute) { var matches; var regex = RegExp(attribute + "=(\"([^\"]*)\")|('([^']*)')", "gi"); if (matches = regex.exec(source)) { return matches[2]; } return null; }
javascript
function getScriptAttribute(source, attribute) { var matches; var regex = RegExp(attribute + "=(\"([^\"]*)\")|('([^']*)')", "gi"); if (matches = regex.exec(source)) { return matches[2]; } return null; }
[ "function", "getScriptAttribute", "(", "source", ",", "attribute", ")", "{", "var", "matches", ";", "var", "regex", "=", "RegExp", "(", "attribute", "+", "\"=(\\\"([^\\\"]*)\\\")|('([^']*)')\"", ",", "\"gi\"", ")", ";", "if", "(", "matches", "=", "regex", ".", "exec", "(", "source", ")", ")", "{", "return", "matches", "[", "2", "]", ";", "}", "return", "null", ";", "}" ]
End of function SPScriptAuditPage
[ "End", "of", "function", "SPScriptAuditPage" ]
7ff0d24658d1d354a937bc82ab21cb6352025ea3
https://github.com/sympmarc/SPServices/blob/7ff0d24658d1d354a937bc82ab21cb6352025ea3/dist/jquery.SPServices.js#L3149-L3156
15,894
sympmarc/SPServices
dist/jquery.SPServices.js
showAttrs
function showAttrs(node) { var i; var out = "<table class='ms-vb' width='100%'>"; for (i = 0; i < node.attributes.length; i++) { out += "<tr><td width='10px' style='font-weight:bold;'>" + i + "</td><td width='100px'>" + node.attributes.item(i).nodeName + "</td><td>" + checkLink(node.attributes.item(i).nodeValue) + "</td></tr>"; } out += "</table>"; return out; }
javascript
function showAttrs(node) { var i; var out = "<table class='ms-vb' width='100%'>"; for (i = 0; i < node.attributes.length; i++) { out += "<tr><td width='10px' style='font-weight:bold;'>" + i + "</td><td width='100px'>" + node.attributes.item(i).nodeName + "</td><td>" + checkLink(node.attributes.item(i).nodeValue) + "</td></tr>"; } out += "</table>"; return out; }
[ "function", "showAttrs", "(", "node", ")", "{", "var", "i", ";", "var", "out", "=", "\"<table class='ms-vb' width='100%'>\"", ";", "for", "(", "i", "=", "0", ";", "i", "<", "node", ".", "attributes", ".", "length", ";", "i", "++", ")", "{", "out", "+=", "\"<tr><td width='10px' style='font-weight:bold;'>\"", "+", "i", "+", "\"</td><td width='100px'>\"", "+", "node", ".", "attributes", ".", "item", "(", "i", ")", ".", "nodeName", "+", "\"</td><td>\"", "+", "checkLink", "(", "node", ".", "attributes", ".", "item", "(", "i", ")", ".", "nodeValue", ")", "+", "\"</td></tr>\"", ";", "}", "out", "+=", "\"</table>\"", ";", "return", "out", ";", "}" ]
Show a single attribute of a node, enclosed in a table node The XML node opt The current set of options
[ "Show", "a", "single", "attribute", "of", "a", "node", "enclosed", "in", "a", "table", "node", "The", "XML", "node", "opt", "The", "current", "set", "of", "options" ]
7ff0d24658d1d354a937bc82ab21cb6352025ea3
https://github.com/sympmarc/SPServices/blob/7ff0d24658d1d354a937bc82ab21cb6352025ea3/dist/jquery.SPServices.js#L4325-L4334
15,895
sympmarc/SPServices
dist/jquery.SPServices.js
errBox
function errBox(func, param, msg) { var errMsg = "<b>Error in function</b><br/>" + func + "<br/>" + "<b>Parameter</b><br/>" + param + "<br/>" + "<b>Message</b><br/>" + msg + "<br/><br/>" + "<span onmouseover='this.style.cursor=\"hand\";' onmouseout='this.style.cursor=\"inherit\";' style='width=100%;text-align:right;'>Click to continue</span></div>"; modalBox(errMsg); }
javascript
function errBox(func, param, msg) { var errMsg = "<b>Error in function</b><br/>" + func + "<br/>" + "<b>Parameter</b><br/>" + param + "<br/>" + "<b>Message</b><br/>" + msg + "<br/><br/>" + "<span onmouseover='this.style.cursor=\"hand\";' onmouseout='this.style.cursor=\"inherit\";' style='width=100%;text-align:right;'>Click to continue</span></div>"; modalBox(errMsg); }
[ "function", "errBox", "(", "func", ",", "param", ",", "msg", ")", "{", "var", "errMsg", "=", "\"<b>Error in function</b><br/>\"", "+", "func", "+", "\"<br/>\"", "+", "\"<b>Parameter</b><br/>\"", "+", "param", "+", "\"<br/>\"", "+", "\"<b>Message</b><br/>\"", "+", "msg", "+", "\"<br/><br/>\"", "+", "\"<span onmouseover='this.style.cursor=\\\"hand\\\";' onmouseout='this.style.cursor=\\\"inherit\\\";' style='width=100%;text-align:right;'>Click to continue</span></div>\"", ";", "modalBox", "(", "errMsg", ")", ";", "}" ]
End of function getDropdownSelected Build an error message based on passed parameters
[ "End", "of", "function", "getDropdownSelected", "Build", "an", "error", "message", "based", "on", "passed", "parameters" ]
7ff0d24658d1d354a937bc82ab21cb6352025ea3
https://github.com/sympmarc/SPServices/blob/7ff0d24658d1d354a937bc82ab21cb6352025ea3/dist/jquery.SPServices.js#L4374-L4380
15,896
sympmarc/SPServices
dist/jquery.SPServices.js
modalBox
function modalBox(msg) { var boxCSS = "position:absolute;width:300px;height:150px;padding:10px;background-color:#000000;color:#ffffff;z-index:30;font-family:'Arial';font-size:12px;display:none;"; $("#aspnetForm").parent().append("<div id='SPServices_msgBox' style=" + boxCSS + ">" + msg); var msgBoxObj = $("#SPServices_msgBox"); var height = msgBoxObj.height(); var width = msgBoxObj.width(); var leftVal = ($(window).width() / 2) - (width / 2) + "px"; var topVal = ($(window).height() / 2) - (height / 2) - 100 + "px"; msgBoxObj.css({ border: '5px #C02000 solid', left: leftVal, top: topVal }).show().fadeTo("slow", 0.75).click(function () { $(this).fadeOut("3000", function () { $(this).remove(); }); }); }
javascript
function modalBox(msg) { var boxCSS = "position:absolute;width:300px;height:150px;padding:10px;background-color:#000000;color:#ffffff;z-index:30;font-family:'Arial';font-size:12px;display:none;"; $("#aspnetForm").parent().append("<div id='SPServices_msgBox' style=" + boxCSS + ">" + msg); var msgBoxObj = $("#SPServices_msgBox"); var height = msgBoxObj.height(); var width = msgBoxObj.width(); var leftVal = ($(window).width() / 2) - (width / 2) + "px"; var topVal = ($(window).height() / 2) - (height / 2) - 100 + "px"; msgBoxObj.css({ border: '5px #C02000 solid', left: leftVal, top: topVal }).show().fadeTo("slow", 0.75).click(function () { $(this).fadeOut("3000", function () { $(this).remove(); }); }); }
[ "function", "modalBox", "(", "msg", ")", "{", "var", "boxCSS", "=", "\"position:absolute;width:300px;height:150px;padding:10px;background-color:#000000;color:#ffffff;z-index:30;font-family:'Arial';font-size:12px;display:none;\"", ";", "$", "(", "\"#aspnetForm\"", ")", ".", "parent", "(", ")", ".", "append", "(", "\"<div id='SPServices_msgBox' style=\"", "+", "boxCSS", "+", "\">\"", "+", "msg", ")", ";", "var", "msgBoxObj", "=", "$", "(", "\"#SPServices_msgBox\"", ")", ";", "var", "height", "=", "msgBoxObj", ".", "height", "(", ")", ";", "var", "width", "=", "msgBoxObj", ".", "width", "(", ")", ";", "var", "leftVal", "=", "(", "$", "(", "window", ")", ".", "width", "(", ")", "/", "2", ")", "-", "(", "width", "/", "2", ")", "+", "\"px\"", ";", "var", "topVal", "=", "(", "$", "(", "window", ")", ".", "height", "(", ")", "/", "2", ")", "-", "(", "height", "/", "2", ")", "-", "100", "+", "\"px\"", ";", "msgBoxObj", ".", "css", "(", "{", "border", ":", "'5px #C02000 solid'", ",", "left", ":", "leftVal", ",", "top", ":", "topVal", "}", ")", ".", "show", "(", ")", ".", "fadeTo", "(", "\"slow\"", ",", "0.75", ")", ".", "click", "(", "function", "(", ")", "{", "$", "(", "this", ")", ".", "fadeOut", "(", "\"3000\"", ",", "function", "(", ")", "{", "$", "(", "this", ")", ".", "remove", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
End of function errBox Call this function to pop up a branded modal msgBox
[ "End", "of", "function", "errBox", "Call", "this", "function", "to", "pop", "up", "a", "branded", "modal", "msgBox" ]
7ff0d24658d1d354a937bc82ab21cb6352025ea3
https://github.com/sympmarc/SPServices/blob/7ff0d24658d1d354a937bc82ab21cb6352025ea3/dist/jquery.SPServices.js#L4383-L4400
15,897
sympmarc/SPServices
dist/jquery.SPServices.js
genContainerId
function genContainerId(funcname, columnName, listName) { var l = listName !== undefined ? listName : $().SPServices.SPListNameFromUrl(); return funcname + "_" + $().SPServices.SPGetStaticFromDisplay({ listName: l, columnDisplayName: columnName }); }
javascript
function genContainerId(funcname, columnName, listName) { var l = listName !== undefined ? listName : $().SPServices.SPListNameFromUrl(); return funcname + "_" + $().SPServices.SPGetStaticFromDisplay({ listName: l, columnDisplayName: columnName }); }
[ "function", "genContainerId", "(", "funcname", ",", "columnName", ",", "listName", ")", "{", "var", "l", "=", "listName", "!==", "undefined", "?", "listName", ":", "$", "(", ")", ".", "SPServices", ".", "SPListNameFromUrl", "(", ")", ";", "return", "funcname", "+", "\"_\"", "+", "$", "(", ")", ".", "SPServices", ".", "SPGetStaticFromDisplay", "(", "{", "listName", ":", "l", ",", "columnDisplayName", ":", "columnName", "}", ")", ";", "}" ]
End of function modalBox Generate a unique id for a containing div using the function name and the column display name
[ "End", "of", "function", "modalBox", "Generate", "a", "unique", "id", "for", "a", "containing", "div", "using", "the", "function", "name", "and", "the", "column", "display", "name" ]
7ff0d24658d1d354a937bc82ab21cb6352025ea3
https://github.com/sympmarc/SPServices/blob/7ff0d24658d1d354a937bc82ab21cb6352025ea3/dist/jquery.SPServices.js#L4403-L4409
15,898
sympmarc/SPServices
dist/jquery.SPServices.js
getListFormUrl
function getListFormUrl(l, f) { var u; $().SPServices({ operation: "GetFormCollection", async: false, listName: l, completefunc: function (xData) { u = $(xData.responseXML).find("Form[Type='" + f + "']").attr("Url"); } }); return u; }
javascript
function getListFormUrl(l, f) { var u; $().SPServices({ operation: "GetFormCollection", async: false, listName: l, completefunc: function (xData) { u = $(xData.responseXML).find("Form[Type='" + f + "']").attr("Url"); } }); return u; }
[ "function", "getListFormUrl", "(", "l", ",", "f", ")", "{", "var", "u", ";", "$", "(", ")", ".", "SPServices", "(", "{", "operation", ":", "\"GetFormCollection\"", ",", "async", ":", "false", ",", "listName", ":", "l", ",", "completefunc", ":", "function", "(", "xData", ")", "{", "u", "=", "$", "(", "xData", ".", "responseXML", ")", ".", "find", "(", "\"Form[Type='\"", "+", "f", "+", "\"']\"", ")", ".", "attr", "(", "\"Url\"", ")", ";", "}", "}", ")", ";", "return", "u", ";", "}" ]
End of function genContainerId Get the URL for a specified form for a list
[ "End", "of", "function", "genContainerId", "Get", "the", "URL", "for", "a", "specified", "form", "for", "a", "list" ]
7ff0d24658d1d354a937bc82ab21cb6352025ea3
https://github.com/sympmarc/SPServices/blob/7ff0d24658d1d354a937bc82ab21cb6352025ea3/dist/jquery.SPServices.js#L4412-L4425
15,899
sympmarc/SPServices
dist/jquery.SPServices.js
checkLink
function checkLink(s) { return ((s.indexOf("http") === 0) || (s.indexOf(SLASH) === 0)) ? "<a href='" + s + "'>" + s + "</a>" : s; }
javascript
function checkLink(s) { return ((s.indexOf("http") === 0) || (s.indexOf(SLASH) === 0)) ? "<a href='" + s + "'>" + s + "</a>" : s; }
[ "function", "checkLink", "(", "s", ")", "{", "return", "(", "(", "s", ".", "indexOf", "(", "\"http\"", ")", "===", "0", ")", "||", "(", "s", ".", "indexOf", "(", "SLASH", ")", "===", "0", ")", ")", "?", "\"<a href='\"", "+", "s", "+", "\"'>\"", "+", "s", "+", "\"</a>\"", ":", "s", ";", "}" ]
If a string is a URL, format it as a link, else return the string as-is
[ "If", "a", "string", "is", "a", "URL", "format", "it", "as", "a", "link", "else", "return", "the", "string", "as", "-", "is" ]
7ff0d24658d1d354a937bc82ab21cb6352025ea3
https://github.com/sympmarc/SPServices/blob/7ff0d24658d1d354a937bc82ab21cb6352025ea3/dist/jquery.SPServices.js#L4497-L4499