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
partition
stringclasses
1 value
anicollection/anicollection
config/grunt/tasks/generate_db.js
createAnimationObject
function createAnimationObject(categoryName, fileName){ var animation, inputFilepath = config.src + categoryName + '/' + fileName + '.css', inputPlainFilepath = config.unprefixedSrc + categoryName + '/' + fileName + '.css', outpuFilepath = config.dest + categoryName + '/' + 'db_'+ fileName + '.json', currentFileSource, currentFilePlainSource, metadataObject; // read the file currentFileSource = grunt.file.read(inputFilepath); currentFilePlainSource = grunt.file.read(inputPlainFilepath); // extract relevant data animation = parseString(currentFileSource); // TODO: quitar los comentarios antes de guardarlo if(animation.length > 0){ animation = animation[0]; animation.cssCode = new CleanCSS({ noAdvanced:false, aggressiveMerging:false, keepBreaks:true }).minify(currentFileSource); animation.plainCssCode = new CleanCSS({ noAdvanced:false, aggressiveMerging:false, keepBreaks:true }).minify(currentFilePlainSource); animation.cssCode = beautify_css(animation.cssCode, { indent_size: 2 }); animation.plainCssCode = beautify_css(animation.plainCssCode, { indent_size: 2 }); } // write destiny grunt.file.write(outpuFilepath, JSON.stringify(animation, null, 4)); }
javascript
function createAnimationObject(categoryName, fileName){ var animation, inputFilepath = config.src + categoryName + '/' + fileName + '.css', inputPlainFilepath = config.unprefixedSrc + categoryName + '/' + fileName + '.css', outpuFilepath = config.dest + categoryName + '/' + 'db_'+ fileName + '.json', currentFileSource, currentFilePlainSource, metadataObject; // read the file currentFileSource = grunt.file.read(inputFilepath); currentFilePlainSource = grunt.file.read(inputPlainFilepath); // extract relevant data animation = parseString(currentFileSource); // TODO: quitar los comentarios antes de guardarlo if(animation.length > 0){ animation = animation[0]; animation.cssCode = new CleanCSS({ noAdvanced:false, aggressiveMerging:false, keepBreaks:true }).minify(currentFileSource); animation.plainCssCode = new CleanCSS({ noAdvanced:false, aggressiveMerging:false, keepBreaks:true }).minify(currentFilePlainSource); animation.cssCode = beautify_css(animation.cssCode, { indent_size: 2 }); animation.plainCssCode = beautify_css(animation.plainCssCode, { indent_size: 2 }); } // write destiny grunt.file.write(outpuFilepath, JSON.stringify(animation, null, 4)); }
[ "function", "createAnimationObject", "(", "categoryName", ",", "fileName", ")", "{", "var", "animation", ",", "inputFilepath", "=", "config", ".", "src", "+", "categoryName", "+", "'/'", "+", "fileName", "+", "'.css'", ",", "inputPlainFilepath", "=", "config", ".", "unprefixedSrc", "+", "categoryName", "+", "'/'", "+", "fileName", "+", "'.css'", ",", "outpuFilepath", "=", "config", ".", "dest", "+", "categoryName", "+", "'/'", "+", "'db_'", "+", "fileName", "+", "'.json'", ",", "currentFileSource", ",", "currentFilePlainSource", ",", "metadataObject", ";", "currentFileSource", "=", "grunt", ".", "file", ".", "read", "(", "inputFilepath", ")", ";", "currentFilePlainSource", "=", "grunt", ".", "file", ".", "read", "(", "inputPlainFilepath", ")", ";", "animation", "=", "parseString", "(", "currentFileSource", ")", ";", "if", "(", "animation", ".", "length", ">", "0", ")", "{", "animation", "=", "animation", "[", "0", "]", ";", "animation", ".", "cssCode", "=", "new", "CleanCSS", "(", "{", "noAdvanced", ":", "false", ",", "aggressiveMerging", ":", "false", ",", "keepBreaks", ":", "true", "}", ")", ".", "minify", "(", "currentFileSource", ")", ";", "animation", ".", "plainCssCode", "=", "new", "CleanCSS", "(", "{", "noAdvanced", ":", "false", ",", "aggressiveMerging", ":", "false", ",", "keepBreaks", ":", "true", "}", ")", ".", "minify", "(", "currentFilePlainSource", ")", ";", "animation", ".", "cssCode", "=", "beautify_css", "(", "animation", ".", "cssCode", ",", "{", "indent_size", ":", "2", "}", ")", ";", "animation", ".", "plainCssCode", "=", "beautify_css", "(", "animation", ".", "plainCssCode", ",", "{", "indent_size", ":", "2", "}", ")", ";", "}", "grunt", ".", "file", ".", "write", "(", "outpuFilepath", ",", "JSON", ".", "stringify", "(", "animation", ",", "null", ",", "4", ")", ")", ";", "}" ]
Create and save the animation object as json @author Dariel Noel <[email protected]> @since 2015-03-10 @param {[type]} categoryName [description] @param {[type]} fileName [description] @return {[type]} [description]
[ "Create", "and", "save", "the", "animation", "object", "as", "json" ]
f998306f29ae1d130eebcd4c64a9c9737a7613e9
https://github.com/anicollection/anicollection/blob/f998306f29ae1d130eebcd4c64a9c9737a7613e9/config/grunt/tasks/generate_db.js#L95-L131
train
micromatch/expand-brackets
index.js
brackets
function brackets(pattern, options) { const res = brackets.create(pattern, options); return res.output; }
javascript
function brackets(pattern, options) { const res = brackets.create(pattern, options); return res.output; }
[ "function", "brackets", "(", "pattern", ",", "options", ")", "{", "const", "res", "=", "brackets", ".", "create", "(", "pattern", ",", "options", ")", ";", "return", "res", ".", "output", ";", "}" ]
Parses the given POSIX character class `pattern` and returns a string that can be used for creating regular expressions for matching. @param {String} `pattern` @param {Object} `options` @return {Object} @api public
[ "Parses", "the", "given", "POSIX", "character", "class", "pattern", "and", "returns", "a", "string", "that", "can", "be", "used", "for", "creating", "regular", "expressions", "for", "matching", "." ]
60d30312976b36065e24a81abdce23b868ccf0ef
https://github.com/micromatch/expand-brackets/blob/60d30312976b36065e24a81abdce23b868ccf0ef/index.js#L27-L30
train
riot/tmpl
src/notevil/index.js
safeEval
function safeEval(src, parentContext){ var tree = prepareAst(src) var context = Object.create(parentContext || {}) return finalValue(evaluateAst(tree, context)) }
javascript
function safeEval(src, parentContext){ var tree = prepareAst(src) var context = Object.create(parentContext || {}) return finalValue(evaluateAst(tree, context)) }
[ "function", "safeEval", "(", "src", ",", "parentContext", ")", "{", "var", "tree", "=", "prepareAst", "(", "src", ")", "var", "context", "=", "Object", ".", "create", "(", "parentContext", "||", "{", "}", ")", "return", "finalValue", "(", "evaluateAst", "(", "tree", ",", "context", ")", ")", "}" ]
'eval' with a controlled environment
[ "eval", "with", "a", "controlled", "environment" ]
e01c28f094ce293c61aba90b7c9242d9b050fb49
https://github.com/riot/tmpl/blob/e01c28f094ce293c61aba90b7c9242d9b050fb49/src/notevil/index.js#L11-L15
train
riot/tmpl
src/notevil/index.js
FunctionFactory
function FunctionFactory(parentContext){ var context = Object.create(parentContext || {}) return function Function() { // normalize arguments array var args = Array.prototype.slice.call(arguments) var src = args.slice(-1)[0] args = args.slice(0,-1) if (typeof src === 'string'){ //HACK: esprima doesn't like returns outside functions src = parse('function a(){ ' + src + '}').body[0].body } var tree = prepareAst(src) return getFunction(tree, args, context) } }
javascript
function FunctionFactory(parentContext){ var context = Object.create(parentContext || {}) return function Function() { // normalize arguments array var args = Array.prototype.slice.call(arguments) var src = args.slice(-1)[0] args = args.slice(0,-1) if (typeof src === 'string'){ //HACK: esprima doesn't like returns outside functions src = parse('function a(){ ' + src + '}').body[0].body } var tree = prepareAst(src) return getFunction(tree, args, context) } }
[ "function", "FunctionFactory", "(", "parentContext", ")", "{", "var", "context", "=", "Object", ".", "create", "(", "parentContext", "||", "{", "}", ")", "return", "function", "Function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", "var", "src", "=", "args", ".", "slice", "(", "-", "1", ")", "[", "0", "]", "args", "=", "args", ".", "slice", "(", "0", ",", "-", "1", ")", "if", "(", "typeof", "src", "===", "'string'", ")", "{", "src", "=", "parse", "(", "'function a(){ '", "+", "src", "+", "'}'", ")", ".", "body", "[", "0", "]", ".", "body", "}", "var", "tree", "=", "prepareAst", "(", "src", ")", "return", "getFunction", "(", "tree", ",", "args", ",", "context", ")", "}", "}" ]
create a 'Function' constructor for a controlled environment
[ "create", "a", "Function", "constructor", "for", "a", "controlled", "environment" ]
e01c28f094ce293c61aba90b7c9242d9b050fb49
https://github.com/riot/tmpl/blob/e01c28f094ce293c61aba90b7c9242d9b050fb49/src/notevil/index.js#L20-L34
train
riot/tmpl
src/notevil/index.js
walkAll
function walkAll(nodes){ var result = undefined for (var i=0;i<nodes.length;i++){ var childNode = nodes[i] if (childNode.type === 'EmptyStatement') continue result = walk(childNode) if (result instanceof ReturnValue){ return result } } return result }
javascript
function walkAll(nodes){ var result = undefined for (var i=0;i<nodes.length;i++){ var childNode = nodes[i] if (childNode.type === 'EmptyStatement') continue result = walk(childNode) if (result instanceof ReturnValue){ return result } } return result }
[ "function", "walkAll", "(", "nodes", ")", "{", "var", "result", "=", "undefined", "for", "(", "var", "i", "=", "0", ";", "i", "<", "nodes", ".", "length", ";", "i", "++", ")", "{", "var", "childNode", "=", "nodes", "[", "i", "]", "if", "(", "childNode", ".", "type", "===", "'EmptyStatement'", ")", "continue", "result", "=", "walk", "(", "childNode", ")", "if", "(", "result", "instanceof", "ReturnValue", ")", "{", "return", "result", "}", "}", "return", "result", "}" ]
recursively walk every node in an array
[ "recursively", "walk", "every", "node", "in", "an", "array" ]
e01c28f094ce293c61aba90b7c9242d9b050fb49
https://github.com/riot/tmpl/blob/e01c28f094ce293c61aba90b7c9242d9b050fb49/src/notevil/index.js#L54-L65
train
riot/tmpl
src/notevil/index.js
setValue
function setValue(object, left, right, operator){ var name = null if (left.type === 'Identifier'){ name = left.name // handle parent context shadowing object = objectForKey(object, name, primitives) } else if (left.type === 'MemberExpression'){ if (left.computed){ name = walk(left.property) } else { name = left.property.name } object = walk(left.object) } // stop built in properties from being able to be changed if (canSetProperty(object, name, primitives)){ switch(operator) { case undefined: return object[name] = walk(right) case '=': return object[name] = walk(right) case '+=': return object[name] += walk(right) case '-=': return object[name] -= walk(right) case '++': return object[name]++ case '--': return object[name]-- } } }
javascript
function setValue(object, left, right, operator){ var name = null if (left.type === 'Identifier'){ name = left.name // handle parent context shadowing object = objectForKey(object, name, primitives) } else if (left.type === 'MemberExpression'){ if (left.computed){ name = walk(left.property) } else { name = left.property.name } object = walk(left.object) } // stop built in properties from being able to be changed if (canSetProperty(object, name, primitives)){ switch(operator) { case undefined: return object[name] = walk(right) case '=': return object[name] = walk(right) case '+=': return object[name] += walk(right) case '-=': return object[name] -= walk(right) case '++': return object[name]++ case '--': return object[name]-- } } }
[ "function", "setValue", "(", "object", ",", "left", ",", "right", ",", "operator", ")", "{", "var", "name", "=", "null", "if", "(", "left", ".", "type", "===", "'Identifier'", ")", "{", "name", "=", "left", ".", "name", "object", "=", "objectForKey", "(", "object", ",", "name", ",", "primitives", ")", "}", "else", "if", "(", "left", ".", "type", "===", "'MemberExpression'", ")", "{", "if", "(", "left", ".", "computed", ")", "{", "name", "=", "walk", "(", "left", ".", "property", ")", "}", "else", "{", "name", "=", "left", ".", "property", ".", "name", "}", "object", "=", "walk", "(", "left", ".", "object", ")", "}", "if", "(", "canSetProperty", "(", "object", ",", "name", ",", "primitives", ")", ")", "{", "switch", "(", "operator", ")", "{", "case", "undefined", ":", "return", "object", "[", "name", "]", "=", "walk", "(", "right", ")", "case", "'='", ":", "return", "object", "[", "name", "]", "=", "walk", "(", "right", ")", "case", "'+='", ":", "return", "object", "[", "name", "]", "+=", "walk", "(", "right", ")", "case", "'-='", ":", "return", "object", "[", "name", "]", "-=", "walk", "(", "right", ")", "case", "'++'", ":", "return", "object", "[", "name", "]", "++", "case", "'--'", ":", "return", "object", "[", "name", "]", "--", "}", "}", "}" ]
set a value in the specified context if allowed
[ "set", "a", "value", "in", "the", "specified", "context", "if", "allowed" ]
e01c28f094ce293c61aba90b7c9242d9b050fb49
https://github.com/riot/tmpl/blob/e01c28f094ce293c61aba90b7c9242d9b050fb49/src/notevil/index.js#L387-L415
train
riot/tmpl
src/notevil/index.js
unsupportedExpression
function unsupportedExpression(node){ console.error(node) var err = new Error('Unsupported expression: ' + node.type) err.node = node throw err }
javascript
function unsupportedExpression(node){ console.error(node) var err = new Error('Unsupported expression: ' + node.type) err.node = node throw err }
[ "function", "unsupportedExpression", "(", "node", ")", "{", "console", ".", "error", "(", "node", ")", "var", "err", "=", "new", "Error", "(", "'Unsupported expression: '", "+", "node", ".", "type", ")", "err", ".", "node", "=", "node", "throw", "err", "}" ]
when an unsupported expression is encountered, throw an error
[ "when", "an", "unsupported", "expression", "is", "encountered", "throw", "an", "error" ]
e01c28f094ce293c61aba90b7c9242d9b050fb49
https://github.com/riot/tmpl/blob/e01c28f094ce293c61aba90b7c9242d9b050fb49/src/notevil/index.js#L420-L425
train
riot/tmpl
src/notevil/index.js
objectForKey
function objectForKey(object, key, primitives){ var proto = primitives.getPrototypeOf(object) if (!proto || hasOwnProperty(object, key)){ return object } else { return objectForKey(proto, key, primitives) } }
javascript
function objectForKey(object, key, primitives){ var proto = primitives.getPrototypeOf(object) if (!proto || hasOwnProperty(object, key)){ return object } else { return objectForKey(proto, key, primitives) } }
[ "function", "objectForKey", "(", "object", ",", "key", ",", "primitives", ")", "{", "var", "proto", "=", "primitives", ".", "getPrototypeOf", "(", "object", ")", "if", "(", "!", "proto", "||", "hasOwnProperty", "(", "object", ",", "key", ")", ")", "{", "return", "object", "}", "else", "{", "return", "objectForKey", "(", "proto", ",", "key", ",", "primitives", ")", "}", "}" ]
walk a provided object's prototypal hierarchy to retrieve an inherited object
[ "walk", "a", "provided", "object", "s", "prototypal", "hierarchy", "to", "retrieve", "an", "inherited", "object" ]
e01c28f094ce293c61aba90b7c9242d9b050fb49
https://github.com/riot/tmpl/blob/e01c28f094ce293c61aba90b7c9242d9b050fb49/src/notevil/index.js#L428-L435
train
riot/tmpl
src/notevil/index.js
canSetProperty
function canSetProperty(object, property, primitives){ if (property === '__proto__' || primitives.isPrimitive(object)){ return false } else if (object != null){ if (hasOwnProperty(object, property)){ if (propertyIsEnumerable(object, property)){ return true } else { return false } } else { return canSetProperty(primitives.getPrototypeOf(object), property, primitives) } } else { return true } }
javascript
function canSetProperty(object, property, primitives){ if (property === '__proto__' || primitives.isPrimitive(object)){ return false } else if (object != null){ if (hasOwnProperty(object, property)){ if (propertyIsEnumerable(object, property)){ return true } else { return false } } else { return canSetProperty(primitives.getPrototypeOf(object), property, primitives) } } else { return true } }
[ "function", "canSetProperty", "(", "object", ",", "property", ",", "primitives", ")", "{", "if", "(", "property", "===", "'__proto__'", "||", "primitives", ".", "isPrimitive", "(", "object", ")", ")", "{", "return", "false", "}", "else", "if", "(", "object", "!=", "null", ")", "{", "if", "(", "hasOwnProperty", "(", "object", ",", "property", ")", ")", "{", "if", "(", "propertyIsEnumerable", "(", "object", ",", "property", ")", ")", "{", "return", "true", "}", "else", "{", "return", "false", "}", "}", "else", "{", "return", "canSetProperty", "(", "primitives", ".", "getPrototypeOf", "(", "object", ")", ",", "property", ",", "primitives", ")", "}", "}", "else", "{", "return", "true", "}", "}" ]
determine if we have write access to a property
[ "determine", "if", "we", "have", "write", "access", "to", "a", "property" ]
e01c28f094ce293c61aba90b7c9242d9b050fb49
https://github.com/riot/tmpl/blob/e01c28f094ce293c61aba90b7c9242d9b050fb49/src/notevil/index.js#L459-L477
train
howdyai/botkit-storage-firebase
src/index.js
get
function get(firebaseRef) { return function(id, cb) { firebaseRef.child(id).once('value').then(function(snapshot) { cb(null, snapshot.val()); }, cb); }; }
javascript
function get(firebaseRef) { return function(id, cb) { firebaseRef.child(id).once('value').then(function(snapshot) { cb(null, snapshot.val()); }, cb); }; }
[ "function", "get", "(", "firebaseRef", ")", "{", "return", "function", "(", "id", ",", "cb", ")", "{", "firebaseRef", ".", "child", "(", "id", ")", ".", "once", "(", "'value'", ")", ".", "then", "(", "function", "(", "snapshot", ")", "{", "cb", "(", "null", ",", "snapshot", ".", "val", "(", ")", ")", ";", "}", ",", "cb", ")", ";", "}", ";", "}" ]
Given a firebase ref, will return a function that will get a single value by ID @param {Object} firebaseRef A reference to the firebase Object @returns {Function} The get function
[ "Given", "a", "firebase", "ref", "will", "return", "a", "function", "that", "will", "get", "a", "single", "value", "by", "ID" ]
205d043124e2b253004458727ee12f5823b7ccc1
https://github.com/howdyai/botkit-storage-firebase/blob/205d043124e2b253004458727ee12f5823b7ccc1/src/index.js#L57-L64
train
howdyai/botkit-storage-firebase
src/index.js
save
function save(firebaseRef) { return function(data, cb) { var firebase_update = {}; firebase_update[data.id] = data; firebaseRef.update(firebase_update).then(cb); }; }
javascript
function save(firebaseRef) { return function(data, cb) { var firebase_update = {}; firebase_update[data.id] = data; firebaseRef.update(firebase_update).then(cb); }; }
[ "function", "save", "(", "firebaseRef", ")", "{", "return", "function", "(", "data", ",", "cb", ")", "{", "var", "firebase_update", "=", "{", "}", ";", "firebase_update", "[", "data", ".", "id", "]", "=", "data", ";", "firebaseRef", ".", "update", "(", "firebase_update", ")", ".", "then", "(", "cb", ")", ";", "}", ";", "}" ]
Given a firebase ref, will return a function that will save an object. The object must have an id property @param {Object} firebaseRef A reference to the firebase Object @returns {Function} The save function
[ "Given", "a", "firebase", "ref", "will", "return", "a", "function", "that", "will", "save", "an", "object", ".", "The", "object", "must", "have", "an", "id", "property" ]
205d043124e2b253004458727ee12f5823b7ccc1
https://github.com/howdyai/botkit-storage-firebase/blob/205d043124e2b253004458727ee12f5823b7ccc1/src/index.js#L72-L78
train
howdyai/botkit-storage-firebase
src/index.js
all
function all(firebaseRef) { return function(cb) { firebaseRef.once('value').then(function success(records) { var results = records.val(); if (!results) { return cb(null, []); } var list = Object.keys(results).map(function(key) { return results[key]; }); cb(null, list); }, cb); }; }
javascript
function all(firebaseRef) { return function(cb) { firebaseRef.once('value').then(function success(records) { var results = records.val(); if (!results) { return cb(null, []); } var list = Object.keys(results).map(function(key) { return results[key]; }); cb(null, list); }, cb); }; }
[ "function", "all", "(", "firebaseRef", ")", "{", "return", "function", "(", "cb", ")", "{", "firebaseRef", ".", "once", "(", "'value'", ")", ".", "then", "(", "function", "success", "(", "records", ")", "{", "var", "results", "=", "records", ".", "val", "(", ")", ";", "if", "(", "!", "results", ")", "{", "return", "cb", "(", "null", ",", "[", "]", ")", ";", "}", "var", "list", "=", "Object", ".", "keys", "(", "results", ")", ".", "map", "(", "function", "(", "key", ")", "{", "return", "results", "[", "key", "]", ";", "}", ")", ";", "cb", "(", "null", ",", "list", ")", ";", "}", ",", "cb", ")", ";", "}", ";", "}" ]
Given a firebase ref, will return a function that will return all objects stored. @param {Object} firebaseRef A reference to the firebase Object @returns {Function} The all function
[ "Given", "a", "firebase", "ref", "will", "return", "a", "function", "that", "will", "return", "all", "objects", "stored", "." ]
205d043124e2b253004458727ee12f5823b7ccc1
https://github.com/howdyai/botkit-storage-firebase/blob/205d043124e2b253004458727ee12f5823b7ccc1/src/index.js#L86-L102
train
travist/jquery.go.js
lib/jquery.go.js
function(selector, context) { this.selector = selector; if (typeof context == 'function') { this.context = null; this.asyncExecute(null, null, context); } else { this.context = context; } this.instance = -1; this.index = -1; this.length = -1; }
javascript
function(selector, context) { this.selector = selector; if (typeof context == 'function') { this.context = null; this.asyncExecute(null, null, context); } else { this.context = context; } this.instance = -1; this.index = -1; this.length = -1; }
[ "function", "(", "selector", ",", "context", ")", "{", "this", ".", "selector", "=", "selector", ";", "if", "(", "typeof", "context", "==", "'function'", ")", "{", "this", ".", "context", "=", "null", ";", "this", ".", "asyncExecute", "(", "null", ",", "null", ",", "context", ")", ";", "}", "else", "{", "this", ".", "context", "=", "context", ";", "}", "this", ".", "instance", "=", "-", "1", ";", "this", ".", "index", "=", "-", "1", ";", "this", ".", "length", "=", "-", "1", ";", "}" ]
jQuery Interface class. @param {string} selector The selector to use for the interface. @param {string} context The context to use for the interface. @returns {jQueryInterface}
[ "jQuery", "Interface", "class", "." ]
0aad43403b26ed73d892451a7dff8087004cc922
https://github.com/travist/jquery.go.js/blob/0aad43403b26ed73d892451a7dff8087004cc922/lib/jquery.go.js#L100-L113
train
travist/jquery.go.js
lib/jquery.go.js
function(url, callback) { var self = this; getPage(function(page) { // Set the page size if it hasn't already been set. if (!self.viewportSizeSet) { self.viewportSizeSet = true; page.set('viewportSize', { width: self.config.width, height: self.config.height }, function (result) { self.debug("Viewport set to: " + result.width + "x" + result.height); }); } // Set a custom user agent if it hasn't already been set. if (self.config.userAgent && !self.userAgentSet) { self.userAgentSet = true; page.set('settings.userAgent', self.config.userAgent, function (result) { self.debug("Useragent set to: " + result); }); } // Open the page. self.debug('Navigating to ' + self.config.site + url); page.open(self.config.site + url, function(status) { if (status == 'fail') { self.close(); throw new Error(status); } if (self.config.addJQuery) { var loadJS = function() { if (loading) { setTimeout(loadJS, 100); } else { page.includeJs(self.config.jQuery, callback); } } loadJS(); } else { self.waitForPage(callback); } }); }); }
javascript
function(url, callback) { var self = this; getPage(function(page) { // Set the page size if it hasn't already been set. if (!self.viewportSizeSet) { self.viewportSizeSet = true; page.set('viewportSize', { width: self.config.width, height: self.config.height }, function (result) { self.debug("Viewport set to: " + result.width + "x" + result.height); }); } // Set a custom user agent if it hasn't already been set. if (self.config.userAgent && !self.userAgentSet) { self.userAgentSet = true; page.set('settings.userAgent', self.config.userAgent, function (result) { self.debug("Useragent set to: " + result); }); } // Open the page. self.debug('Navigating to ' + self.config.site + url); page.open(self.config.site + url, function(status) { if (status == 'fail') { self.close(); throw new Error(status); } if (self.config.addJQuery) { var loadJS = function() { if (loading) { setTimeout(loadJS, 100); } else { page.includeJs(self.config.jQuery, callback); } } loadJS(); } else { self.waitForPage(callback); } }); }); }
[ "function", "(", "url", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "getPage", "(", "function", "(", "page", ")", "{", "if", "(", "!", "self", ".", "viewportSizeSet", ")", "{", "self", ".", "viewportSizeSet", "=", "true", ";", "page", ".", "set", "(", "'viewportSize'", ",", "{", "width", ":", "self", ".", "config", ".", "width", ",", "height", ":", "self", ".", "config", ".", "height", "}", ",", "function", "(", "result", ")", "{", "self", ".", "debug", "(", "\"Viewport set to: \"", "+", "result", ".", "width", "+", "\"x\"", "+", "result", ".", "height", ")", ";", "}", ")", ";", "}", "if", "(", "self", ".", "config", ".", "userAgent", "&&", "!", "self", ".", "userAgentSet", ")", "{", "self", ".", "userAgentSet", "=", "true", ";", "page", ".", "set", "(", "'settings.userAgent'", ",", "self", ".", "config", ".", "userAgent", ",", "function", "(", "result", ")", "{", "self", ".", "debug", "(", "\"Useragent set to: \"", "+", "result", ")", ";", "}", ")", ";", "}", "self", ".", "debug", "(", "'Navigating to '", "+", "self", ".", "config", ".", "site", "+", "url", ")", ";", "page", ".", "open", "(", "self", ".", "config", ".", "site", "+", "url", ",", "function", "(", "status", ")", "{", "if", "(", "status", "==", "'fail'", ")", "{", "self", ".", "close", "(", ")", ";", "throw", "new", "Error", "(", "status", ")", ";", "}", "if", "(", "self", ".", "config", ".", "addJQuery", ")", "{", "var", "loadJS", "=", "function", "(", ")", "{", "if", "(", "loading", ")", "{", "setTimeout", "(", "loadJS", ",", "100", ")", ";", "}", "else", "{", "page", ".", "includeJs", "(", "self", ".", "config", ".", "jQuery", ",", "callback", ")", ";", "}", "}", "loadJS", "(", ")", ";", "}", "else", "{", "self", ".", "waitForPage", "(", "callback", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Used to visit a page. @param {string} url The url you wish to visit. @param {function} callback Called when the page is done visiting.
[ "Used", "to", "visit", "a", "page", "." ]
0aad43403b26ed73d892451a7dff8087004cc922
https://github.com/travist/jquery.go.js/blob/0aad43403b26ed73d892451a7dff8087004cc922/lib/jquery.go.js#L353-L399
train
travist/jquery.go.js
lib/jquery.go.js
function(callback, nowait) { var self = this; var loadWait = function() { setTimeout(function() { self.waitForPage(callback, true); }, 100); }; if (nowait) { if (loading) { loadWait(); } else { getPage(function(page) { page.evaluate(function() { return jQuery.isReady; }, function(ready) { if (ready) { callback.call(self); } else { loadWait(); } }); }); } } else { loadWait(); } }
javascript
function(callback, nowait) { var self = this; var loadWait = function() { setTimeout(function() { self.waitForPage(callback, true); }, 100); }; if (nowait) { if (loading) { loadWait(); } else { getPage(function(page) { page.evaluate(function() { return jQuery.isReady; }, function(ready) { if (ready) { callback.call(self); } else { loadWait(); } }); }); } } else { loadWait(); } }
[ "function", "(", "callback", ",", "nowait", ")", "{", "var", "self", "=", "this", ";", "var", "loadWait", "=", "function", "(", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "self", ".", "waitForPage", "(", "callback", ",", "true", ")", ";", "}", ",", "100", ")", ";", "}", ";", "if", "(", "nowait", ")", "{", "if", "(", "loading", ")", "{", "loadWait", "(", ")", ";", "}", "else", "{", "getPage", "(", "function", "(", "page", ")", "{", "page", ".", "evaluate", "(", "function", "(", ")", "{", "return", "jQuery", ".", "isReady", ";", "}", ",", "function", "(", "ready", ")", "{", "if", "(", "ready", ")", "{", "callback", ".", "call", "(", "self", ")", ";", "}", "else", "{", "loadWait", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}", "}", "else", "{", "loadWait", "(", ")", ";", "}", "}" ]
Wait for the page to load. @param {type} callback @returns {undefined}
[ "Wait", "for", "the", "page", "to", "load", "." ]
0aad43403b26ed73d892451a7dff8087004cc922
https://github.com/travist/jquery.go.js/blob/0aad43403b26ed73d892451a7dff8087004cc922/lib/jquery.go.js#L407-L436
train
travist/jquery.go.js
lib/jquery.go.js
function(element, callback, nowait) { var self = this; if (!nowait) { this.waitForPage(function() { self.waitForElement(element, callback, true); }); } else { var loadWait = function() { setTimeout(function() { self.waitForElement(element, callback, true); }, 100); }; if (nowait) { getPage(function(page) { page.evaluate(function(element) { var element = jQuery(element); return ((element.length > 0) && element.is(':visible')); }, function(found) { if (found) { self.debug('Element ' + element + ' found'); callback.call(self); } else { loadWait(); } }, element); }); } else { loadWait(); } } }
javascript
function(element, callback, nowait) { var self = this; if (!nowait) { this.waitForPage(function() { self.waitForElement(element, callback, true); }); } else { var loadWait = function() { setTimeout(function() { self.waitForElement(element, callback, true); }, 100); }; if (nowait) { getPage(function(page) { page.evaluate(function(element) { var element = jQuery(element); return ((element.length > 0) && element.is(':visible')); }, function(found) { if (found) { self.debug('Element ' + element + ' found'); callback.call(self); } else { loadWait(); } }, element); }); } else { loadWait(); } } }
[ "function", "(", "element", ",", "callback", ",", "nowait", ")", "{", "var", "self", "=", "this", ";", "if", "(", "!", "nowait", ")", "{", "this", ".", "waitForPage", "(", "function", "(", ")", "{", "self", ".", "waitForElement", "(", "element", ",", "callback", ",", "true", ")", ";", "}", ")", ";", "}", "else", "{", "var", "loadWait", "=", "function", "(", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "self", ".", "waitForElement", "(", "element", ",", "callback", ",", "true", ")", ";", "}", ",", "100", ")", ";", "}", ";", "if", "(", "nowait", ")", "{", "getPage", "(", "function", "(", "page", ")", "{", "page", ".", "evaluate", "(", "function", "(", "element", ")", "{", "var", "element", "=", "jQuery", "(", "element", ")", ";", "return", "(", "(", "element", ".", "length", ">", "0", ")", "&&", "element", ".", "is", "(", "':visible'", ")", ")", ";", "}", ",", "function", "(", "found", ")", "{", "if", "(", "found", ")", "{", "self", ".", "debug", "(", "'Element '", "+", "element", "+", "' found'", ")", ";", "callback", ".", "call", "(", "self", ")", ";", "}", "else", "{", "loadWait", "(", ")", ";", "}", "}", ",", "element", ")", ";", "}", ")", ";", "}", "else", "{", "loadWait", "(", ")", ";", "}", "}", "}" ]
Waits for an element to be present.
[ "Waits", "for", "an", "element", "to", "be", "present", "." ]
0aad43403b26ed73d892451a7dff8087004cc922
https://github.com/travist/jquery.go.js/blob/0aad43403b26ed73d892451a7dff8087004cc922/lib/jquery.go.js#L441-L474
train
travist/jquery.go.js
lib/jquery.go.js
function(filename, done) { this.debug('Capturing page at ' + filename); getPage(function(page) { page.render(filename, done); }); }
javascript
function(filename, done) { this.debug('Capturing page at ' + filename); getPage(function(page) { page.render(filename, done); }); }
[ "function", "(", "filename", ",", "done", ")", "{", "this", ".", "debug", "(", "'Capturing page at '", "+", "filename", ")", ";", "getPage", "(", "function", "(", "page", ")", "{", "page", ".", "render", "(", "filename", ",", "done", ")", ";", "}", ")", ";", "}" ]
Capture the page as an image.
[ "Capture", "the", "page", "as", "an", "image", "." ]
0aad43403b26ed73d892451a7dff8087004cc922
https://github.com/travist/jquery.go.js/blob/0aad43403b26ed73d892451a7dff8087004cc922/lib/jquery.go.js#L479-L484
train
travist/jquery.go.js
lib/jquery.go.js
function(selector, filename, done) { this.debug('Upload ' + filename + ' to ' + selector); getPage(function(page) { page.uploadFile(selector, filename, done); }); done(); }
javascript
function(selector, filename, done) { this.debug('Upload ' + filename + ' to ' + selector); getPage(function(page) { page.uploadFile(selector, filename, done); }); done(); }
[ "function", "(", "selector", ",", "filename", ",", "done", ")", "{", "this", ".", "debug", "(", "'Upload '", "+", "filename", "+", "' to '", "+", "selector", ")", ";", "getPage", "(", "function", "(", "page", ")", "{", "page", ".", "uploadFile", "(", "selector", ",", "filename", ",", "done", ")", ";", "}", ")", ";", "done", "(", ")", ";", "}" ]
Upload File to a Form.
[ "Upload", "File", "to", "a", "Form", "." ]
0aad43403b26ed73d892451a7dff8087004cc922
https://github.com/travist/jquery.go.js/blob/0aad43403b26ed73d892451a7dff8087004cc922/lib/jquery.go.js#L489-L495
train
misterhat/omdb
index.js
formatRuntime
function formatRuntime(raw) { var hours, minutes; if (!raw) { return null; } hours = raw.match(/(\d+) h/); minutes = raw.match(/(\d+) min/); hours = hours ? hours[1] : 0; minutes = minutes ? +minutes[1] : 0; return (hours * 60) + minutes; }
javascript
function formatRuntime(raw) { var hours, minutes; if (!raw) { return null; } hours = raw.match(/(\d+) h/); minutes = raw.match(/(\d+) min/); hours = hours ? hours[1] : 0; minutes = minutes ? +minutes[1] : 0; return (hours * 60) + minutes; }
[ "function", "formatRuntime", "(", "raw", ")", "{", "var", "hours", ",", "minutes", ";", "if", "(", "!", "raw", ")", "{", "return", "null", ";", "}", "hours", "=", "raw", ".", "match", "(", "/", "(\\d+) h", "/", ")", ";", "minutes", "=", "raw", ".", "match", "(", "/", "(\\d+) min", "/", ")", ";", "hours", "=", "hours", "?", "hours", "[", "1", "]", ":", "0", ";", "minutes", "=", "minutes", "?", "+", "minutes", "[", "1", "]", ":", "0", ";", "return", "(", "hours", "*", "60", ")", "+", "minutes", ";", "}" ]
Format strings of hours & minutes into minutes. For example, "1 h 30 min" == 90.
[ "Format", "strings", "of", "hours", "&", "minutes", "into", "minutes", ".", "For", "example", "1", "h", "30", "min", "==", "90", "." ]
bac33cae87a24d3d2ae9e57836f2e35d8f4deb7e
https://github.com/misterhat/omdb/blob/bac33cae87a24d3d2ae9e57836f2e35d8f4deb7e/index.js#L34-L48
train
misterhat/omdb
index.js
formatList
function formatList(raw) { var list; if (!raw) { return []; } list = raw.replace(/\(.+?\)/g, '').split(', '); list = list.map(function (item) { return item.trim(); }); return list; }
javascript
function formatList(raw) { var list; if (!raw) { return []; } list = raw.replace(/\(.+?\)/g, '').split(', '); list = list.map(function (item) { return item.trim(); }); return list; }
[ "function", "formatList", "(", "raw", ")", "{", "var", "list", ";", "if", "(", "!", "raw", ")", "{", "return", "[", "]", ";", "}", "list", "=", "raw", ".", "replace", "(", "/", "\\(.+?\\)", "/", "g", ",", "''", ")", ".", "split", "(", "', '", ")", ";", "list", "=", "list", ".", "map", "(", "function", "(", "item", ")", "{", "return", "item", ".", "trim", "(", ")", ";", "}", ")", ";", "return", "list", ";", "}" ]
Remove all the strings found within brackets and split by comma.
[ "Remove", "all", "the", "strings", "found", "within", "brackets", "and", "split", "by", "comma", "." ]
bac33cae87a24d3d2ae9e57836f2e35d8f4deb7e
https://github.com/misterhat/omdb/blob/bac33cae87a24d3d2ae9e57836f2e35d8f4deb7e/index.js#L56-L69
train
misterhat/omdb
index.js
formatAwards
function formatAwards(raw) { var wins, nominations; if (!raw) { return { wins: 0, nominations: 0, text: '' }; } wins = raw.match(/(\d+) wins?/i); nominations = raw.match(/(\d+) nominations?/i); return { wins: wins ? +wins[1] : 0, nominations: nominations ? +nominations[1] : 0, text: raw }; }
javascript
function formatAwards(raw) { var wins, nominations; if (!raw) { return { wins: 0, nominations: 0, text: '' }; } wins = raw.match(/(\d+) wins?/i); nominations = raw.match(/(\d+) nominations?/i); return { wins: wins ? +wins[1] : 0, nominations: nominations ? +nominations[1] : 0, text: raw }; }
[ "function", "formatAwards", "(", "raw", ")", "{", "var", "wins", ",", "nominations", ";", "if", "(", "!", "raw", ")", "{", "return", "{", "wins", ":", "0", ",", "nominations", ":", "0", ",", "text", ":", "''", "}", ";", "}", "wins", "=", "raw", ".", "match", "(", "/", "(\\d+) wins?", "/", "i", ")", ";", "nominations", "=", "raw", ".", "match", "(", "/", "(\\d+) nominations?", "/", "i", ")", ";", "return", "{", "wins", ":", "wins", "?", "+", "wins", "[", "1", "]", ":", "0", ",", "nominations", ":", "nominations", "?", "+", "nominations", "[", "1", "]", ":", "0", ",", "text", ":", "raw", "}", ";", "}" ]
Try to find the win and nomination count, but also keep raw just in case.
[ "Try", "to", "find", "the", "win", "and", "nomination", "count", "but", "also", "keep", "raw", "just", "in", "case", "." ]
bac33cae87a24d3d2ae9e57836f2e35d8f4deb7e
https://github.com/misterhat/omdb/blob/bac33cae87a24d3d2ae9e57836f2e35d8f4deb7e/index.js#L72-L87
train
BlockchainZoo/keyhub-vault
packages/keyhub-vault-nxt/lib/js/crypto/curve25519_.js
function(r, x) { var r1 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; var r2 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; curve25519_sqrmodp(r1, x); // r1 = x^2 curve25519_mulasmall(r2, x, 486662); // r2 = Ax curve25519_addmodp(r, r1, r2); // r = x^2 + Ax curve25519_addmodp(r1, r, curve25519_one()); // r1 = x^2 + Ax + 1 curve25519_mulmodp(r, r1, x); // r = x^3 + Ax^2 + x }
javascript
function(r, x) { var r1 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; var r2 = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; curve25519_sqrmodp(r1, x); // r1 = x^2 curve25519_mulasmall(r2, x, 486662); // r2 = Ax curve25519_addmodp(r, r1, r2); // r = x^2 + Ax curve25519_addmodp(r1, r, curve25519_one()); // r1 = x^2 + Ax + 1 curve25519_mulmodp(r, r1, x); // r = x^3 + Ax^2 + x }
[ "function", "(", "r", ",", "x", ")", "{", "var", "r1", "=", "[", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", "]", ";", "var", "r2", "=", "[", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", "]", ";", "curve25519_sqrmodp", "(", "r1", ",", "x", ")", ";", "curve25519_mulasmall", "(", "r2", ",", "x", ",", "486662", ")", ";", "curve25519_addmodp", "(", "r", ",", "r1", ",", "r2", ")", ";", "curve25519_addmodp", "(", "r1", ",", "r", ",", "curve25519_one", "(", ")", ")", ";", "curve25519_mulmodp", "(", "r", ",", "r1", ",", "x", ")", ";", "}" ]
Montgomery curve with A=486662 and B=1
[ "Montgomery", "curve", "with", "A", "=", "486662", "and", "B", "=", "1" ]
dbf4936224aa53a4a33acbe0fa84fb38a62bbd13
https://github.com/BlockchainZoo/keyhub-vault/blob/dbf4936224aa53a4a33acbe0fa84fb38a62bbd13/packages/keyhub-vault-nxt/lib/js/crypto/curve25519_.js#L607-L615
train
rdub80/aframe-gui
examples/visualizer/third-party/components/ring-on-beat.js
function () { this.rings.forEach(function (ringEl) { var scale = ringEl.getComputedAttribute('scale'); ringEl.setAttribute('scale', { x: scale.x * 1.06 + .05, y: scale.y * 1.06 + .05, z: scale.z }); }); }
javascript
function () { this.rings.forEach(function (ringEl) { var scale = ringEl.getComputedAttribute('scale'); ringEl.setAttribute('scale', { x: scale.x * 1.06 + .05, y: scale.y * 1.06 + .05, z: scale.z }); }); }
[ "function", "(", ")", "{", "this", ".", "rings", ".", "forEach", "(", "function", "(", "ringEl", ")", "{", "var", "scale", "=", "ringEl", ".", "getComputedAttribute", "(", "'scale'", ")", ";", "ringEl", ".", "setAttribute", "(", "'scale'", ",", "{", "x", ":", "scale", ".", "x", "*", "1.06", "+", ".05", ",", "y", ":", "scale", ".", "y", "*", "1.06", "+", ".05", ",", "z", ":", "scale", ".", "z", "}", ")", ";", "}", ")", ";", "}" ]
Expand ring radii.
[ "Expand", "ring", "radii", "." ]
eb4549f17543b2ada039b1c65658dd72c35b19d1
https://github.com/rdub80/aframe-gui/blob/eb4549f17543b2ada039b1c65658dd72c35b19d1/examples/visualizer/third-party/components/ring-on-beat.js#L34-L43
train
MaartenDesnouck/google-apps-script
lib/functions/authenticate.js
getTokenDefault
function getTokenDefault(code, token, oauth2Client) { return new Promise((resolve, reject) => { const requestData = { code, token, }; request({ url: 'https://us-central1-gas-include.cloudfunctions.net/getToken', method: "POST", json: true, headers: { "content-type": "application/json", }, body: requestData, }, (error, response, body) => { const token = body; if (error) { reject(error); } else if (response.statusCode === 200) { resolve(token); } else { reject({ message: 'Failed to get a token for the default Oauth client.', print: true, }); } }); }); }
javascript
function getTokenDefault(code, token, oauth2Client) { return new Promise((resolve, reject) => { const requestData = { code, token, }; request({ url: 'https://us-central1-gas-include.cloudfunctions.net/getToken', method: "POST", json: true, headers: { "content-type": "application/json", }, body: requestData, }, (error, response, body) => { const token = body; if (error) { reject(error); } else if (response.statusCode === 200) { resolve(token); } else { reject({ message: 'Failed to get a token for the default Oauth client.', print: true, }); } }); }); }
[ "function", "getTokenDefault", "(", "code", ",", "token", ",", "oauth2Client", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "requestData", "=", "{", "code", ",", "token", ",", "}", ";", "request", "(", "{", "url", ":", "'https://us-central1-gas-include.cloudfunctions.net/getToken'", ",", "method", ":", "\"POST\"", ",", "json", ":", "true", ",", "headers", ":", "{", "\"content-type\"", ":", "\"application/json\"", ",", "}", ",", "body", ":", "requestData", ",", "}", ",", "(", "error", ",", "response", ",", "body", ")", "=>", "{", "const", "token", "=", "body", ";", "if", "(", "error", ")", "{", "reject", "(", "error", ")", ";", "}", "else", "if", "(", "response", ".", "statusCode", "===", "200", ")", "{", "resolve", "(", "token", ")", ";", "}", "else", "{", "reject", "(", "{", "message", ":", "'Failed to get a token for the default Oauth client.'", ",", "print", ":", "true", ",", "}", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Get a token for a the defaut Oauth client. @param {google.auth.OAuth2} code - Optional code to get token for. @param {google.auth.OAuth2} token - Optional token to refresh. @param {google.auth.OAuth2} oauth2Client - The OAuth2 client to get token for. @returns {Promise} - A promise resolving a tokent
[ "Get", "a", "token", "for", "a", "the", "defaut", "Oauth", "client", "." ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/authenticate.js#L37-L65
train
MaartenDesnouck/google-apps-script
lib/functions/authenticate.js
getTokenCustom
function getTokenCustom(code, oauth2Client) { return new Promise((resolve, reject) => { if (code) { oauth2Client.getToken(code, (err, newToken) => { if (err) { reject(err); return; } resolve(newToken); return; }); } else { oauth2Client.refreshAccessToken((err, newToken) => { if (err) { reject(err); } resolve(newToken); return; }); } }); }
javascript
function getTokenCustom(code, oauth2Client) { return new Promise((resolve, reject) => { if (code) { oauth2Client.getToken(code, (err, newToken) => { if (err) { reject(err); return; } resolve(newToken); return; }); } else { oauth2Client.refreshAccessToken((err, newToken) => { if (err) { reject(err); } resolve(newToken); return; }); } }); }
[ "function", "getTokenCustom", "(", "code", ",", "oauth2Client", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "code", ")", "{", "oauth2Client", ".", "getToken", "(", "code", ",", "(", "err", ",", "newToken", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "return", ";", "}", "resolve", "(", "newToken", ")", ";", "return", ";", "}", ")", ";", "}", "else", "{", "oauth2Client", ".", "refreshAccessToken", "(", "(", "err", ",", "newToken", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "resolve", "(", "newToken", ")", ";", "return", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Get a token for a custom Oauth client. @param {google.auth.OAuth2} code - Optional code to get token for. @param {google.auth.OAuth2} oauth2Client - The OAuth2 client to get token for. @returns {Promise} - A promise resolving a token
[ "Get", "a", "token", "for", "a", "custom", "Oauth", "client", "." ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/authenticate.js#L74-L95
train
MaartenDesnouck/google-apps-script
lib/functions/getScripts.js
getScripts
function getScripts(auth, nameFilter, nextPageToken, allFiles) { return new Promise((resolve, reject) => { let query = ''; if (nameFilter) { query = `mimeType='${constants.MIME_GAS}' and name contains '${nameFilter}'`; } else { query = `mimeType='${constants.MIME_GAS}'`; } const drive = google.drive('v3'); drive.files.list({ auth, pageSize: 1000, fields: 'nextPageToken, files(id, name, description, createdTime, modifiedTime)', orderBy: 'name', includeTeamDriveItems: true, supportsTeamDrives: true, q: query, spaces: 'drive', pageToken: nextPageToken, }, (err, response) => { if (err) { triageGoogleError(err, 'listScriptFiles').then((triaged) => { reject(triaged); }).catch((notTriaged) => { reject(notTriaged); }); return; } const files = response.data.files; allFiles = allFiles.concat(files); // Need to get another page of results? if (response.nextPageToken) { getScripts(auth, nameFilter, response.nextPageToken, allFiles).then((allFiles) => { resolve(allFiles); }).catch((err) => { reject(err); }); return; } else { resolve(allFiles); return; } }); }); }
javascript
function getScripts(auth, nameFilter, nextPageToken, allFiles) { return new Promise((resolve, reject) => { let query = ''; if (nameFilter) { query = `mimeType='${constants.MIME_GAS}' and name contains '${nameFilter}'`; } else { query = `mimeType='${constants.MIME_GAS}'`; } const drive = google.drive('v3'); drive.files.list({ auth, pageSize: 1000, fields: 'nextPageToken, files(id, name, description, createdTime, modifiedTime)', orderBy: 'name', includeTeamDriveItems: true, supportsTeamDrives: true, q: query, spaces: 'drive', pageToken: nextPageToken, }, (err, response) => { if (err) { triageGoogleError(err, 'listScriptFiles').then((triaged) => { reject(triaged); }).catch((notTriaged) => { reject(notTriaged); }); return; } const files = response.data.files; allFiles = allFiles.concat(files); // Need to get another page of results? if (response.nextPageToken) { getScripts(auth, nameFilter, response.nextPageToken, allFiles).then((allFiles) => { resolve(allFiles); }).catch((err) => { reject(err); }); return; } else { resolve(allFiles); return; } }); }); }
[ "function", "getScripts", "(", "auth", ",", "nameFilter", ",", "nextPageToken", ",", "allFiles", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "query", "=", "''", ";", "if", "(", "nameFilter", ")", "{", "query", "=", "`", "${", "constants", ".", "MIME_GAS", "}", "${", "nameFilter", "}", "`", ";", "}", "else", "{", "query", "=", "`", "${", "constants", ".", "MIME_GAS", "}", "`", ";", "}", "const", "drive", "=", "google", ".", "drive", "(", "'v3'", ")", ";", "drive", ".", "files", ".", "list", "(", "{", "auth", ",", "pageSize", ":", "1000", ",", "fields", ":", "'nextPageToken, files(id, name, description, createdTime, modifiedTime)'", ",", "orderBy", ":", "'name'", ",", "includeTeamDriveItems", ":", "true", ",", "supportsTeamDrives", ":", "true", ",", "q", ":", "query", ",", "spaces", ":", "'drive'", ",", "pageToken", ":", "nextPageToken", ",", "}", ",", "(", "err", ",", "response", ")", "=>", "{", "if", "(", "err", ")", "{", "triageGoogleError", "(", "err", ",", "'listScriptFiles'", ")", ".", "then", "(", "(", "triaged", ")", "=>", "{", "reject", "(", "triaged", ")", ";", "}", ")", ".", "catch", "(", "(", "notTriaged", ")", "=>", "{", "reject", "(", "notTriaged", ")", ";", "}", ")", ";", "return", ";", "}", "const", "files", "=", "response", ".", "data", ".", "files", ";", "allFiles", "=", "allFiles", ".", "concat", "(", "files", ")", ";", "if", "(", "response", ".", "nextPageToken", ")", "{", "getScripts", "(", "auth", ",", "nameFilter", ",", "response", ".", "nextPageToken", ",", "allFiles", ")", ".", "then", "(", "(", "allFiles", ")", "=>", "{", "resolve", "(", "allFiles", ")", ";", "}", ")", ".", "catch", "(", "(", "err", ")", "=>", "{", "reject", "(", "err", ")", ";", "}", ")", ";", "return", ";", "}", "else", "{", "resolve", "(", "allFiles", ")", ";", "return", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Lists the names and IDs of script files. @param {google.auth.OAuth2} auth - An authorized OAuth2 client. @param {String} nameFilter - String to filter results on. @param {String} nextPageToken - Token of the resultpage to get. @param {String} allFiles - String to filter results on. @returns {Promise} - A promise resolving a list of files
[ "Lists", "the", "names", "and", "IDs", "of", "script", "files", "." ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/getScripts.js#L16-L63
train
MaartenDesnouck/google-apps-script
lib/config.js
endDialog
function endDialog(success, config) { if (success) { createConfigFile(config); console.log(); process.stdout.write('Succesfully configured gas'); checkbox.display('green'); process.exit(0); } else { console.log(`Only 'y' and 'n' are accepted inputs.`); process.stdout.write('Failed to configure gas'); checkbox.display('red'); process.exit(1); } }
javascript
function endDialog(success, config) { if (success) { createConfigFile(config); console.log(); process.stdout.write('Succesfully configured gas'); checkbox.display('green'); process.exit(0); } else { console.log(`Only 'y' and 'n' are accepted inputs.`); process.stdout.write('Failed to configure gas'); checkbox.display('red'); process.exit(1); } }
[ "function", "endDialog", "(", "success", ",", "config", ")", "{", "if", "(", "success", ")", "{", "createConfigFile", "(", "config", ")", ";", "console", ".", "log", "(", ")", ";", "process", ".", "stdout", ".", "write", "(", "'Succesfully configured gas'", ")", ";", "checkbox", ".", "display", "(", "'green'", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "else", "{", "console", ".", "log", "(", "`", "`", ")", ";", "process", ".", "stdout", ".", "write", "(", "'Failed to configure gas'", ")", ";", "checkbox", ".", "display", "(", "'red'", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "}" ]
Create a config file based on the values provided @param {String} success - Whether or not the dialog completed succesfully @param {String} config - The config we created trough the dialog @returns {void}
[ "Create", "a", "config", "file", "based", "on", "the", "values", "provided" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/config.js#L31-L44
train
MaartenDesnouck/google-apps-script
lib/config.js
importConfig
function importConfig(optionalPath) { process.stdout.write(`Importing your config from '${optionalPath}'`); let config; try { config = fs.readJsonSync(optionalPath, 'utf8'); } catch (err) { checkbox.display('red'); process.stdout.write(`Can't seem to read '${optionalPath}'`); checkbox.display('red'); process.exit(1); } fs.removeSync(tokenFile); // Overwrite current config createConfigFile(config); checkbox.display('green'); }
javascript
function importConfig(optionalPath) { process.stdout.write(`Importing your config from '${optionalPath}'`); let config; try { config = fs.readJsonSync(optionalPath, 'utf8'); } catch (err) { checkbox.display('red'); process.stdout.write(`Can't seem to read '${optionalPath}'`); checkbox.display('red'); process.exit(1); } fs.removeSync(tokenFile); // Overwrite current config createConfigFile(config); checkbox.display('green'); }
[ "function", "importConfig", "(", "optionalPath", ")", "{", "process", ".", "stdout", ".", "write", "(", "`", "${", "optionalPath", "}", "`", ")", ";", "let", "config", ";", "try", "{", "config", "=", "fs", ".", "readJsonSync", "(", "optionalPath", ",", "'utf8'", ")", ";", "}", "catch", "(", "err", ")", "{", "checkbox", ".", "display", "(", "'red'", ")", ";", "process", ".", "stdout", ".", "write", "(", "`", "${", "optionalPath", "}", "`", ")", ";", "checkbox", ".", "display", "(", "'red'", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "fs", ".", "removeSync", "(", "tokenFile", ")", ";", "createConfigFile", "(", "config", ")", ";", "checkbox", ".", "display", "(", "'green'", ")", ";", "}" ]
Import a config file @param {String} optionalPath - The path where we will import the config from @returns {void}
[ "Import", "a", "config", "file" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/config.js#L52-L70
train
MaartenDesnouck/google-apps-script
lib/config.js
exportConfig
function exportConfig(optionalPath) { // Read content of the global config file let config = fs.readFileSync(configFile, 'utf8'); if (!config) { config = '{}'; } // Create file or print output if (optionalPath) { process.stdout.write(`Exporting your config to '${optionalPath}'`); // Create a file in the specified location const file = { name: optionalPath, source: config, }; createFile(file); checkbox.display('green'); } else { console.log(config); } }
javascript
function exportConfig(optionalPath) { // Read content of the global config file let config = fs.readFileSync(configFile, 'utf8'); if (!config) { config = '{}'; } // Create file or print output if (optionalPath) { process.stdout.write(`Exporting your config to '${optionalPath}'`); // Create a file in the specified location const file = { name: optionalPath, source: config, }; createFile(file); checkbox.display('green'); } else { console.log(config); } }
[ "function", "exportConfig", "(", "optionalPath", ")", "{", "let", "config", "=", "fs", ".", "readFileSync", "(", "configFile", ",", "'utf8'", ")", ";", "if", "(", "!", "config", ")", "{", "config", "=", "'{}'", ";", "}", "if", "(", "optionalPath", ")", "{", "process", ".", "stdout", ".", "write", "(", "`", "${", "optionalPath", "}", "`", ")", ";", "const", "file", "=", "{", "name", ":", "optionalPath", ",", "source", ":", "config", ",", "}", ";", "createFile", "(", "file", ")", ";", "checkbox", ".", "display", "(", "'green'", ")", ";", "}", "else", "{", "console", ".", "log", "(", "config", ")", ";", "}", "}" ]
Export a config file @param {String} optionalPath - The path where we will export the config to @returns {void}
[ "Export", "a", "config", "file" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/config.js#L78-L100
train
MaartenDesnouck/google-apps-script
lib/config.js
enterConfig
function enterConfig() { const config = {}; const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question(`Do you want to use .gs as extension for your local code files instead of .js? [${'y'.green}/${'n'.red}]\n > `, (input) => { if (input === 'y') { config.extension = '.gs'; } else if (input !== 'n') { endDialog(false); rl.close(); } rl.question(`Do you want to use a custom OAuth 2.0 client to authenticate with Google? [${'y'.green}/${'n'.red}]\n > `, (input) => { if (input === 'y') { config.client = {}; console.log(); rl.question(`Enter the 'Client ID' of your client \n > `, (input) => { config.client.id = input; rl.question(`Enter the 'Client secret' of your client\n > `, (input) => { config.client.secret = input; // Remove token file to force reauth fs.removeSync(tokenFile); endDialog(true, config); rl.close(); }); }); } else if (input === 'n') { endDialog(true, config); rl.close(); } else { endDialog(false); rl.close(); } }); }); }
javascript
function enterConfig() { const config = {}; const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); rl.question(`Do you want to use .gs as extension for your local code files instead of .js? [${'y'.green}/${'n'.red}]\n > `, (input) => { if (input === 'y') { config.extension = '.gs'; } else if (input !== 'n') { endDialog(false); rl.close(); } rl.question(`Do you want to use a custom OAuth 2.0 client to authenticate with Google? [${'y'.green}/${'n'.red}]\n > `, (input) => { if (input === 'y') { config.client = {}; console.log(); rl.question(`Enter the 'Client ID' of your client \n > `, (input) => { config.client.id = input; rl.question(`Enter the 'Client secret' of your client\n > `, (input) => { config.client.secret = input; // Remove token file to force reauth fs.removeSync(tokenFile); endDialog(true, config); rl.close(); }); }); } else if (input === 'n') { endDialog(true, config); rl.close(); } else { endDialog(false); rl.close(); } }); }); }
[ "function", "enterConfig", "(", ")", "{", "const", "config", "=", "{", "}", ";", "const", "rl", "=", "readline", ".", "createInterface", "(", "{", "input", ":", "process", ".", "stdin", ",", "output", ":", "process", ".", "stdout", ",", "}", ")", ";", "rl", ".", "question", "(", "`", "${", "'y'", ".", "green", "}", "${", "'n'", ".", "red", "}", "\\n", "`", ",", "(", "input", ")", "=>", "{", "if", "(", "input", "===", "'y'", ")", "{", "config", ".", "extension", "=", "'.gs'", ";", "}", "else", "if", "(", "input", "!==", "'n'", ")", "{", "endDialog", "(", "false", ")", ";", "rl", ".", "close", "(", ")", ";", "}", "rl", ".", "question", "(", "`", "${", "'y'", ".", "green", "}", "${", "'n'", ".", "red", "}", "\\n", "`", ",", "(", "input", ")", "=>", "{", "if", "(", "input", "===", "'y'", ")", "{", "config", ".", "client", "=", "{", "}", ";", "console", ".", "log", "(", ")", ";", "rl", ".", "question", "(", "`", "\\n", "`", ",", "(", "input", ")", "=>", "{", "config", ".", "client", ".", "id", "=", "input", ";", "rl", ".", "question", "(", "`", "\\n", "`", ",", "(", "input", ")", "=>", "{", "config", ".", "client", ".", "secret", "=", "input", ";", "fs", ".", "removeSync", "(", "tokenFile", ")", ";", "endDialog", "(", "true", ",", "config", ")", ";", "rl", ".", "close", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", "else", "if", "(", "input", "===", "'n'", ")", "{", "endDialog", "(", "true", ",", "config", ")", ";", "rl", ".", "close", "(", ")", ";", "}", "else", "{", "endDialog", "(", "false", ")", ";", "rl", ".", "close", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Enter a configuration using questions in the terminal @returns {void}
[ "Enter", "a", "configuration", "using", "questions", "in", "the", "terminal" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/config.js#L107-L147
train
MaartenDesnouck/google-apps-script
lib/functions/remoteDeleteProject.js
deleteRemote
function deleteRemote(auth, projectId, name) { return new Promise((resolve, reject) => { const drive = google.drive('v3'); const options = { auth, supportsTeamDrives: true, fileId: projectId, }; drive.files.delete(options, (err, result) => { if (err) { triageGoogleError(err, 'remoteDeleteProject').then((triaged) => { reject(triaged); }).catch((notTriaged) => { reject(notTriaged); }); } else { resolve(result.data); return; } return; }); }); }
javascript
function deleteRemote(auth, projectId, name) { return new Promise((resolve, reject) => { const drive = google.drive('v3'); const options = { auth, supportsTeamDrives: true, fileId: projectId, }; drive.files.delete(options, (err, result) => { if (err) { triageGoogleError(err, 'remoteDeleteProject').then((triaged) => { reject(triaged); }).catch((notTriaged) => { reject(notTriaged); }); } else { resolve(result.data); return; } return; }); }); }
[ "function", "deleteRemote", "(", "auth", ",", "projectId", ",", "name", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "drive", "=", "google", ".", "drive", "(", "'v3'", ")", ";", "const", "options", "=", "{", "auth", ",", "supportsTeamDrives", ":", "true", ",", "fileId", ":", "projectId", ",", "}", ";", "drive", ".", "files", ".", "delete", "(", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "{", "triageGoogleError", "(", "err", ",", "'remoteDeleteProject'", ")", ".", "then", "(", "(", "triaged", ")", "=>", "{", "reject", "(", "triaged", ")", ";", "}", ")", ".", "catch", "(", "(", "notTriaged", ")", "=>", "{", "reject", "(", "notTriaged", ")", ";", "}", ")", ";", "}", "else", "{", "resolve", "(", "result", ".", "data", ")", ";", "return", ";", "}", "return", ";", "}", ")", ";", "}", ")", ";", "}" ]
Delete a remote script file @param {google.auth.OAuth2} auth - An authorized OAuth2 client. @param {String} projectId - Id of file to delete. @param {String} name - Name of project we'ere deleting. @returns {Promise} - A promise resolving the metadata of the deleted project
[ "Delete", "a", "remote", "script", "file" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/remoteDeleteProject.js#L14-L37
train
tree-sitter/tree-sitter-cli
lib/api/properties.js
queryProperties
function queryProperties(props, nodeTypeStack, childIndexStack = [], text) { let stateId = 0 for (let i = 0, {length} = nodeTypeStack; i < length; i++) { const nodeType = nodeTypeStack[i]; const state = props.states[stateId]; let found_transition = false; for (const transition of state.transitions) { if ( (transition.type === nodeType) && (transition.index == null || transition.index === childIndexStack[i]) && (transition.text == null || new RegExp(transition.text).test(text)) ) { stateId = transition.state_id; found_transition = true; break; } } if (!found_transition) { stateId = state.default_next_state_id } // console.log( // nodeType, '->', stateId, // props.property_sets[props.states[stateId].property_set_id] // ); } return props.property_sets[props.states[stateId].property_set_id] }
javascript
function queryProperties(props, nodeTypeStack, childIndexStack = [], text) { let stateId = 0 for (let i = 0, {length} = nodeTypeStack; i < length; i++) { const nodeType = nodeTypeStack[i]; const state = props.states[stateId]; let found_transition = false; for (const transition of state.transitions) { if ( (transition.type === nodeType) && (transition.index == null || transition.index === childIndexStack[i]) && (transition.text == null || new RegExp(transition.text).test(text)) ) { stateId = transition.state_id; found_transition = true; break; } } if (!found_transition) { stateId = state.default_next_state_id } // console.log( // nodeType, '->', stateId, // props.property_sets[props.states[stateId].property_set_id] // ); } return props.property_sets[props.states[stateId].property_set_id] }
[ "function", "queryProperties", "(", "props", ",", "nodeTypeStack", ",", "childIndexStack", "=", "[", "]", ",", "text", ")", "{", "let", "stateId", "=", "0", "for", "(", "let", "i", "=", "0", ",", "{", "length", "}", "=", "nodeTypeStack", ";", "i", "<", "length", ";", "i", "++", ")", "{", "const", "nodeType", "=", "nodeTypeStack", "[", "i", "]", ";", "const", "state", "=", "props", ".", "states", "[", "stateId", "]", ";", "let", "found_transition", "=", "false", ";", "for", "(", "const", "transition", "of", "state", ".", "transitions", ")", "{", "if", "(", "(", "transition", ".", "type", "===", "nodeType", ")", "&&", "(", "transition", ".", "index", "==", "null", "||", "transition", ".", "index", "===", "childIndexStack", "[", "i", "]", ")", "&&", "(", "transition", ".", "text", "==", "null", "||", "new", "RegExp", "(", "transition", ".", "text", ")", ".", "test", "(", "text", ")", ")", ")", "{", "stateId", "=", "transition", ".", "state_id", ";", "found_transition", "=", "true", ";", "break", ";", "}", "}", "if", "(", "!", "found_transition", ")", "{", "stateId", "=", "state", ".", "default_next_state_id", "}", "}", "return", "props", ".", "property_sets", "[", "props", ".", "states", "[", "stateId", "]", ".", "property_set_id", "]", "}" ]
Test a property state machine against a node structure specified as an array of node types.
[ "Test", "a", "property", "state", "machine", "against", "a", "node", "structure", "specified", "as", "an", "array", "of", "node", "types", "." ]
44ba293422c8b7f115e57ff247e454d5b66dee9e
https://github.com/tree-sitter/tree-sitter-cli/blob/44ba293422c8b7f115e57ff247e454d5b66dee9e/lib/api/properties.js#L10-L36
train
tree-sitter/tree-sitter-cli
lib/api/properties.js
parseProperties
function parseProperties(source, baseDirectory) { // Get the raw SCSS concrete syntax tree. const rawTree = parseCSS(source); removeWhitespace(rawTree); // Convert the concrete syntax tree into a more convenient AST. let schema const rootRules = [] for (const rule of rawTree.value) { if (rule.type === 'atrule') { removeWhitespace(rule); const [keyword, argument] = rule.value; if (keyword.value === 'schema') { schema = visitSchema(argument, baseDirectory) } else if (keyword.value === 'import') { rootRules.push(...visitImport(argument, baseDirectory)) } } else { rootRules.push(visitRule(rule, false)) } } // Flatten out any nested selectors. const rules = [] for (const rootRule of rootRules) { flattenRule(rootRule, rules, [[]]); } const validator = new Validator(); for (const rule of rules) { // Validate each rule's properties against the schema. for (const property in rule.properties) { if (schema) { const propertySchema = schema[property] const value = rule.properties[property] if (!propertySchema) { throw new Error(`Property '${property}' is not present in the schema`); } const {errors} = validator.validate(value, propertySchema); if (errors.length > 0) { throw new Error(`Invalid value '${value}' for property '${property}'`) } } } rule.selectors = rule.selectors.map(applyPseudoClasses) } return rules; }
javascript
function parseProperties(source, baseDirectory) { // Get the raw SCSS concrete syntax tree. const rawTree = parseCSS(source); removeWhitespace(rawTree); // Convert the concrete syntax tree into a more convenient AST. let schema const rootRules = [] for (const rule of rawTree.value) { if (rule.type === 'atrule') { removeWhitespace(rule); const [keyword, argument] = rule.value; if (keyword.value === 'schema') { schema = visitSchema(argument, baseDirectory) } else if (keyword.value === 'import') { rootRules.push(...visitImport(argument, baseDirectory)) } } else { rootRules.push(visitRule(rule, false)) } } // Flatten out any nested selectors. const rules = [] for (const rootRule of rootRules) { flattenRule(rootRule, rules, [[]]); } const validator = new Validator(); for (const rule of rules) { // Validate each rule's properties against the schema. for (const property in rule.properties) { if (schema) { const propertySchema = schema[property] const value = rule.properties[property] if (!propertySchema) { throw new Error(`Property '${property}' is not present in the schema`); } const {errors} = validator.validate(value, propertySchema); if (errors.length > 0) { throw new Error(`Invalid value '${value}' for property '${property}'`) } } } rule.selectors = rule.selectors.map(applyPseudoClasses) } return rules; }
[ "function", "parseProperties", "(", "source", ",", "baseDirectory", ")", "{", "const", "rawTree", "=", "parseCSS", "(", "source", ")", ";", "removeWhitespace", "(", "rawTree", ")", ";", "let", "schema", "const", "rootRules", "=", "[", "]", "for", "(", "const", "rule", "of", "rawTree", ".", "value", ")", "{", "if", "(", "rule", ".", "type", "===", "'atrule'", ")", "{", "removeWhitespace", "(", "rule", ")", ";", "const", "[", "keyword", ",", "argument", "]", "=", "rule", ".", "value", ";", "if", "(", "keyword", ".", "value", "===", "'schema'", ")", "{", "schema", "=", "visitSchema", "(", "argument", ",", "baseDirectory", ")", "}", "else", "if", "(", "keyword", ".", "value", "===", "'import'", ")", "{", "rootRules", ".", "push", "(", "...", "visitImport", "(", "argument", ",", "baseDirectory", ")", ")", "}", "}", "else", "{", "rootRules", ".", "push", "(", "visitRule", "(", "rule", ",", "false", ")", ")", "}", "}", "const", "rules", "=", "[", "]", "for", "(", "const", "rootRule", "of", "rootRules", ")", "{", "flattenRule", "(", "rootRule", ",", "rules", ",", "[", "[", "]", "]", ")", ";", "}", "const", "validator", "=", "new", "Validator", "(", ")", ";", "for", "(", "const", "rule", "of", "rules", ")", "{", "for", "(", "const", "property", "in", "rule", ".", "properties", ")", "{", "if", "(", "schema", ")", "{", "const", "propertySchema", "=", "schema", "[", "property", "]", "const", "value", "=", "rule", ".", "properties", "[", "property", "]", "if", "(", "!", "propertySchema", ")", "{", "throw", "new", "Error", "(", "`", "${", "property", "}", "`", ")", ";", "}", "const", "{", "errors", "}", "=", "validator", ".", "validate", "(", "value", ",", "propertySchema", ")", ";", "if", "(", "errors", ".", "length", ">", "0", ")", "{", "throw", "new", "Error", "(", "`", "${", "value", "}", "${", "property", "}", "`", ")", "}", "}", "}", "rule", ".", "selectors", "=", "rule", ".", "selectors", ".", "map", "(", "applyPseudoClasses", ")", "}", "return", "rules", ";", "}" ]
Parse a property sheet written in CSS into the intermediate object structure that is passed to the `ts_compile_property_sheet` function.
[ "Parse", "a", "property", "sheet", "written", "in", "CSS", "into", "the", "intermediate", "object", "structure", "that", "is", "passed", "to", "the", "ts_compile_property_sheet", "function", "." ]
44ba293422c8b7f115e57ff247e454d5b66dee9e
https://github.com/tree-sitter/tree-sitter-cli/blob/44ba293422c8b7f115e57ff247e454d5b66dee9e/lib/api/properties.js#L41-L91
train
tree-sitter/tree-sitter-cli
lib/api/properties.js
removeWhitespace
function removeWhitespace(node) { node.value = node.value.filter(node => !isWhitespace(node)) }
javascript
function removeWhitespace(node) { node.value = node.value.filter(node => !isWhitespace(node)) }
[ "function", "removeWhitespace", "(", "node", ")", "{", "node", ".", "value", "=", "node", ".", "value", ".", "filter", "(", "node", "=>", "!", "isWhitespace", "(", "node", ")", ")", "}" ]
Get rid of useless nodes and properties.
[ "Get", "rid", "of", "useless", "nodes", "and", "properties", "." ]
44ba293422c8b7f115e57ff247e454d5b66dee9e
https://github.com/tree-sitter/tree-sitter-cli/blob/44ba293422c8b7f115e57ff247e454d5b66dee9e/lib/api/properties.js#L300-L302
train
MaartenDesnouck/google-apps-script
lib/functions/extensionAndFiletype.js
getExtensionFromFiletype
function getExtensionFromFiletype(filetype, codeExtensions) { let extension; if (filetype === 'HTML') { extension = '.html'; } else if (filetype === 'JSON') { extension = '.json'; } else { extension = codeExtensions[0]; } return extension; }
javascript
function getExtensionFromFiletype(filetype, codeExtensions) { let extension; if (filetype === 'HTML') { extension = '.html'; } else if (filetype === 'JSON') { extension = '.json'; } else { extension = codeExtensions[0]; } return extension; }
[ "function", "getExtensionFromFiletype", "(", "filetype", ",", "codeExtensions", ")", "{", "let", "extension", ";", "if", "(", "filetype", "===", "'HTML'", ")", "{", "extension", "=", "'.html'", ";", "}", "else", "if", "(", "filetype", "===", "'JSON'", ")", "{", "extension", "=", "'.json'", ";", "}", "else", "{", "extension", "=", "codeExtensions", "[", "0", "]", ";", "}", "return", "extension", ";", "}" ]
Get the correct extension from the filetype @param {String} filetype - Filetype we will convert. @param {array} codeExtensions - Array of extensions we should treat as pushable for code files @returns {String} method - The extension matching the filetype.
[ "Get", "the", "correct", "extension", "from", "the", "filetype" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/extensionAndFiletype.js#L12-L23
train
MaartenDesnouck/google-apps-script
lib/functions/extensionAndFiletype.js
isPushable
function isPushable(extension, filename, codeExtensions, ignoreRegexes) { const fullFilename = `${filename}${extension}`; let ignored = false; const filenameAndExtensionIsValid = (codeExtensions && codeExtensions.indexOf(extension) > -1 || extension === '.html' || (extension === '.json' && filename === 'appsscript')); for (const regex of ignoreRegexes) { if (fullFilename.match(regex)) { ignored = true; break; } } return filenameAndExtensionIsValid && !ignored; }
javascript
function isPushable(extension, filename, codeExtensions, ignoreRegexes) { const fullFilename = `${filename}${extension}`; let ignored = false; const filenameAndExtensionIsValid = (codeExtensions && codeExtensions.indexOf(extension) > -1 || extension === '.html' || (extension === '.json' && filename === 'appsscript')); for (const regex of ignoreRegexes) { if (fullFilename.match(regex)) { ignored = true; break; } } return filenameAndExtensionIsValid && !ignored; }
[ "function", "isPushable", "(", "extension", ",", "filename", ",", "codeExtensions", ",", "ignoreRegexes", ")", "{", "const", "fullFilename", "=", "`", "${", "filename", "}", "${", "extension", "}", "`", ";", "let", "ignored", "=", "false", ";", "const", "filenameAndExtensionIsValid", "=", "(", "codeExtensions", "&&", "codeExtensions", ".", "indexOf", "(", "extension", ")", ">", "-", "1", "||", "extension", "===", "'.html'", "||", "(", "extension", "===", "'.json'", "&&", "filename", "===", "'appsscript'", ")", ")", ";", "for", "(", "const", "regex", "of", "ignoreRegexes", ")", "{", "if", "(", "fullFilename", ".", "match", "(", "regex", ")", ")", "{", "ignored", "=", "true", ";", "break", ";", "}", "}", "return", "filenameAndExtensionIsValid", "&&", "!", "ignored", ";", "}" ]
Check if we can push a file to remote @param {String} extension - The extension of the file we are checking @param {String} filename - The name without extension of the file we are checking @param {array} codeExtensions - Array of extensions we should treat as pushable for code files @param {array} ignoreRegexes - Array of regexes we should ignore @returns {boolean} - Boolean whether this file is pushable or not
[ "Check", "if", "we", "can", "push", "a", "file", "to", "remote" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/extensionAndFiletype.js#L53-L68
train
MaartenDesnouck/google-apps-script
lib/functions/checkbox.js
get
function get(color) { const symbols = getSymbols(); let result; if (color === 'green') { result = `[${symbols.check.green}]`; } else if (color === 'red') { result = `[${symbols.cross.red}]`; } else if (color === 'yellow') { result = `[${symbols.check.yellow}]`; } return result; }
javascript
function get(color) { const symbols = getSymbols(); let result; if (color === 'green') { result = `[${symbols.check.green}]`; } else if (color === 'red') { result = `[${symbols.cross.red}]`; } else if (color === 'yellow') { result = `[${symbols.check.yellow}]`; } return result; }
[ "function", "get", "(", "color", ")", "{", "const", "symbols", "=", "getSymbols", "(", ")", ";", "let", "result", ";", "if", "(", "color", "===", "'green'", ")", "{", "result", "=", "`", "${", "symbols", ".", "check", ".", "green", "}", "`", ";", "}", "else", "if", "(", "color", "===", "'red'", ")", "{", "result", "=", "`", "${", "symbols", ".", "cross", ".", "red", "}", "`", ";", "}", "else", "if", "(", "color", "===", "'yellow'", ")", "{", "result", "=", "`", "${", "symbols", ".", "check", ".", "yellow", "}", "`", ";", "}", "return", "result", ";", "}" ]
Get a checkbox @param {String} color - Identifier of the type of checkbox you want to print @returns {void}
[ "Get", "a", "checkbox" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/checkbox.js#L27-L38
train
MaartenDesnouck/google-apps-script
lib/functions/createFile.js
createFile
function createFile(file) { fs.ensureFileSync(file.name); fs.writeFileSync(file.name, file.source); return; }
javascript
function createFile(file) { fs.ensureFileSync(file.name); fs.writeFileSync(file.name, file.source); return; }
[ "function", "createFile", "(", "file", ")", "{", "fs", ".", "ensureFileSync", "(", "file", ".", "name", ")", ";", "fs", ".", "writeFileSync", "(", "file", ".", "name", ",", "file", ".", "source", ")", ";", "return", ";", "}" ]
Synch create file and necessary folders @param {Object} file - File to create. @returns {void}
[ "Synch", "create", "file", "and", "necessary", "folders" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/createFile.js#L9-L13
train
MaartenDesnouck/google-apps-script
lib/functions/getMetadata.js
getMetadata
async function getMetadata(auth, identifier) { // Try to get info assuming identifier is an id const metadata = await new Promise((resolve, reject) => { const script = google.script('v1'); script.projects.get({ auth, scriptId: identifier, }, (err, result) => { if (err) { resolve(false); } else { resolve(result.data); } return; }); }); if (metadata) { return { projectId: metadata.scriptId, name: metadata.title, createTime: metadata.createTime, updateTime: metadata.updateTime, creator: { name: metadata.creator.name, email: metadata.creator.email, }, }; } // Identifier did not match an id const files = await getScripts(auth, identifier, null, []); if (files.length === 0) { // 0 results throw { message: `No remote project with name or id '${identifier}' found ${checkbox.get('red')}\n` + `Use 'gas get projects' to show all your remote Google Apps Script projects`, print: true, }; } else if (files.length === 1) { // 1 result const result = files[0]; if (result.name === identifier) { result.name = sanitize(result.name); return { projectId: result.id, name: result.name, createTime: result.createdTime, updateTime: result.modifiedTime, creator: { name: '', email: '', }, }; } else { // Check for exact match if exists throw { message: `No exact match with name or id '${identifier}' found ${checkbox.get('red')}\n` + `Did you perhaps mean: '${result.name}'?`, print: true, }; } } else { // More than 1 result const exactMatches = []; for (const match of files) { if (match.name === identifier) { exactMatches.push(match); } } if (exactMatches.length === 0) { // 0 results let message = `No project called '${identifier}' found ${checkbox.get('red')}\n`; message += 'Did you mean one of these projects? :\n'; for (const file2 of files) { message += `[${file2.id}] ${file2.name}\n`; } const err = { message, print: true, }; } else if (exactMatches.length === 1) { // 1 result exactMatches[0].name = sanitize(exactMatches[0].name); return { projectId: exactMatches[0].id, name: exactMatches[0].name, createTime: exactMatches[0].createdTime, updateTime: exactMatches[0].lastModifiedAt, creator: { name: '', email: '', }, }; } else { let message = `Multiple projects called '${identifier}' found ${checkbox.get('red')}\n`; message += `Use 'gas rename <projectId> <newProjectName>' to rename script so they have a unique name or use the projectId as identifier\n\n`; for (const exactMatch of exactMatches) { message += `[${exactMatch.id}] ${exactMatch.name}\n`; } throw { message, print: true, }; } } }
javascript
async function getMetadata(auth, identifier) { // Try to get info assuming identifier is an id const metadata = await new Promise((resolve, reject) => { const script = google.script('v1'); script.projects.get({ auth, scriptId: identifier, }, (err, result) => { if (err) { resolve(false); } else { resolve(result.data); } return; }); }); if (metadata) { return { projectId: metadata.scriptId, name: metadata.title, createTime: metadata.createTime, updateTime: metadata.updateTime, creator: { name: metadata.creator.name, email: metadata.creator.email, }, }; } // Identifier did not match an id const files = await getScripts(auth, identifier, null, []); if (files.length === 0) { // 0 results throw { message: `No remote project with name or id '${identifier}' found ${checkbox.get('red')}\n` + `Use 'gas get projects' to show all your remote Google Apps Script projects`, print: true, }; } else if (files.length === 1) { // 1 result const result = files[0]; if (result.name === identifier) { result.name = sanitize(result.name); return { projectId: result.id, name: result.name, createTime: result.createdTime, updateTime: result.modifiedTime, creator: { name: '', email: '', }, }; } else { // Check for exact match if exists throw { message: `No exact match with name or id '${identifier}' found ${checkbox.get('red')}\n` + `Did you perhaps mean: '${result.name}'?`, print: true, }; } } else { // More than 1 result const exactMatches = []; for (const match of files) { if (match.name === identifier) { exactMatches.push(match); } } if (exactMatches.length === 0) { // 0 results let message = `No project called '${identifier}' found ${checkbox.get('red')}\n`; message += 'Did you mean one of these projects? :\n'; for (const file2 of files) { message += `[${file2.id}] ${file2.name}\n`; } const err = { message, print: true, }; } else if (exactMatches.length === 1) { // 1 result exactMatches[0].name = sanitize(exactMatches[0].name); return { projectId: exactMatches[0].id, name: exactMatches[0].name, createTime: exactMatches[0].createdTime, updateTime: exactMatches[0].lastModifiedAt, creator: { name: '', email: '', }, }; } else { let message = `Multiple projects called '${identifier}' found ${checkbox.get('red')}\n`; message += `Use 'gas rename <projectId> <newProjectName>' to rename script so they have a unique name or use the projectId as identifier\n\n`; for (const exactMatch of exactMatches) { message += `[${exactMatch.id}] ${exactMatch.name}\n`; } throw { message, print: true, }; } } }
[ "async", "function", "getMetadata", "(", "auth", ",", "identifier", ")", "{", "const", "metadata", "=", "await", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "script", "=", "google", ".", "script", "(", "'v1'", ")", ";", "script", ".", "projects", ".", "get", "(", "{", "auth", ",", "scriptId", ":", "identifier", ",", "}", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "{", "resolve", "(", "false", ")", ";", "}", "else", "{", "resolve", "(", "result", ".", "data", ")", ";", "}", "return", ";", "}", ")", ";", "}", ")", ";", "if", "(", "metadata", ")", "{", "return", "{", "projectId", ":", "metadata", ".", "scriptId", ",", "name", ":", "metadata", ".", "title", ",", "createTime", ":", "metadata", ".", "createTime", ",", "updateTime", ":", "metadata", ".", "updateTime", ",", "creator", ":", "{", "name", ":", "metadata", ".", "creator", ".", "name", ",", "email", ":", "metadata", ".", "creator", ".", "email", ",", "}", ",", "}", ";", "}", "const", "files", "=", "await", "getScripts", "(", "auth", ",", "identifier", ",", "null", ",", "[", "]", ")", ";", "if", "(", "files", ".", "length", "===", "0", ")", "{", "throw", "{", "message", ":", "`", "${", "identifier", "}", "${", "checkbox", ".", "get", "(", "'red'", ")", "}", "\\n", "`", "+", "`", "`", ",", "print", ":", "true", ",", "}", ";", "}", "else", "if", "(", "files", ".", "length", "===", "1", ")", "{", "const", "result", "=", "files", "[", "0", "]", ";", "if", "(", "result", ".", "name", "===", "identifier", ")", "{", "result", ".", "name", "=", "sanitize", "(", "result", ".", "name", ")", ";", "return", "{", "projectId", ":", "result", ".", "id", ",", "name", ":", "result", ".", "name", ",", "createTime", ":", "result", ".", "createdTime", ",", "updateTime", ":", "result", ".", "modifiedTime", ",", "creator", ":", "{", "name", ":", "''", ",", "email", ":", "''", ",", "}", ",", "}", ";", "}", "else", "{", "throw", "{", "message", ":", "`", "${", "identifier", "}", "${", "checkbox", ".", "get", "(", "'red'", ")", "}", "\\n", "`", "+", "`", "${", "result", ".", "name", "}", "`", ",", "print", ":", "true", ",", "}", ";", "}", "}", "else", "{", "const", "exactMatches", "=", "[", "]", ";", "for", "(", "const", "match", "of", "files", ")", "{", "if", "(", "match", ".", "name", "===", "identifier", ")", "{", "exactMatches", ".", "push", "(", "match", ")", ";", "}", "}", "if", "(", "exactMatches", ".", "length", "===", "0", ")", "{", "let", "message", "=", "`", "${", "identifier", "}", "${", "checkbox", ".", "get", "(", "'red'", ")", "}", "\\n", "`", ";", "message", "+=", "'Did you mean one of these projects? :\\n'", ";", "\\n", "for", "(", "const", "file2", "of", "files", ")", "{", "message", "+=", "`", "${", "file2", ".", "id", "}", "${", "file2", ".", "name", "}", "\\n", "`", ";", "}", "}", "else", "const", "err", "=", "{", "message", ",", "print", ":", "true", ",", "}", ";", "}", "}" ]
Get the metadata of a file with a given id @param {google.auth.OAuth2} auth - An authorized OAuth2 client. @param {String} identifier - Identifier we want to get data from, could be id or a name. @returns {Object} - metadata of the project
[ "Get", "the", "metadata", "of", "a", "file", "with", "a", "given", "id" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/getMetadata.js#L15-L116
train
pugjs/then-pug
packages/pug-parser/index.js
Parser
function Parser(tokens, options) { options = options || {}; if (!Array.isArray(tokens)) { throw new Error('Expected tokens to be an Array but got "' + (typeof tokens) + '"'); } if (typeof options !== 'object') { throw new Error('Expected "options" to be an object but got "' + (typeof options) + '"'); } this.tokens = new TokenStream(tokens); this.filename = options.filename; this.src = options.src; this.inMixin = 0; this.plugins = options.plugins || []; }
javascript
function Parser(tokens, options) { options = options || {}; if (!Array.isArray(tokens)) { throw new Error('Expected tokens to be an Array but got "' + (typeof tokens) + '"'); } if (typeof options !== 'object') { throw new Error('Expected "options" to be an object but got "' + (typeof options) + '"'); } this.tokens = new TokenStream(tokens); this.filename = options.filename; this.src = options.src; this.inMixin = 0; this.plugins = options.plugins || []; }
[ "function", "Parser", "(", "tokens", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "Array", ".", "isArray", "(", "tokens", ")", ")", "{", "throw", "new", "Error", "(", "'Expected tokens to be an Array but got \"'", "+", "(", "typeof", "tokens", ")", "+", "'\"'", ")", ";", "}", "if", "(", "typeof", "options", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'Expected \"options\" to be an object but got \"'", "+", "(", "typeof", "options", ")", "+", "'\"'", ")", ";", "}", "this", ".", "tokens", "=", "new", "TokenStream", "(", "tokens", ")", ";", "this", ".", "filename", "=", "options", ".", "filename", ";", "this", ".", "src", "=", "options", ".", "src", ";", "this", ".", "inMixin", "=", "0", ";", "this", ".", "plugins", "=", "options", ".", "plugins", "||", "[", "]", ";", "}" ]
Initialize `Parser` with the given input `str` and `filename`. @param {String} str @param {String} filename @param {Object} options @api public
[ "Initialize", "Parser", "with", "the", "given", "input", "str", "and", "filename", "." ]
a96c2a9c6d1f0875aef4641064500f818f7e7571
https://github.com/pugjs/then-pug/blob/a96c2a9c6d1f0875aef4641064500f818f7e7571/packages/pug-parser/index.js#L25-L38
train
pugjs/then-pug
packages/pug-parser/index.js
function(type){ if (this.peek().type === type) { return this.advance(); } else { this.error('INVALID_TOKEN', 'expected "' + type + '", but got "' + this.peek().type + '"', this.peek()); } }
javascript
function(type){ if (this.peek().type === type) { return this.advance(); } else { this.error('INVALID_TOKEN', 'expected "' + type + '", but got "' + this.peek().type + '"', this.peek()); } }
[ "function", "(", "type", ")", "{", "if", "(", "this", ".", "peek", "(", ")", ".", "type", "===", "type", ")", "{", "return", "this", ".", "advance", "(", ")", ";", "}", "else", "{", "this", ".", "error", "(", "'INVALID_TOKEN'", ",", "'expected \"'", "+", "type", "+", "'\", but got \"'", "+", "this", ".", "peek", "(", ")", ".", "type", "+", "'\"'", ",", "this", ".", "peek", "(", ")", ")", ";", "}", "}" ]
Expect the given type, or throw an exception. @param {String} type @api private
[ "Expect", "the", "given", "type", "or", "throw", "an", "exception", "." ]
a96c2a9c6d1f0875aef4641064500f818f7e7571
https://github.com/pugjs/then-pug/blob/a96c2a9c6d1f0875aef4641064500f818f7e7571/packages/pug-parser/index.js#L133-L139
train
pugjs/then-pug
packages/pug-parser/index.js
function(){ var tok = this.expect('call'); var name = tok.val; var args = tok.args; var mixin = { type: 'Mixin', name: name, args: args, block: this.emptyBlock(tok.loc.start.line), call: true, attrs: [], attributeBlocks: [], line: tok.loc.start.line, column: tok.loc.start.column, filename: this.filename }; this.tag(mixin); if (mixin.code) { mixin.block.nodes.push(mixin.code); delete mixin.code; } if (mixin.block.nodes.length === 0) mixin.block = null; return mixin; }
javascript
function(){ var tok = this.expect('call'); var name = tok.val; var args = tok.args; var mixin = { type: 'Mixin', name: name, args: args, block: this.emptyBlock(tok.loc.start.line), call: true, attrs: [], attributeBlocks: [], line: tok.loc.start.line, column: tok.loc.start.column, filename: this.filename }; this.tag(mixin); if (mixin.code) { mixin.block.nodes.push(mixin.code); delete mixin.code; } if (mixin.block.nodes.length === 0) mixin.block = null; return mixin; }
[ "function", "(", ")", "{", "var", "tok", "=", "this", ".", "expect", "(", "'call'", ")", ";", "var", "name", "=", "tok", ".", "val", ";", "var", "args", "=", "tok", ".", "args", ";", "var", "mixin", "=", "{", "type", ":", "'Mixin'", ",", "name", ":", "name", ",", "args", ":", "args", ",", "block", ":", "this", ".", "emptyBlock", "(", "tok", ".", "loc", ".", "start", ".", "line", ")", ",", "call", ":", "true", ",", "attrs", ":", "[", "]", ",", "attributeBlocks", ":", "[", "]", ",", "line", ":", "tok", ".", "loc", ".", "start", ".", "line", ",", "column", ":", "tok", ".", "loc", ".", "start", ".", "column", ",", "filename", ":", "this", ".", "filename", "}", ";", "this", ".", "tag", "(", "mixin", ")", ";", "if", "(", "mixin", ".", "code", ")", "{", "mixin", ".", "block", ".", "nodes", ".", "push", "(", "mixin", ".", "code", ")", ";", "delete", "mixin", ".", "code", ";", "}", "if", "(", "mixin", ".", "block", ".", "nodes", ".", "length", "===", "0", ")", "mixin", ".", "block", "=", "null", ";", "return", "mixin", ";", "}" ]
call ident block
[ "call", "ident", "block" ]
a96c2a9c6d1f0875aef4641064500f818f7e7571
https://github.com/pugjs/then-pug/blob/a96c2a9c6d1f0875aef4641064500f818f7e7571/packages/pug-parser/index.js#L874-L898
train
MaartenDesnouck/google-apps-script
lib/functions/triageGoogleError.js
triageGoogleError
async function triageGoogleError(err, origin) { // console.log(err); const triaged = { err, origin, print: true, }; if (err && err.code === 401) { triaged.message = `Your credentials appear to be invalid.\nRun 'gas auth -f' to re-authenticate.`; triaged.extraInfo = `Invalid Credentials`; } else if (err === `Error: invalid_grant`) { triaged.message = `Your credentials appear to be invalid.\nRun 'gas auth -f' to re-authenticate.`; triaged.extraInfo = `Invalid Grant`; } else if (err && err.code === 403) { triaged.message = err.message; triaged.extraInfo = `Not allowed`; } else if (err && err.code === 404) { triaged.message = err.message; triaged.extraInfo = `Not found`; } else if (err && err.code === `ENOTFOUND`) { triaged.message = `Can't seem to reach the Google servers.`; triaged.extraInfo = `No connection`; } else if (err && err.code === `ECONNRESET`) { triaged.message = `Unexpected closed connection.`; triaged.extraInfo = `Closed connection`; } else if (err && err.code === 400 && origin === 'pushToRemote') { const projectRoot = await findInProject('.', constants.META_DIR); if (projectRoot.found) { // Find syntax errors in all files const files = getAllFiles(projectRoot.folder, '.', []); const syntaxErrors = []; for (const file of files) { const extension = path.parse(file).ext; if (extension === '.js' || extension === '.gs') { const src = fs.readFileSync(path.join(projectRoot.folder, file)); const syntaxErr = check(src, file); if (syntaxErr) { syntaxErrors.push(syntaxErr); } } } // Create a message with a summary of found syntax errors if (syntaxErrors.length > 0) { let message = `The code you are trying to push appears to have 1 or more syntax error(s).`; for (const err of syntaxErrors) { message += `-------------------------------------------------------------------------------------------------\n`; message += `${err}\n`; } triaged.extraInfo = `${syntaxErrors}`; } else { triaged.message = `Google doesn't accept the code you are trying to push. Try doublechecking for project structure errors.`; triaged.extraInfo = `No syntax errors`; } } else { triaged.message = `Google doesn't accept the code you are trying to push. Try doublechecking for project structure errors.`; triaged.extraInfo = `No .gas folder found`; } } else if (err) { triaged.message = (`gas returned an error: ${err}`); triaged.extraInfo = `Not a known error`; } else { triaged.message = (`O-oh. Something seems to have gone wrong.`); triaged.extraInfo = `No error passed to the function`; } return triaged; }
javascript
async function triageGoogleError(err, origin) { // console.log(err); const triaged = { err, origin, print: true, }; if (err && err.code === 401) { triaged.message = `Your credentials appear to be invalid.\nRun 'gas auth -f' to re-authenticate.`; triaged.extraInfo = `Invalid Credentials`; } else if (err === `Error: invalid_grant`) { triaged.message = `Your credentials appear to be invalid.\nRun 'gas auth -f' to re-authenticate.`; triaged.extraInfo = `Invalid Grant`; } else if (err && err.code === 403) { triaged.message = err.message; triaged.extraInfo = `Not allowed`; } else if (err && err.code === 404) { triaged.message = err.message; triaged.extraInfo = `Not found`; } else if (err && err.code === `ENOTFOUND`) { triaged.message = `Can't seem to reach the Google servers.`; triaged.extraInfo = `No connection`; } else if (err && err.code === `ECONNRESET`) { triaged.message = `Unexpected closed connection.`; triaged.extraInfo = `Closed connection`; } else if (err && err.code === 400 && origin === 'pushToRemote') { const projectRoot = await findInProject('.', constants.META_DIR); if (projectRoot.found) { // Find syntax errors in all files const files = getAllFiles(projectRoot.folder, '.', []); const syntaxErrors = []; for (const file of files) { const extension = path.parse(file).ext; if (extension === '.js' || extension === '.gs') { const src = fs.readFileSync(path.join(projectRoot.folder, file)); const syntaxErr = check(src, file); if (syntaxErr) { syntaxErrors.push(syntaxErr); } } } // Create a message with a summary of found syntax errors if (syntaxErrors.length > 0) { let message = `The code you are trying to push appears to have 1 or more syntax error(s).`; for (const err of syntaxErrors) { message += `-------------------------------------------------------------------------------------------------\n`; message += `${err}\n`; } triaged.extraInfo = `${syntaxErrors}`; } else { triaged.message = `Google doesn't accept the code you are trying to push. Try doublechecking for project structure errors.`; triaged.extraInfo = `No syntax errors`; } } else { triaged.message = `Google doesn't accept the code you are trying to push. Try doublechecking for project structure errors.`; triaged.extraInfo = `No .gas folder found`; } } else if (err) { triaged.message = (`gas returned an error: ${err}`); triaged.extraInfo = `Not a known error`; } else { triaged.message = (`O-oh. Something seems to have gone wrong.`); triaged.extraInfo = `No error passed to the function`; } return triaged; }
[ "async", "function", "triageGoogleError", "(", "err", ",", "origin", ")", "{", "const", "triaged", "=", "{", "err", ",", "origin", ",", "print", ":", "true", ",", "}", ";", "if", "(", "err", "&&", "err", ".", "code", "===", "401", ")", "{", "triaged", ".", "message", "=", "`", "\\n", "`", ";", "triaged", ".", "extraInfo", "=", "`", "`", ";", "}", "else", "if", "(", "err", "===", "`", "`", ")", "{", "triaged", ".", "message", "=", "`", "\\n", "`", ";", "triaged", ".", "extraInfo", "=", "`", "`", ";", "}", "else", "if", "(", "err", "&&", "err", ".", "code", "===", "403", ")", "{", "triaged", ".", "message", "=", "err", ".", "message", ";", "triaged", ".", "extraInfo", "=", "`", "`", ";", "}", "else", "if", "(", "err", "&&", "err", ".", "code", "===", "404", ")", "{", "triaged", ".", "message", "=", "err", ".", "message", ";", "triaged", ".", "extraInfo", "=", "`", "`", ";", "}", "else", "if", "(", "err", "&&", "err", ".", "code", "===", "`", "`", ")", "{", "triaged", ".", "message", "=", "`", "`", ";", "triaged", ".", "extraInfo", "=", "`", "`", ";", "}", "else", "if", "(", "err", "&&", "err", ".", "code", "===", "`", "`", ")", "{", "triaged", ".", "message", "=", "`", "`", ";", "triaged", ".", "extraInfo", "=", "`", "`", ";", "}", "else", "if", "(", "err", "&&", "err", ".", "code", "===", "400", "&&", "origin", "===", "'pushToRemote'", ")", "{", "const", "projectRoot", "=", "await", "findInProject", "(", "'.'", ",", "constants", ".", "META_DIR", ")", ";", "if", "(", "projectRoot", ".", "found", ")", "{", "const", "files", "=", "getAllFiles", "(", "projectRoot", ".", "folder", ",", "'.'", ",", "[", "]", ")", ";", "const", "syntaxErrors", "=", "[", "]", ";", "for", "(", "const", "file", "of", "files", ")", "{", "const", "extension", "=", "path", ".", "parse", "(", "file", ")", ".", "ext", ";", "if", "(", "extension", "===", "'.js'", "||", "extension", "===", "'.gs'", ")", "{", "const", "src", "=", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "projectRoot", ".", "folder", ",", "file", ")", ")", ";", "const", "syntaxErr", "=", "check", "(", "src", ",", "file", ")", ";", "if", "(", "syntaxErr", ")", "{", "syntaxErrors", ".", "push", "(", "syntaxErr", ")", ";", "}", "}", "}", "if", "(", "syntaxErrors", ".", "length", ">", "0", ")", "{", "let", "message", "=", "`", "`", ";", "for", "(", "const", "err", "of", "syntaxErrors", ")", "{", "message", "+=", "`", "\\n", "`", ";", "message", "+=", "`", "${", "err", "}", "\\n", "`", ";", "}", "triaged", ".", "extraInfo", "=", "`", "${", "syntaxErrors", "}", "`", ";", "}", "else", "{", "triaged", ".", "message", "=", "`", "`", ";", "triaged", ".", "extraInfo", "=", "`", "`", ";", "}", "}", "else", "{", "triaged", ".", "message", "=", "`", "`", ";", "triaged", ".", "extraInfo", "=", "`", "`", ";", "}", "}", "else", "if", "(", "err", ")", "{", "triaged", ".", "message", "=", "(", "`", "${", "err", "}", "`", ")", ";", "triaged", ".", "extraInfo", "=", "`", "`", ";", "}", "else", "{", "triaged", ".", "message", "=", "(", "`", "`", ")", ";", "triaged", ".", "extraInfo", "=", "`", "`", ";", "}", "return", "triaged", ";", "}" ]
Triage Google error @param {Object} err - The error to triage. @param {String} origin - Origin of the error @returns {Object} - Object with the error and extra info after triage
[ "Triage", "Google", "error" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/triageGoogleError.js#L15-L83
train
MaartenDesnouck/google-apps-script
lib/functions/downloadDependencies.js
processSource
function processSource(code, dependencyList, depedencyName) { // Replace function declarations const packageName = dependencyList[depedencyName].packageName; code = code.replace(/(\s*)function\s([A-z]*)\s*\(*/g, `$1function ${packageName}_$2(`); // TODO replace function calls to dependencies const dependencies = dependencyList[depedencyName].dependencies; if (dependencies) { for (const dependency of Reflect.ownKeys(dependencies)) { const oldPrefix = dependencyList[dependency].packageName; console.log(oldPrefix); var re = new RegExp(`[ ]*${oldPrefix}_([A-z]*)[ ]*\\(`, "g"); code = code.replace(re, ` ${dependency}_$1(`); } } return code; }
javascript
function processSource(code, dependencyList, depedencyName) { // Replace function declarations const packageName = dependencyList[depedencyName].packageName; code = code.replace(/(\s*)function\s([A-z]*)\s*\(*/g, `$1function ${packageName}_$2(`); // TODO replace function calls to dependencies const dependencies = dependencyList[depedencyName].dependencies; if (dependencies) { for (const dependency of Reflect.ownKeys(dependencies)) { const oldPrefix = dependencyList[dependency].packageName; console.log(oldPrefix); var re = new RegExp(`[ ]*${oldPrefix}_([A-z]*)[ ]*\\(`, "g"); code = code.replace(re, ` ${dependency}_$1(`); } } return code; }
[ "function", "processSource", "(", "code", ",", "dependencyList", ",", "depedencyName", ")", "{", "const", "packageName", "=", "dependencyList", "[", "depedencyName", "]", ".", "packageName", ";", "code", "=", "code", ".", "replace", "(", "/", "(\\s*)function\\s([A-z]*)\\s*\\(*", "/", "g", ",", "`", "${", "packageName", "}", "`", ")", ";", "const", "dependencies", "=", "dependencyList", "[", "depedencyName", "]", ".", "dependencies", ";", "if", "(", "dependencies", ")", "{", "for", "(", "const", "dependency", "of", "Reflect", ".", "ownKeys", "(", "dependencies", ")", ")", "{", "const", "oldPrefix", "=", "dependencyList", "[", "dependency", "]", ".", "packageName", ";", "console", ".", "log", "(", "oldPrefix", ")", ";", "var", "re", "=", "new", "RegExp", "(", "`", "${", "oldPrefix", "}", "\\\\", "`", ",", "\"g\"", ")", ";", "code", "=", "code", ".", "replace", "(", "re", ",", "`", "${", "dependency", "}", "`", ")", ";", "}", "}", "return", "code", ";", "}" ]
Process all function declarations and calls to use the libraries @param {String} code - Code to process @param {Object} dependencyList - all dependencies @param {String} depedencyName - name of the dependency @returns {String} Processed code
[ "Process", "all", "function", "declarations", "and", "calls", "to", "use", "the", "libraries" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/downloadDependencies.js#L17-L33
train
MaartenDesnouck/google-apps-script
lib/functions/downloadDependencies.js
downloadDependencies
async function downloadDependencies(rootFolder, dependencyList) { const includeFolder = path.join(rootFolder, constants.INCLUDE_DIR); fs.removeSync(includeFolder); const contentPath = path.join(includeFolder, 'content.json'); // Create new content.json createFile({ name: contentPath, source: JSON.stringify(dependencyList), }); // Extensions const extensions = eaft.getCodeExtensions(); // Download new dependencies for (const dependency of Reflect.ownKeys(dependencyList)) { const dependencies = dependencyList[dependency].dependencies; const package = dependencyList[dependency].packageName; const version = dependencyList[dependency].version; const isRootDependency = dependencyList[dependency].isRootDependency; // Use package name as dependency if it is a root dependency let dependencyName; if (isRootDependency) { dependencyName = package; } else { dependencyName = dependency; } const packagePath = path.join(includeFolder, dependencyName); // Get library code url = `${constants.FIREBASE_DATABASE_URL}/package/${package}/version/${version}/code.json`; const library = await request({ url, method: "GET", json: true, headers: { "content-type": "application/json", }, }); // Write library files for (const file of library.files) { const extension = eaft.getExtensionFromFiletype(file.type, extensions); const fileName = `${file.name}${extension}`; const source = processSource(file.source, dependencyList, dependency); createFile({ name: path.join(packagePath, fileName), source, }); } } }
javascript
async function downloadDependencies(rootFolder, dependencyList) { const includeFolder = path.join(rootFolder, constants.INCLUDE_DIR); fs.removeSync(includeFolder); const contentPath = path.join(includeFolder, 'content.json'); // Create new content.json createFile({ name: contentPath, source: JSON.stringify(dependencyList), }); // Extensions const extensions = eaft.getCodeExtensions(); // Download new dependencies for (const dependency of Reflect.ownKeys(dependencyList)) { const dependencies = dependencyList[dependency].dependencies; const package = dependencyList[dependency].packageName; const version = dependencyList[dependency].version; const isRootDependency = dependencyList[dependency].isRootDependency; // Use package name as dependency if it is a root dependency let dependencyName; if (isRootDependency) { dependencyName = package; } else { dependencyName = dependency; } const packagePath = path.join(includeFolder, dependencyName); // Get library code url = `${constants.FIREBASE_DATABASE_URL}/package/${package}/version/${version}/code.json`; const library = await request({ url, method: "GET", json: true, headers: { "content-type": "application/json", }, }); // Write library files for (const file of library.files) { const extension = eaft.getExtensionFromFiletype(file.type, extensions); const fileName = `${file.name}${extension}`; const source = processSource(file.source, dependencyList, dependency); createFile({ name: path.join(packagePath, fileName), source, }); } } }
[ "async", "function", "downloadDependencies", "(", "rootFolder", ",", "dependencyList", ")", "{", "const", "includeFolder", "=", "path", ".", "join", "(", "rootFolder", ",", "constants", ".", "INCLUDE_DIR", ")", ";", "fs", ".", "removeSync", "(", "includeFolder", ")", ";", "const", "contentPath", "=", "path", ".", "join", "(", "includeFolder", ",", "'content.json'", ")", ";", "createFile", "(", "{", "name", ":", "contentPath", ",", "source", ":", "JSON", ".", "stringify", "(", "dependencyList", ")", ",", "}", ")", ";", "const", "extensions", "=", "eaft", ".", "getCodeExtensions", "(", ")", ";", "for", "(", "const", "dependency", "of", "Reflect", ".", "ownKeys", "(", "dependencyList", ")", ")", "{", "const", "dependencies", "=", "dependencyList", "[", "dependency", "]", ".", "dependencies", ";", "const", "package", "=", "dependencyList", "[", "dependency", "]", ".", "packageName", ";", "const", "version", "=", "dependencyList", "[", "dependency", "]", ".", "version", ";", "const", "isRootDependency", "=", "dependencyList", "[", "dependency", "]", ".", "isRootDependency", ";", "let", "dependencyName", ";", "if", "(", "isRootDependency", ")", "{", "dependencyName", "=", "package", ";", "}", "else", "{", "dependencyName", "=", "dependency", ";", "}", "const", "packagePath", "=", "path", ".", "join", "(", "includeFolder", ",", "dependencyName", ")", ";", "url", "=", "`", "${", "constants", ".", "FIREBASE_DATABASE_URL", "}", "${", "package", "}", "${", "version", "}", "`", ";", "const", "library", "=", "await", "request", "(", "{", "url", ",", "method", ":", "\"GET\"", ",", "json", ":", "true", ",", "headers", ":", "{", "\"content-type\"", ":", "\"application/json\"", ",", "}", ",", "}", ")", ";", "for", "(", "const", "file", "of", "library", ".", "files", ")", "{", "const", "extension", "=", "eaft", ".", "getExtensionFromFiletype", "(", "file", ".", "type", ",", "extensions", ")", ";", "const", "fileName", "=", "`", "${", "file", ".", "name", "}", "${", "extension", "}", "`", ";", "const", "source", "=", "processSource", "(", "file", ".", "source", ",", "dependencyList", ",", "dependency", ")", ";", "createFile", "(", "{", "name", ":", "path", ".", "join", "(", "packagePath", ",", "fileName", ")", ",", "source", ",", "}", ")", ";", "}", "}", "}" ]
Download all necessary dependencies @param {String} rootFolder - Folder where we will create the gas-include folder @param {Object} dependencyList - List of exact dependencies that we need to download @returns {void}
[ "Download", "all", "necessary", "dependencies" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/downloadDependencies.js#L42-L94
train
MaartenDesnouck/google-apps-script
lib/functions/saveDependencies.js
saveDependencies
async function saveDependencies(dependency, includeFile, projectRoot) { let gasInclude = {}; if (includeFile.found) { gasInclude = fs.readJsonSync(path.join(includeFile.folder, constants.INCLUDE_FILE)); } else if (projectRoot.found) { includeFile.folder = projectRoot.folder; } else { includeFile.folder = '.'; } if (!gasInclude.dependencies) { gasInclude.dependencies = {}; } const url = `${constants.FIREBASE_DATABASE_URL}/package/${dependency}/versions.json`; const versions = await request({ url, method: "GET", json: true, headers: { "content-type": "application/json", }, }); if (versions) { // Get highest version let maxVersion = '0.0.0'; for (const version of Reflect.ownKeys(versions)) { const newVersion = version.replace(/_/g, '.'); if (semver.gt(newVersion, maxVersion)) { maxVersion = newVersion; } } gasInclude.dependencies[dependency] = `^${maxVersion}`; createFile({ name: path.join(includeFile.folder, constants.INCLUDE_FILE), source: JSON.stringify(gasInclude), }); return includeFile.folder; } else { throw { message: `Can't seem to find '${dependency}' in gas-include. Please double check your input.`, print: true, }; } }
javascript
async function saveDependencies(dependency, includeFile, projectRoot) { let gasInclude = {}; if (includeFile.found) { gasInclude = fs.readJsonSync(path.join(includeFile.folder, constants.INCLUDE_FILE)); } else if (projectRoot.found) { includeFile.folder = projectRoot.folder; } else { includeFile.folder = '.'; } if (!gasInclude.dependencies) { gasInclude.dependencies = {}; } const url = `${constants.FIREBASE_DATABASE_URL}/package/${dependency}/versions.json`; const versions = await request({ url, method: "GET", json: true, headers: { "content-type": "application/json", }, }); if (versions) { // Get highest version let maxVersion = '0.0.0'; for (const version of Reflect.ownKeys(versions)) { const newVersion = version.replace(/_/g, '.'); if (semver.gt(newVersion, maxVersion)) { maxVersion = newVersion; } } gasInclude.dependencies[dependency] = `^${maxVersion}`; createFile({ name: path.join(includeFile.folder, constants.INCLUDE_FILE), source: JSON.stringify(gasInclude), }); return includeFile.folder; } else { throw { message: `Can't seem to find '${dependency}' in gas-include. Please double check your input.`, print: true, }; } }
[ "async", "function", "saveDependencies", "(", "dependency", ",", "includeFile", ",", "projectRoot", ")", "{", "let", "gasInclude", "=", "{", "}", ";", "if", "(", "includeFile", ".", "found", ")", "{", "gasInclude", "=", "fs", ".", "readJsonSync", "(", "path", ".", "join", "(", "includeFile", ".", "folder", ",", "constants", ".", "INCLUDE_FILE", ")", ")", ";", "}", "else", "if", "(", "projectRoot", ".", "found", ")", "{", "includeFile", ".", "folder", "=", "projectRoot", ".", "folder", ";", "}", "else", "{", "includeFile", ".", "folder", "=", "'.'", ";", "}", "if", "(", "!", "gasInclude", ".", "dependencies", ")", "{", "gasInclude", ".", "dependencies", "=", "{", "}", ";", "}", "const", "url", "=", "`", "${", "constants", ".", "FIREBASE_DATABASE_URL", "}", "${", "dependency", "}", "`", ";", "const", "versions", "=", "await", "request", "(", "{", "url", ",", "method", ":", "\"GET\"", ",", "json", ":", "true", ",", "headers", ":", "{", "\"content-type\"", ":", "\"application/json\"", ",", "}", ",", "}", ")", ";", "if", "(", "versions", ")", "{", "let", "maxVersion", "=", "'0.0.0'", ";", "for", "(", "const", "version", "of", "Reflect", ".", "ownKeys", "(", "versions", ")", ")", "{", "const", "newVersion", "=", "version", ".", "replace", "(", "/", "_", "/", "g", ",", "'.'", ")", ";", "if", "(", "semver", ".", "gt", "(", "newVersion", ",", "maxVersion", ")", ")", "{", "maxVersion", "=", "newVersion", ";", "}", "}", "gasInclude", ".", "dependencies", "[", "dependency", "]", "=", "`", "${", "maxVersion", "}", "`", ";", "createFile", "(", "{", "name", ":", "path", ".", "join", "(", "includeFile", ".", "folder", ",", "constants", ".", "INCLUDE_FILE", ")", ",", "source", ":", "JSON", ".", "stringify", "(", "gasInclude", ")", ",", "}", ")", ";", "return", "includeFile", ".", "folder", ";", "}", "else", "{", "throw", "{", "message", ":", "`", "${", "dependency", "}", "`", ",", "print", ":", "true", ",", "}", ";", "}", "}" ]
Save a dependency to the gas-include file @param {Object} dependency - Dedendencies to save @param {Object} includeFile - Object indicating if and where the include file is @param {Object} projectRoot - Object indicating if and where the .gas dir is @returns {string} - FolderPath where we have stored the gas-inlcude.json file
[ "Save", "a", "dependency", "to", "the", "gas", "-", "include", "file" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/saveDependencies.js#L16-L66
train
pugjs/then-pug
packages/then-pug/lib/index.js
function (locals) { var stream = new ReadableStream(); // streaming will be set to false whenever there is back-pressure var streaming = false; function release() { streaming = true; } // make sure _read is always implemented stream._read = release; // then-yield unwrap function // which implements the backpressure pause mechanism function unwrap(value) { if (streaming) return value; return new Promise(function (resolve) { stream._read = function () { release(); this._read = release; resolve(value); } }); } var template = fn(locals, runtime, { push: function () { for (var i = 0; i < arguments.length; i++) if (!stream.push(arguments[i].toString())) streaming = false; } }); // call our function, setting `streaming` to `false` whenever // the buffer is full and there is back-pressure var result = ty.spawn(template, Promise.resolve, unwrap); // once the function completes, we end the stream by pushing `null` if (result) result.then(stream.push.bind(stream, null), function (err) { stream.emit('error', err); stream.push(null); }); else stream.push(null); return stream; }
javascript
function (locals) { var stream = new ReadableStream(); // streaming will be set to false whenever there is back-pressure var streaming = false; function release() { streaming = true; } // make sure _read is always implemented stream._read = release; // then-yield unwrap function // which implements the backpressure pause mechanism function unwrap(value) { if (streaming) return value; return new Promise(function (resolve) { stream._read = function () { release(); this._read = release; resolve(value); } }); } var template = fn(locals, runtime, { push: function () { for (var i = 0; i < arguments.length; i++) if (!stream.push(arguments[i].toString())) streaming = false; } }); // call our function, setting `streaming` to `false` whenever // the buffer is full and there is back-pressure var result = ty.spawn(template, Promise.resolve, unwrap); // once the function completes, we end the stream by pushing `null` if (result) result.then(stream.push.bind(stream, null), function (err) { stream.emit('error', err); stream.push(null); }); else stream.push(null); return stream; }
[ "function", "(", "locals", ")", "{", "var", "stream", "=", "new", "ReadableStream", "(", ")", ";", "var", "streaming", "=", "false", ";", "function", "release", "(", ")", "{", "streaming", "=", "true", ";", "}", "stream", ".", "_read", "=", "release", ";", "function", "unwrap", "(", "value", ")", "{", "if", "(", "streaming", ")", "return", "value", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "stream", ".", "_read", "=", "function", "(", ")", "{", "release", "(", ")", ";", "this", ".", "_read", "=", "release", ";", "resolve", "(", "value", ")", ";", "}", "}", ")", ";", "}", "var", "template", "=", "fn", "(", "locals", ",", "runtime", ",", "{", "push", ":", "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "if", "(", "!", "stream", ".", "push", "(", "arguments", "[", "i", "]", ".", "toString", "(", ")", ")", ")", "streaming", "=", "false", ";", "}", "}", ")", ";", "var", "result", "=", "ty", ".", "spawn", "(", "template", ",", "Promise", ".", "resolve", ",", "unwrap", ")", ";", "if", "(", "result", ")", "result", ".", "then", "(", "stream", ".", "push", ".", "bind", "(", "stream", ",", "null", ")", ",", "function", "(", "err", ")", "{", "stream", ".", "emit", "(", "'error'", ",", "err", ")", ";", "stream", ".", "push", "(", "null", ")", ";", "}", ")", ";", "else", "stream", ".", "push", "(", "null", ")", ";", "return", "stream", ";", "}" ]
convert it to a function that takes `locals` and returns a readable stream
[ "convert", "it", "to", "a", "function", "that", "takes", "locals", "and", "returns", "a", "readable", "stream" ]
a96c2a9c6d1f0875aef4641064500f818f7e7571
https://github.com/pugjs/then-pug/blob/a96c2a9c6d1f0875aef4641064500f818f7e7571/packages/then-pug/lib/index.js#L315-L362
train
pugjs/then-pug
packages/then-pug/lib/index.js
unwrap
function unwrap(value) { if (streaming) return value; return new Promise(function (resolve) { stream._read = function () { release(); this._read = release; resolve(value); } }); }
javascript
function unwrap(value) { if (streaming) return value; return new Promise(function (resolve) { stream._read = function () { release(); this._read = release; resolve(value); } }); }
[ "function", "unwrap", "(", "value", ")", "{", "if", "(", "streaming", ")", "return", "value", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "stream", ".", "_read", "=", "function", "(", ")", "{", "release", "(", ")", ";", "this", ".", "_read", "=", "release", ";", "resolve", "(", "value", ")", ";", "}", "}", ")", ";", "}" ]
then-yield unwrap function which implements the backpressure pause mechanism
[ "then", "-", "yield", "unwrap", "function", "which", "implements", "the", "backpressure", "pause", "mechanism" ]
a96c2a9c6d1f0875aef4641064500f818f7e7571
https://github.com/pugjs/then-pug/blob/a96c2a9c6d1f0875aef4641064500f818f7e7571/packages/then-pug/lib/index.js#L330-L339
train
restify/enroute
lib/install.js
enrouteHotReloadProxy
function enrouteHotReloadProxy(req, res, next) { return reloadProxy({ basePath: opts.basePath, method: method, req: req, res: res, routeName: routeName, sourceFile: sourceFile, excludePath: opts.excludePath }, next); }
javascript
function enrouteHotReloadProxy(req, res, next) { return reloadProxy({ basePath: opts.basePath, method: method, req: req, res: res, routeName: routeName, sourceFile: sourceFile, excludePath: opts.excludePath }, next); }
[ "function", "enrouteHotReloadProxy", "(", "req", ",", "res", ",", "next", ")", "{", "return", "reloadProxy", "(", "{", "basePath", ":", "opts", ".", "basePath", ",", "method", ":", "method", ",", "req", ":", "req", ",", "res", ":", "res", ",", "routeName", ":", "routeName", ",", "sourceFile", ":", "sourceFile", ",", "excludePath", ":", "opts", ".", "excludePath", "}", ",", "next", ")", ";", "}" ]
restify middleware wrapper for hot reload
[ "restify", "middleware", "wrapper", "for", "hot", "reload" ]
df5f9f25149fcb248267db9d8927aba28b9a3d4e
https://github.com/restify/enroute/blob/df5f9f25149fcb248267db9d8927aba28b9a3d4e/lib/install.js#L77-L87
train
restify/enroute
lib/install.js
reloadProxy
function reloadProxy(opts, cb) { assert.object(opts, 'opts'); assert.string(opts.basePath, 'opts.basePath'); assert.optionalString(opts.excludePath, 'opts.excludePath'); assert.string(opts.method, 'opts.method'); assert.object(opts.req, 'opts.req'); assert.object(opts.res, 'opts.res'); assert.string(opts.routeName, 'opts.routeName'); assert.string(opts.sourceFile, 'opts.sourceFile'); assert.func(cb, 'cb'); var excludeFullpath = opts.basePath + '/' + opts.excludePath; // clear require cache for code loaded from a specific base dir Object.keys(require.cache).forEach(function (cacheKey) { if (opts.excludePath && cacheKey.indexOf(excludeFullpath) !== -1) { return; } else if (cacheKey.indexOf(opts.basePath) !== -1) { delete require.cache[cacheKey]; } }); var handlers; try { handlers = require(opts.sourceFile); } catch (e) { var err = new verror.VError({ name: 'EnrouteRequireError', cause: e, info: { file: opts.sourceFile, route: opts.routeName, method: opts.method } }, 'failed to require file, possible syntax error'); // now that the chain has failed, send back the require error. return cb(err); } // if no require error, execute the handler chain. any errors that occur at // runtime should be a runtime exception. var handlerChain = compose(handlers); return handlerChain(opts.req, opts.res, cb); }
javascript
function reloadProxy(opts, cb) { assert.object(opts, 'opts'); assert.string(opts.basePath, 'opts.basePath'); assert.optionalString(opts.excludePath, 'opts.excludePath'); assert.string(opts.method, 'opts.method'); assert.object(opts.req, 'opts.req'); assert.object(opts.res, 'opts.res'); assert.string(opts.routeName, 'opts.routeName'); assert.string(opts.sourceFile, 'opts.sourceFile'); assert.func(cb, 'cb'); var excludeFullpath = opts.basePath + '/' + opts.excludePath; // clear require cache for code loaded from a specific base dir Object.keys(require.cache).forEach(function (cacheKey) { if (opts.excludePath && cacheKey.indexOf(excludeFullpath) !== -1) { return; } else if (cacheKey.indexOf(opts.basePath) !== -1) { delete require.cache[cacheKey]; } }); var handlers; try { handlers = require(opts.sourceFile); } catch (e) { var err = new verror.VError({ name: 'EnrouteRequireError', cause: e, info: { file: opts.sourceFile, route: opts.routeName, method: opts.method } }, 'failed to require file, possible syntax error'); // now that the chain has failed, send back the require error. return cb(err); } // if no require error, execute the handler chain. any errors that occur at // runtime should be a runtime exception. var handlerChain = compose(handlers); return handlerChain(opts.req, opts.res, cb); }
[ "function", "reloadProxy", "(", "opts", ",", "cb", ")", "{", "assert", ".", "object", "(", "opts", ",", "'opts'", ")", ";", "assert", ".", "string", "(", "opts", ".", "basePath", ",", "'opts.basePath'", ")", ";", "assert", ".", "optionalString", "(", "opts", ".", "excludePath", ",", "'opts.excludePath'", ")", ";", "assert", ".", "string", "(", "opts", ".", "method", ",", "'opts.method'", ")", ";", "assert", ".", "object", "(", "opts", ".", "req", ",", "'opts.req'", ")", ";", "assert", ".", "object", "(", "opts", ".", "res", ",", "'opts.res'", ")", ";", "assert", ".", "string", "(", "opts", ".", "routeName", ",", "'opts.routeName'", ")", ";", "assert", ".", "string", "(", "opts", ".", "sourceFile", ",", "'opts.sourceFile'", ")", ";", "assert", ".", "func", "(", "cb", ",", "'cb'", ")", ";", "var", "excludeFullpath", "=", "opts", ".", "basePath", "+", "'/'", "+", "opts", ".", "excludePath", ";", "Object", ".", "keys", "(", "require", ".", "cache", ")", ".", "forEach", "(", "function", "(", "cacheKey", ")", "{", "if", "(", "opts", ".", "excludePath", "&&", "cacheKey", ".", "indexOf", "(", "excludeFullpath", ")", "!==", "-", "1", ")", "{", "return", ";", "}", "else", "if", "(", "cacheKey", ".", "indexOf", "(", "opts", ".", "basePath", ")", "!==", "-", "1", ")", "{", "delete", "require", ".", "cache", "[", "cacheKey", "]", ";", "}", "}", ")", ";", "var", "handlers", ";", "try", "{", "handlers", "=", "require", "(", "opts", ".", "sourceFile", ")", ";", "}", "catch", "(", "e", ")", "{", "var", "err", "=", "new", "verror", ".", "VError", "(", "{", "name", ":", "'EnrouteRequireError'", ",", "cause", ":", "e", ",", "info", ":", "{", "file", ":", "opts", ".", "sourceFile", ",", "route", ":", "opts", ".", "routeName", ",", "method", ":", "opts", ".", "method", "}", "}", ",", "'failed to require file, possible syntax error'", ")", ";", "return", "cb", "(", "err", ")", ";", "}", "var", "handlerChain", "=", "compose", "(", "handlers", ")", ";", "return", "handlerChain", "(", "opts", ".", "req", ",", "opts", ".", "res", ",", "cb", ")", ";", "}" ]
using the restify handler composer, create a middleware on the fly that re-requires the file on every load executes it. @private @function reloadProxy @param {Object} opts an options object @param {String} opts.basePath The basepath to resolve source files. @param {String} opts.method http verb @param {Object} opts.log the enroute logger @param {Object} opts.req the request object @param {Object} opts.res the response object @param {String} opts.routeName the name of the restify route @param {String} opts.sourceFile the response object @param {Function} cb callback fn @returns {undefined}
[ "using", "the", "restify", "handler", "composer", "create", "a", "middleware", "on", "the", "fly", "that", "re", "-", "requires", "the", "file", "on", "every", "load", "executes", "it", "." ]
df5f9f25149fcb248267db9d8927aba28b9a3d4e
https://github.com/restify/enroute/blob/df5f9f25149fcb248267db9d8927aba28b9a3d4e/lib/install.js#L154-L199
train
MaartenDesnouck/google-apps-script
lib/functions/downloadRemote.js
downloadRemote
function downloadRemote(auth, projectId, dir, method) { return new Promise((resolve, reject) => { const gasDir = path.join('.', dir, constants.META_DIR); if (method === 'clone' && fs.existsSync(path.join('.', dir))) { reject({ message: `Oops, the directory '${dir}' seems to exist already.\nRemove this folder or use 'gas link' to link your project to the correct folder.`, print: true, }); return; } const file = { name: path.join(gasDir, constants.META_ID), source: projectId, }; createFile(file); const remote = path.join(gasDir, constants.META_REMOTE); const script = google.script('v1'); script.projects.getContent({ auth, scriptId: projectId, }, (err, content) => { if (err) { fs.removeSync(remote); triageGoogleError(err, 'downloadRemote').then((triaged) => { reject(triaged); }).catch((notTriaged) => { reject(notTriaged); }); } else { createFile({ name: remote, source: JSON.stringify(content.data), }); resolve(); } return; }); }); }
javascript
function downloadRemote(auth, projectId, dir, method) { return new Promise((resolve, reject) => { const gasDir = path.join('.', dir, constants.META_DIR); if (method === 'clone' && fs.existsSync(path.join('.', dir))) { reject({ message: `Oops, the directory '${dir}' seems to exist already.\nRemove this folder or use 'gas link' to link your project to the correct folder.`, print: true, }); return; } const file = { name: path.join(gasDir, constants.META_ID), source: projectId, }; createFile(file); const remote = path.join(gasDir, constants.META_REMOTE); const script = google.script('v1'); script.projects.getContent({ auth, scriptId: projectId, }, (err, content) => { if (err) { fs.removeSync(remote); triageGoogleError(err, 'downloadRemote').then((triaged) => { reject(triaged); }).catch((notTriaged) => { reject(notTriaged); }); } else { createFile({ name: remote, source: JSON.stringify(content.data), }); resolve(); } return; }); }); }
[ "function", "downloadRemote", "(", "auth", ",", "projectId", ",", "dir", ",", "method", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "gasDir", "=", "path", ".", "join", "(", "'.'", ",", "dir", ",", "constants", ".", "META_DIR", ")", ";", "if", "(", "method", "===", "'clone'", "&&", "fs", ".", "existsSync", "(", "path", ".", "join", "(", "'.'", ",", "dir", ")", ")", ")", "{", "reject", "(", "{", "message", ":", "`", "${", "dir", "}", "\\n", "`", ",", "print", ":", "true", ",", "}", ")", ";", "return", ";", "}", "const", "file", "=", "{", "name", ":", "path", ".", "join", "(", "gasDir", ",", "constants", ".", "META_ID", ")", ",", "source", ":", "projectId", ",", "}", ";", "createFile", "(", "file", ")", ";", "const", "remote", "=", "path", ".", "join", "(", "gasDir", ",", "constants", ".", "META_REMOTE", ")", ";", "const", "script", "=", "google", ".", "script", "(", "'v1'", ")", ";", "script", ".", "projects", ".", "getContent", "(", "{", "auth", ",", "scriptId", ":", "projectId", ",", "}", ",", "(", "err", ",", "content", ")", "=>", "{", "if", "(", "err", ")", "{", "fs", ".", "removeSync", "(", "remote", ")", ";", "triageGoogleError", "(", "err", ",", "'downloadRemote'", ")", ".", "then", "(", "(", "triaged", ")", "=>", "{", "reject", "(", "triaged", ")", ";", "}", ")", ".", "catch", "(", "(", "notTriaged", ")", "=>", "{", "reject", "(", "notTriaged", ")", ";", "}", ")", ";", "}", "else", "{", "createFile", "(", "{", "name", ":", "remote", ",", "source", ":", "JSON", ".", "stringify", "(", "content", ".", "data", ")", ",", "}", ")", ";", "resolve", "(", ")", ";", "}", "return", ";", "}", ")", ";", "}", ")", ";", "}" ]
Download remote script json @param {google.auth.OAuth2} auth - An authorized OAuth2 client. @param {String} projectId - Id of project to download. @param {String} dir - Optional directory in which the project is located. @param {String} method - Identifier for the flow calling this function. @returns {Promise} - A promise resolving no value
[ "Download", "remote", "script", "json" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/downloadRemote.js#L19-L61
train
victorquinn/memcache-plus
lib/client.js
Client
function Client(opts) { if (!(this instanceof Client)) { return new Client(opts); } var options = {}; // If single connection provided, array-ify it if (typeof opts === 'string') { options.hosts = [opts]; opts = options; } else if (typeof opts === 'undefined') { opts = {}; } else if (_.isArray(opts)) { options.hosts = opts; opts = options; } _.defaults(opts, { autodiscover: false, bufferBeforeError: 1000, disabled: false, hosts: null, reconnect: true, onNetError: function onNetError(err) { console.error(err); }, queue: true, netTimeout: 500, backoffLimit: 10000, maxValueSize: 1048576 }); // Iterate over options, assign each to this object R.keys(opts).forEach(function(key) { this[key] = opts[key]; }, this); if (this.queue) { this.buffer = new Immutable.List(); } debug('Connect options', opts); this.connect(); }
javascript
function Client(opts) { if (!(this instanceof Client)) { return new Client(opts); } var options = {}; // If single connection provided, array-ify it if (typeof opts === 'string') { options.hosts = [opts]; opts = options; } else if (typeof opts === 'undefined') { opts = {}; } else if (_.isArray(opts)) { options.hosts = opts; opts = options; } _.defaults(opts, { autodiscover: false, bufferBeforeError: 1000, disabled: false, hosts: null, reconnect: true, onNetError: function onNetError(err) { console.error(err); }, queue: true, netTimeout: 500, backoffLimit: 10000, maxValueSize: 1048576 }); // Iterate over options, assign each to this object R.keys(opts).forEach(function(key) { this[key] = opts[key]; }, this); if (this.queue) { this.buffer = new Immutable.List(); } debug('Connect options', opts); this.connect(); }
[ "function", "Client", "(", "opts", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Client", ")", ")", "{", "return", "new", "Client", "(", "opts", ")", ";", "}", "var", "options", "=", "{", "}", ";", "if", "(", "typeof", "opts", "===", "'string'", ")", "{", "options", ".", "hosts", "=", "[", "opts", "]", ";", "opts", "=", "options", ";", "}", "else", "if", "(", "typeof", "opts", "===", "'undefined'", ")", "{", "opts", "=", "{", "}", ";", "}", "else", "if", "(", "_", ".", "isArray", "(", "opts", ")", ")", "{", "options", ".", "hosts", "=", "opts", ";", "opts", "=", "options", ";", "}", "_", ".", "defaults", "(", "opts", ",", "{", "autodiscover", ":", "false", ",", "bufferBeforeError", ":", "1000", ",", "disabled", ":", "false", ",", "hosts", ":", "null", ",", "reconnect", ":", "true", ",", "onNetError", ":", "function", "onNetError", "(", "err", ")", "{", "console", ".", "error", "(", "err", ")", ";", "}", ",", "queue", ":", "true", ",", "netTimeout", ":", "500", ",", "backoffLimit", ":", "10000", ",", "maxValueSize", ":", "1048576", "}", ")", ";", "R", ".", "keys", "(", "opts", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "this", "[", "key", "]", "=", "opts", "[", "key", "]", ";", "}", ",", "this", ")", ";", "if", "(", "this", ".", "queue", ")", "{", "this", ".", "buffer", "=", "new", "Immutable", ".", "List", "(", ")", ";", "}", "debug", "(", "'Connect options'", ",", "opts", ")", ";", "this", ".", "connect", "(", ")", ";", "}" ]
Constructor - Initiate client
[ "Constructor", "-", "Initiate", "client" ]
cabf91d69eaff0cb6a80858561911f8e664a5e42
https://github.com/victorquinn/memcache-plus/blob/cabf91d69eaff0cb6a80858561911f8e664a5e42/lib/client.js#L25-L67
train
MaartenDesnouck/google-apps-script
lib/functions/getUserInfo.js
getUserInfo
function getUserInfo(auth) { return new Promise((resolve, reject) => { const oauth2 = google.oauth2({ auth, version: 'v2', }); oauth2.userinfo.v2.me.get((err, res) => { if (err) { reject(err); } else { resolve(res.data); } return; }); }); }
javascript
function getUserInfo(auth) { return new Promise((resolve, reject) => { const oauth2 = google.oauth2({ auth, version: 'v2', }); oauth2.userinfo.v2.me.get((err, res) => { if (err) { reject(err); } else { resolve(res.data); } return; }); }); }
[ "function", "getUserInfo", "(", "auth", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "oauth2", "=", "google", ".", "oauth2", "(", "{", "auth", ",", "version", ":", "'v2'", ",", "}", ")", ";", "oauth2", ".", "userinfo", ".", "v2", ".", "me", ".", "get", "(", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "res", ".", "data", ")", ";", "}", "return", ";", "}", ")", ";", "}", ")", ";", "}" ]
Log info about users @param {google.auth.OAuth2} auth - An authorized OAuth2 client. @returns {Promise} - A promise resolving user info of the current user
[ "Log", "info", "about", "users" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/getUserInfo.js#L11-L27
train
MaartenDesnouck/google-apps-script
lib/functions/firebase.js
authWithFirebase
async function authWithFirebase(auth) { try { const config = { apiKey: constants.FIREBASE_DATABASE_PUBLIC_APIKEY, databaseURL: constants.FIREBASE_DATABASE_URL, }; if (!firebase.apps.length) { firebase.initializeApp(config); } const credential = firebase.auth.GoogleAuthProvider.credential(auth.credentials.id_token); await firebase.auth().signInAndRetrieveDataWithCredential(credential); return true; } catch (err) { err.origin = 'authWithFirebase'; await error.log(err); return false; } }
javascript
async function authWithFirebase(auth) { try { const config = { apiKey: constants.FIREBASE_DATABASE_PUBLIC_APIKEY, databaseURL: constants.FIREBASE_DATABASE_URL, }; if (!firebase.apps.length) { firebase.initializeApp(config); } const credential = firebase.auth.GoogleAuthProvider.credential(auth.credentials.id_token); await firebase.auth().signInAndRetrieveDataWithCredential(credential); return true; } catch (err) { err.origin = 'authWithFirebase'; await error.log(err); return false; } }
[ "async", "function", "authWithFirebase", "(", "auth", ")", "{", "try", "{", "const", "config", "=", "{", "apiKey", ":", "constants", ".", "FIREBASE_DATABASE_PUBLIC_APIKEY", ",", "databaseURL", ":", "constants", ".", "FIREBASE_DATABASE_URL", ",", "}", ";", "if", "(", "!", "firebase", ".", "apps", ".", "length", ")", "{", "firebase", ".", "initializeApp", "(", "config", ")", ";", "}", "const", "credential", "=", "firebase", ".", "auth", ".", "GoogleAuthProvider", ".", "credential", "(", "auth", ".", "credentials", ".", "id_token", ")", ";", "await", "firebase", ".", "auth", "(", ")", ".", "signInAndRetrieveDataWithCredential", "(", "credential", ")", ";", "return", "true", ";", "}", "catch", "(", "err", ")", "{", "err", ".", "origin", "=", "'authWithFirebase'", ";", "await", "error", ".", "log", "(", "err", ")", ";", "return", "false", ";", "}", "}" ]
Get firebase credentails @param {google.auth.OAuth2} auth - An authorized OAuth2 client. @returns {Promise} - Promise resolving a firebase credential
[ "Get", "firebase", "credentails" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/firebase.js#L17-L37
train
MaartenDesnouck/google-apps-script
lib/functions/firebase.js
setUserInfo
async function setUserInfo(auth) { try { const authenticated = await authWithFirebase(auth); const token = await firebase.auth().currentUser.getIdToken(); const userId = firebase.auth().currentUser.uid; const userInfo = await getUserInfo(auth); userInfo.version = pjson.version; userInfo.lastLogin = { ".sv": "timestamp", }; const infoUrl = `${constants.FIREBASE_DATABASE_URL}/users/${userId}.json?auth=${token}`; await request({ url: infoUrl, method: "PATCH", json: true, headers: { "content-type": "application/json", }, body: userInfo, }); return true; } catch (err) { err.origin = 'setUserInfo'; await error.log(err); return false; } }
javascript
async function setUserInfo(auth) { try { const authenticated = await authWithFirebase(auth); const token = await firebase.auth().currentUser.getIdToken(); const userId = firebase.auth().currentUser.uid; const userInfo = await getUserInfo(auth); userInfo.version = pjson.version; userInfo.lastLogin = { ".sv": "timestamp", }; const infoUrl = `${constants.FIREBASE_DATABASE_URL}/users/${userId}.json?auth=${token}`; await request({ url: infoUrl, method: "PATCH", json: true, headers: { "content-type": "application/json", }, body: userInfo, }); return true; } catch (err) { err.origin = 'setUserInfo'; await error.log(err); return false; } }
[ "async", "function", "setUserInfo", "(", "auth", ")", "{", "try", "{", "const", "authenticated", "=", "await", "authWithFirebase", "(", "auth", ")", ";", "const", "token", "=", "await", "firebase", ".", "auth", "(", ")", ".", "currentUser", ".", "getIdToken", "(", ")", ";", "const", "userId", "=", "firebase", ".", "auth", "(", ")", ".", "currentUser", ".", "uid", ";", "const", "userInfo", "=", "await", "getUserInfo", "(", "auth", ")", ";", "userInfo", ".", "version", "=", "pjson", ".", "version", ";", "userInfo", ".", "lastLogin", "=", "{", "\".sv\"", ":", "\"timestamp\"", ",", "}", ";", "const", "infoUrl", "=", "`", "${", "constants", ".", "FIREBASE_DATABASE_URL", "}", "${", "userId", "}", "${", "token", "}", "`", ";", "await", "request", "(", "{", "url", ":", "infoUrl", ",", "method", ":", "\"PATCH\"", ",", "json", ":", "true", ",", "headers", ":", "{", "\"content-type\"", ":", "\"application/json\"", ",", "}", ",", "body", ":", "userInfo", ",", "}", ")", ";", "return", "true", ";", "}", "catch", "(", "err", ")", "{", "err", ".", "origin", "=", "'setUserInfo'", ";", "await", "error", ".", "log", "(", "err", ")", ";", "return", "false", ";", "}", "}" ]
Log user to firebase @param {google.auth.OAuth2} auth - An authorized OAuth2 client. @returns {Promise} - a promise resolving true if user info has been set in firebase
[ "Log", "user", "to", "firebase" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/firebase.js#L45-L73
train
MaartenDesnouck/google-apps-script
lib/functions/firebase.js
publish
async function publish(auth, rootPath) { // check if version does not exist yet // check if user is allowed to publish // check if version is larger than last version // names cant contain _- etc, maybe just stick to lowercase letters? // if projectKey, check that we can access the file? package = fs.readJsonSync(path.join(rootPath, constants.INCLUDE_FILE)); code = fs.readJsonSync(path.join(rootPath, '.gas/publish.json')); const versionUrl = package.version.replace(/\./g, '_'); // TODO // console.log(semver.valid(package.version)); // console.log(versionUrl); try { const authenticated = await authWithFirebase(auth); const token = await firebase.auth().currentUser.getIdToken(); const userId = firebase.auth().currentUser.uid; let url; let result; // Set a packageName to active url = `${constants.FIREBASE_DATABASE_URL}/packages/${package.name}.json?auth=${token}`; result = await request({ url, method: "PATCH", json: true, headers: { "content-type": "application/json", }, body: { status: 'active', }, }); // Patch users in a package url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/userIds/${userId}.json?auth=${token}`; result = await request({ url, method: "PATCH", json: true, headers: { "content-type": "application/json", }, body: { status: 'active', }, }); // Set version of a package to active url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/versions.json?auth=${token}`; result = await request({ url, method: "PATCH", json: true, headers: { "content-type": "application/json", }, body: { [versionUrl]: true, }, }); // Patch a version in a package url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/version/${versionUrl}.json?auth=${token}`; result = await request({ url, method: "PATCH", json: true, headers: { "content-type": "application/json", }, body: { code, dependencies: package.dependencies, description: package.description, homepage: package.homepage, license: package.license, readme: 'README.md', repository: package.repository, projectKey: package.projectKey, timestamp: { ".sv": "timestamp", }, userId, }, }); return true; } catch (err) { err.origin = 'test'; await error.log(err); return false; } }
javascript
async function publish(auth, rootPath) { // check if version does not exist yet // check if user is allowed to publish // check if version is larger than last version // names cant contain _- etc, maybe just stick to lowercase letters? // if projectKey, check that we can access the file? package = fs.readJsonSync(path.join(rootPath, constants.INCLUDE_FILE)); code = fs.readJsonSync(path.join(rootPath, '.gas/publish.json')); const versionUrl = package.version.replace(/\./g, '_'); // TODO // console.log(semver.valid(package.version)); // console.log(versionUrl); try { const authenticated = await authWithFirebase(auth); const token = await firebase.auth().currentUser.getIdToken(); const userId = firebase.auth().currentUser.uid; let url; let result; // Set a packageName to active url = `${constants.FIREBASE_DATABASE_URL}/packages/${package.name}.json?auth=${token}`; result = await request({ url, method: "PATCH", json: true, headers: { "content-type": "application/json", }, body: { status: 'active', }, }); // Patch users in a package url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/userIds/${userId}.json?auth=${token}`; result = await request({ url, method: "PATCH", json: true, headers: { "content-type": "application/json", }, body: { status: 'active', }, }); // Set version of a package to active url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/versions.json?auth=${token}`; result = await request({ url, method: "PATCH", json: true, headers: { "content-type": "application/json", }, body: { [versionUrl]: true, }, }); // Patch a version in a package url = `${constants.FIREBASE_DATABASE_URL}/package/${package.name}/version/${versionUrl}.json?auth=${token}`; result = await request({ url, method: "PATCH", json: true, headers: { "content-type": "application/json", }, body: { code, dependencies: package.dependencies, description: package.description, homepage: package.homepage, license: package.license, readme: 'README.md', repository: package.repository, projectKey: package.projectKey, timestamp: { ".sv": "timestamp", }, userId, }, }); return true; } catch (err) { err.origin = 'test'; await error.log(err); return false; } }
[ "async", "function", "publish", "(", "auth", ",", "rootPath", ")", "{", "package", "=", "fs", ".", "readJsonSync", "(", "path", ".", "join", "(", "rootPath", ",", "constants", ".", "INCLUDE_FILE", ")", ")", ";", "code", "=", "fs", ".", "readJsonSync", "(", "path", ".", "join", "(", "rootPath", ",", "'.gas/publish.json'", ")", ")", ";", "const", "versionUrl", "=", "package", ".", "version", ".", "replace", "(", "/", "\\.", "/", "g", ",", "'_'", ")", ";", "try", "{", "const", "authenticated", "=", "await", "authWithFirebase", "(", "auth", ")", ";", "const", "token", "=", "await", "firebase", ".", "auth", "(", ")", ".", "currentUser", ".", "getIdToken", "(", ")", ";", "const", "userId", "=", "firebase", ".", "auth", "(", ")", ".", "currentUser", ".", "uid", ";", "let", "url", ";", "let", "result", ";", "url", "=", "`", "${", "constants", ".", "FIREBASE_DATABASE_URL", "}", "${", "package", ".", "name", "}", "${", "token", "}", "`", ";", "result", "=", "await", "request", "(", "{", "url", ",", "method", ":", "\"PATCH\"", ",", "json", ":", "true", ",", "headers", ":", "{", "\"content-type\"", ":", "\"application/json\"", ",", "}", ",", "body", ":", "{", "status", ":", "'active'", ",", "}", ",", "}", ")", ";", "url", "=", "`", "${", "constants", ".", "FIREBASE_DATABASE_URL", "}", "${", "package", ".", "name", "}", "${", "userId", "}", "${", "token", "}", "`", ";", "result", "=", "await", "request", "(", "{", "url", ",", "method", ":", "\"PATCH\"", ",", "json", ":", "true", ",", "headers", ":", "{", "\"content-type\"", ":", "\"application/json\"", ",", "}", ",", "body", ":", "{", "status", ":", "'active'", ",", "}", ",", "}", ")", ";", "url", "=", "`", "${", "constants", ".", "FIREBASE_DATABASE_URL", "}", "${", "package", ".", "name", "}", "${", "token", "}", "`", ";", "result", "=", "await", "request", "(", "{", "url", ",", "method", ":", "\"PATCH\"", ",", "json", ":", "true", ",", "headers", ":", "{", "\"content-type\"", ":", "\"application/json\"", ",", "}", ",", "body", ":", "{", "[", "versionUrl", "]", ":", "true", ",", "}", ",", "}", ")", ";", "url", "=", "`", "${", "constants", ".", "FIREBASE_DATABASE_URL", "}", "${", "package", ".", "name", "}", "${", "versionUrl", "}", "${", "token", "}", "`", ";", "result", "=", "await", "request", "(", "{", "url", ",", "method", ":", "\"PATCH\"", ",", "json", ":", "true", ",", "headers", ":", "{", "\"content-type\"", ":", "\"application/json\"", ",", "}", ",", "body", ":", "{", "code", ",", "dependencies", ":", "package", ".", "dependencies", ",", "description", ":", "package", ".", "description", ",", "homepage", ":", "package", ".", "homepage", ",", "license", ":", "package", ".", "license", ",", "readme", ":", "'README.md'", ",", "repository", ":", "package", ".", "repository", ",", "projectKey", ":", "package", ".", "projectKey", ",", "timestamp", ":", "{", "\".sv\"", ":", "\"timestamp\"", ",", "}", ",", "userId", ",", "}", ",", "}", ")", ";", "return", "true", ";", "}", "catch", "(", "err", ")", "{", "err", ".", "origin", "=", "'test'", ";", "await", "error", ".", "log", "(", "err", ")", ";", "return", "false", ";", "}", "}" ]
Firebase test function @param {google.auth.OAuth2} auth - An authorized OAuth2 client. @return {Boolean} - true if test was succesful, false otherwise
[ "Firebase", "test", "function" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/firebase.js#L81-L176
train
MaartenDesnouck/google-apps-script
lib/functions/getId.js
getId
function getId(rootFolder) { return new Promise((resolve, reject) => { const dir = path.join(rootFolder, constants.META_DIR, constants.META_ID); fs.readFile(dir, 'utf8', (err, id) => { if (err) { reject(err); return; } else { resolve(id); return; } }); }); }
javascript
function getId(rootFolder) { return new Promise((resolve, reject) => { const dir = path.join(rootFolder, constants.META_DIR, constants.META_ID); fs.readFile(dir, 'utf8', (err, id) => { if (err) { reject(err); return; } else { resolve(id); return; } }); }); }
[ "function", "getId", "(", "rootFolder", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "dir", "=", "path", ".", "join", "(", "rootFolder", ",", "constants", ".", "META_DIR", ",", "constants", ".", "META_ID", ")", ";", "fs", ".", "readFile", "(", "dir", ",", "'utf8'", ",", "(", "err", ",", "id", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "return", ";", "}", "else", "{", "resolve", "(", "id", ")", ";", "return", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Get the id of the current google apps script project @param {String} rootFolder - relative path to the rootFolder of the project @returns {Promise} - A promise resolving an id
[ "Get", "the", "id", "of", "the", "current", "google", "apps", "script", "project" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/getId.js#L11-L24
train
MaartenDesnouck/google-apps-script
lib/functions/remoteRenameProject.js
renameRemote
function renameRemote(auth, projectId, name, newName) { return new Promise((resolve, reject) => { if (newName === name) { resolve(false); return; } const drive = google.drive('v3'); drive.files.update({ auth, supportsTeamDrives: true, fileId: projectId, resource: { name: newName, }, }, (err, result) => { if (err) { triageGoogleError(err, 'remoteRenameProject').then((triaged) => { reject(triaged); }).catch((notTriaged) => { reject(notTriaged); }); } else { resolve(true); } return; }); }); }
javascript
function renameRemote(auth, projectId, name, newName) { return new Promise((resolve, reject) => { if (newName === name) { resolve(false); return; } const drive = google.drive('v3'); drive.files.update({ auth, supportsTeamDrives: true, fileId: projectId, resource: { name: newName, }, }, (err, result) => { if (err) { triageGoogleError(err, 'remoteRenameProject').then((triaged) => { reject(triaged); }).catch((notTriaged) => { reject(notTriaged); }); } else { resolve(true); } return; }); }); }
[ "function", "renameRemote", "(", "auth", ",", "projectId", ",", "name", ",", "newName", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "if", "(", "newName", "===", "name", ")", "{", "resolve", "(", "false", ")", ";", "return", ";", "}", "const", "drive", "=", "google", ".", "drive", "(", "'v3'", ")", ";", "drive", ".", "files", ".", "update", "(", "{", "auth", ",", "supportsTeamDrives", ":", "true", ",", "fileId", ":", "projectId", ",", "resource", ":", "{", "name", ":", "newName", ",", "}", ",", "}", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "{", "triageGoogleError", "(", "err", ",", "'remoteRenameProject'", ")", ".", "then", "(", "(", "triaged", ")", "=>", "{", "reject", "(", "triaged", ")", ";", "}", ")", ".", "catch", "(", "(", "notTriaged", ")", "=>", "{", "reject", "(", "notTriaged", ")", ";", "}", ")", ";", "}", "else", "{", "resolve", "(", "true", ")", ";", "}", "return", ";", "}", ")", ";", "}", ")", ";", "}" ]
Rename a remote script file @param {google.auth.OAuth2} auth - An authorized OAuth2 client. @param {String} projectId - Id of the script project to rename. @param {String} name - Old name of the Google Apps Script project. @param {String} newName - New name to give to the new Google Apps Script project. @returns {Promise} A promise resolving a boolean wether we renamed or not
[ "Rename", "a", "remote", "script", "file" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/remoteRenameProject.js#L15-L43
train
NextCenturyCorporation/neon
neon-server/src/main/javascript/util/ajaxUtils.js
doAjaxRequest
function doAjaxRequest(type, url, opts) { var params = {}; params.type = type; params.url = url; // don't just do a blind copy of params here. we want to restrict what can be used to avoid any jquery specific options. params.data = opts.data; params.contentType = opts.contentType; params.dataType = opts.responseType; params.success = opts.success; params.error = opts.error; params.global = opts.global; params.async = opts.async; logRequest(params); var xhr = $.ajax(params); return new neon.util.AjaxRequest(xhr); }
javascript
function doAjaxRequest(type, url, opts) { var params = {}; params.type = type; params.url = url; // don't just do a blind copy of params here. we want to restrict what can be used to avoid any jquery specific options. params.data = opts.data; params.contentType = opts.contentType; params.dataType = opts.responseType; params.success = opts.success; params.error = opts.error; params.global = opts.global; params.async = opts.async; logRequest(params); var xhr = $.ajax(params); return new neon.util.AjaxRequest(xhr); }
[ "function", "doAjaxRequest", "(", "type", ",", "url", ",", "opts", ")", "{", "var", "params", "=", "{", "}", ";", "params", ".", "type", "=", "type", ";", "params", ".", "url", "=", "url", ";", "params", ".", "data", "=", "opts", ".", "data", ";", "params", ".", "contentType", "=", "opts", ".", "contentType", ";", "params", ".", "dataType", "=", "opts", ".", "responseType", ";", "params", ".", "success", "=", "opts", ".", "success", ";", "params", ".", "error", "=", "opts", ".", "error", ";", "params", ".", "global", "=", "opts", ".", "global", ";", "params", ".", "async", "=", "opts", ".", "async", ";", "logRequest", "(", "params", ")", ";", "var", "xhr", "=", "$", ".", "ajax", "(", "params", ")", ";", "return", "new", "neon", ".", "util", ".", "AjaxRequest", "(", "xhr", ")", ";", "}" ]
Executes the request using an ajax call @method doAjaxRequest @private @param {String} type The type of request, e.g. <code>GET</code> or <code>POST</code> @param {String} url The url of the request @param {Object} opts An associative array of options to configure the call <ul> <li>data: Any data to include with the request (typically for POST requests)</li> <li>contentType: The mime type of data being sent, such as <code>application/json</code></li> <li>responseType: The type of data expected as a return value, such as <code>json</code> or <code>text</code></li> <li>success: The callback function to execute on success. It will be passed the return value of the call</li> <li>async: If the call should be asynchronous (defaults to true)</li> <li>global: If the call should trigger global ajax handlers</li> <li>error: The callback function to execute on error. It will have 3 parameters - the xhr, a short error status message and the error message</li> </ul> @return {neon.util.AjaxRequest} The xhr request object
[ "Executes", "the", "request", "using", "an", "ajax", "call" ]
728ff8c494bf73812ffb3410e44018d60798fbd3
https://github.com/NextCenturyCorporation/neon/blob/728ff8c494bf73812ffb3410e44018d60798fbd3/neon-server/src/main/javascript/util/ajaxUtils.js#L52-L68
train
NextCenturyCorporation/neon
neon-server/src/main/javascript/util/ajaxUtils.js
doPostBinary
function doPostBinary(binary, url, successCallback, errorCallback) { var xhr = new XMLHttpRequest(); xhr.open('POST', url); xhr.onload = function() { if(xhr.status === 200) { successCallback(xhr.response); } else { errorCallback(xhr.response); } hideDefaultSpinner(); }; showDefaultSpinner(); xhr.send(binary); }
javascript
function doPostBinary(binary, url, successCallback, errorCallback) { var xhr = new XMLHttpRequest(); xhr.open('POST', url); xhr.onload = function() { if(xhr.status === 200) { successCallback(xhr.response); } else { errorCallback(xhr.response); } hideDefaultSpinner(); }; showDefaultSpinner(); xhr.send(binary); }
[ "function", "doPostBinary", "(", "binary", ",", "url", ",", "successCallback", ",", "errorCallback", ")", "{", "var", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ";", "xhr", ".", "open", "(", "'POST'", ",", "url", ")", ";", "xhr", ".", "onload", "=", "function", "(", ")", "{", "if", "(", "xhr", ".", "status", "===", "200", ")", "{", "successCallback", "(", "xhr", ".", "response", ")", ";", "}", "else", "{", "errorCallback", "(", "xhr", ".", "response", ")", ";", "}", "hideDefaultSpinner", "(", ")", ";", "}", ";", "showDefaultSpinner", "(", ")", ";", "xhr", ".", "send", "(", "binary", ")", ";", "}" ]
Asynchronously posts binary data to the specified URL. @method doPostBinary @param {Blob} binary The binary data to be uploaded. @param {String} url The URL to post to. @param {Function} successCallback The function to call when the post successfuly completes. This function takes the server's response as its parameter. @param {Function} errorCallback The function to call when an error occurs. This function takes the server's response as its parameter.
[ "Asynchronously", "posts", "binary", "data", "to", "the", "specified", "URL", "." ]
728ff8c494bf73812ffb3410e44018d60798fbd3
https://github.com/NextCenturyCorporation/neon/blob/728ff8c494bf73812ffb3410e44018d60798fbd3/neon-server/src/main/javascript/util/ajaxUtils.js#L114-L127
train
NextCenturyCorporation/neon
neon-server/src/main/javascript/widget/widget.js
saveState
function saveState(instanceId, stateObject, successCallback, errorCallback) { var strObject = JSON.stringify(stateObject); return neon.util.ajaxUtils.doPostJSON({ instanceId: instanceId, state: strObject }, neon.serviceUrl('widgetservice', 'savestate'), { success: successCallback, error: errorCallback, global: false }); }
javascript
function saveState(instanceId, stateObject, successCallback, errorCallback) { var strObject = JSON.stringify(stateObject); return neon.util.ajaxUtils.doPostJSON({ instanceId: instanceId, state: strObject }, neon.serviceUrl('widgetservice', 'savestate'), { success: successCallback, error: errorCallback, global: false }); }
[ "function", "saveState", "(", "instanceId", ",", "stateObject", ",", "successCallback", ",", "errorCallback", ")", "{", "var", "strObject", "=", "JSON", ".", "stringify", "(", "stateObject", ")", ";", "return", "neon", ".", "util", ".", "ajaxUtils", ".", "doPostJSON", "(", "{", "instanceId", ":", "instanceId", ",", "state", ":", "strObject", "}", ",", "neon", ".", "serviceUrl", "(", "'widgetservice'", ",", "'savestate'", ")", ",", "{", "success", ":", "successCallback", ",", "error", ":", "errorCallback", ",", "global", ":", "false", "}", ")", ";", "}" ]
Save the current state of a widget. @method saveState @param {String} instanceId a unique identifier of an instance of a widget @param {Object} stateObject an object that is to be saved. @param {Function} successCallback The callback to execute when the state is saved. The callback will have no data. @param {Function} errorCallback The optional callback when an error occurs. This is a 3 parameter function that contains the xhr, a short error status and the full error message. @return {neon.util.AjaxRequest} The xhr request object
[ "Save", "the", "current", "state", "of", "a", "widget", "." ]
728ff8c494bf73812ffb3410e44018d60798fbd3
https://github.com/NextCenturyCorporation/neon/blob/728ff8c494bf73812ffb3410e44018d60798fbd3/neon-server/src/main/javascript/widget/widget.js#L32-L42
train
NextCenturyCorporation/neon
neon-server/src/main/javascript/widget/widget.js
getSavedState
function getSavedState(id, successCallback) { return neon.util.ajaxUtils.doGet( neon.serviceUrl('widgetservice', 'restorestate/' + encodeURIComponent(id)), { success: function(data) { if(!data) { return; } if(successCallback && typeof successCallback === 'function') { successCallback(data); } }, error: function() { //Do nothing, the state does not exist. }, responseType: 'json' } ); }
javascript
function getSavedState(id, successCallback) { return neon.util.ajaxUtils.doGet( neon.serviceUrl('widgetservice', 'restorestate/' + encodeURIComponent(id)), { success: function(data) { if(!data) { return; } if(successCallback && typeof successCallback === 'function') { successCallback(data); } }, error: function() { //Do nothing, the state does not exist. }, responseType: 'json' } ); }
[ "function", "getSavedState", "(", "id", ",", "successCallback", ")", "{", "return", "neon", ".", "util", ".", "ajaxUtils", ".", "doGet", "(", "neon", ".", "serviceUrl", "(", "'widgetservice'", ",", "'restorestate/'", "+", "encodeURIComponent", "(", "id", ")", ")", ",", "{", "success", ":", "function", "(", "data", ")", "{", "if", "(", "!", "data", ")", "{", "return", ";", "}", "if", "(", "successCallback", "&&", "typeof", "successCallback", "===", "'function'", ")", "{", "successCallback", "(", "data", ")", ";", "}", "}", ",", "error", ":", "function", "(", ")", "{", "}", ",", "responseType", ":", "'json'", "}", ")", ";", "}" ]
Gets the current state that has been saved. @method getSavedState @param {String} id an unique identifier of a client widget @param {Function} successCallback The callback that contains the saved data. @return {neon.util.AjaxRequest} The xhr request object
[ "Gets", "the", "current", "state", "that", "has", "been", "saved", "." ]
728ff8c494bf73812ffb3410e44018d60798fbd3
https://github.com/NextCenturyCorporation/neon/blob/728ff8c494bf73812ffb3410e44018d60798fbd3/neon-server/src/main/javascript/widget/widget.js#L51-L68
train
NextCenturyCorporation/neon
neon-server/src/main/javascript/widget/widget.js
getPropertyKeys
function getPropertyKeys(successCallback, errorCallback) { return neon.util.ajaxUtils.doGet( neon.serviceUrl('propertyservice', '*'), { success: successCallback, error: errorCallback, responseType: 'json' } ); }
javascript
function getPropertyKeys(successCallback, errorCallback) { return neon.util.ajaxUtils.doGet( neon.serviceUrl('propertyservice', '*'), { success: successCallback, error: errorCallback, responseType: 'json' } ); }
[ "function", "getPropertyKeys", "(", "successCallback", ",", "errorCallback", ")", "{", "return", "neon", ".", "util", ".", "ajaxUtils", ".", "doGet", "(", "neon", ".", "serviceUrl", "(", "'propertyservice'", ",", "'*'", ")", ",", "{", "success", ":", "successCallback", ",", "error", ":", "errorCallback", ",", "responseType", ":", "'json'", "}", ")", ";", "}" ]
Gets the list of property keys @method getPropertyKeys @param {Function} successCallback The callback that contains the array of key names @param {Function} errorCallback The optional callback when an error occurs. This is a 3 parameter function that contains the xhr, a short error status and the full error message. @return {neon.util.AjaxRequest} The xhr request object
[ "Gets", "the", "list", "of", "property", "keys" ]
728ff8c494bf73812ffb3410e44018d60798fbd3
https://github.com/NextCenturyCorporation/neon/blob/728ff8c494bf73812ffb3410e44018d60798fbd3/neon-server/src/main/javascript/widget/widget.js#L77-L85
train
NextCenturyCorporation/neon
neon-server/src/main/javascript/widget/widget.js
removeProperty
function removeProperty(key, successCallback, errorCallback) { return neon.util.ajaxUtils.doDelete( neon.serviceUrl('propertyservice', key), { success: successCallback, error: errorCallback, responseType: 'json' } ); }
javascript
function removeProperty(key, successCallback, errorCallback) { return neon.util.ajaxUtils.doDelete( neon.serviceUrl('propertyservice', key), { success: successCallback, error: errorCallback, responseType: 'json' } ); }
[ "function", "removeProperty", "(", "key", ",", "successCallback", ",", "errorCallback", ")", "{", "return", "neon", ".", "util", ".", "ajaxUtils", ".", "doDelete", "(", "neon", ".", "serviceUrl", "(", "'propertyservice'", ",", "key", ")", ",", "{", "success", ":", "successCallback", ",", "error", ":", "errorCallback", ",", "responseType", ":", "'json'", "}", ")", ";", "}" ]
Remove a property @method removeProperty @param {String} the property key to remove @param {Function} successCallback The callback @param {Function} errorCallback The optional callback when an error occurs. This is a 3 parameter function that contains the xhr, a short error status and the full error message. @return {neon.util.AjaxRequest} The xhr request object
[ "Remove", "a", "property" ]
728ff8c494bf73812ffb3410e44018d60798fbd3
https://github.com/NextCenturyCorporation/neon/blob/728ff8c494bf73812ffb3410e44018d60798fbd3/neon-server/src/main/javascript/widget/widget.js#L113-L121
train
NextCenturyCorporation/neon
neon-server/src/main/javascript/widget/widget.js
setProperty
function setProperty(key, value, successCallback, errorCallback) { return neon.util.ajaxUtils.doPost( neon.serviceUrl('propertyservice', key), { data: value, contentType: 'text/plain', success: successCallback, error: errorCallback, responseType: 'json' } ); }
javascript
function setProperty(key, value, successCallback, errorCallback) { return neon.util.ajaxUtils.doPost( neon.serviceUrl('propertyservice', key), { data: value, contentType: 'text/plain', success: successCallback, error: errorCallback, responseType: 'json' } ); }
[ "function", "setProperty", "(", "key", ",", "value", ",", "successCallback", ",", "errorCallback", ")", "{", "return", "neon", ".", "util", ".", "ajaxUtils", ".", "doPost", "(", "neon", ".", "serviceUrl", "(", "'propertyservice'", ",", "key", ")", ",", "{", "data", ":", "value", ",", "contentType", ":", "'text/plain'", ",", "success", ":", "successCallback", ",", "error", ":", "errorCallback", ",", "responseType", ":", "'json'", "}", ")", ";", "}" ]
Sets a property @method setProperty @param {String} the property key to set @param {String} the new value for the property @param {Function} successCallback The callback @param {Function} errorCallback The optional callback when an error occurs. This is a 3 parameter function that contains the xhr, a short error status and the full error message. @return {neon.util.AjaxRequest} The xhr request object
[ "Sets", "a", "property" ]
728ff8c494bf73812ffb3410e44018d60798fbd3
https://github.com/NextCenturyCorporation/neon/blob/728ff8c494bf73812ffb3410e44018d60798fbd3/neon-server/src/main/javascript/widget/widget.js#L132-L142
train
NextCenturyCorporation/neon
neon-server/src/main/javascript/widget/widget.js
getInstanceId
function getInstanceId(qualifier, successCallback) { // If the first argument is a function, assume that is the callback and that the caller // wants the session id if(typeof qualifier === 'function') { successCallback = qualifier; qualifier = null; } return neon.util.ajaxUtils.doGet( neon.serviceUrl('widgetservice', 'instanceid', buildInstanceIdQueryString(qualifier)), { success: function(instanceId) { if(!instanceId) { return; } if(successCallback && typeof successCallback === 'function') { successCallback(instanceId); } }, error: function() { } } ); }
javascript
function getInstanceId(qualifier, successCallback) { // If the first argument is a function, assume that is the callback and that the caller // wants the session id if(typeof qualifier === 'function') { successCallback = qualifier; qualifier = null; } return neon.util.ajaxUtils.doGet( neon.serviceUrl('widgetservice', 'instanceid', buildInstanceIdQueryString(qualifier)), { success: function(instanceId) { if(!instanceId) { return; } if(successCallback && typeof successCallback === 'function') { successCallback(instanceId); } }, error: function() { } } ); }
[ "function", "getInstanceId", "(", "qualifier", ",", "successCallback", ")", "{", "if", "(", "typeof", "qualifier", "===", "'function'", ")", "{", "successCallback", "=", "qualifier", ";", "qualifier", "=", "null", ";", "}", "return", "neon", ".", "util", ".", "ajaxUtils", ".", "doGet", "(", "neon", ".", "serviceUrl", "(", "'widgetservice'", ",", "'instanceid'", ",", "buildInstanceIdQueryString", "(", "qualifier", ")", ")", ",", "{", "success", ":", "function", "(", "instanceId", ")", "{", "if", "(", "!", "instanceId", ")", "{", "return", ";", "}", "if", "(", "successCallback", "&&", "typeof", "successCallback", "===", "'function'", ")", "{", "successCallback", "(", "instanceId", ")", ";", "}", "}", ",", "error", ":", "function", "(", ")", "{", "}", "}", ")", ";", "}" ]
Gets a unique id for a widget for a particular session. Repeated calls to this method in a single session with the same parameters will result in the same id being returned. @param {String} [qualifier] If a qualifier is specified, the id will be tied to that qualifier. This allows multiple ids to be created for a single session. If a qualifier is not specified, the id returned will be unique to the session. If running within OWF, the OWF instanceId is appended to the identifier so the same widget can be reused in multiple windows without conflict. @param {Function} successCallback The callback that contains the unique id string @method getInstanceId @return {String} The xhr request object
[ "Gets", "a", "unique", "id", "for", "a", "widget", "for", "a", "particular", "session", ".", "Repeated", "calls", "to", "this", "method", "in", "a", "single", "session", "with", "the", "same", "parameters", "will", "result", "in", "the", "same", "id", "being", "returned", "." ]
728ff8c494bf73812ffb3410e44018d60798fbd3
https://github.com/NextCenturyCorporation/neon/blob/728ff8c494bf73812ffb3410e44018d60798fbd3/neon-server/src/main/javascript/widget/widget.js#L156-L177
train
NextCenturyCorporation/neon
neon-server/src/main/javascript/widget/widget.js
buildQualifierString
function buildQualifierString(qualifier) { var fullQualifier = qualifier || ''; // when running in OWF, it is possible to have the same widget running multiple times so append // the owf widget instanceid to the qualifier if(neon.util.owfUtils.isRunningInOWF()) { fullQualifier += OWF.getInstanceId(); } return fullQualifier; }
javascript
function buildQualifierString(qualifier) { var fullQualifier = qualifier || ''; // when running in OWF, it is possible to have the same widget running multiple times so append // the owf widget instanceid to the qualifier if(neon.util.owfUtils.isRunningInOWF()) { fullQualifier += OWF.getInstanceId(); } return fullQualifier; }
[ "function", "buildQualifierString", "(", "qualifier", ")", "{", "var", "fullQualifier", "=", "qualifier", "||", "''", ";", "if", "(", "neon", ".", "util", ".", "owfUtils", ".", "isRunningInOWF", "(", ")", ")", "{", "fullQualifier", "+=", "OWF", ".", "getInstanceId", "(", ")", ";", "}", "return", "fullQualifier", ";", "}" ]
Given the text qualifier value, if running in OWF, the OWF instance id is appended to it. Otherwise, the original value is returned. @method buildQualifierString @param {String} [qualifier] @return {string} The full qualifier, which may include the OWF instance id if running in OWF
[ "Given", "the", "text", "qualifier", "value", "if", "running", "in", "OWF", "the", "OWF", "instance", "id", "is", "appended", "to", "it", ".", "Otherwise", "the", "original", "value", "is", "returned", "." ]
728ff8c494bf73812ffb3410e44018d60798fbd3
https://github.com/NextCenturyCorporation/neon/blob/728ff8c494bf73812ffb3410e44018d60798fbd3/neon-server/src/main/javascript/widget/widget.js#L186-L194
train
MaartenDesnouck/google-apps-script
lib/functions/ignore.js
addGitIgnore
function addGitIgnore(rootFolder) { // If no .gitignore files exists, add one const gitignore = path.join(rootFolder, '.gitignore'); if (!fs.existsSync(gitignore)) { fs.writeFileSync(gitignore, gitignoreContent); } }
javascript
function addGitIgnore(rootFolder) { // If no .gitignore files exists, add one const gitignore = path.join(rootFolder, '.gitignore'); if (!fs.existsSync(gitignore)) { fs.writeFileSync(gitignore, gitignoreContent); } }
[ "function", "addGitIgnore", "(", "rootFolder", ")", "{", "const", "gitignore", "=", "path", ".", "join", "(", "rootFolder", ",", "'.gitignore'", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "gitignore", ")", ")", "{", "fs", ".", "writeFileSync", "(", "gitignore", ",", "gitignoreContent", ")", ";", "}", "}" ]
Add a gitignore file if none is present yet @param {String} rootFolder - Folder to add .gitignore in @returns {void}
[ "Add", "a", "gitignore", "file", "if", "none", "is", "present", "yet" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/ignore.js#L18-L25
train
MaartenDesnouck/google-apps-script
lib/functions/ignore.js
addGasIgnore
function addGasIgnore(rootFolder) { // If no .gitignore files exists, add one const gasignore = path.join(rootFolder, constants.IGNORE_FILE); if (!fs.existsSync(gasignore)) { fs.writeFileSync(gasignore, gasignoreContent); } }
javascript
function addGasIgnore(rootFolder) { // If no .gitignore files exists, add one const gasignore = path.join(rootFolder, constants.IGNORE_FILE); if (!fs.existsSync(gasignore)) { fs.writeFileSync(gasignore, gasignoreContent); } }
[ "function", "addGasIgnore", "(", "rootFolder", ")", "{", "const", "gasignore", "=", "path", ".", "join", "(", "rootFolder", ",", "constants", ".", "IGNORE_FILE", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "gasignore", ")", ")", "{", "fs", ".", "writeFileSync", "(", "gasignore", ",", "gasignoreContent", ")", ";", "}", "}" ]
Add a .gasignore file if none is present yet @param {String} rootFolder - Folder to add .gasignore in @returns {void}
[ "Add", "a", ".", "gasignore", "file", "if", "none", "is", "present", "yet" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/ignore.js#L33-L40
train
MaartenDesnouck/google-apps-script
lib/functions/ignore.js
getIgnoreRegexes
function getIgnoreRegexes(rootFolder) { const gasignoreFilepath = path.join(rootFolder, constants.IGNORE_FILE); let regexes = []; if (fs.existsSync(gasignoreFilepath)) { regexes = parse(fs.readFileSync(gasignoreFilepath)); } return regexes; }
javascript
function getIgnoreRegexes(rootFolder) { const gasignoreFilepath = path.join(rootFolder, constants.IGNORE_FILE); let regexes = []; if (fs.existsSync(gasignoreFilepath)) { regexes = parse(fs.readFileSync(gasignoreFilepath)); } return regexes; }
[ "function", "getIgnoreRegexes", "(", "rootFolder", ")", "{", "const", "gasignoreFilepath", "=", "path", ".", "join", "(", "rootFolder", ",", "constants", ".", "IGNORE_FILE", ")", ";", "let", "regexes", "=", "[", "]", ";", "if", "(", "fs", ".", "existsSync", "(", "gasignoreFilepath", ")", ")", "{", "regexes", "=", "parse", "(", "fs", ".", "readFileSync", "(", "gasignoreFilepath", ")", ")", ";", "}", "return", "regexes", ";", "}" ]
Get a list of regexes of filenames to ignore while pushing @param {String} rootFolder - relative path to the rootFolder of the project @returns {array} - An array of regexes
[ "Get", "a", "list", "of", "regexes", "of", "filenames", "to", "ignore", "while", "pushing" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/ignore.js#L48-L56
train
MaartenDesnouck/google-apps-script
lib/functions/downloadIncludedFiles.js
getAndWriteIncludedFile
function getAndWriteIncludedFile(file, includeDir) { return new Promise((resolve, reject) => { const fileName = file[0]; const fileURL = file[1]; const options = { url: fileURL, headers: { 'User-Agent': 'request', }, }; request.get(options, (err, response, body) => { if (!err && response.statusCode === 200) { fs.writeFile(path.join(includeDir, fileName), body, (writeErr) => { if (writeErr) { resolve({ fileName, successful: false, }); } else { resolve({ fileName, successful: true, }); } return; }); } else { resolve({ fileName, successful: false, }); return; } }); }); }
javascript
function getAndWriteIncludedFile(file, includeDir) { return new Promise((resolve, reject) => { const fileName = file[0]; const fileURL = file[1]; const options = { url: fileURL, headers: { 'User-Agent': 'request', }, }; request.get(options, (err, response, body) => { if (!err && response.statusCode === 200) { fs.writeFile(path.join(includeDir, fileName), body, (writeErr) => { if (writeErr) { resolve({ fileName, successful: false, }); } else { resolve({ fileName, successful: true, }); } return; }); } else { resolve({ fileName, successful: false, }); return; } }); }); }
[ "function", "getAndWriteIncludedFile", "(", "file", ",", "includeDir", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "fileName", "=", "file", "[", "0", "]", ";", "const", "fileURL", "=", "file", "[", "1", "]", ";", "const", "options", "=", "{", "url", ":", "fileURL", ",", "headers", ":", "{", "'User-Agent'", ":", "'request'", ",", "}", ",", "}", ";", "request", ".", "get", "(", "options", ",", "(", "err", ",", "response", ",", "body", ")", "=>", "{", "if", "(", "!", "err", "&&", "response", ".", "statusCode", "===", "200", ")", "{", "fs", ".", "writeFile", "(", "path", ".", "join", "(", "includeDir", ",", "fileName", ")", ",", "body", ",", "(", "writeErr", ")", "=>", "{", "if", "(", "writeErr", ")", "{", "resolve", "(", "{", "fileName", ",", "successful", ":", "false", ",", "}", ")", ";", "}", "else", "{", "resolve", "(", "{", "fileName", ",", "successful", ":", "true", ",", "}", ")", ";", "}", "return", ";", "}", ")", ";", "}", "else", "{", "resolve", "(", "{", "fileName", ",", "successful", ":", "false", ",", "}", ")", ";", "return", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Get and write all included files @param {Object} file - File to get and write. @param {String} includeDir - Where to write the included files. @returns {Promise} - Promise resolving an object with the fileName and if include was successful
[ "Get", "and", "write", "all", "included", "files" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/downloadIncludedFiles.js#L16-L53
train
MaartenDesnouck/google-apps-script
lib/functions/downloadIncludedFiles.js
downloadIncludedFiles
function downloadIncludedFiles(included, dir) { return new Promise((resolve, reject) => { const includeDir = dir ? path.join('.', dir, constants.INCLUDE_DIR) : path.join('.', constants.INCLUDE_DIR); // Create include folder if it doesn't exist yet try { if (!fs.existsSync(includeDir)) { fs.mkdirSync(includeDir); } // Create list of filenames const filenames = []; for (const includeFile of included) { filenames.push(includeFile[0]); } // Remove all files in includeDir not in includeFile const allFiles = fs.readdirSync(includeDir); const filesToDelete = []; for (const file of allFiles) { if (filenames.indexOf(file) < 0) { filesToDelete.push(path.join(includeDir, file)); } } for (const fileToDelete of filesToDelete) { fs.removeSync(fileToDelete); } // Download all the files const promises = []; for (const file of included) { promises.push(getAndWriteIncludedFile(file, includeDir)); } Promise.all(promises).then((values) => { const failed = []; const successful = []; for (const value of values) { if (value.successful) { successful.push(value.fileName); } else { failed.push(value.fileName); } } resolve({ failed, successful, }); }); } catch (err) { reject(err); return; } }); }
javascript
function downloadIncludedFiles(included, dir) { return new Promise((resolve, reject) => { const includeDir = dir ? path.join('.', dir, constants.INCLUDE_DIR) : path.join('.', constants.INCLUDE_DIR); // Create include folder if it doesn't exist yet try { if (!fs.existsSync(includeDir)) { fs.mkdirSync(includeDir); } // Create list of filenames const filenames = []; for (const includeFile of included) { filenames.push(includeFile[0]); } // Remove all files in includeDir not in includeFile const allFiles = fs.readdirSync(includeDir); const filesToDelete = []; for (const file of allFiles) { if (filenames.indexOf(file) < 0) { filesToDelete.push(path.join(includeDir, file)); } } for (const fileToDelete of filesToDelete) { fs.removeSync(fileToDelete); } // Download all the files const promises = []; for (const file of included) { promises.push(getAndWriteIncludedFile(file, includeDir)); } Promise.all(promises).then((values) => { const failed = []; const successful = []; for (const value of values) { if (value.successful) { successful.push(value.fileName); } else { failed.push(value.fileName); } } resolve({ failed, successful, }); }); } catch (err) { reject(err); return; } }); }
[ "function", "downloadIncludedFiles", "(", "included", ",", "dir", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "includeDir", "=", "dir", "?", "path", ".", "join", "(", "'.'", ",", "dir", ",", "constants", ".", "INCLUDE_DIR", ")", ":", "path", ".", "join", "(", "'.'", ",", "constants", ".", "INCLUDE_DIR", ")", ";", "try", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "includeDir", ")", ")", "{", "fs", ".", "mkdirSync", "(", "includeDir", ")", ";", "}", "const", "filenames", "=", "[", "]", ";", "for", "(", "const", "includeFile", "of", "included", ")", "{", "filenames", ".", "push", "(", "includeFile", "[", "0", "]", ")", ";", "}", "const", "allFiles", "=", "fs", ".", "readdirSync", "(", "includeDir", ")", ";", "const", "filesToDelete", "=", "[", "]", ";", "for", "(", "const", "file", "of", "allFiles", ")", "{", "if", "(", "filenames", ".", "indexOf", "(", "file", ")", "<", "0", ")", "{", "filesToDelete", ".", "push", "(", "path", ".", "join", "(", "includeDir", ",", "file", ")", ")", ";", "}", "}", "for", "(", "const", "fileToDelete", "of", "filesToDelete", ")", "{", "fs", ".", "removeSync", "(", "fileToDelete", ")", ";", "}", "const", "promises", "=", "[", "]", ";", "for", "(", "const", "file", "of", "included", ")", "{", "promises", ".", "push", "(", "getAndWriteIncludedFile", "(", "file", ",", "includeDir", ")", ")", ";", "}", "Promise", ".", "all", "(", "promises", ")", ".", "then", "(", "(", "values", ")", "=>", "{", "const", "failed", "=", "[", "]", ";", "const", "successful", "=", "[", "]", ";", "for", "(", "const", "value", "of", "values", ")", "{", "if", "(", "value", ".", "successful", ")", "{", "successful", ".", "push", "(", "value", ".", "fileName", ")", ";", "}", "else", "{", "failed", ".", "push", "(", "value", ".", "fileName", ")", ";", "}", "}", "resolve", "(", "{", "failed", ",", "successful", ",", "}", ")", ";", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "return", ";", "}", "}", ")", ";", "}" ]
Download files specified by include file @param {array} included - An authorized OAuth2 client. @param {String} dir - Directory in which the project is located. @returns {Promise} - Promise resolving
[ "Download", "files", "specified", "by", "include", "file" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/downloadIncludedFiles.js#L62-L115
train
MaartenDesnouck/google-apps-script
lib/functions/displayProjectInfo.js
displayProjectInfo
function displayProjectInfo(metadata) { console.log(`NAME ${metadata.name}`); console.log(`ID ${metadata.projectId}`); console.log(`CREATED_AT ${metadata.createTime}`); console.log(`LAST_MODIFIED_AT ${metadata.updateTime}`); console.log(`CREATOR ${metadata.creator.name} - ${metadata.creator.email}`); return; }
javascript
function displayProjectInfo(metadata) { console.log(`NAME ${metadata.name}`); console.log(`ID ${metadata.projectId}`); console.log(`CREATED_AT ${metadata.createTime}`); console.log(`LAST_MODIFIED_AT ${metadata.updateTime}`); console.log(`CREATOR ${metadata.creator.name} - ${metadata.creator.email}`); return; }
[ "function", "displayProjectInfo", "(", "metadata", ")", "{", "console", ".", "log", "(", "`", "${", "metadata", ".", "name", "}", "`", ")", ";", "console", ".", "log", "(", "`", "${", "metadata", ".", "projectId", "}", "`", ")", ";", "console", ".", "log", "(", "`", "${", "metadata", ".", "createTime", "}", "`", ")", ";", "console", ".", "log", "(", "`", "${", "metadata", ".", "updateTime", "}", "`", ")", ";", "console", ".", "log", "(", "`", "${", "metadata", ".", "creator", ".", "name", "}", "${", "metadata", ".", "creator", ".", "email", "}", "`", ")", ";", "return", ";", "}" ]
Display info about the project. @param {Object} metadata - Metadata to display. @returns {void}
[ "Display", "info", "about", "the", "project", "." ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/displayProjectInfo.js#L7-L14
train
MaartenDesnouck/google-apps-script
lib/functions/pack.js
getFileJSON
function getFileJSON(rootFolder, file, fileName, extension, id) { return new Promise((resolve, reject) => { fs.stat(path.join(rootFolder, file), (err, stats) => { if (err) { reject(); return; } if (stats.isFile()) { // Read local javascript file fs.readFile(path.join(rootFolder, file), 'utf8', (err, source) => { if (err) { reject(err); return; } const type = eaft.getFiletypeFromExtension(extension); const fileJSON = { name: fileName, type, source, id, }; resolve(fileJSON); return; }); } else { reject(); return; } }); }); }
javascript
function getFileJSON(rootFolder, file, fileName, extension, id) { return new Promise((resolve, reject) => { fs.stat(path.join(rootFolder, file), (err, stats) => { if (err) { reject(); return; } if (stats.isFile()) { // Read local javascript file fs.readFile(path.join(rootFolder, file), 'utf8', (err, source) => { if (err) { reject(err); return; } const type = eaft.getFiletypeFromExtension(extension); const fileJSON = { name: fileName, type, source, id, }; resolve(fileJSON); return; }); } else { reject(); return; } }); }); }
[ "function", "getFileJSON", "(", "rootFolder", ",", "file", ",", "fileName", ",", "extension", ",", "id", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "fs", ".", "stat", "(", "path", ".", "join", "(", "rootFolder", ",", "file", ")", ",", "(", "err", ",", "stats", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", ")", ";", "return", ";", "}", "if", "(", "stats", ".", "isFile", "(", ")", ")", "{", "fs", ".", "readFile", "(", "path", ".", "join", "(", "rootFolder", ",", "file", ")", ",", "'utf8'", ",", "(", "err", ",", "source", ")", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "return", ";", "}", "const", "type", "=", "eaft", ".", "getFiletypeFromExtension", "(", "extension", ")", ";", "const", "fileJSON", "=", "{", "name", ":", "fileName", ",", "type", ",", "source", ",", "id", ",", "}", ";", "resolve", "(", "fileJSON", ")", ";", "return", ";", "}", ")", ";", "}", "else", "{", "reject", "(", ")", ";", "return", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Getting the json form of a file. @param {String} rootFolder - relative path to the rootFOldr of the project. @param {String} file - Full filename of the file to process. @param {String} fileName - fileName without extension. @param {String} extension - Only the extension of the filename. @param {String} id - Optional id of the file in the remote project. @returns {Promise} - Promise resolving the json form of the file
[ "Getting", "the", "json", "form", "of", "a", "file", "." ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/pack.js#L19-L51
train
MaartenDesnouck/google-apps-script
lib/functions/pack.js
local
function local(rootFolder) { // Construct name to remote id map const remote = path.join(rootFolder, constants.META_DIR, constants.META_REMOTE); const remoteSource = fs.readJsonSync(remote, 'utf8'); const destination = constants.META_LOCAL; return pack(rootFolder, destination); }
javascript
function local(rootFolder) { // Construct name to remote id map const remote = path.join(rootFolder, constants.META_DIR, constants.META_REMOTE); const remoteSource = fs.readJsonSync(remote, 'utf8'); const destination = constants.META_LOCAL; return pack(rootFolder, destination); }
[ "function", "local", "(", "rootFolder", ")", "{", "const", "remote", "=", "path", ".", "join", "(", "rootFolder", ",", "constants", ".", "META_DIR", ",", "constants", ".", "META_REMOTE", ")", ";", "const", "remoteSource", "=", "fs", ".", "readJsonSync", "(", "remote", ",", "'utf8'", ")", ";", "const", "destination", "=", "constants", ".", "META_LOCAL", ";", "return", "pack", "(", "rootFolder", ",", "destination", ")", ";", "}" ]
Pack all seperate .js files into a raw google script file for pushing @param {String} rootFolder - relative path to the rootFolder of the project @returns {Promise} - A promise resolving no value
[ "Pack", "all", "seperate", ".", "js", "files", "into", "a", "raw", "google", "script", "file", "for", "pushing" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/pack.js#L133-L139
train
MaartenDesnouck/google-apps-script
lib/functions/pack.js
publish
function publish(rootFolder) { // Read every local file and create a correct json file in .gas/${destination} ignore.addGitIgnore(rootFolder); ignore.addGasIgnore(rootFolder); const destination = constants.META_PUBLISH; return pack(rootFolder, destination); }
javascript
function publish(rootFolder) { // Read every local file and create a correct json file in .gas/${destination} ignore.addGitIgnore(rootFolder); ignore.addGasIgnore(rootFolder); const destination = constants.META_PUBLISH; return pack(rootFolder, destination); }
[ "function", "publish", "(", "rootFolder", ")", "{", "ignore", ".", "addGitIgnore", "(", "rootFolder", ")", ";", "ignore", ".", "addGasIgnore", "(", "rootFolder", ")", ";", "const", "destination", "=", "constants", ".", "META_PUBLISH", ";", "return", "pack", "(", "rootFolder", ",", "destination", ")", ";", "}" ]
Pack all seperate .js files into a raw google script file for publishing @param {String} rootFolder - relative path to the rootFolder of the project @returns {Promise} - A promise resolving no value
[ "Pack", "all", "seperate", ".", "js", "files", "into", "a", "raw", "google", "script", "file", "for", "publishing" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/pack.js#L147-L153
train
restify/enroute
lib/index.js
function (opts, cb) { assert.object(opts, 'opts'); assert.func(cb, 'cb'); // asserts of other inputs done by parse and installRoutes respectively vasync.pipeline({arg: {}, funcs: [ function parse(ctx, _cb) { parser.parse(opts, function (err, config) { ctx.config = config.validatedConfig; ctx.basePath = config.basePath; return _cb(err); }); }, function installRoutes(ctx, _cb) { install({ enroute: ctx.config, server: opts.server, basePath: ctx.basePath, hotReload: opts.hotReload, excludePath: opts.excludePath }, function (err) { return _cb(err); }); } ]}, function (err, res) { return cb(err); }); }
javascript
function (opts, cb) { assert.object(opts, 'opts'); assert.func(cb, 'cb'); // asserts of other inputs done by parse and installRoutes respectively vasync.pipeline({arg: {}, funcs: [ function parse(ctx, _cb) { parser.parse(opts, function (err, config) { ctx.config = config.validatedConfig; ctx.basePath = config.basePath; return _cb(err); }); }, function installRoutes(ctx, _cb) { install({ enroute: ctx.config, server: opts.server, basePath: ctx.basePath, hotReload: opts.hotReload, excludePath: opts.excludePath }, function (err) { return _cb(err); }); } ]}, function (err, res) { return cb(err); }); }
[ "function", "(", "opts", ",", "cb", ")", "{", "assert", ".", "object", "(", "opts", ",", "'opts'", ")", ";", "assert", ".", "func", "(", "cb", ",", "'cb'", ")", ";", "vasync", ".", "pipeline", "(", "{", "arg", ":", "{", "}", ",", "funcs", ":", "[", "function", "parse", "(", "ctx", ",", "_cb", ")", "{", "parser", ".", "parse", "(", "opts", ",", "function", "(", "err", ",", "config", ")", "{", "ctx", ".", "config", "=", "config", ".", "validatedConfig", ";", "ctx", ".", "basePath", "=", "config", ".", "basePath", ";", "return", "_cb", "(", "err", ")", ";", "}", ")", ";", "}", ",", "function", "installRoutes", "(", "ctx", ",", "_cb", ")", "{", "install", "(", "{", "enroute", ":", "ctx", ".", "config", ",", "server", ":", "opts", ".", "server", ",", "basePath", ":", "ctx", ".", "basePath", ",", "hotReload", ":", "opts", ".", "hotReload", ",", "excludePath", ":", "opts", ".", "excludePath", "}", ",", "function", "(", "err", ")", "{", "return", "_cb", "(", "err", ")", ";", "}", ")", ";", "}", "]", "}", ",", "function", "(", "err", ",", "res", ")", "{", "return", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
Installs configuration driven routes onto a restify server. Note only one of opts.config or opts.configPath is needed. exports @param {object} opts Options object. @param {string} [opts.config] The POJO of the config you want to validate. @param {string} [opts.configPath] The path to the data on disk to validate. @param {boolean} [opts.hotReload] Whether to hot reload the routes @param {string} [opts.excludePath] The path to exclude relative to the base path @param {string} opts.server The restify server to install the routes onto. @param {function} cb The callback f(err, result) @returns {undefined}
[ "Installs", "configuration", "driven", "routes", "onto", "a", "restify", "server", ".", "Note", "only", "one", "of", "opts", ".", "config", "or", "opts", ".", "configPath", "is", "needed", "." ]
df5f9f25149fcb248267db9d8927aba28b9a3d4e
https://github.com/restify/enroute/blob/df5f9f25149fcb248267db9d8927aba28b9a3d4e/lib/index.js#L29-L55
train
MaartenDesnouck/google-apps-script
lib/functions/remoteCreateProject.js
remoteCreateProject
function remoteCreateProject(auth, name) { return new Promise((resolve, reject) => { const drive = google.drive('v3'); const options = { auth, resource: { name, mimeType: constants.MIME_GAS_JSON, }, media: { mimeType: constants.MIME_GAS_JSON, body: JSON.stringify(files), }, }; drive.files.create(options, (err, result) => { if (err) { triageGoogleError(err, 'remoteCreateProject').then((triaged) => { reject(triaged); }).catch((notTriaged) => { reject(notTriaged); }); } else { resolve(result.data); return; } return; }); }); }
javascript
function remoteCreateProject(auth, name) { return new Promise((resolve, reject) => { const drive = google.drive('v3'); const options = { auth, resource: { name, mimeType: constants.MIME_GAS_JSON, }, media: { mimeType: constants.MIME_GAS_JSON, body: JSON.stringify(files), }, }; drive.files.create(options, (err, result) => { if (err) { triageGoogleError(err, 'remoteCreateProject').then((triaged) => { reject(triaged); }).catch((notTriaged) => { reject(notTriaged); }); } else { resolve(result.data); return; } return; }); }); }
[ "function", "remoteCreateProject", "(", "auth", ",", "name", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "drive", "=", "google", ".", "drive", "(", "'v3'", ")", ";", "const", "options", "=", "{", "auth", ",", "resource", ":", "{", "name", ",", "mimeType", ":", "constants", ".", "MIME_GAS_JSON", ",", "}", ",", "media", ":", "{", "mimeType", ":", "constants", ".", "MIME_GAS_JSON", ",", "body", ":", "JSON", ".", "stringify", "(", "files", ")", ",", "}", ",", "}", ";", "drive", ".", "files", ".", "create", "(", "options", ",", "(", "err", ",", "result", ")", "=>", "{", "if", "(", "err", ")", "{", "triageGoogleError", "(", "err", ",", "'remoteCreateProject'", ")", ".", "then", "(", "(", "triaged", ")", "=>", "{", "reject", "(", "triaged", ")", ";", "}", ")", ".", "catch", "(", "(", "notTriaged", ")", "=>", "{", "reject", "(", "notTriaged", ")", ";", "}", ")", ";", "}", "else", "{", "resolve", "(", "result", ".", "data", ")", ";", "return", ";", "}", "return", ";", "}", ")", ";", "}", ")", ";", "}" ]
Create a new remote script file @param {google.auth.OAuth2} auth - An authorized OAuth2 client. @param {String} name - Name to give to the new Google Apps Script file. @returns {Promise} - A promise resolving the metadata of the newly created project
[ "Create", "a", "new", "remote", "script", "file" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/remoteCreateProject.js#L26-L55
train
pugjs/then-pug
packages/then-pug/lib/pug-code-gen-module.js
function(block){ var escapePrettyMode = this.escapePrettyMode; var pp = this.pp; var ast = []; // Pretty print multi-line text if (pp && block.nodes.length > 1 && !escapePrettyMode && block.nodes[0].type === 'Text' && block.nodes[1].type === 'Text' ) { push.apply(ast, this.prettyIndent(1, true)); } for (var i = 0; i < block.nodes.length; ++i) { // Pretty print text if (pp && i > 0 && !escapePrettyMode && block.nodes[i].type === 'Text' && block.nodes[i-1].type === 'Text' && /\n$/.test(block.nodes[i - 1].val)) { push.apply(ast,this.prettyIndent(1, false)); } push.apply(ast, this.visit(block.nodes[i], block)); } return ast; }
javascript
function(block){ var escapePrettyMode = this.escapePrettyMode; var pp = this.pp; var ast = []; // Pretty print multi-line text if (pp && block.nodes.length > 1 && !escapePrettyMode && block.nodes[0].type === 'Text' && block.nodes[1].type === 'Text' ) { push.apply(ast, this.prettyIndent(1, true)); } for (var i = 0; i < block.nodes.length; ++i) { // Pretty print text if (pp && i > 0 && !escapePrettyMode && block.nodes[i].type === 'Text' && block.nodes[i-1].type === 'Text' && /\n$/.test(block.nodes[i - 1].val)) { push.apply(ast,this.prettyIndent(1, false)); } push.apply(ast, this.visit(block.nodes[i], block)); } return ast; }
[ "function", "(", "block", ")", "{", "var", "escapePrettyMode", "=", "this", ".", "escapePrettyMode", ";", "var", "pp", "=", "this", ".", "pp", ";", "var", "ast", "=", "[", "]", ";", "if", "(", "pp", "&&", "block", ".", "nodes", ".", "length", ">", "1", "&&", "!", "escapePrettyMode", "&&", "block", ".", "nodes", "[", "0", "]", ".", "type", "===", "'Text'", "&&", "block", ".", "nodes", "[", "1", "]", ".", "type", "===", "'Text'", ")", "{", "push", ".", "apply", "(", "ast", ",", "this", ".", "prettyIndent", "(", "1", ",", "true", ")", ")", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "block", ".", "nodes", ".", "length", ";", "++", "i", ")", "{", "if", "(", "pp", "&&", "i", ">", "0", "&&", "!", "escapePrettyMode", "&&", "block", ".", "nodes", "[", "i", "]", ".", "type", "===", "'Text'", "&&", "block", ".", "nodes", "[", "i", "-", "1", "]", ".", "type", "===", "'Text'", "&&", "/", "\\n$", "/", ".", "test", "(", "block", ".", "nodes", "[", "i", "-", "1", "]", ".", "val", ")", ")", "{", "push", ".", "apply", "(", "ast", ",", "this", ".", "prettyIndent", "(", "1", ",", "false", ")", ")", ";", "}", "push", ".", "apply", "(", "ast", ",", "this", ".", "visit", "(", "block", ".", "nodes", "[", "i", "]", ",", "block", ")", ")", ";", "}", "return", "ast", ";", "}" ]
Visit all nodes in `block`. @param {Block} block @api public
[ "Visit", "all", "nodes", "in", "block", "." ]
a96c2a9c6d1f0875aef4641064500f818f7e7571
https://github.com/pugjs/then-pug/blob/a96c2a9c6d1f0875aef4641064500f818f7e7571/packages/then-pug/lib/pug-code-gen-module.js#L538-L557
train
pugjs/then-pug
packages/then-pug/lib/pug-code-gen-module.js
function(comment){ var ast = []; if (!comment.buffer) return; if (this.pp) push.apply(ast, this.prettyIndent(1, true)); push.apply(ast, this.buffer('<!--' + comment.val + '-->')); return ast; }
javascript
function(comment){ var ast = []; if (!comment.buffer) return; if (this.pp) push.apply(ast, this.prettyIndent(1, true)); push.apply(ast, this.buffer('<!--' + comment.val + '-->')); return ast; }
[ "function", "(", "comment", ")", "{", "var", "ast", "=", "[", "]", ";", "if", "(", "!", "comment", ".", "buffer", ")", "return", ";", "if", "(", "this", ".", "pp", ")", "push", ".", "apply", "(", "ast", ",", "this", ".", "prettyIndent", "(", "1", ",", "true", ")", ")", ";", "push", ".", "apply", "(", "ast", ",", "this", ".", "buffer", "(", "'<!--'", "+", "comment", ".", "val", "+", "'", ")", ")", ";", "return", "ast", ";", "}" ]
Visit a `comment`, only buffering when the buffer flag is set. @param {Comment} comment @api public
[ "Visit", "a", "comment", "only", "buffering", "when", "the", "buffer", "flag", "is", "set", "." ]
a96c2a9c6d1f0875aef4641064500f818f7e7571
https://github.com/pugjs/then-pug/blob/a96c2a9c6d1f0875aef4641064500f818f7e7571/packages/then-pug/lib/pug-code-gen-module.js#L929-L935
train
pugjs/then-pug
packages/then-pug/lib/pug-code-gen-module.js
function(attrs, buffer){ var res = compileAttrs(attrs, { terse: this.terse, format: buffer ? 'html' : 'object', runtime: this.runtime.bind(this) }); return res; }
javascript
function(attrs, buffer){ var res = compileAttrs(attrs, { terse: this.terse, format: buffer ? 'html' : 'object', runtime: this.runtime.bind(this) }); return res; }
[ "function", "(", "attrs", ",", "buffer", ")", "{", "var", "res", "=", "compileAttrs", "(", "attrs", ",", "{", "terse", ":", "this", ".", "terse", ",", "format", ":", "buffer", "?", "'html'", ":", "'object'", ",", "runtime", ":", "this", ".", "runtime", ".", "bind", "(", "this", ")", "}", ")", ";", "return", "res", ";", "}" ]
Compile attributes.
[ "Compile", "attributes", "." ]
a96c2a9c6d1f0875aef4641064500f818f7e7571
https://github.com/pugjs/then-pug/blob/a96c2a9c6d1f0875aef4641064500f818f7e7571/packages/then-pug/lib/pug-code-gen-module.js#L1228-L1235
train
MaartenDesnouck/google-apps-script
lib/init.js
createPackageFile
function createPackageFile(content) { // todo in the rootfolder createFile({ name: constants.INCLUDE_FILE, source: `${JSON.stringify(content)}\n`, }); }
javascript
function createPackageFile(content) { // todo in the rootfolder createFile({ name: constants.INCLUDE_FILE, source: `${JSON.stringify(content)}\n`, }); }
[ "function", "createPackageFile", "(", "content", ")", "{", "createFile", "(", "{", "name", ":", "constants", ".", "INCLUDE_FILE", ",", "source", ":", "`", "${", "JSON", ".", "stringify", "(", "content", ")", "}", "\\n", "`", ",", "}", ")", ";", "}" ]
Create a package.json file based on the values provided @param {Object} content - Package.json to create @returns {void}
[ "Create", "a", "package", ".", "json", "file", "based", "on", "the", "values", "provided" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/init.js#L13-L19
train
MaartenDesnouck/google-apps-script
lib/init.js
endDialog
function endDialog(success, content) { if (success) { createPackageFile(content); process.stdout.write('Succesfully created gas-include.json'); checkbox.display('green'); process.exit(0); } else { process.stdout.write('Failed to create gas-include.json'); checkbox.display('red'); process.exit(1); } }
javascript
function endDialog(success, content) { if (success) { createPackageFile(content); process.stdout.write('Succesfully created gas-include.json'); checkbox.display('green'); process.exit(0); } else { process.stdout.write('Failed to create gas-include.json'); checkbox.display('red'); process.exit(1); } }
[ "function", "endDialog", "(", "success", ",", "content", ")", "{", "if", "(", "success", ")", "{", "createPackageFile", "(", "content", ")", ";", "process", ".", "stdout", ".", "write", "(", "'Succesfully created gas-include.json'", ")", ";", "checkbox", ".", "display", "(", "'green'", ")", ";", "process", ".", "exit", "(", "0", ")", ";", "}", "else", "{", "process", ".", "stdout", ".", "write", "(", "'Failed to create gas-include.json'", ")", ";", "checkbox", ".", "display", "(", "'red'", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "}" ]
Create a package file based on the values provided @param {String} success - Whether or not the dialog completed succesfully @param {String} content - Package.json to create @returns {void}
[ "Create", "a", "package", "file", "based", "on", "the", "values", "provided" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/init.js#L28-L39
train
MaartenDesnouck/google-apps-script
lib/functions/findInProject.js
findInProject
function findInProject(dir, name) { return new Promise((resolve, reject) => { const fullPath = process.cwd(); const pieces = fullPath.split(path.sep); let folderCounter = 0; let found = false; let folder = dir; while (folderCounter < pieces.length - 1 && !found) { if (fs.existsSync(path.join(folder, name))) { found = true; } else { folderCounter++; folder = path.join('..', folder); } } resolve({ found, folder, }); }); }
javascript
function findInProject(dir, name) { return new Promise((resolve, reject) => { const fullPath = process.cwd(); const pieces = fullPath.split(path.sep); let folderCounter = 0; let found = false; let folder = dir; while (folderCounter < pieces.length - 1 && !found) { if (fs.existsSync(path.join(folder, name))) { found = true; } else { folderCounter++; folder = path.join('..', folder); } } resolve({ found, folder, }); }); }
[ "function", "findInProject", "(", "dir", ",", "name", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "fullPath", "=", "process", ".", "cwd", "(", ")", ";", "const", "pieces", "=", "fullPath", ".", "split", "(", "path", ".", "sep", ")", ";", "let", "folderCounter", "=", "0", ";", "let", "found", "=", "false", ";", "let", "folder", "=", "dir", ";", "while", "(", "folderCounter", "<", "pieces", ".", "length", "-", "1", "&&", "!", "found", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "path", ".", "join", "(", "folder", ",", "name", ")", ")", ")", "{", "found", "=", "true", ";", "}", "else", "{", "folderCounter", "++", ";", "folder", "=", "path", ".", "join", "(", "'..'", ",", "folder", ")", ";", "}", "}", "resolve", "(", "{", "found", ",", "folder", ",", "}", ")", ";", "}", ")", ";", "}" ]
Find the project root folder @param {String} dir - Current directory @param {String} name - Name of item of folder to find @returns {void}
[ "Find", "the", "project", "root", "folder" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/findInProject.js#L11-L32
train
MaartenDesnouck/google-apps-script
lib/functions/unpackRemote.js
unpackRemote
function unpackRemote(rootFolder, fileName) { let foundSingleFile = false; const local = path.join(rootFolder, constants.META_DIR, constants.META_LOCAL); const remote = path.join(rootFolder, constants.META_DIR, constants.META_REMOTE); // Read local files const localFiles = getAllFiles(rootFolder, '.', []); // Get valid extensions for code files const extensions = eaft.getCodeExtensions(); // Get contents of .gasignore file const ignoreRegexes = ignore.getIgnoreRegexes(rootFolder); // Read remote.json const data = fs.readFileSync(remote, 'utf8'); const result = JSON.parse(data); // Create all javascript/html files from remote.json const remoteFiles = []; const remoteNames = []; for (const file of result.files) { const extension = eaft.getExtensionFromFiletype(file.type, extensions); const remoteFileName = file.name + extension; file.name = path.join(rootFolder, remoteFileName); remoteNames.push(remoteFileName); const included = file.name.substring(0, constants.INCLUDE_DIR.length + 1) === `${constants.INCLUDE_DIR}/`; // What files do we need to create? if (!fileName) { remoteFiles.push(file); } else if (fileName === remoteFileName) { remoteFiles.push(file); foundSingleFile = true; } } // If we have not found our file if (fileName && !foundSingleFile) { console.log(`Can't seem to find the file '${fileName}' in this project`); return; } // Write local.json createFile({ name: local, source: data, }); // Sync create all necessary files for (const remoteFile of remoteFiles) { createFile(remoteFile); } // If there was no file specified to pull we will do a cleanup if (!fileName) { // Remove all .gs, .js, .html and appsscript.json files that were not in remote.json unless they are in .gasignore const toDelete = []; for (const localFileName of localFiles) { const localExtension = path.parse(localFileName).ext; const fileNameWithoutExtension = path.join(path.parse(localFileName).dir, path.parse(localFileName).name); if (eaft.isPushable(localExtension, fileNameWithoutExtension, extensions, ignoreRegexes) && !remoteNames.includes(localFileName) && localFileName !== constants.INCLUDE_FILE) { toDelete.push(path.join(rootFolder, localFileName)); } } // Delete files for (const fileToDelete of toDelete) { fs.removeSync(fileToDelete); } // Remove all empty folders const allFolders = getAllFolders(rootFolder).sort().reverse(); for (const emptyFolder of allFolders) { const files = fs.readdirSync(emptyFolder); if (files.length === 0) { fs.removeSync(emptyFolder); } else if (files.length === 1 && files[0] === '.DS_Store') { fs.removeSync(emptyFolder); } } } ignore.addGitIgnore(rootFolder); ignore.addGasIgnore(rootFolder); }
javascript
function unpackRemote(rootFolder, fileName) { let foundSingleFile = false; const local = path.join(rootFolder, constants.META_DIR, constants.META_LOCAL); const remote = path.join(rootFolder, constants.META_DIR, constants.META_REMOTE); // Read local files const localFiles = getAllFiles(rootFolder, '.', []); // Get valid extensions for code files const extensions = eaft.getCodeExtensions(); // Get contents of .gasignore file const ignoreRegexes = ignore.getIgnoreRegexes(rootFolder); // Read remote.json const data = fs.readFileSync(remote, 'utf8'); const result = JSON.parse(data); // Create all javascript/html files from remote.json const remoteFiles = []; const remoteNames = []; for (const file of result.files) { const extension = eaft.getExtensionFromFiletype(file.type, extensions); const remoteFileName = file.name + extension; file.name = path.join(rootFolder, remoteFileName); remoteNames.push(remoteFileName); const included = file.name.substring(0, constants.INCLUDE_DIR.length + 1) === `${constants.INCLUDE_DIR}/`; // What files do we need to create? if (!fileName) { remoteFiles.push(file); } else if (fileName === remoteFileName) { remoteFiles.push(file); foundSingleFile = true; } } // If we have not found our file if (fileName && !foundSingleFile) { console.log(`Can't seem to find the file '${fileName}' in this project`); return; } // Write local.json createFile({ name: local, source: data, }); // Sync create all necessary files for (const remoteFile of remoteFiles) { createFile(remoteFile); } // If there was no file specified to pull we will do a cleanup if (!fileName) { // Remove all .gs, .js, .html and appsscript.json files that were not in remote.json unless they are in .gasignore const toDelete = []; for (const localFileName of localFiles) { const localExtension = path.parse(localFileName).ext; const fileNameWithoutExtension = path.join(path.parse(localFileName).dir, path.parse(localFileName).name); if (eaft.isPushable(localExtension, fileNameWithoutExtension, extensions, ignoreRegexes) && !remoteNames.includes(localFileName) && localFileName !== constants.INCLUDE_FILE) { toDelete.push(path.join(rootFolder, localFileName)); } } // Delete files for (const fileToDelete of toDelete) { fs.removeSync(fileToDelete); } // Remove all empty folders const allFolders = getAllFolders(rootFolder).sort().reverse(); for (const emptyFolder of allFolders) { const files = fs.readdirSync(emptyFolder); if (files.length === 0) { fs.removeSync(emptyFolder); } else if (files.length === 1 && files[0] === '.DS_Store') { fs.removeSync(emptyFolder); } } } ignore.addGitIgnore(rootFolder); ignore.addGasIgnore(rootFolder); }
[ "function", "unpackRemote", "(", "rootFolder", ",", "fileName", ")", "{", "let", "foundSingleFile", "=", "false", ";", "const", "local", "=", "path", ".", "join", "(", "rootFolder", ",", "constants", ".", "META_DIR", ",", "constants", ".", "META_LOCAL", ")", ";", "const", "remote", "=", "path", ".", "join", "(", "rootFolder", ",", "constants", ".", "META_DIR", ",", "constants", ".", "META_REMOTE", ")", ";", "const", "localFiles", "=", "getAllFiles", "(", "rootFolder", ",", "'.'", ",", "[", "]", ")", ";", "const", "extensions", "=", "eaft", ".", "getCodeExtensions", "(", ")", ";", "const", "ignoreRegexes", "=", "ignore", ".", "getIgnoreRegexes", "(", "rootFolder", ")", ";", "const", "data", "=", "fs", ".", "readFileSync", "(", "remote", ",", "'utf8'", ")", ";", "const", "result", "=", "JSON", ".", "parse", "(", "data", ")", ";", "const", "remoteFiles", "=", "[", "]", ";", "const", "remoteNames", "=", "[", "]", ";", "for", "(", "const", "file", "of", "result", ".", "files", ")", "{", "const", "extension", "=", "eaft", ".", "getExtensionFromFiletype", "(", "file", ".", "type", ",", "extensions", ")", ";", "const", "remoteFileName", "=", "file", ".", "name", "+", "extension", ";", "file", ".", "name", "=", "path", ".", "join", "(", "rootFolder", ",", "remoteFileName", ")", ";", "remoteNames", ".", "push", "(", "remoteFileName", ")", ";", "const", "included", "=", "file", ".", "name", ".", "substring", "(", "0", ",", "constants", ".", "INCLUDE_DIR", ".", "length", "+", "1", ")", "===", "`", "${", "constants", ".", "INCLUDE_DIR", "}", "`", ";", "if", "(", "!", "fileName", ")", "{", "remoteFiles", ".", "push", "(", "file", ")", ";", "}", "else", "if", "(", "fileName", "===", "remoteFileName", ")", "{", "remoteFiles", ".", "push", "(", "file", ")", ";", "foundSingleFile", "=", "true", ";", "}", "}", "if", "(", "fileName", "&&", "!", "foundSingleFile", ")", "{", "console", ".", "log", "(", "`", "${", "fileName", "}", "`", ")", ";", "return", ";", "}", "createFile", "(", "{", "name", ":", "local", ",", "source", ":", "data", ",", "}", ")", ";", "for", "(", "const", "remoteFile", "of", "remoteFiles", ")", "{", "createFile", "(", "remoteFile", ")", ";", "}", "if", "(", "!", "fileName", ")", "{", "const", "toDelete", "=", "[", "]", ";", "for", "(", "const", "localFileName", "of", "localFiles", ")", "{", "const", "localExtension", "=", "path", ".", "parse", "(", "localFileName", ")", ".", "ext", ";", "const", "fileNameWithoutExtension", "=", "path", ".", "join", "(", "path", ".", "parse", "(", "localFileName", ")", ".", "dir", ",", "path", ".", "parse", "(", "localFileName", ")", ".", "name", ")", ";", "if", "(", "eaft", ".", "isPushable", "(", "localExtension", ",", "fileNameWithoutExtension", ",", "extensions", ",", "ignoreRegexes", ")", "&&", "!", "remoteNames", ".", "includes", "(", "localFileName", ")", "&&", "localFileName", "!==", "constants", ".", "INCLUDE_FILE", ")", "{", "toDelete", ".", "push", "(", "path", ".", "join", "(", "rootFolder", ",", "localFileName", ")", ")", ";", "}", "}", "for", "(", "const", "fileToDelete", "of", "toDelete", ")", "{", "fs", ".", "removeSync", "(", "fileToDelete", ")", ";", "}", "const", "allFolders", "=", "getAllFolders", "(", "rootFolder", ")", ".", "sort", "(", ")", ".", "reverse", "(", ")", ";", "for", "(", "const", "emptyFolder", "of", "allFolders", ")", "{", "const", "files", "=", "fs", ".", "readdirSync", "(", "emptyFolder", ")", ";", "if", "(", "files", ".", "length", "===", "0", ")", "{", "fs", ".", "removeSync", "(", "emptyFolder", ")", ";", "}", "else", "if", "(", "files", ".", "length", "===", "1", "&&", "files", "[", "0", "]", "===", "'.DS_Store'", ")", "{", "fs", ".", "removeSync", "(", "emptyFolder", ")", ";", "}", "}", "}", "ignore", ".", "addGitIgnore", "(", "rootFolder", ")", ";", "ignore", ".", "addGasIgnore", "(", "rootFolder", ")", ";", "}" ]
Unpack a remote google script file into seperate .js and .html files @param {String} rootFolder - relative path to the rootFolder of the project @param {String} fileName - if specified, only this file will get unpacked @returns {Promise} - A promise resolving no value
[ "Unpack", "a", "remote", "google", "script", "file", "into", "seperate", ".", "js", "and", ".", "html", "files" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/unpackRemote.js#L17-L104
train
MaartenDesnouck/google-apps-script
lib/functions/resolveDependencies.js
recDependencies
async function recDependencies(dependencies, root) { let url; // TODO think about doing this in parallel using promises for (const dependency of Reflect.ownKeys(dependencies)) { const range = dependencies[dependency]; url = `${constants.FIREBASE_DATABASE_URL}/package/${dependency}/versions.json`; const versions = await request({ url, method: "GET", json: true, headers: { "content-type": "application/json", }, }); // Translate db versions to semver versions const semverVersions = {}; for (const version of Reflect.ownKeys(versions)) { semverVersions[version.replace(/_/g, '.')] = true; } const semverMatch = semver.maxSatisfying(Reflect.ownKeys(semverVersions), range); const match = semverMatch.replace(/\./g, '_'); const versionKey = `${dependency}_${match}`; // Set result if (dependencies[dependency]) { Reflect.deleteProperty(dependencies, dependency); } dependencies[versionKey] = true; // check if in dependency list yet if (!depencyList[versionKey]) { // Resolve new dependencies url = `${constants.FIREBASE_DATABASE_URL}/package/${dependency}/version/${match}/dependencies.json`; const newDependencies = await request({ url, method: "GET", json: true, headers: { "content-type": "application/json", }, }); // Add to dependencyList depencyList[versionKey] = {}; // Resolve new dependencies if (newDependencies) { depencyList[versionKey].dependencies = await recDependencies(newDependencies); } } if (root) { depencyList[versionKey].isRootDependency = true; } depencyList[versionKey].packageName = dependency; depencyList[versionKey].version = match; } return dependencies; }
javascript
async function recDependencies(dependencies, root) { let url; // TODO think about doing this in parallel using promises for (const dependency of Reflect.ownKeys(dependencies)) { const range = dependencies[dependency]; url = `${constants.FIREBASE_DATABASE_URL}/package/${dependency}/versions.json`; const versions = await request({ url, method: "GET", json: true, headers: { "content-type": "application/json", }, }); // Translate db versions to semver versions const semverVersions = {}; for (const version of Reflect.ownKeys(versions)) { semverVersions[version.replace(/_/g, '.')] = true; } const semverMatch = semver.maxSatisfying(Reflect.ownKeys(semverVersions), range); const match = semverMatch.replace(/\./g, '_'); const versionKey = `${dependency}_${match}`; // Set result if (dependencies[dependency]) { Reflect.deleteProperty(dependencies, dependency); } dependencies[versionKey] = true; // check if in dependency list yet if (!depencyList[versionKey]) { // Resolve new dependencies url = `${constants.FIREBASE_DATABASE_URL}/package/${dependency}/version/${match}/dependencies.json`; const newDependencies = await request({ url, method: "GET", json: true, headers: { "content-type": "application/json", }, }); // Add to dependencyList depencyList[versionKey] = {}; // Resolve new dependencies if (newDependencies) { depencyList[versionKey].dependencies = await recDependencies(newDependencies); } } if (root) { depencyList[versionKey].isRootDependency = true; } depencyList[versionKey].packageName = dependency; depencyList[versionKey].version = match; } return dependencies; }
[ "async", "function", "recDependencies", "(", "dependencies", ",", "root", ")", "{", "let", "url", ";", "for", "(", "const", "dependency", "of", "Reflect", ".", "ownKeys", "(", "dependencies", ")", ")", "{", "const", "range", "=", "dependencies", "[", "dependency", "]", ";", "url", "=", "`", "${", "constants", ".", "FIREBASE_DATABASE_URL", "}", "${", "dependency", "}", "`", ";", "const", "versions", "=", "await", "request", "(", "{", "url", ",", "method", ":", "\"GET\"", ",", "json", ":", "true", ",", "headers", ":", "{", "\"content-type\"", ":", "\"application/json\"", ",", "}", ",", "}", ")", ";", "const", "semverVersions", "=", "{", "}", ";", "for", "(", "const", "version", "of", "Reflect", ".", "ownKeys", "(", "versions", ")", ")", "{", "semverVersions", "[", "version", ".", "replace", "(", "/", "_", "/", "g", ",", "'.'", ")", "]", "=", "true", ";", "}", "const", "semverMatch", "=", "semver", ".", "maxSatisfying", "(", "Reflect", ".", "ownKeys", "(", "semverVersions", ")", ",", "range", ")", ";", "const", "match", "=", "semverMatch", ".", "replace", "(", "/", "\\.", "/", "g", ",", "'_'", ")", ";", "const", "versionKey", "=", "`", "${", "dependency", "}", "${", "match", "}", "`", ";", "if", "(", "dependencies", "[", "dependency", "]", ")", "{", "Reflect", ".", "deleteProperty", "(", "dependencies", ",", "dependency", ")", ";", "}", "dependencies", "[", "versionKey", "]", "=", "true", ";", "if", "(", "!", "depencyList", "[", "versionKey", "]", ")", "{", "url", "=", "`", "${", "constants", ".", "FIREBASE_DATABASE_URL", "}", "${", "dependency", "}", "${", "match", "}", "`", ";", "const", "newDependencies", "=", "await", "request", "(", "{", "url", ",", "method", ":", "\"GET\"", ",", "json", ":", "true", ",", "headers", ":", "{", "\"content-type\"", ":", "\"application/json\"", ",", "}", ",", "}", ")", ";", "depencyList", "[", "versionKey", "]", "=", "{", "}", ";", "if", "(", "newDependencies", ")", "{", "depencyList", "[", "versionKey", "]", ".", "dependencies", "=", "await", "recDependencies", "(", "newDependencies", ")", ";", "}", "}", "if", "(", "root", ")", "{", "depencyList", "[", "versionKey", "]", ".", "isRootDependency", "=", "true", ";", "}", "depencyList", "[", "versionKey", "]", ".", "packageName", "=", "dependency", ";", "depencyList", "[", "versionKey", "]", ".", "version", "=", "match", ";", "}", "return", "dependencies", ";", "}" ]
Recursively resolve a set of dependencies to fixed versions @param {Object} dependencies - Dedendencies with ranges to resolve @param {Boolean} root - Boolean indicating if these are root dependencies @returns {void}
[ "Recursively", "resolve", "a", "set", "of", "dependencies", "to", "fixed", "versions" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/resolveDependencies.js#L16-L77
train
MaartenDesnouck/google-apps-script
lib/functions/resolveDependencies.js
resolveDependencies
async function resolveDependencies(rootFolder) { const includeFile = path.join(rootFolder, constants.INCLUDE_FILE); const includeJson = fs.readJsonSync(includeFile, 'utf8'); await recDependencies(includeJson.dependencies, true); return depencyList; }
javascript
async function resolveDependencies(rootFolder) { const includeFile = path.join(rootFolder, constants.INCLUDE_FILE); const includeJson = fs.readJsonSync(includeFile, 'utf8'); await recDependencies(includeJson.dependencies, true); return depencyList; }
[ "async", "function", "resolveDependencies", "(", "rootFolder", ")", "{", "const", "includeFile", "=", "path", ".", "join", "(", "rootFolder", ",", "constants", ".", "INCLUDE_FILE", ")", ";", "const", "includeJson", "=", "fs", ".", "readJsonSync", "(", "includeFile", ",", "'utf8'", ")", ";", "await", "recDependencies", "(", "includeJson", ".", "dependencies", ",", "true", ")", ";", "return", "depencyList", ";", "}" ]
Read the gas-include file a return a dependency tree with exact versions @param {String} rootFolder - Folder where we can find the gas-include file @returns {void}
[ "Read", "the", "gas", "-", "include", "file", "a", "return", "a", "dependency", "tree", "with", "exact", "versions" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/resolveDependencies.js#L85-L90
train
MaartenDesnouck/google-apps-script
lib/functions/packLocalSingleFile.js
writeLocalJson
function writeLocalJson(source, rootFolder) { // Write to local.json const local = path.join(rootFolder, constants.META_DIR, constants.META_LOCAL); const file = { name: local, source: JSON.stringify(source), }; createFile(file); }
javascript
function writeLocalJson(source, rootFolder) { // Write to local.json const local = path.join(rootFolder, constants.META_DIR, constants.META_LOCAL); const file = { name: local, source: JSON.stringify(source), }; createFile(file); }
[ "function", "writeLocalJson", "(", "source", ",", "rootFolder", ")", "{", "const", "local", "=", "path", ".", "join", "(", "rootFolder", ",", "constants", ".", "META_DIR", ",", "constants", ".", "META_LOCAL", ")", ";", "const", "file", "=", "{", "name", ":", "local", ",", "source", ":", "JSON", ".", "stringify", "(", "source", ")", ",", "}", ";", "createFile", "(", "file", ")", ";", "}" ]
Write the source to the write file @param {String} source - relative path to the rootFolder of the project @param {String} rootFolder - relative path to the rootFolder of the project @returns {void}
[ "Write", "the", "source", "to", "the", "write", "file" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/packLocalSingleFile.js#L16-L24
train
MaartenDesnouck/google-apps-script
lib/functions/getAllFolders.js
getAllFolders
function getAllFolders(dir, folderlist) { const files = fs.readdirSync(dir); folderlist = folderlist || []; files.forEach((file) => { if (fs.statSync(path.join(dir, file)).isDirectory()) { folderlist = getAllFolders(path.join(dir, file), folderlist); folderlist.push(path.join(dir, file)); } }); return folderlist; }
javascript
function getAllFolders(dir, folderlist) { const files = fs.readdirSync(dir); folderlist = folderlist || []; files.forEach((file) => { if (fs.statSync(path.join(dir, file)).isDirectory()) { folderlist = getAllFolders(path.join(dir, file), folderlist); folderlist.push(path.join(dir, file)); } }); return folderlist; }
[ "function", "getAllFolders", "(", "dir", ",", "folderlist", ")", "{", "const", "files", "=", "fs", ".", "readdirSync", "(", "dir", ")", ";", "folderlist", "=", "folderlist", "||", "[", "]", ";", "files", ".", "forEach", "(", "(", "file", ")", "=>", "{", "if", "(", "fs", ".", "statSync", "(", "path", ".", "join", "(", "dir", ",", "file", ")", ")", ".", "isDirectory", "(", ")", ")", "{", "folderlist", "=", "getAllFolders", "(", "path", ".", "join", "(", "dir", ",", "file", ")", ",", "folderlist", ")", ";", "folderlist", ".", "push", "(", "path", ".", "join", "(", "dir", ",", "file", ")", ")", ";", "}", "}", ")", ";", "return", "folderlist", ";", "}" ]
List all folders in a directory @param {dir} dir - Current folder. @param {object} folderlist - List of folders already found. @returns {object} - List of all folders in dir
[ "List", "all", "folders", "in", "a", "directory" ]
07f2d40f396d932c34ef823670321b25c02ddded
https://github.com/MaartenDesnouck/google-apps-script/blob/07f2d40f396d932c34ef823670321b25c02ddded/lib/functions/getAllFolders.js#L11-L21
train
rrdelaney/ReasonablyTyped
lib/index.js
format
function format(source) { var fmtedCode = 'NotInitialized' try { fmtedCode = reason.printRE(reason.parseRE(source)) } catch (e) { fmtedCode = 'line ' + e.location.startLine + ', characters ' + e.location.startLineStartChar + '-' + e.location.endLineEndChar + ', ' + e.message + '\n' + source } return fmtedCode }
javascript
function format(source) { var fmtedCode = 'NotInitialized' try { fmtedCode = reason.printRE(reason.parseRE(source)) } catch (e) { fmtedCode = 'line ' + e.location.startLine + ', characters ' + e.location.startLineStartChar + '-' + e.location.endLineEndChar + ', ' + e.message + '\n' + source } return fmtedCode }
[ "function", "format", "(", "source", ")", "{", "var", "fmtedCode", "=", "'NotInitialized'", "try", "{", "fmtedCode", "=", "reason", ".", "printRE", "(", "reason", ".", "parseRE", "(", "source", ")", ")", "}", "catch", "(", "e", ")", "{", "fmtedCode", "=", "'line '", "+", "e", ".", "location", ".", "startLine", "+", "', characters '", "+", "e", ".", "location", ".", "startLineStartChar", "+", "'-'", "+", "e", ".", "location", ".", "endLineEndChar", "+", "', '", "+", "e", ".", "message", "+", "'\\n'", "+", "\\n", "}", "source", "}" ]
Runs `refmt` on a string of Reason code @param {string} source Reason source code @return {string} Formatted Reason code
[ "Runs", "refmt", "on", "a", "string", "of", "Reason", "code" ]
0b9cd39ac97f87f98a85b0a6491b50c9308c3be5
https://github.com/rrdelaney/ReasonablyTyped/blob/0b9cd39ac97f87f98a85b0a6491b50c9308c3be5/lib/index.js#L10-L29
train
rrdelaney/ReasonablyTyped
lib/index.js
compile
function compile( source, filename = '', includeModule = false, debugMode = false, ) { let res let resName let errors try { const [moduleName, bsCode, diagnosticErrors] = Retyped.compile(filename, source, debugMode) const fmtCode = format(bsCode) res = fmtCode resName = moduleName errors = diagnosticErrors } catch (e) { console.error(e) throw new Error(`${e[0][0]}`) } if (res.includes('SYNTAX ERROR>')) { throw new Error(res) } if (!includeModule) { return res } else { return { moduleName: resName, bsCode: res, diagnosticErrors: errors } } }
javascript
function compile( source, filename = '', includeModule = false, debugMode = false, ) { let res let resName let errors try { const [moduleName, bsCode, diagnosticErrors] = Retyped.compile(filename, source, debugMode) const fmtCode = format(bsCode) res = fmtCode resName = moduleName errors = diagnosticErrors } catch (e) { console.error(e) throw new Error(`${e[0][0]}`) } if (res.includes('SYNTAX ERROR>')) { throw new Error(res) } if (!includeModule) { return res } else { return { moduleName: resName, bsCode: res, diagnosticErrors: errors } } }
[ "function", "compile", "(", "source", ",", "filename", "=", "''", ",", "includeModule", "=", "false", ",", "debugMode", "=", "false", ",", ")", "{", "let", "res", "let", "resName", "let", "errors", "try", "{", "const", "[", "moduleName", ",", "bsCode", ",", "diagnosticErrors", "]", "=", "Retyped", ".", "compile", "(", "filename", ",", "source", ",", "debugMode", ")", "const", "fmtCode", "=", "format", "(", "bsCode", ")", "res", "=", "fmtCode", "resName", "=", "moduleName", "errors", "=", "diagnosticErrors", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "e", ")", "throw", "new", "Error", "(", "`", "${", "e", "[", "0", "]", "[", "0", "]", "}", "`", ")", "}", "if", "(", "res", ".", "includes", "(", "'SYNTAX ERROR>'", ")", ")", "{", "throw", "new", "Error", "(", "res", ")", "}", "if", "(", "!", "includeModule", ")", "{", "return", "res", "}", "else", "{", "return", "{", "moduleName", ":", "resName", ",", "bsCode", ":", "res", ",", "diagnosticErrors", ":", "errors", "}", "}", "}" ]
Compiles a Flow libdef to a Reason interface, formatted and error handled @param {string} source Flow libdef to compile @param {string} [filename] Name of file being compiled for better error messages @return {string} Reason interface
[ "Compiles", "a", "Flow", "libdef", "to", "a", "Reason", "interface", "formatted", "and", "error", "handled" ]
0b9cd39ac97f87f98a85b0a6491b50c9308c3be5
https://github.com/rrdelaney/ReasonablyTyped/blob/0b9cd39ac97f87f98a85b0a6491b50c9308c3be5/lib/index.js#L38-L72
train
rappid/rAppid.js
js/core/NotificationManager.js
function (templateName, attributes, options) { if (!this.$container) { this.$container = this.createComponent(HtmlElement, {"class": this.$.containerClass, tagName: "div"}); this.$stage.addChild(this.$container); } if (!this.$templates[templateName]) { console.warn("Couldn't find template " + templateName); return null; } options = options || {}; var duration = options.hasOwnProperty("duration") ? options.duration : this.$.duration; var notification = this.$templates[templateName].createInstance(attributes || {}); notification.bind('remove:dom', function () { notification.destroy(); }); this.$container.addChild(notification); var self = this; notification.close = function () { self.closeNotification(this); }; this.$notifications.push(notification); if (duration) { setTimeout(function () { self.closeNotification(notification); }, duration * 1000); } return notification; }
javascript
function (templateName, attributes, options) { if (!this.$container) { this.$container = this.createComponent(HtmlElement, {"class": this.$.containerClass, tagName: "div"}); this.$stage.addChild(this.$container); } if (!this.$templates[templateName]) { console.warn("Couldn't find template " + templateName); return null; } options = options || {}; var duration = options.hasOwnProperty("duration") ? options.duration : this.$.duration; var notification = this.$templates[templateName].createInstance(attributes || {}); notification.bind('remove:dom', function () { notification.destroy(); }); this.$container.addChild(notification); var self = this; notification.close = function () { self.closeNotification(this); }; this.$notifications.push(notification); if (duration) { setTimeout(function () { self.closeNotification(notification); }, duration * 1000); } return notification; }
[ "function", "(", "templateName", ",", "attributes", ",", "options", ")", "{", "if", "(", "!", "this", ".", "$container", ")", "{", "this", ".", "$container", "=", "this", ".", "createComponent", "(", "HtmlElement", ",", "{", "\"class\"", ":", "this", ".", "$", ".", "containerClass", ",", "tagName", ":", "\"div\"", "}", ")", ";", "this", ".", "$stage", ".", "addChild", "(", "this", ".", "$container", ")", ";", "}", "if", "(", "!", "this", ".", "$templates", "[", "templateName", "]", ")", "{", "console", ".", "warn", "(", "\"Couldn't find template \"", "+", "templateName", ")", ";", "return", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "var", "duration", "=", "options", ".", "hasOwnProperty", "(", "\"duration\"", ")", "?", "options", ".", "duration", ":", "this", ".", "$", ".", "duration", ";", "var", "notification", "=", "this", ".", "$templates", "[", "templateName", "]", ".", "createInstance", "(", "attributes", "||", "{", "}", ")", ";", "notification", ".", "bind", "(", "'remove:dom'", ",", "function", "(", ")", "{", "notification", ".", "destroy", "(", ")", ";", "}", ")", ";", "this", ".", "$container", ".", "addChild", "(", "notification", ")", ";", "var", "self", "=", "this", ";", "notification", ".", "close", "=", "function", "(", ")", "{", "self", ".", "closeNotification", "(", "this", ")", ";", "}", ";", "this", ".", "$notifications", ".", "push", "(", "notification", ")", ";", "if", "(", "duration", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "self", ".", "closeNotification", "(", "notification", ")", ";", "}", ",", "duration", "*", "1000", ")", ";", "}", "return", "notification", ";", "}" ]
Shows a notification with the given template. The templates need to be defined in the NotificationManager instance via XAML. @param {String} templateName - the name of the Template for the Notification @param {Object} [attributes] - attributes for the template @param {Object} [options] - options for @returns {js.core.DomElement} - the created notification instance
[ "Shows", "a", "notification", "with", "the", "given", "template", ".", "The", "templates", "need", "to", "be", "defined", "in", "the", "NotificationManager", "instance", "via", "XAML", "." ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/NotificationManager.js#L34-L70
train
rappid/rAppid.js
js/core/Router.js
function (to, createHistoryEntry, triggerRoute, force, callback) { return this.history.navigate(to, createHistoryEntry, triggerRoute, force, callback); }
javascript
function (to, createHistoryEntry, triggerRoute, force, callback) { return this.history.navigate(to, createHistoryEntry, triggerRoute, force, callback); }
[ "function", "(", "to", ",", "createHistoryEntry", ",", "triggerRoute", ",", "force", ",", "callback", ")", "{", "return", "this", ".", "history", ".", "navigate", "(", "to", ",", "createHistoryEntry", ",", "triggerRoute", ",", "force", ",", "callback", ")", ";", "}" ]
shortcut to history.navigate @param to @param createHistoryEntry @param triggerRoute
[ "shortcut", "to", "history", ".", "navigate" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Router.js#L206-L208
train
rappid/rAppid.js
srv/auth/DataSourceAuthenticationProvider.js
function (password, algorithm, salt) { salt = salt || Crypto.randomBytes(128).toString("hex"); algorithm = algorithm || this.$.algorithm; var hash = Crypto.createHash(this.$.algorithm); hash.update(salt + password, "utf8"); return [algorithm, salt, hash.digest("hex")].join(this.$.delimiter); }
javascript
function (password, algorithm, salt) { salt = salt || Crypto.randomBytes(128).toString("hex"); algorithm = algorithm || this.$.algorithm; var hash = Crypto.createHash(this.$.algorithm); hash.update(salt + password, "utf8"); return [algorithm, salt, hash.digest("hex")].join(this.$.delimiter); }
[ "function", "(", "password", ",", "algorithm", ",", "salt", ")", "{", "salt", "=", "salt", "||", "Crypto", ".", "randomBytes", "(", "128", ")", ".", "toString", "(", "\"hex\"", ")", ";", "algorithm", "=", "algorithm", "||", "this", ".", "$", ".", "algorithm", ";", "var", "hash", "=", "Crypto", ".", "createHash", "(", "this", ".", "$", ".", "algorithm", ")", ";", "hash", ".", "update", "(", "salt", "+", "password", ",", "\"utf8\"", ")", ";", "return", "[", "algorithm", ",", "salt", ",", "hash", ".", "digest", "(", "\"hex\"", ")", "]", ".", "join", "(", "this", ".", "$", ".", "delimiter", ")", ";", "}" ]
Creates an hash for a password @param {String} password @param {String} [algorithm] - default sha1 @param {String} [salt] - default is generated @returns {String}
[ "Creates", "an", "hash", "for", "a", "password" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/srv/auth/DataSourceAuthenticationProvider.js#L77-L85
train
rappid/rAppid.js
srv/auth/DataSourceAuthenticationProvider.js
function (password, algorithm, salt) { return { hash: this.createHash(password, algorithm, salt), loginAttempts: 0, loginBlocked: null } }
javascript
function (password, algorithm, salt) { return { hash: this.createHash(password, algorithm, salt), loginAttempts: 0, loginBlocked: null } }
[ "function", "(", "password", ",", "algorithm", ",", "salt", ")", "{", "return", "{", "hash", ":", "this", ".", "createHash", "(", "password", ",", "algorithm", ",", "salt", ")", ",", "loginAttempts", ":", "0", ",", "loginBlocked", ":", "null", "}", "}" ]
Creates an authentication Object which contains all authentication relevant data for an user @param password @param algorithm @param salt @returns {{encryptedPassword: *, loginAttempts: number, loginBlocked: null}}
[ "Creates", "an", "authentication", "Object", "which", "contains", "all", "authentication", "relevant", "data", "for", "an", "user" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/srv/auth/DataSourceAuthenticationProvider.js#L115-L123
train
rappid/rAppid.js
srv/auth/DataSourceAuthenticationProvider.js
function (registrationRequest, cb) { if (registrationRequest.$.password) { var ret = { providerUserId: registrationRequest.get(this.$.usernameField), authenticationData: this.createAuthenticationData(registrationRequest.$.password) }; cb(null, ret); } else { cb("No password set"); } }
javascript
function (registrationRequest, cb) { if (registrationRequest.$.password) { var ret = { providerUserId: registrationRequest.get(this.$.usernameField), authenticationData: this.createAuthenticationData(registrationRequest.$.password) }; cb(null, ret); } else { cb("No password set"); } }
[ "function", "(", "registrationRequest", ",", "cb", ")", "{", "if", "(", "registrationRequest", ".", "$", ".", "password", ")", "{", "var", "ret", "=", "{", "providerUserId", ":", "registrationRequest", ".", "get", "(", "this", ".", "$", ".", "usernameField", ")", ",", "authenticationData", ":", "this", ".", "createAuthenticationData", "(", "registrationRequest", ".", "$", ".", "password", ")", "}", ";", "cb", "(", "null", ",", "ret", ")", ";", "}", "else", "{", "cb", "(", "\"No password set\"", ")", ";", "}", "}" ]
RegistrationRequest requires a password to create the registrationData @param registrationRequest @param cb
[ "RegistrationRequest", "requires", "a", "password", "to", "create", "the", "registrationData" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/srv/auth/DataSourceAuthenticationProvider.js#L129-L139
train
rappid/rAppid.js
srv/auth/DataSourceAuthenticationProvider.js
function (registrationRequest, callback) { this.fetchUser(registrationRequest, function (err, user) { if (!err && user) { err = RegistrationError.USER_ALREADY_EXISTS } callback(err); }); }
javascript
function (registrationRequest, callback) { this.fetchUser(registrationRequest, function (err, user) { if (!err && user) { err = RegistrationError.USER_ALREADY_EXISTS } callback(err); }); }
[ "function", "(", "registrationRequest", ",", "callback", ")", "{", "this", ".", "fetchUser", "(", "registrationRequest", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "!", "err", "&&", "user", ")", "{", "err", "=", "RegistrationError", ".", "USER_ALREADY_EXISTS", "}", "callback", "(", "err", ")", ";", "}", ")", ";", "}" ]
Checks if the user already exists @param registrationRequest @param callback
[ "Checks", "if", "the", "user", "already", "exists" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/srv/auth/DataSourceAuthenticationProvider.js#L146-L153
train
rappid/rAppid.js
srv/auth/DataSourceAuthenticationProvider.js
function (authenticationRequest, callback) { // create query to fetch the user var query = this._createQueryForUser(authenticationRequest.get(this.$.usernameField)); var collection = this.$.dataSource.createCollection(this.$collectionClass).query(query); collection.fetch({limit: 1}, function (err, users) { var user; if (!err && users.size()) { user = users.at(0); user.fetch(null, callback); } else { callback(err, null); } }); }
javascript
function (authenticationRequest, callback) { // create query to fetch the user var query = this._createQueryForUser(authenticationRequest.get(this.$.usernameField)); var collection = this.$.dataSource.createCollection(this.$collectionClass).query(query); collection.fetch({limit: 1}, function (err, users) { var user; if (!err && users.size()) { user = users.at(0); user.fetch(null, callback); } else { callback(err, null); } }); }
[ "function", "(", "authenticationRequest", ",", "callback", ")", "{", "var", "query", "=", "this", ".", "_createQueryForUser", "(", "authenticationRequest", ".", "get", "(", "this", ".", "$", ".", "usernameField", ")", ")", ";", "var", "collection", "=", "this", ".", "$", ".", "dataSource", ".", "createCollection", "(", "this", ".", "$collectionClass", ")", ".", "query", "(", "query", ")", ";", "collection", ".", "fetch", "(", "{", "limit", ":", "1", "}", ",", "function", "(", "err", ",", "users", ")", "{", "var", "user", ";", "if", "(", "!", "err", "&&", "users", ".", "size", "(", ")", ")", "{", "user", "=", "users", ".", "at", "(", "0", ")", ";", "user", ".", "fetch", "(", "null", ",", "callback", ")", ";", "}", "else", "{", "callback", "(", "err", ",", "null", ")", ";", "}", "}", ")", ";", "}" ]
Fetches a user by username, returns a User or NULL @param {srv.auth.AuthenticationRequest} authenticationRequest @param {Function} callback
[ "Fetches", "a", "user", "by", "username", "returns", "a", "User", "or", "NULL" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/srv/auth/DataSourceAuthenticationProvider.js#L175-L189
train
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.storage.js
function(key) { var value = this.storage.get(key); if (typeof value == 'undefined' || value == null || value == '') { return value; } try { return JSON.parse(value); } catch(e) { return value; } }
javascript
function(key) { var value = this.storage.get(key); if (typeof value == 'undefined' || value == null || value == '') { return value; } try { return JSON.parse(value); } catch(e) { return value; } }
[ "function", "(", "key", ")", "{", "var", "value", "=", "this", ".", "storage", ".", "get", "(", "key", ")", ";", "if", "(", "typeof", "value", "==", "'undefined'", "||", "value", "==", "null", "||", "value", "==", "''", ")", "{", "return", "value", ";", "}", "try", "{", "return", "JSON", ".", "parse", "(", "value", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "value", ";", "}", "}" ]
Returns the set value at `key`, parsing with `JSON.parse` and turning into an object if possible
[ "Returns", "the", "set", "value", "at", "key", "parsing", "with", "JSON", ".", "parse", "and", "turning", "into", "an", "object", "if", "possible" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.storage.js#L117-L127
train
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.storage.js
function(callback) { var found = false; this.each(function(key, value) { if (callback(key, value)) { found = [key, value]; return false; } }); return found; }
javascript
function(callback) { var found = false; this.each(function(key, value) { if (callback(key, value)) { found = [key, value]; return false; } }); return found; }
[ "function", "(", "callback", ")", "{", "var", "found", "=", "false", ";", "this", ".", "each", "(", "function", "(", "key", ",", "value", ")", "{", "if", "(", "callback", "(", "key", ",", "value", ")", ")", "{", "found", "=", "[", "key", ",", "value", "]", ";", "return", "false", ";", "}", "}", ")", ";", "return", "found", ";", "}" ]
Works exactly like filter except only returns the first matching key value pair instead of all of them
[ "Works", "exactly", "like", "filter", "except", "only", "returns", "the", "first", "matching", "key", "value", "pair", "instead", "of", "all", "of", "them" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.storage.js#L191-L200
train